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/evidence-and-conflicts.md

Evidence, Claims, and Conflicts

Engrava persists thoughts and directional edges. It gives an application a durable graph in which incompatible statements can coexist and remain traceable, but it is not an entity resolver, claim extractor, contradiction classifier, truth engine, or clarification workflow.

In particular, Engrava does not automatically:

  • identify that two names refer to the same real-world entity;

  • turn prose into typed subject/predicate/object claims;

  • decide that two thoughts are semantically incompatible;

  • choose which conflicting thought is true, current, or authoritative;

  • create a CONTESTED_BY edge; or

  • open a clarification task.

Those decisions belong to the caller. The caller establishes that a conflict exists and creates the CONTESTED_BY edge; Engrava Free does not detect contradictions automatically. Engrava stores the resulting thoughts, edges, valid-time bounds, metadata, and provenance without silently resolving the conflict.

What happens to incompatible writes

create_thought() creates a new row by default. Two differently worded or otherwise byte-distinct claims therefore coexist, even when they concern the same entity and cannot both be true.

Content-hash deduplication is opt-in with deduplicate=True, and matches on the stored SHA-256 content_hash. update_thought() never rewrites that column, so editing a thought's content leaves its stored hash pointing at the superseded text: a later deduplication hit on that row's hash does not guarantee the row's current content is byte-identical to what you are deduplicating against. A match returns the existing thought and increments its confirmation_count; it does not compare meaning. Likewise, upsert_by_hash() only updates a row with the same content hash. Engrava never uses either operation to overwrite a semantic conflict.

A caller can still deliberately update, archive, invalidate, or delete a thought. A high-ranked search result is also not a truth decision: ranking and conflict resolution are separate concerns. See Hybrid Search and Data Lifecycle.

A practical graph convention

Engrava does not prescribe an ontology. The following convention keeps entity, claim, and evidence responsibilities explicit while using only the public API.

ConceptRecommended representation
EntityA stable caller-owned identifier in nested thought metadata, for example metadata["entity"] = {"type": "customer", "id": "customer-42"}. Engrava does not canonicalize it.
ClaimA thought whose metadata contains a stable entity id, predicate, and object. Keep the complete human-readable proposition in content.
EvidenceA separate thought containing or locating the observed source material. Put source-specific scalar fields in metadata.
Computational lineageProvenanceContext, especially retrieval_context_ids, when retrieved thoughts actually shaped a synthesized thought. This is caller-declared write-time context, not proof that the claim is true.
Semantic supportA caller-owned convention. For example, use a claim-to-evidence DERIVED_FROM edge only when that accurately describes the derivation, and document the convention in edge metadata. Engrava has no native SUPPORTED_BY inference rule.
ConflictOne directional CONTESTED_BY edge for a claim pair, with the detector, rule version, and workflow state in edge metadata. The caller detects the tension.

Thought and edge metadata accepts scalar leaves and nested dictionaries, but not lists. Use ProvenanceContext.retrieval_context_ids for a bounded list of retrieved thought ids when its lineage meaning is accurate; do not use it as a generic bag of citations.

Time and reliability

Use valid_from and valid_until for the real-world interval during which a claim applies. This prevents a legitimate change over time from being mistaken for a simultaneous conflict. Open bounds are represented by None; Engrava validates interval ordering but does not calculate whether two claims are incompatible. See The Bi-temporal Model.

Keep these reliability signals distinct:

  • confidence is the caller's nullable 0.0-1.0 estimate for one thought;

  • confirmation_count counts successful deduplication hash hits when the caller opts into deduplication, or confirmations maintained by caller logic; Engrava does not establish that those hits are independent re-encounters, and, per the stale-hash caveat above, a hit's own content_hash can lag the row's current content; and

  • EdgeRecord.weight is the caller's strength for the relationship, not a probability that either endpoint is true.

None of these fields resolves a conflict automatically. A high-confidence thought can be contested by another high-confidence thought.

Direction and edge semantics

EdgeType values are persisted labels: they carry no automatic graph reasoning, symmetry, transitivity, or conflict propagation. Ranking is the exception, twice over. graph_expansion_enabled (default True) traverses CONSOLIDATED_FROM edges from top-ranked REFLECTIONs to pull in their source OBSERVATIONs with a propagated score, regardless of what any other edge type means. And once a search config sets graph_weight > 0, the 1-hop graph signal builds adjacency from every edge in the pool in both directions, type-agnostic — a CONTESTED_BY edge boosts a neighbour's score exactly like any other. Both of these are separate from ranking's absence of edge-type awareness above: specific edge types do drive specific non-ranking workflow behavior elsewhere — an outgoing DERIVED_FROM edge marks a thought as already derived, so derive_existing() skips it, and CONSOLIDATED_FROM edges are what the graph-expansion traversal above and orphan-reflection retirement both follow. Neither is general-purpose ontology reasoning; each is a specific subsystem interpreting a specific label.

For CONTESTED_BY, choose and document one direction. This guide uses:

existing claim --CONTESTED_BY--> challenging claim

The edge means only that the caller recorded the challenging claim as a contest to the existing claim. Engrava neither evaluates the relationship nor prefers the target. get_edges(..., direction="BOTH") can traverse the stored edge from either endpoint; store a reciprocal edge only when your own graph contract requires one.

The database permits only one edge for a given (from_thought_id, to_thought_id, edge_type) triple. A second CONTESTED_BY edge in the same direction between the same claims is therefore not a second conflict event; update the existing edge metadata or create a new claim node when your application needs a distinct tension. Deleting either claim cascades to this edge row. That cascade does not produce a separate DELETE_EDGE journal entry. When journaling is enabled and the endpoint is deleted through a journaled store path, the journal records its DELETE_THOUGHT mutation instead.

Below core schema 12 there is no such cascade. The ON DELETE CASCADE on edge, embedding and action arrives with the core-12 migration. delete_thought does not rely on it: it issues its own deletes for the thought's rows in those three tables, in the same savepoint as the parent delete, which runs first. See Deletion on a database that has not been migrated for what engrava migrate cleans up on a database that already holds dangling embedding rows.

Complete example

The following script uses an explicit single-value domain rule. It stores two source observations, two incompatible claims, a CONTESTED_BY edge, and a caller-created clarification task. No LLM is involved.

import asyncio
import sys
import uuid

import aiosqlite

from engrava import (
    EdgeRecord,
    EdgeType,
    KnowledgeSource,
    LifecycleStatus,
    Priority,
    ProvenanceContext,
    SqliteEngravaCore,
    ThoughtRecord,
    ThoughtType,
)


def new_id() -> str:
    return str(uuid.uuid4())


def incompatible_single_value_claims(
    left: ThoughtRecord,
    right: ThoughtRecord,
) -> bool:
    """Caller-owned rule: one entity/predicate cannot have two values."""
    left_entity = left.metadata.get("entity")
    right_entity = right.metadata.get("entity")
    left_claim = left.metadata.get("claim")
    right_claim = right.metadata.get("claim")

    if not all(
        isinstance(value, dict)
        for value in (left_entity, right_entity, left_claim, right_claim)
    ):
        return False

    return (
        left_entity.get("type") == right_entity.get("type")
        and left_entity.get("id") == right_entity.get("id")
        and left_claim.get("predicate") == right_claim.get("predicate")
        and left_claim.get("object") != right_claim.get("object")
    )


async def _close_quietly(connection: aiosqlite.Connection) -> None:
    """Close *connection*, reporting rather than raising if the close itself fails.

    ``aiosqlite.Connection.__aexit__`` is an unconditional ``await
    close()``, so a bare ``async with aiosqlite.connect(...)`` would let a
    close failure here replace whatever the block above actually raised.
    Used only from the exception path below -- the ordinary success-path
    close still propagates a genuine failure normally.
    """
    try:
        await connection.close()
    except Exception as exc:  # noqa: BLE001 - deliberately broad: never replace the real error
        print(f"warning: failed to close the database connection: {exc}", file=sys.stderr)


async def main() -> None:
    connection = await aiosqlite.connect(":memory:")
    try:
        connection.row_factory = aiosqlite.Row
        store = SqliteEngravaCore(connection, journal_enabled=True)
        await store.ensure_schema()

        crm_evidence = await store.create_thought(
            ThoughtRecord(
                thought_id=new_id(),
                thought_type=ThoughtType.OBSERVATION,
                essence="CRM lists billing country as Poland",
                content="CRM export row 831: billing_country=PL",
                priority=Priority.P2,
                lifecycle_status=LifecycleStatus.ACTIVE,
                created_cycle=41,
                updated_cycle=41,
                source="crm-import",
                source_type=KnowledgeSource.EXPERIENCE,
                confidence=0.95,
                metadata={
                    "record_kind": "evidence",
                    "entity": {"type": "customer", "id": "customer-42"},
                    "source_ref": {"system": "crm", "record": "831"},
                },
            )
        )

        invoice_evidence = await store.create_thought(
            ThoughtRecord(
                thought_id=new_id(),
                thought_type=ThoughtType.OBSERVATION,
                essence="Invoice lists billing country as Germany",
                content="Invoice 2026-104: billing_country=DE",
                priority=Priority.P2,
                lifecycle_status=LifecycleStatus.ACTIVE,
                created_cycle=42,
                updated_cycle=42,
                source="invoice-import",
                source_type=KnowledgeSource.EXPERIENCE,
                confidence=0.98,
                metadata={
                    "record_kind": "evidence",
                    "entity": {"type": "customer", "id": "customer-42"},
                    "source_ref": {"system": "billing", "record": "2026-104"},
                },
            )
        )

        claim_pl = await store.create_thought(
            ThoughtRecord(
                thought_id=new_id(),
                thought_type=ThoughtType.BELIEF,
                essence="Customer 42 billing country is Poland",
                content="The billing country for customer 42 is Poland.",
                priority=Priority.P2,
                lifecycle_status=LifecycleStatus.ACTIVE,
                created_cycle=41,
                updated_cycle=41,
                source="profile-reconciler",
                source_type=KnowledgeSource.EXPERIENCE,
                confidence=0.95,
                valid_from="2026-01-01T00:00:00+00:00",
                metadata={
                    "record_kind": "claim",
                    "entity": {"type": "customer", "id": "customer-42"},
                    "claim": {"predicate": "billing_country", "object": "PL"},
                },
                provenance=ProvenanceContext(
                    session_id="reconcile-2026-07-23",
                    actor_id="profile-reconciler",
                    instruction_context="Map the CRM billing country to the profile.",
                    retrieval_context_ids=[crm_evidence.thought_id],
                ),
            )
        )

        claim_de = await store.create_thought(
            ThoughtRecord(
                thought_id=new_id(),
                thought_type=ThoughtType.BELIEF,
                essence="Customer 42 billing country is Germany",
                content="The billing country for customer 42 is Germany.",
                priority=Priority.P2,
                lifecycle_status=LifecycleStatus.ACTIVE,
                created_cycle=42,
                updated_cycle=42,
                source="profile-reconciler",
                source_type=KnowledgeSource.EXPERIENCE,
                confidence=0.98,
                valid_from="2026-01-01T00:00:00+00:00",
                metadata={
                    "record_kind": "claim",
                    "entity": {"type": "customer", "id": "customer-42"},
                    "claim": {"predicate": "billing_country", "object": "DE"},
                },
                provenance=ProvenanceContext(
                    session_id="reconcile-2026-07-23",
                    actor_id="profile-reconciler",
                    instruction_context="Map the invoice billing country to the profile.",
                    retrieval_context_ids=[invoice_evidence.thought_id],
                ),
            )
        )

        if not incompatible_single_value_claims(claim_pl, claim_de):
            raise RuntimeError("The caller's domain rule found no conflict")

        conflict = await store.create_edge(
            EdgeRecord(
                edge_id=new_id(),
                from_thought_id=claim_pl.thought_id,
                to_thought_id=claim_de.thought_id,
                edge_type=EdgeType.CONTESTED_BY,
                weight=1.0,
                created_cycle=42,
                source=KnowledgeSource.EXPERIENCE,
                metadata={
                    "conflict": {
                        "detector": "single-value-slot",
                        "rule_version": "1",
                        "status": "open",
                    }
                },
            )
        )

        # Read the stored edge and the write-time lineage on both endpoints.
        for edge in await store.get_edges(claim_pl.thought_id, direction="OUT"):
            if edge.edge_type is not EdgeType.CONTESTED_BY:
                continue
            existing = await store.get_thought(edge.from_thought_id)
            challenger = await store.get_thought(edge.to_thought_id)
            if existing is None or challenger is None:
                continue
            print(existing.content)
            print(challenger.content)
            print(existing.provenance)
            print(challenger.provenance)

        # This task is proposed and worded by the caller. Engrava only stores it.
        clarification = await store.create_thought(
            ThoughtRecord(
                thought_id=new_id(),
                thought_type=ThoughtType.TASK,
                essence="Clarify customer 42 billing country",
                content=(
                    "Clarify whether customer 42's billing country is Poland or "
                    "Germany, and record the effective date of the confirmed value."
                ),
                priority=Priority.P1,
                lifecycle_status=LifecycleStatus.ACTIVE,
                created_cycle=43,
                updated_cycle=43,
                source="conflict-workflow",
                source_type=KnowledgeSource.EXPERIENCE,
                metadata={
                    "record_kind": "clarification_task",
                    "conflict": {"edge_id": conflict.edge_id, "status": "open"},
                },
                provenance=ProvenanceContext(
                    session_id="reconcile-2026-07-23",
                    actor_id="conflict-workflow",
                    instruction_context="Open a task for an unresolved single-value slot.",
                    retrieval_context_ids=[claim_pl.thought_id, claim_de.thought_id],
                ),
            )
        )
        print(clarification.thought_id)
    except BaseException:
        await _close_quietly(connection)
        raise
    else:
        await connection.close()


asyncio.run(main())

The two claims are deliberately inserted without semantic deduplication. The rule, edge direction, edge metadata, and task wording are application policy, not hidden engine behavior. In a production detector, also test whether the claims' valid-time intervals overlap before declaring a conflict.

Detection without and with an LLM

An LLM is not required when the caller already has comparable, typed values. Examples include:

  • one customer and one single-valued billing_country slot with two different normalized country codes;

  • overlapping employment intervals that violate a domain constraint;

  • incompatible version, status, or ownership values from structured systems; and

  • a source-specific precedence rule that always requires human confirmation when two authorities disagree.

These checks are ordinary deterministic application code. Record the detector name and version on the conflict edge so the decision can be reproduced.

An LLM can be useful for open-ended prose where contradiction depends on paraphrase, implication, negation, or missing context. That is an optional caller-side classifier, not an Engrava dependency. Treat its output as a proposal: retain both claims and their evidence, record the model/rule context, and let policy or a human resolve consequential cases. Embedding similarity alone indicates relatedness, not contradiction.

Three kinds of provenance

The word provenance can refer to different guarantees. Keep them separate:

  1. Write-time computational context. ThoughtRecord.provenance stores the caller-supplied session, actor, retrieval query, instruction context, and retrieved thought ids that shaped a write. It is an untrusted query hint, not authentication, authorization, or a truth signal. See API Reference: provenance capture.

  2. Semantic evidence provenance. Evidence thoughts, source references in metadata, and caller-defined lineage edges explain why a domain claim was made. Their meaning is established by the application's schema and trust policy; Engrava does not verify the external source.

  3. Mutation provenance. With journaling enabled, the hash-chain journal records explicit thought and edge inserts, updates, and deletes as before/after deltas — not every database mutation: buffered access telemetry (access_count / last_accessed_at) is intentionally unjournaled, and a cascaded edge delete (see above) does not get its own DELETE_EDGE entry. See Audit Trail for the exact coverage. It can show that a conflict edge was added and detect inconsistent retained journal rows within its documented threat model. It does not reconcile live claim/edge rows against the journal, prove that either claim is true, authenticate an external document, or replace semantic evidence. See Audit Trail.

The journal is tamper-evident, not tamper-proof: it is a keyless chain stored in the same database. A ProvenanceContext included in a thought is itself journaled as part of that thought when journaling is enabled, but the chain only protects the recorded mutation history; it does not promote caller-supplied provenance into verified identity or evidence.

Operational recommendations

  • Define stable entity ids, claim predicates, normalization rules, and edge direction before ingesting production data.

  • Preserve conflicting claims until a deliberate policy closes, invalidates, archives, or supersedes one of them.

  • Use valid time to distinguish simultaneous incompatibility from legitimate historical change.

  • Record detector/rule versions and resolution state on edge metadata.

  • Keep conflict detection separate from ranking. Retrieve all relevant claims for the entity/slot before applying resolution policy.

  • Treat metadata and provenance filters as query refinements, not access-control boundaries. See Known Limitations.

For exact record fields and method signatures, see the API Reference.

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