Home/Docs/Core Services/ContextBrain

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πŸ”—

LayerCurrent locationResponsibility
server and interceptorsservice/server.py, service/interceptors.pygRPC lifecycle, token verification, request context
application serviceservice/brain_service.pyRPC dispatch and shared dependencies
handlersservice/handlers/cells, document lifecycle, cell edges, engrams, conversation history, synapses, traces, UDB, blackboard, embeddings, admin
storesstorage/postgres/, storage/sqlite/production PostgreSQL (with RLS) and local SQLite parity stores
transient analyticsstorage/duckdb_store.pybounded DuckDB matching and analytical paths
embedding providersservice/embeddings/deterministic, ONNX, HTTP, and sentence-transformers adapters
reward mathreward_constants.pynamed Q-value deltas, apply_delta, clamp_q, and bit-identical q_composite
configurationcore/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.

Important
  • INV-BRAIN-AUTHENTICATED-BOUNDARY: BrainService owns its persistence stores (PostgresBrainStore and SqliteBrainStore) 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 to services/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/*"]
SymbolRoleInputs / Outputs
BrainServiceUnified Brain gRPC servicerAuthenticated ContextUnit / proto RPCs -> tenant-scoped persistence & retrieval responses
PostgresBrainStoreProduction PostgreSQL + pgvector storeTenant-scoped queries under RLS -> durable rows, vector search, graph & engram records
SqliteBrainStoreLocal SQLite parity storeLocal db_path + vector_dim (768 default) -> local Brain persistence
BrainConfigTyped C0 Brain configurationYAML + 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):

ModuleCanonical tableResponsibilityBoundary
BlackboardblackboardTTL-managed PassByRef pointer store (WriteBlackboard, ReadBlackboard, PruneExpiredBlackboard)Never schedules agents, merges hypotheses, or stores durable knowledge
BrainCellcellsAtomic facts, user/project knowledge, and _doc documentation chunks (SearchCells, UpsertCell, QueryCells, GetCell)Source-managed cells mutate only via canonical document revisions (IngestDocument, DeleteDocument)
BrainSynapsesynapsesExperience 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
CellEdgescell_edgesTyped, revision-bound semantic relationships between BrainCell endpoints (CreateCellEdges, ReviseCellEdges, TraverseCellGraph)Enforces endpoint currentness and scope visibility
BrainEngramengramsCurated 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πŸ”—

TenantPurposeAccess policy
_systemInternal platform health and operational stateInternal service views only; never blanket-visible
_docDocumentation-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
_testGolden evaluation fixtures and depersonalized test dataExcluded from production retrieval, consolidation, Q-aging, and distillation unless explicitly authorized
_auditTarget system scope for Shield-signed derived audit findings keyed by subject_tenant_idStores derived metadata/findings only; raw tenant evidence stays in its owning tenant store
Important

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:

  1. Tenant and scope_path boundary: token-derived tenant plus AuthorizedSearchScope (tenant, exact, or bounded descendants) narrows the candidate space first.
  2. Exact, structured, and lexical seeding: structured predicates (governance_state, q_composite, source_type, metadata) and lexical tsvector / BM25 ranking select bounded initial BrainCell seeds.
  3. Knowledge graph expansion (TraverseCellGraph): bounded multi-hop cell_edges traversal discovers semantically related BrainCells and edges from those seeds.
  4. Reverse BrainEngram resolution: Brain's batched reverse lookup resolves active BrainEngrams whose closed source refs contain the discovered evidence, preferring verified Engram View / EngramIndex or canonical Markdown under the Router's context budget.
  5. Single-pass vector fallback: only when structured/lexical seeding is insufficient, bounded pgvector / sqlite-vec similarity produces fallback BrainCell seeds that pass once through the same scope check, CellEdges expansion, and reverse BrainEngram lookup 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 UpsertCell cannot overwrite manifest-owned document cells.
  • Logical deletion (DeleteDocument) atomically removes a source from current reads while retaining a durable tombstone so stale snapshots, caches, or ContextSeed imports 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. Planned B-201 governance enforces eight durable-promotion gates (tenant, source, novelty, relevance, contradiction, evidence, redaction, review), derived Engram View states (generated | verified | stale | regenerate_required | blocked), and _doc documentation lifecycle states (draft | review | published | deprecated | blocked with independent private | tenant | public ACLs). 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_delta computes clamp_q(q_old + delta * LEARNING_RATE).
  • Composite score: q_composite computes q_action * 0.5 + q_hypothesis * 0.3 + q_relevance * 0.2 in unrounded IEEE 754 float64 so PostgreSQL GENERATED ALWAYS AS columns and SqliteBrainStore produce bit-identical scores, weighted at query time by LIFECYCLE_WEIGHTS.
  • Fault isolation: REWARD_NODE_SUCCESS (+0.05) and PENALTY_AGENT_FAULT (-0.30) adjust local execution quality, whereas infra_fault, upstream_fault, policy_fault, and reference_fault never penalize agent Q-values.
  • Session & planner attribution: REWARD_SESSION_CONTINUED (+0.03) and PENALTY_SESSION_ABANDONED (-0.05) decay across hops via DISCOUNT_FACTOR (0.7 ** distance_from_terminal); planner paths apply REWARD_PATH_SUCCESS (+0.05) and PENALTY_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) pass review_id to UpdateSynapseQ and apply idempotent override (SET) semantics tracked in metadata.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) behind synapses.outcome_resolver_enabled; Brain resolves FinalVerdict.attribution_candidates via role-scoped reward deltas in the transactional outcome_synapse_effects ledger without callers supplying Synapse IDs or Q values (REWARD_OUTCOME_POSITIVE / PENALTY_OUTCOME_NEGATIVE remain available in reward_policy.apply_pipeline_outcome_reward for terminal-only trajectory policies).

Flat Memory threat model (FM-1..FM-8)πŸ”—

ThreatVectorArchitectural mitigation
FM-1 External network callerUnauthenticated gRPC accessMandatory ContextToken verification at gRPC interceptor boundary
FM-2 Compromised graph nodePrompt-injected node attempting lateral readsPer-node capability stripping in Router + PostgreSQL RLS + AuthorizedSearchScope
FM-3 Database operator boundaryDirect SQL access on PostgreSQLLeast-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 synthesisAdversarial inputs promoted into durable factsSource-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 manipulationWriting synapses or observations for another tenantToken tenant enforcement + RLS on synapses + admin-authenticated ReportOutcomeObservation
FM-6 Distillation poisoningHigh-Q injected experience entering future adaptersConservative promotion gates, human review override, _test exclusion, and golden-holdout evaluation
FM-7 Blackboard scope escapeWriting/listing Blackboard outside allowed scope_pathToken tenant + scope_path validation on WriteBlackboard and ReadBlackboard
FM-8 Operator credential compromiseStolen Forge/admin session reading memory viewsShort-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/tests

SDK clients live under packages/core/src/contextunity/core/sdk/clients/brain/.