Generated banner for Engrava
Generated logo for Engrava

Engrava

Memory frameworkOfficial Sovantica project

Created by Sovantica

Published in sovantica/engrava. Publisher page

12 GitHub stars

What it is

The memory database for AI agents - graph memory, hybrid search, tamper-evident thought/edge journal.
— the description by Sovantica

AutoGineer overview, from the brain’s own files

Engrava is an in-process memory database designed for AI agents, built on SQLite. It provides a structured way to store and retrieve agent thoughts using a graph-based model, where thoughts are linked by typed edges. The system supports hybrid search, combining vector similarity, full-text search (FTS5), recency, and priority. It includes built-in mechanisms for memory consolidation (dreaming), memory hygiene (archiving and garbage collection), and a tamper-evident journal for tracking mutations. Engrava operates as a library with no external service dependencies in its core path, allowing agents to maintain persistent, queryable state locally.

How it works

Memory model: Hybrid

AutoGineer overview, from the brain’s own files

Engrava uses a SQLite database to store thoughts and their relationships. It organizes data into thoughts and typed edges, which can be queried using the MindQL language. The system supports hybrid search by combining vector embeddings, keyword search, and metadata signals. It manages memory through a lifecycle that includes archiving and garbage collection, and it can consolidate memories into reflections. The system is extensible via hooks and provides an MCP server for integration with various AI agent frameworks.

Folders
FolderRoleFiles
.githubagent-config16
docsdocs37
examplesexamples13
scriptsscripts24
srcsource-code89
teststests201
.githooksfolder1

The agent reads

Requirements

Runtimes: Python >=3.11

Databases: SQLite

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. This brain runs code automatically: 2 scripts. Review .githooks/commit-msg, Makefile before opening the folder in Claude Code. No step below turns a hook on for you.

    • .githooks/commit-msg: runs on git commit-msg
    • Makefile: echo "$(BLUE)>> Installing engrava + dev dependencies$(RESET)"; $(PIP) install --upgrade pip setuptools wheel; $(PIP) install -e ".[dev]"; bash scripts/install_hooks.sh; echo "$(GREEN)>> Done. Run 'make check' to verify quality gate.$(RESET)"
  2. Not scanned by AutoGineerIts dependencies are installed by pip or uv when you run it and were not scanned by AutoGineer (5 declared). https://pypi.org/project/engrava/
  3. Created by Sovantica. Published in sovantica/engrava. Licence: MIT License.

Usage

AutoGineer overview, from the brain’s own files

  • Persistent memory for autonomous AI agents
  • Personal knowledge base management
  • Conversation storage with semantic retrieval
  • Research notes with associative linking
  • Memory-backed agent development
  • Audit-trailed thought and edge tracking
“Store a new observation about a project requirement.”
The agent uses the remember() method to persist the thought, which is then indexed for future hybrid search and graph traversal.
“Retrieve relevant context for a coding task.”
The agent uses the recall() method, which performs a hybrid search across FTS5, vector, and graph signals to return ranked, contextually relevant thoughts.
“Query the memory graph for all observations with high priority.”
The agent executes a MindQL query: FIND thoughts WHERE thought_type = 'OBSERVATION' AND priority = 'P1'.
“Consolidate old memories to free up space.”
The agent triggers the DreamingExtension to cluster related thoughts and compute reflections, or uses the memory hygiene loop to archive low-signal thoughts.

Documentation by Sovantica

Engrava

The memory database for AI agents.

A queryable memory graph with bi-temporal valid-time predicates — in an in-process Python library over one SQLite file, with no generative-model call in the core write path.

Image: CI Image: PyPI Image: Python Image: License: MIT

Engrava is a standalone, in-process database for AI agent memory. Built on SQLite, it provides thought CRUD, edge-based knowledge graphs, embedding-based similarity search, full-text search (FTS5/BM25), and a declarative extension system — all in a single package with zero external service dependencies.

Benchmark results are published, and the runs are reproducible from a separate repository. Every published run is Group A — memory_pipeline_llms: [], no language model anywhere in the memory layer's built-in path. That is a property of the architecture's default signals and hooks rather than a measurement, unless a custom Dreaming signal or Memory Hygiene hook is configured to call one.

  • Benchmark results — the live table: every published row with the comparability segment it belongs to.

  • engrava-benchmark — the runner. Clone it and reproduce a result against the package from PyPI. MIT.

  • Discussions — questions; reproduction questions belong in the Q&A category.

Use Cases

  • AI agent persistent memory

  • Personal knowledge base

  • Conversation storage with semantic search

  • Research notes with associative linking

  • Any application that needs a thought-graph with embeddings

Quick Start

Installation
pip install engrava

Optional extras:

pip install 'engrava[vec]'                # sqlite-vec vector search backend
pip install 'engrava[embeddings-local]'   # sentence-transformers embeddings (local model)
pip install 'engrava[embeddings-openai]'  # OpenAI-compatible embeddings API
pip install 'engrava[embeddings-ollama]'  # Ollama local embeddings server
pip install 'engrava[embeddings-hf]'      # HuggingFace Inference API embeddings

Dreaming/consolidation and the knowledge graph need no extra — they are part of the base install.

embeddings-local carries a large first-run download. It pulls sentence-transformers and torch, plus a further, separate model download (~88 MB for all-MiniLM-L6-v2, cached under ~/.cache/huggingface/hub) on first use. On Linux, the PyPI build of torch also pulls the NVIDIA CUDA libraries as dependencies: several gigabytes, most of it usable only with an NVIDIA GPU. Without one, install the CPU-only build first (see Configuration: No NVIDIA GPU for the exact command and numbers). engrava-mcp[local] is the exact same download, reached through the server package instead of this one. If you do not need semantic search in-process, pip install engrava alone (no extra, no download, no model) already gives you keyword search, the graph, and MindQL — see Configuration → Quick-start profiles for that and the Ollama-backed alternative that keeps the model out of this process entirely.

Basic Usage

Store a memory and search for it in two calls — no IDs to generate, no record to assemble:

import asyncio

import aiosqlite

from engrava import SqliteEngravaCore


async def main() -> None:
    # SqliteEngravaCore wraps an open aiosqlite connection.
    async with aiosqlite.connect(":memory:") as conn:
        conn.row_factory = aiosqlite.Row
        store = SqliteEngravaCore(conn)
        await store.ensure_schema()

        await store.remember("Python is great for AI agents")
        await store.remember("SQLite needs no server")

        result = await store.recall("what language is good for agents?")
        for thought_id, score in result.results:
            thought = await store.get_thought(thought_id)
            if thought is not None:
                print(f"{thought.essence}  (score: {score:.3f})")


asyncio.run(main())

remember() stores the text as a thought (generating its ID for you) and returns the stored ThoughtRecord; recall() runs the same hybrid search as search_hybrid() and returns the ranked results. This store has no SearchConfig of its own, and it still ranks with the same default weights — FTS 0.30, vector 0.55, recency 0.10, priority 0.05, graph 0.00 (opt-in) — as a store built with one; see Hybrid Search. For full control — setting priority, thought type, metadata, or the cognitive cycle on a write — build a ThoughtRecord yourself and call create_thought().

From here, link thoughts with typed edges, query them with MindQL, or run the full ingest → dream → search tour in the Quick Start guide.

Configuration-Driven Setup
from engrava import SqliteEngravaCore

# from_config opens and OWNS the connection — use it as an async context manager.
async with await SqliteEngravaCore.from_config("engrava.yaml") as store:
    # The schema is already applied by from_config.
    thought = await store.get_thought("some-id")

See docs/configuration.md for the full YAML schema.

Upgrading

Automatic schema migration runs on first connection. See the upgrade guide for compatibility notes, backup guidance, and troubleshooting steps.

Features

Thought CRUD

Create, read, update, and archive thoughts with full lifecycle management. All models are frozen Pydantic objects — mutations happen via evolve().

Edge-Based Knowledge Graph

Link thoughts with typed, weighted edges. Edge types include ASSOCIATED, DEPENDS_ON, DERIVED_FROM, CONSOLIDATED_FROM (created by dreaming), and CONTESTED_BY.

Store embeddings alongside thoughts and search them with the built-in NumPy cosine backend or the optional sqlite-vec backend (pip install 'engrava[vec]'). Pluggable embedding providers:

ProviderExtraBackend
SentenceTransformerProviderembeddings-localLocal model via sentence-transformers
OpenAICompatibleProviderembeddings-openaiAny OpenAI-compatible API
OllamaProviderembeddings-ollamaLocal Ollama server
HuggingFaceProviderembeddings-hfHuggingFace Inference API
CallbackProvider(built-in)Custom callable
Full-Text Search (FTS5)

SQLite FTS5 virtual table with BM25 ranking. Hybrid search combines vector similarity, text relevance, recency, priority, and graph connectivity. Signals that cannot run for a query are skipped and the remaining weights are redistributed.

MindQL Query Language

Declarative query language for the thought-graph:

FIND thoughts WHERE thought_type = 'OBSERVATION' AND priority = 'P1' LIMIT 10
COUNT thoughts WHERE lifecycle_status = 'ACTIVE'
SELECT thought_id, essence FROM thought WHERE thought_type = 'BELIEF'

Extensible with custom commands through MindQLExecutor or an ExtensionManifest; the lifecycle hook registry is reserved and is not consulted by the core executor.

Extension System

Plug into the thought lifecycle via EngravaHooksProtocol. Subclass DefaultEngravaHooks when you only need selected active methods:

from engrava import DefaultEngravaHooks, ThoughtRecord

class MyHooks(DefaultEngravaHooks):
    async def on_store(self, thought: ThoughtRecord) -> ThoughtRecord:
        # Observe or enrich the object returned after persistence.
        return thought

    async def decay_function(
        self, thought: ThoughtRecord, elapsed_cycles: int
    ) -> float:
        # Supply a decay multiplier to an enabled Memory Hygiene pass.
        return 1.0

Core currently invokes on_store, on_retrieve, and decay_function. on_store runs after the source thought's row is inserted; changing its return value does not rewrite the persisted row. score_function and mindql_extension_registry() remain reserved protocol methods and are not called by core.

Dreaming / Memory Consolidation

Built-in DreamingExtension for periodic memory consolidation — scores thoughts via its default signals (no LLM calls), promotes high-value entries, and creates REFLECTION thoughts by clustering semantically related thoughts and computing centroid embeddings through a deterministic structural function, not an LLM. A custom signal you register with DreamingExtension runs whatever code it contains. Available since 0.3.0.

→ See docs/benchmarks.md for reproducible evidence (synthetic benchmark suite runnable in ~5 minutes).

Forgetting / Memory Hygiene

The subtractive half of memory maintenance, paired with Dreaming: an opt-in loop whose built-in scoring makes no LLM calls, that archives cold, low-signal thoughts — the default action, reversible via restore_thought — and, as a separately opted-in step, garbage-collects them (not reversible) once both restore windows have elapsed under their non-zero defaults — a cycle count and a wall-clock duration, either of which can be configured to 0 to disable that window. OFF by default; once enabled, archived thoughts drop out of default retrieval and can be restored (restore_thought / include_archived).

→ See docs/memory-hygiene.md for the loop, protection, restore windows, and the honest deletion posture.

Tamper-Evident Thought/Edge Journal

Opt-in hash-chain journal that records thought and edge mutations (plus action status/verification_status transitions) as SHA-256-linked, before/after entries — a tamper-evident thought/edge journal, not a whole-database audit (embeddings and action creation are not covered). Off by default, one config flag to enable. Query history with store.journal.get_entries(...) and validate the chain with store.verify_journal(), which audits whatever chain is on disk independent of the current journal.enabled state — the store.journal writer handle does not exist while journaling is off, but the chain earlier sessions wrote is still in journal_entry and still needs verifying.

→ See docs/audit-trail.md for enabling, querying, verification, and the security model (what "tamper-evident" does and does not guarantee).

Multi-Service Isolation

Run multiple independent databases under one EngravaManager:

from pathlib import Path

from engrava import EngravaManager

async with EngravaManager(data_dir=Path("./data")) as mgr:
    agent_a = await mgr.get_store("agent-a")
    agent_b = await mgr.get_store("agent-b")
    # Completely isolated databases
MCP Server

Want Engrava as a memory server for your agent? The MCP server ships as its own package, engrava-mcp — a native stdio server (no HTTP shim) with read tools, optional write tools, attachable engrava:// resources, and guided prompts, for any MCP client (Claude Desktop, Claude Code, Cursor, Windsurf, VS Code):

uvx engrava-mcp        # or: pip install engrava-mcp

engrava-mcp pulls engrava in transitively, so installing it also gives you the import engrava library. See the engrava-mcp package for install, client configuration, the full tool/resource/prompt reference, and read-only mode.

uvx vs. a persistent install. uvx engrava-mcp (equivalently uv tool run engrava-mcp) installs into "an ephemeral virtual environment in the uv cache directory" per uv's own --help text — fine for the lexical/network profiles above, which add nothing heavier than httpx. Once you are on the local profile (engrava-mcp[local], the same sentence-transformers + torch download as engrava[embeddings-local]), uv tool install 'engrava-mcp[local]' is the better fit: it installs once into a persistent environment — the same uvx engrava-mcp invocation then reuses that installed environment instead of resolving a fresh ephemeral one — and a later uv tool upgrade engrava-mcp re-pays only the changed packages, not the whole dependency tree.

CLI

engrava --db mydata.db info          # Database stats
engrava --db mydata.db query "FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 5"
engrava --db mydata.db snapshot -o backup.jsonl
engrava --db mydata.db restore -i backup.jsonl
engrava --db mydata.db gc            # Collect ARCHIVED thoughts + their edges/embeddings/actions
engrava --db mydata.db migrate       # Ensure schema is up-to-date
engrava --db mydata.db export -o portable.json

gc physically deletes ARCHIVED thoughts together with every edge touching one on either end — including edges whose other end is still live — their embeddings and the actions sourced from them, then reconciles the vector index by removing every vec0 row no embedding row owns; on a vec0-indexed store where sqlite-vec cannot be loaded — most commonly because engrava[vec] is not installed — a pass that is about to delete stops before deleting anything and exits 1 rather than stranding those vectors in an index nothing can then reach them through.

engrava info's --format json output carries every field of the metrics snapshot exposed by await store.metrics(), with the snapshot's own schema version renamed metrics_schema_version, plus two fields the snapshot itself does not carry, db_path and database_schema_version — see Upgrade Guide. The default text output is a shorter summary of that same data, not the full snapshot.

See the CLI reference for every command and option.

Architecture

  • SQLite with WAL mode for concurrent reads

  • Frozen Pydantic models — immutable domain objects

  • Async-first — all I/O via aiosqlite

  • Hook-based extension — zero monkey-patching

  • Template method pattern — subclass SqliteEngravaCore for extended schemas

  • Zero external services — everything runs locally in-process

Documentation

  • Documentation Index — choose a path by task: learn, build, operate, extend, or migrate

  • Core Concepts — the mental model (thought, edge, reflection, cycle, …) — start here

  • The Bi-temporal Model — the optional valid-time axis: query a fact as of any instant, invalidate without deleting

  • Positioning — when Engrava is (and isn't) the right tool, and how it compares

  • Quick Start — 5-minute setup guide

  • Tutorial — build a small notes memory end to end

  • Recipes — copy-paste snippets for common tasks (store a turn, retrieve context, TTL, dedup, …)

  • Building a memory-backed agent — the end-to-end agent turn loop (ingest → retrieve → generate → consolidate)

  • Migrating from another memory system — concept mapping, porting calls, bulk import, and scoping/multi-tenancy

  • Embeddings — wiring a real embedding provider (local / OpenAI / Ollama / HuggingFace / custom)

  • MCP server (engrava-mcp) — expose a store to MCP clients (Claude Desktop, Claude Code, Cursor, Windsurf, VS Code) via the standalone server package: install, run, client config, tools/resources/prompts

  • Configuration — YAML config format and options

  • Upgrade Guide — compatibility matrix, backups, and troubleshooting

  • Extensions — Writing custom extensions and hooks

  • Observability — Metrics snapshot API

  • Audit Trail — Tamper-evident hash-chain journal (enabling, querying, verifying, security model)

  • Evidence and Conflicts — model claims, provenance, contested facts, and caller-owned clarification

  • Security — trust boundaries, data egress, tenant isolation, encryption posture, and journal limits

  • Error Handling and Recovery — decide when to retry, repair input, or replace a store

  • Benchmarks — release gates, versioned observed values, and LongMemEval

  • API Reference — Full protocol and class reference

  • CLI Reference — every engrava command and option

  • Glossary — quick definitions of every Engrava term

  • MindQL — Query language syntax and examples

  • Troubleshooting — symptom → cause → fix for common errors

  • FAQ — quick answers (LLM/keys, embeddings-optional, scale, concurrency, backups, …)

  • Performance & Scaling — the vector-backend switch, bulk-ingest, and dreaming cost at scale

  • Data Lifecycle & Retention — lifecycle states, TTL, archive-vs-delete, GDPR erasure, disk reclamation

  • Deployment — process model, database files on disk, containers, graceful shutdown

  • Concurrency — the WAL single-writer model, busy timeout, and per-service isolation

  • Backup & Recovery — WAL-safe backups, snapshot vs file copy, restore verification

  • Known Limitations — Platform notes and constraints

Development

make install   # deps + dev extras + local git hooks -- from the primary checkout
make gate      # fast: hooks-active + lint + format check + type check + goldens drift, ~70s
make check     # lint + format check + type check + the full test suite with coverage (unchanged; no hooks-active, no goldens drift)

make install also wires a commit-msg hook that lints the message of the commit a squash merge creates — including on a local branch that never opens a pull request, where nothing else does. It refuses to install from a linked worktree (core.hooksPath is shared across all of them). See CONTRIBUTING.md for what it covers and what it does not.

License

MIT — see LICENSE for details.

docs/mindql.md

MindQL

MindQL is a small declarative query language for the engrava thought-graph. It provides a human-readable syntax for retrieving and counting rows, plus a read-only SQL passthrough.

Syntax

[EXPLAIN] FIND  <table> [WHERE <bool-expr>] [ORDER BY <sort> ...] [LIMIT <n>] [OFFSET <n>]
[EXPLAIN] COUNT <table> [WHERE <bool-expr>]
[EXPLAIN] SELECT <raw read-only SQL>
  • The command verb (FIND, COUNT, SELECT) is case-insensitive.

  • FIND and COUNT require a table name as the second token.

  • A simple WHERE condition is field operator value. The quoting decides the type: a single-quoted value is kept verbatim as a string, so a zero-padded identifier like source = '007' matches the stored string '007', whereas an unquoted created_cycle = 7 is coerced to the integer 7 (or to a float, for 7.5). An unquoted word that is not a number stays a string (source = abc), but a value containing spaces must be quoted. A single-quoted value may contain a literal quote by doubling it, SQL-style: source = 'O''Brien' matches the stored string O'Brien, in a condition or inside an IN (...) list.

  • A boolean keyword (AND, OR) is recognised only as a whole word outside a quoted value, so an unquoted value that happens to end or start with one — source = vendor, source = ORACLE — is never mistaken for the operator.

  • Operators: =, !=, >, <, >=, <=, and IN (...).

  • Conditions combine with AND, OR, and parentheses (see Boolean expressions).

  • FIND additionally supports ORDER BY and OFFSET; any read query may be prefixed with EXPLAIN to see the compiled SQL without running it.

Queryable tables
Token(s)Table
thoughts, thoughtthought
edges, edgeedge
embeddings, embeddingembedding
actions, actionaction

Commands

FIND

Retrieve rows from a table.

FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 10
FIND thoughts WHERE lifecycle_status = 'ACTIVE' AND priority = 'P1'
FIND thoughts WHERE priority IN ('P1', 'P2') ORDER BY created_cycle DESC LIMIT 20
FIND thoughts ORDER BY created_cycle DESC LIMIT 10 OFFSET 20
FIND edges WHERE edge_type = 'ASSOCIATED' LIMIT 5

Filterable thought columns include thought_type, lifecycle_status, priority, essence, content, source, confidence, visibility, confirmation_count, created_cycle, updated_cycle, and thought_id. A column outside the per-table allowlist raises MindQLParseError.

Default row cap. A FIND with no LIMIT clause is capped at 100 rows when it runs, so an unqualified FIND thoughts can never trigger an unbounded scan. The cap is applied at execution, not at parse time — parse("FIND thoughts") leaves query.limit as None, and the executor substitutes the default only if no explicit LIMIT is present. An explicit LIMIT always overrides the default; COUNT queries are unaffected (they aggregate and never materialise the rows).

Returns: matching rows as dicts.

ORDER BY

FIND accepts an ORDER BY clause with one or more sort keys, each with an optional direction (ASC default, or DESC, case-insensitive):

FIND thoughts ORDER BY created_cycle DESC
FIND thoughts WHERE priority = 'P1' ORDER BY priority ASC, created_cycle DESC LIMIT 10

Every sort field must be in the per-table column allowlist. Sort fields are column identifiers, not values — they are validated against the allowlist and never bound as parameters, so an unknown field raises MindQLParseError. ORDER BY is emitted before LIMIT/OFFSET. It is rejected on COUNT (which returns a scalar) and is not used with the raw SELECT passthrough.

OFFSET / pagination

FIND accepts an OFFSET <n> clause (n >= 0) for pagination, combined with LIMIT and ORDER BY. Both LIMIT and OFFSET accept a non-negative integer up to 2^63 - 1 (SQLite's largest integer); a value outside that range raises MindQLParseError.

FIND thoughts ORDER BY created_cycle DESC LIMIT 20 OFFSET 40

SQLite requires a LIMIT for OFFSET, so an OFFSET with no explicit LIMIT applies the default row cap as the limit. OFFSET is rejected on COUNT and the SELECT passthrough. For stable pages, pair OFFSET with an ORDER BY so the row order is deterministic.

WHERE operators
IN

The IN operator matches a column against a set of values:

FIND thoughts WHERE thought_type IN ('BELIEF', 'OBSERVATION')
FIND thoughts WHERE created_cycle IN (1, 2, 3)

Each value follows the same quoting rule as a comparison value: single-quoted stays a verbatim string, unquoted is coerced to int/float. An empty IN () is a parse error. Every value is bound as a ? placeholder (never interpolated), and the field must be in the per-table allowlist.

Boolean expressions: AND, OR, parentheses

Conditions (simple comparisons, IN, and valid-time predicates) combine with AND, OR, and parenthesised grouping, using SQLite-standard precedence: AND binds tighter than OR:

FIND thoughts WHERE priority = 'P1' OR lifecycle_status = 'ACTIVE'
FIND thoughts WHERE priority = 'P1' OR priority = 'P2' AND source = 'x'
FIND thoughts WHERE (priority = 'P1' OR priority = 'P2') AND lifecycle_status = 'ACTIVE'

Because AND binds tighter, the second example groups as priority = 'P1' OR (priority = 'P2' AND source = 'x'). Use parentheses (as in the third example) to group an OR before an AND. A WHERE that uses only simple comparisons and/or valid-time predicates joined by AND (no OR, no parentheses, no IN) is read as a flat list of conditions joined by AND; a leading, trailing, or doubled AND raises MindQLParseError.

Parenthesised grouping may nest up to 256 levels deep; nesting deeper than that raises MindQLParseError.

COUNT

Count rows matching the filters. COUNT does not accept LIMIT, ORDER BY, or OFFSET.

COUNT thoughts WHERE lifecycle_status = 'ACTIVE'
COUNT thoughts WHERE thought_type = 'OBSERVATION'
COUNT edges

Returns: the count is exposed on MindQLResult.count.

SELECT

SELECT is a read-only SQL passthrough — it runs the statement verbatim, so it needs a full FROM clause and standard SQL syntax. The underlying tables are thought, edge, embedding, and action.

SELECT thought_id, essence FROM thought WHERE lifecycle_status = 'ACTIVE'
SELECT thought_id, priority, essence FROM thought WHERE thought_type = 'BELIEF' LIMIT 20

Only statements that begin with SELECT are permitted; anything else is rejected. The passthrough is also restricted to a single statement: once a statement-ending ; appears, only whitespace and comments may follow it — anything else is a second statement and is rejected (MindQLParseError: Only a single SELECT statement is allowed) so a second statement can never be smuggled in. A ; inside a comment, a string literal, a quoted identifier, or a parameter token is not a separator.

Bound parameters. The passthrough can carry bound parameters, set programmatically on the query object (never parsed from the MQL text). When MindQLQuery.select_params is set, the statement runs with those values bound to its ? placeholders — the preferred way to pass untrusted values into a passthrough:

from engrava import MindQLQuery, MindQLCommand, MindQLExecutor

query = MindQLQuery(
    command=MindQLCommand.SELECT,
    raw_sql="SELECT thought_id FROM thought WHERE priority = ?",
    select_params=("P1",),
)
result = await MindQLExecutor(conn).execute(query)

When select_params is None (the default, and what parse() produces) the statement runs with no bound parameters, exactly as before.

The executor re-validates a hand-built query. A MindQLQuery is public API and can be constructed directly, as above, so validation is not left to parse(): every identifier and keyword that has to be interpolated is checked again where the query runs. The executor validates the target table against its allowlist (defaulting to thought), every column named in a WHERE comparison, an IN list or an ORDER BY key against that table's column allowlist, the sort direction against ASC/DESC and the boolean joiner against AND/OR (either case accepted), and limit/offset as non-negative, non-boolean integers. Anything outside those sets raises MindQLParseError before a statement is built. Each check also emits the module's own string — or, for the row bounds, a rebuilt plain int — rather than the object you passed, so a str or int subclass cannot pass the membership check and then render different text through __format__.

EXPLAIN

Any read query may be prefixed with EXPLAIN to see the compiled SQL and its bound parameters without executing it:

EXPLAIN FIND thoughts WHERE priority = 'P1' ORDER BY created_cycle DESC
EXPLAIN COUNT thoughts WHERE thought_type IN ('BELIEF', 'OBSERVATION')
EXPLAIN SELECT thought_id FROM thought WHERE lifecycle_status = 'ACTIVE'

EXPLAIN is a pure compile-and-return: it never touches the database, never runs SQLite's EXPLAIN QUERY PLAN, and never executes the compiled or raw SQL. The result carries the plan as a single row under the columns ["sql", "params"] with command="EXPLAIN":

result = await MindQLExecutor(conn).execute(
    parse("EXPLAIN FIND thoughts WHERE priority = 'P1'")
)
plan = result.rows[0]
print(plan["sql"])     # SELECT * FROM thought WHERE priority = ? LIMIT 100
print(plan["params"])  # ['P1']

For FIND/COUNT the plan is the parameterised SQL that would run; for SELECT it is the guarded raw SQL and its declared select_params (if any). EXPLAIN still validates columns, so an EXPLAIN of a query that references a disallowed column raises MindQLParseError at compile time. EXPLAIN is only supported for FIND, COUNT, and SELECT (not extension commands).

Valid-time predicates

FIND and COUNT against the thoughts and edges tables accept four opt-in valid-time predicates in the WHERE clause, for querying when a fact was true in the world (the second time axis — see The Bi-temporal Model for the full semantics):

FIND thoughts WHERE valid_now
FIND edges WHERE valid_at '2026-01-01T00:00:00+00:00'
FIND thoughts WHERE priority = 'P1' AND valid_within '2026-01-01T00:00:00+00:00' '2026-02-01T00:00:00+00:00'
FIND thoughts WHERE valid_between '2026-01-01T00:00:00+00:00' '2026-12-31T00:00:00+00:00'
  • valid_now takes no argument; valid_at takes one ISO-8601 timestamp; valid_within and valid_between take two.

  • They combine with ordinary conditions via AND.

  • valid_now / valid_at / valid_within are NULL-tolerant (a record with an open valid_from/valid_until bound stays in the result); valid_between requires real bounds on both ends and therefore excludes open-bound rows.

  • A query that uses no temporal predicate behaves exactly as before.

Valid time is predicate-only, not a filterable column. Query valid time only through the four predicates above. valid_from and valid_until are not in the per-table column allowlist, so an ordinary comparison such as WHERE valid_from = '2026-01-01T00:00:00+00:00' is rejected when the query runs (MindQLParseError: Column 'valid_from' not allowed for table 'thought') — use valid_at / valid_within / valid_between instead.

The semantics, the open-interval (NULL = ±∞) rule, and invalidate are documented in full on The Bi-temporal Model.

Extension Commands

Custom MindQL verbs are provided through an extension's ExtensionManifest.mindql_extensions and reach the executor via the extensions= argument (entry-point discovery wires this up automatically). See Extensions for the registration flow.

Extension handlers are read-only too. A handler is invoked with a ReadOnlyAccessor, not the store's live connection. Its only capability is execute(), which runs a single SELECT statement through the same guard described above and returns a restricted cursor: fetchone, fetchall, fetchmany, async iteration, and description — no execute()-family method on the cursor, and no connection to reach back through. A handler that only reads through a single parameterised SELECT (the shape every documented example uses) is unaffected; one that tried to write through the connection it used to receive directly now raises MindQLParseError (for anything that is not a SELECT) or AttributeError (for a write attempted through the cursor). This closes the ordinary and attribute-level paths to a write — a handler is in-process Python code, so deliberate introspection (closure cells, gc) can still reach the underlying connection; the accessor is not a sandbox against that.

Python API

Parsing

parse() returns a MindQLQuery plan. Its fields are command, table, conditions, temporal_predicates (the parsed valid-time predicates, empty when none are used), where (the boolean-expression tree, or None on the pure-AND path), order_by, limit, offset, explain, raw_sql, select_params, extension_name, and extension_args.

where is None whenever the WHERE uses only simple comparisons and/or valid-time predicates joined by AND — in that case conditions + temporal_predicates are populated and execution follows the historical path unchanged. It is a tree (Comparison, InCondition, TemporalPredicate, and BoolExpr nodes, all in engrava.mindql.parser) only when the WHERE contains OR, parentheses, or IN.

from engrava import parse, MindQLParseError

try:
    query = parse("FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 5")
    print(query.command)     # MindQLCommand.FIND
    print(query.table)       # "thought"
    print(query.conditions)  # [Condition(field='thought_type', operator=..., value='OBSERVATION')]
    print(query.limit)       # 5
except MindQLParseError as exc:
    print(f"Parse error: {exc}")
Execution

When you already have a SqliteEngravaCore, use its execute_mindql() convenience method. It executes a parsed query on the store's own connection and accepts the same optional extension-command mapping as the lower-level executor:

from engrava import parse

result = await store.execute_mindql(
    parse("FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 10")
)
for row in result.rows:
    print(row["essence"])

MindQLExecutor runs against an open aiosqlite.Connection, and execute() takes a parsed MindQLQuery — parse the string first. MindQLResult exposes columns, rows, count, and command.

from engrava import MindQLExecutor, parse

executor = MindQLExecutor(conn)  # conn is an aiosqlite.Connection
result = await executor.execute(
    parse("FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 10")
)
for row in result.rows:
    print(row["essence"])

count_result = await executor.execute(
    parse("COUNT thoughts WHERE lifecycle_status = 'ACTIVE'")
)
print(f"Active thoughts: {count_result.count}")
Error Handling
  • MindQLParseError — raised for syntax errors, unknown tables, or columns outside a table's allowlist.

  • Unknown command verbs raise MindQLParseError unless registered as an extension command.

  • A WHERE fragment must match the field operator value grammar in full. Trailing content after a condition (for example WHERE priority = 'P1' OR 1=1) is rejected with a MindQLParseError rather than silently parsing only the leading priority = 'P1' and discarding the rest — so a malformed condition can never quietly change the result set.

CLI Usage

# Find observations
engrava --db my.db query "FIND thoughts WHERE thought_type = 'OBSERVATION' LIMIT 5"

# Count active thoughts
engrava --db my.db query "COUNT thoughts WHERE lifecycle_status = 'ACTIVE'"

# Select specific fields (raw SQL passthrough)
engrava --db my.db query "SELECT thought_id, essence FROM thought LIMIT 5"

Output formats: --format table (default), --format json, --format csv.

402 files · 357 not served here

Advantages

Limitations

Security

Risk level: Low risk

This brain runs

Git hooks (1)

  • .githooks/commit-msg (commit-msg): runs on git commit-msg

Agent instructions that run or fetch something (4)

  • AGENTS.md: Run `git commit` and it fires on the patterns it checks for.
  • CLAUDE.md: pip install -e ".[dev]"
  • CLAUDE.md: Run a clean test suite locally before pushing;
  • CLAUDE.md: Branch from `dev`, follow Conventional Commits, run the local quality gate before pushing.

Install scripts (1)

  • Makefile (make install): echo "$(BLUE)>> Installing engrava + dev dependencies$(RESET)"; $(PIP) install --upgrade pip setuptools wheel; $(PIP) install -e ".[dev]"; bash scripts/install_hooks.sh; echo "$(GREEN)>> Done. Run 'make check' to verify quality gate.$(RESET)"
  • Low risk: scripts-present (.githooks/commit-msg)
  • Low risk: network-instructions (CLAUDE.md:40)
  • Low risk: network-instructions (pyproject.toml:98)
  • Low risk: scripts-present (scripts/install_hooks.sh)

Attribution and licence

Created by
Sovantica
Declared authors
  • Sovantica (declared in pyproject.toml)
Publisher
Sovantica (Official Sovantica project)
Source
sovantica/engrava · commit f6a8b73
Licence
MIT License (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Sovantica.

Install from source

357 of its files are not served here, so there is no ZIP. sovantica/engrava at f6a8b73