ContextBrain architectureπ
ContextBrain is the tenant-scoped persistence, graph-first retrieval, execution-evidence, and memory service. Its public boundary is the Brain gRPC contract in packages/core/protos/brain.proto; service code lives under services/brain/src/contextunity/brain/.
Runtime layersπ
| Layer | Current location | Responsibility |
|---|---|---|
| server and interceptors | service/server.py, service/interceptors.py | gRPC lifecycle, token verification, request context |
| application service | service/brain_service.py | RPC dispatch and shared dependencies |
| handlers | service/handlers/ | cells, document lifecycle, cell edges, engrams, conversation history, synapses, traces, UDB, blackboard, embeddings, admin |
| stores | storage/postgres/, storage/sqlite/ | production PostgreSQL (with RLS) and local SQLite parity stores |
| transient analytics | storage/duckdb_store.py | bounded DuckDB matching and analytical paths |
| embedding providers | service/embeddings/ | deterministic, ONNX, HTTP, and sentence-transformers adapters |
| reward math | reward_constants.py | named Q-value deltas, apply_delta, clamp_q, and bit-identical q_composite |
| configuration | core/config/ | pure parse/validation followed by runtime endpoint resolution |
Production startup requires POSTGRES_DSN. Local CLI startup uses create_local_brain with SqliteBrainStore and the configured CU_BRAIN_SQLITE_PATH (default ~/.contextunity/brain_local.sqlite3). Clients never open that SQLite file directly; the Brain process owns storage and exposes authenticated gRPC.
- INV-BRAIN-AUTHENTICATED-BOUNDARY:
BrainServiceowns its persistence stores (PostgresBrainStoreandSqliteBrainStore) and durable record lifecycle; clients access Brain data exclusively through the authenticated gRPC service boundary. - INV-BRAIN-STORAGE-OWNER: PostgreSQL driver usage (
psycopg,psycopg_pool) inside ContextBrain is confined toservices/brain/src/contextunity/brain/storage/**. - INV-BRAIN-HANDLERS-NO-RAW-DB: Brain gRPC handlers (
services/brain/src/contextunity/brain/service/handlers/**) never import raw database drivers (psycopg,psycopg_pool,sqlite3,asyncpg) directly; all persistence passes through storage abstractions.
Key symbols and inputs/outputsπ
flowchart LR
Clients["gRPC Clients (Router / Worker / Forge / SDK)"] --> Interceptor["BrainPermissionInterceptor"]
Interceptor --> Service["BrainService"]
Service --> Handlers["service/handlers/*"]
Handlers --> PG["PostgresBrainStore (pgvector + RLS)"]
Handlers --> SQLite["SqliteBrainStore (Local PATH L)"]
Handlers --> Embed["service/embeddings/*"]| Symbol | Role | Inputs / Outputs |
|---|---|---|
BrainService | Unified Brain gRPC servicer | Authenticated ContextUnit / proto RPCs -> tenant-scoped persistence & retrieval responses |
PostgresBrainStore | Production PostgreSQL + pgvector store | Tenant-scoped queries under RLS -> durable rows, vector search, graph & engram records |
SqliteBrainStore | Local SQLite parity store | Local db_path + vector_dim (768 default) -> local Brain persistence |
BrainConfig | Typed C0 Brain configuration | YAML + env mappings -> validated BrainConfig (checks postgres.vector_dim == embeddings.dimension) |
Five memory modules and system tenantsπ
ContextBrain organizes cognitive state across five distinct modules rather than a generic CRUD table or event bus (see ADR-0004 and ADR-0007):
| Module | Canonical table | Responsibility | Boundary |
|---|---|---|---|
| Blackboard | blackboard | TTL-managed PassByRef pointer store (WriteBlackboard, ReadBlackboard, PruneExpiredBlackboard) | Never schedules agents, merges hypotheses, or stores durable knowledge |
| BrainCell | cells | Atomic facts, user/project knowledge, and _doc documentation chunks (SearchCells, UpsertCell, QueryCells, GetCell) | Source-managed cells mutate only via canonical document revisions (IngestDocument, DeleteDocument) |
| BrainSynapse | synapses | Experience records with 3D Q-values (q_action, q_hypothesis, q_relevance), derived q_composite, and fault attribution (RecordSynapse, QuerySynapses, UpdateSynapseQ, ReportOutcomeObservation) | Distinct from semantic cell_edges; infra/upstream faults never penalize agent Q-values |
| CellEdges | cell_edges | Typed, revision-bound semantic relationships between BrainCell endpoints (CreateCellEdges, ReviseCellEdges, TraverseCellGraph) | Enforces endpoint currentness and scope visibility |
| BrainEngram | engrams | Curated canonical Markdown knowledge plus derived Engram View / EngramIndex projections (ProposeEngram, CurateEngram, GetEngram, QueryEngrams, GetEngramView) | Canonical Markdown is sole durable truth; Engram View is disposable and regeneratable |
Separate non-memory evidence stores coexist in Brain without being conflated with episodic or semantic memory (see ADR-0014):
- Conversation History (
conversation_records):AppendConversationRecord,QueryConversationHistory,GetConversationHistoryStats,ApplyConversationRetention. - Execution Trace (
execution_traces) and protected trace artifacts:LogTrace,GetTraces,ReserveExecutionTraceArtifact,FinalizeExecutionTraceArtifact,GetExecutionTraceArtifact,ArchiveExecutionTraceArtifact,RestoreExecutionTraceArtifact,PurgeExecutionTraceArtifact. - UniversalDebugBus (UDB): negative-experience and recovery tracking via
ReportFaultOccurrence,ReportMitigationAttempt,ReportRecoveryEvidence,ResolveDebugCase,ReopenDebugCase,GetDebugCase,QueryDebugCases,QueryRecurringFaults.
System tenantsπ
| Tenant | Purpose | Access policy |
|---|---|---|
_system | Internal platform health and operational state | Internal service views only; never blanket-visible |
_doc | Documentation-as-memory (BrainCell chunks for docs, ADRs, configs, plans) | Requires docs:read / docs:write scopes and documentation record kinds; metadata visibility/lifecycle never widens token ACL |
_test | Golden evaluation fixtures and depersonalized test data | Excluded from production retrieval, consolidation, Q-aging, and distillation unless explicitly authorized |
_audit | Target system scope for Shield-signed derived audit findings keyed by subject_tenant_id | Stores derived metadata/findings only; raw tenant evidence stays in its owning tenant store |
Invariant: System tenants (_doc, _test, _audit, _system) never use blanket USING (true) RLS policies; empty allowed_tenants grants zero tenant access unless explicit admin:all authority is verified.
Graph-First, Vector-Fallback retrieval cascadeπ
Router's Graph-First memory read path follows ADR-0011 behind the Router C0 gate graph_first_retrieval.enabled (default false), using bounded Brain RPCs (SearchCells, TraverseCellGraph, ResolveEngramsByEvidenceRefs, GetEngramView, GetEngram) and treating vector similarity strictly as a fallback within that path:
- Tenant and
scope_pathboundary: token-derived tenant plusAuthorizedSearchScope(tenant,exact, or boundeddescendants) narrows the candidate space first. - Exact, structured, and lexical seeding: structured predicates (
governance_state,q_composite,source_type, metadata) and lexicaltsvector/ BM25 ranking select bounded initialBrainCellseeds. - Knowledge graph expansion (
TraverseCellGraph): bounded multi-hopcell_edgestraversal discovers semantically relatedBrainCellsand edges from those seeds. - Reverse
BrainEngramresolution: Brain's batched reverse lookup resolves activeBrainEngramswhose closed source refs contain the discovered evidence, preferring verifiedEngram View/EngramIndexor canonical Markdown under the Router's context budget. - Single-pass vector fallback: only when structured/lexical seeding is insufficient, bounded
pgvector/sqlite-vecsimilarity produces fallbackBrainCellseeds that pass once through the same scope check,CellEdgesexpansion, and reverseBrainEngramlookup before raw vector hits fill any remaining budget (never triggering a recursive vector pass).
Source authority, dual lifecycle axes, and anti-resurrectionπ
Brain is the sole owner of document source identity, immutable accepted revisions, current chunk manifests, and deletion tombstones (IngestDocument, DeleteDocument):
- Producers submit complete normalized source revisions; generic
UpsertCellcannot overwrite manifest-owned document cells. - Logical deletion (
DeleteDocument) atomically removes a source from current reads while retaining a durable tombstone so stale snapshots, caches, orContextSeedimports cannot silently resurrect deleted sources. - Compiled memory eligibility resolves over two orthogonal axes:
materialization_state:draft | active | superseded | archived | rejected;governance_state:provisional | review_required | durable | deprecated | blocked. PlannedB-201governance enforces eight durable-promotion gates (tenant,source,novelty,relevance,contradiction,evidence,redaction,review), derivedEngram Viewstates (generated | verified | stale | regenerate_required | blocked), and_docdocumentation lifecycle states (draft | review | published | deprecated | blockedwith independentprivate | tenant | publicACLs). Missing, tombstoned, or scope-withdrawn upstream sources render dependent Engram reads unavailable or force verified fallback.
Engram source grants and consolidationπ
Brain owns source grants, the active publisher for each Tenant audience, canonical engrams, and operation receipts (SetTenantEngramAuthority, GrantEngramSource, RevokeEngramSourceGrant, SelectEngramSources, CheckEngramSourceEligibility, RecordEngramOperationAttempt, FinalizeEngramConsolidation, GetEngramOperationReceipt). Grant changes use compare-and-swap revisions and pin current source revisions; replaced or revoked sources cannot enter a new selection.
Canonical Project and Tenant engrams have explicit typed owners. Existing User engram reads retain their exact user scope and cannot return service-owned records. Router orchestrates scheduled selection and model drafting; Brain validates evidence and remains the sole persistence owner.
Engram View readsπ
Brain provides four unary Engram View RPCs: GetEngramView, FocusEngramView, ExpandEngramView, and GetEngramViewCells. Every call carries the exact parent pins engram_id, expected_revision, expected_source_hash, and expected_content_hash, plus a token-authorized narrowing SearchScope.
Brain reauthorizes the canonical parent and validates every pin before reading the derived projection. Absent or stale projections reject as unavailable rather than returning degraded data. Router performs a separately authorized canonical GetEngram read before using Markdown as a fallback.
BrainSynapse Q-value math and outcome attributionπ
All Q-value reward deltas live in services/brain/src/contextunity/brain/reward_constants.py (initial Q = 0.5, range [0.0, 1.0], LEARNING_RATE = 0.1):
- Update formula:
apply_deltacomputesclamp_q(q_old + delta * LEARNING_RATE). - Composite score:
q_compositecomputesq_action * 0.5 + q_hypothesis * 0.3 + q_relevance * 0.2in unrounded IEEE 754 float64 so PostgreSQLGENERATED ALWAYS AScolumns andSqliteBrainStoreproduce bit-identical scores, weighted at query time byLIFECYCLE_WEIGHTS. - Fault isolation:
REWARD_NODE_SUCCESS(+0.05) andPENALTY_AGENT_FAULT(-0.30) adjust local execution quality, whereasinfra_fault,upstream_fault,policy_fault, andreference_faultnever penalize agent Q-values. - Session & planner attribution:
REWARD_SESSION_CONTINUED(+0.03) andPENALTY_SESSION_ABANDONED(-0.05) decay across hops viaDISCOUNT_FACTOR(0.7 ** distance_from_terminal); planner paths applyREWARD_PATH_SUCCESS(+0.05) andPENALTY_PATH_FAILURE(-0.15). - Single-Synapse operator override (
UpdateSynapseQ): explicit per-Synapse operator verdicts (REVIEW_VERIFIED_SET_Q = 0.9,REVIEW_REJECTED_SET_Q = 0.1) passreview_idtoUpdateSynapseQand apply idempotent override (SET) semantics tracked inmetadata.processed_reward_events. - Delayed trace outcome attribution (
ReportOutcomeObservation): external domain and review observations (verified_success | verified_failure | neutral, e.g.operator_review/v1) submit(trace_id, graph_run_id, verdict_digest, idempotency_key)behindsynapses.outcome_resolver_enabled; Brain resolvesFinalVerdict.attribution_candidatesvia role-scoped reward deltas in the transactionaloutcome_synapse_effectsledger without callers supplying Synapse IDs or Q values (REWARD_OUTCOME_POSITIVE/PENALTY_OUTCOME_NEGATIVEremain available inreward_policy.apply_pipeline_outcome_rewardfor terminal-only trajectory policies).
Flat Memory threat model (FM-1..FM-8)π
| Threat | Vector | Architectural mitigation |
|---|---|---|
| FM-1 External network caller | Unauthenticated gRPC access | Mandatory ContextToken verification at gRPC interceptor boundary |
| FM-2 Compromised graph node | Prompt-injected node attempting lateral reads | Per-node capability stripping in Router + PostgreSQL RLS + AuthorizedSearchScope |
| FM-3 Database operator boundary | Direct SQL access on PostgreSQL | Least-privilege app DB role (NO BYPASSRLS), infrastructure encryption at rest, and ADR-0015 ciphertext-only external backups (no blanket field encryption on searchable Flat Memory rows) |
| FM-4 Poisoned memory synthesis | Adversarial inputs promoted into durable facts | Source-type confidence caps (< 1.0 for auto-extracted/imported items), Curator validation, planned Memory Linter + WorkerAuditor checks, and Forge human review |
| FM-5 Cross-tenant Q manipulation | Writing synapses or observations for another tenant | Token tenant enforcement + RLS on synapses + admin-authenticated ReportOutcomeObservation |
| FM-6 Distillation poisoning | High-Q injected experience entering future adapters | Conservative promotion gates, human review override, _test exclusion, and golden-holdout evaluation |
| FM-7 Blackboard scope escape | Writing/listing Blackboard outside allowed scope_path | Token tenant + scope_path validation on WriteBlackboard and ReadBlackboard |
| FM-8 Operator credential compromise | Stolen Forge/admin session reading memory views | Short-lived project/tenant-scoped Shield sessions, audited admin actions, and zero raw secret/key exposure in Brain |
Memory-read bulkhead and scope-path retrievalπ
read_bulkhead is enabled by default across SearchCells, QueryCells, QueryConversationHistory, and QuerySynapses, enforcing round-robin tenant queues, global/per-tenant concurrency and queue limits, and a unified deadline (RESOURCE_EXHAUSTED on saturation, DEADLINE_EXCEEDED on timeout). Configure via CU_BRAIN_READ_BULKHEAD_*.
SearchCells validates SearchCellsRequest and token tenant into AuthorizedSearchScope (tenant, exact, or bounded descendants, max_descendant_depth = 8) before gate, bulkhead, embedder, or store execution. QueryCells (BrainClient.query_cells / query_all_cells) accepts an optional typed CellSourceSubject selector to filter stored cells to an exact (tenant_id, user_id) owner before pagination in both SQLite and PostgreSQL. search_cells.enabled (SearchCellsConfig.enabled) defaults to true, whereas synapses.enabled, udb.enabled, cell_edges.enabled, engrams.enabled, and engram_view.enabled default to false.
Storage, migrations, and configurationπ
PostgresBrainStore applies transaction-scoped tenant context and RLS; SqliteBrainStore enforces equivalent predicates in local mode. Vector dimension is fixed at 768 (PGVECTOR_DIM) and must match the configured embedding provider (core/config/providers.py). 0001_brain_v1_canonical is the canonical schema baseline and fails closed on mismatched historical catalogs.
BrainConfig parses without network/mesh I/O; endpoints resolve once at startup. engram_view.enabled / BRAIN_ENGRAM_VIEW_ENABLED defaults to false and rejects conflicting YAML vs env values at startup.
Developmentπ
contextbrain serve
cd packages/core && ./compile_protos.sh
uv run pytest services/brain/testsSDK clients live under packages/core/src/contextunity/core/sdk/clients/brain/.