semantica.context is the memory and decision layer for AI agents:
  • Stores facts with provenance and embedding-backed retrieval
  • Records decisions as first-class graph objects with full causal chains
  • Lets agents search their own history to stay consistent across runs
  • Answers complex queries via multi-hop GraphRAG traversal
  • Enforces versioned policies and tracks compliance exceptions

Exported Classes

What You Get

  • AgentContext: memory, decision tracking, and graph-backed retrieval behind one API
    • Conversation history and checkpoint diffing
    • Persist and restore full context state to disk
  • ContextGraph: thread-safe in-memory knowledge graph
    • PageRank, centrality, community detection, temporal validity
    • Cross-graph navigation and link traversal
  • AgentMemory: embedding-backed memory with retention policy
    • LRU eviction at configurable max_memory_size
    • Per-conversation history isolation
  • DecisionRecorder: records decisions with causal chains and confidence scores
    • Temporal validity windows (valid_from / valid_until)
    • Cross-system context capture on every decision
  • PolicyEngine: versioned policy storage in the knowledge graph
    • Compliance checking against recorded decisions
    • Policy exception tracking with approver audit trail
  • EntityLinker: maps entity text to stable URIs
    • Creates typed links between entity IDs
    • Prevents “Apple”, “Apple Inc.”, “AAPL” becoming separate nodes
  • ContextRetriever: fuses vector similarity, graph traversal, and agent memory
    • Richer context than pure vector search
    • Configurable hybrid_alpha and expansion hops
  • CausalChainAnalyzer: traces upstream causes and downstream effects of any decision
    • Explainability paths with relationship types
    • Configurable depth and direction

Quick Start

1

Initialize the agent context

2

Store facts and retrieve by semantic similarity

3

Record decisions with full provenance

4

Find precedents and trace causal chains

Usage Patterns

Fastest setup: no knowledge graph. Best for agents that need semantic search over facts without graph traversal overhead.
Swap backend="faiss" to backend="inmemory" for zero-dependency local development.

AgentContext

AgentContext is the main entry point. Wraps memory, graph, and decision tracking behind a single unified API.

Constructor Parameters

Set retention_days to avoid memory bloat. The default of 30 prunes automatically. Compliance-critical agents may need retention_days=None with explicit archival via export().
Persist your context between runs. VectorStore does not auto-persist; passing index_path= to its constructor is a no-op. Call context.save("agent_state/") to write memory, the vector index, and the graph to disk, and context.load("agent_state/") on the next process to restore them. See the “Persist & Restore” tab under Real-World Patterns below.

Memory Methods

retrieve() uses max_results=, not top_k=. The parameter is max_results (default 5). Pass use_graph=True to force GraphRAG or use_graph=False to force vector-only retrieval regardless of whether a knowledge_graph is configured.

Conversation Methods

Multi-Hop GraphRAG

Requires knowledge_graph to be set at construction: enables query_with_reasoning() for LLM-grounded multi-hop traversal:

Decision Methods

decision_tracking=True requires knowledge_graph to also be set. Without it, record_decision() raises RuntimeError.
Use find_precedents() before every significant decision. This is how the context module prevents agents from making contradictory choices across runs. Surface precedents to the LLM as context: “we chose X for similar reasons before.”

Checkpoint Methods

Ideal for auditing reasoning loops: take a snapshot before and after a pass to see exactly what changed:

ContextGraph

ContextGraph is the knowledge graph backing AgentContext. Can also be used standalone for relationship modelling without the full context layer.

Constructor Options

ContextGraph: Full Method Reference

Distance Intelligence (v0.5.0)

ContextGraph exposes a full Distance Intelligence API for exploring semantic neighborhoods and blending proximity into retrieval.
Full Distance Intelligence reference (distance matrices, API endpoints, embedding cache, Explorer UI) is covered in the dedicated Distance Intelligence page. This section documents the context-layer API.

Neighbors with Distance Metadata

Pass include_distance_metadata=True to get_neighbors() to receive distance band, confidence decay, and path information alongside every neighbor:

Proximity-Blended Retrieval

Set proximity_weight on AgentContext to blend graph proximity into every retrieve() and find_precedents() call:
proximity_weight=0.0 disables proximity blending entirely (pure semantic). proximity_weight=1.0 returns results ranked purely by graph proximity to the query anchor. Values between 0.2–0.4 work well for most production use cases.

Cross-Graph Navigation

Link multiple independent ContextGraph instances so agents can traverse across problem spaces:

AgentMemory

For fine-grained control over memory storage and retrieval:

Markdown Round Trips

AgentMemory can export human-editable Markdown and import the edited files back. Each file contains one memory item, with required metadata in YAML frontmatter and the memory content in the Markdown body:
The required frontmatter fields are id, created_at, updated_at, and either type or kind. Optional metadata can be edited at the top level. Imports reject malformed or duplicate fields before changing memory, and re-importing unchanged files is idempotent. Memory-local entities and relationships are preserved as provenance but are not applied to ContextGraph by Markdown import. Use a dedicated export directory: matching files are overwritten, but unrelated or stale Markdown files are not deleted automatically. Export refuses to overwrite filesystem links and uses atomic file replacement; import also refuses symlinks, Windows directory junctions, and other Windows reparse points. Timestamp offsets are preserved in Markdown and normalized to UTC only for comparisons, so aware and local-naive records can be queried together safely. Vector-store writes are deferred until the in-memory import commits; adapter synchronization remains best-effort and logs failures.

ErasureCoordinator

ContextGraph.purge_node() is scoped to one graph: the node is removed and a tombstone is written, but the same content can still be live as an AgentMemory item and as an embedding in the vector store. ErasureCoordinator drives the cascade across every bound store and returns an ErasureReceipt recording what each one reported.
Check the receipt. The call returning is not proof the data is gone. FAISS, Milvus, and Weaviate expose no delete method, so erasure cannot be completed on those backends today; the receipt reports unsupported rather than a success it did not achieve.

Constructor Parameters

At least one store is required; a store that is not supplied reports not_configured rather than being silently skipped.

Methods

Store Statuses

ErasureReceipt

Erasure runs outward-in: vectors, then memory, then the graph. The tombstone is the durable attestation that an erasure happened, so it is written last: a crash mid-cascade leaves the node present and the receipt incomplete, rather than a tombstone claiming more than actually happened. A store that raises is recorded as failed and the remaining stores are still erased. Erasing the same entity twice returns a receipt saying there was nothing left to do rather than raising.

PolicyEngine

PolicyEngine manages versioned policies stored in the knowledge graph. Policies are stored as nodes and can be linked to decisions:

EntityLinker

Maps entity text to URIs and creates typed links between entity IDs:
EntityLinker.link_entities() links two entity IDs, not a list. Call link_entities(entity1_id, entity2_id, link_type) to create a typed edge between two known IDs. For linking entities extracted from text, use link(text, entities=[...]) instead.
LinkedEntity fields returned by link():

ContextRetriever

Hybrid retrieval combining vector similarity, graph traversal, and memory:

Support-Aware Retrieval (truth_filter)

Cached vector or memory content can outlive the evidence that originally supported it. ContextRetriever.retrieve(..., truth_filter=...) accepts an opt-in TruthMaintenanceContextFilter that removes candidates whose declared dependencies are no longer supported, before ranking, while the stored records themselves are never modified. The example below runs standalone with no model, database, or network — only semantica itself:

Manual annotation semantics

The filter only validates what the application explicitly wrote into store metadata. It never infers dependencies, and it never annotates records on your behalf:
  • Each candidate must carry metadata["truth_maintenance"] with exactly four keys: schema_version (currently 1), session_id (must equal the filter’s session_id), required_facts, and required_support_ids. At least one fact or support ID must be declared.
  • A candidate is kept only if every entry of required_facts is in the snapshot’s facts and every entry of required_support_ids is in the snapshot’s active supports. Unannotated candidates and candidates with malformed annotations are removed whole — a record ID or node ID is never a trust signal.

Source-specific citations

Two records may assert the same conclusion but cite different sources. required_support_ids binds each record to the evidence it actually used, so withdrawing one support invalidates only the records citing it, while records backed by an alternative derivation or an explicit support are kept.

Graph bundles

For candidates retrieved from a ContextGraph, the root record and every member of related_entities / related_relationships must carry the same annotation shape on their own metadata. If the root or any attachment is unsupported, the entire candidate is excluded — a result never keeps its prose while silently dropping a stale attachment.

Behavior details

  • Filtering happens before ranking and before the legacy merge: a high-scoring stale record cannot crowd out valid lower-scoring records, and dependency metadata survives merging.
  • Survivors are returned as deep copies stamped with metadata["truth_maintenance_validation"] (session_id, version). Original candidates and stored records are never modified.
  • Each call validates against one immutable snapshot; if the session commits a new version while retrieval is in flight, retrieve raises ProcessingError instead of returning mixed-version results.
  • Vector, memory, and graph sources are filtered in the same pass: construct the retriever with memory_store= or knowledge_graph= and pass truth_filter= to retrieve, or to the search, vector_search, and graph_search delegates (they forward to retrieve). memory_search bypasses retrieve and does not apply the filter — use retrieve when memory results must be grounded.

Unsupported entry points

The filter is supported only by ContextRetriever.retrieve(mode="local", ...) (the default mode) and delegates that use that path. Passing truth_filter to retrieve with mode="global", "drift", or "hybrid" raises ValidationError before retrieval starts. Those modes and direct retrieve_global / retrieve_drift calls are outside the dependency-validation guarantee. truth_filter is intentionally not accepted on AgentContext.retrieve, AgentContext.query_with_reasoning, or ContextRetriever.query_with_reasoning — passing it there raises ValidationError immediately. Assemble the verified context yourself with ContextRetriever.retrieve(..., truth_filter=...) and feed it to the model. See Truth Maintenance for the session model behind the filter.

Data Structures

Real-World Patterns