Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hot-memory): invalidate on writes and forgets on every transport (eval wave N5-1)
garrytan3b1d238c3eef
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 4c541e33f9..db8701f350 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -66,5 +66,5 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.-- `src/core/persistence/manual-links.ts` — `coordinatedManualLinkWrite` makes `add_link` / `remove_link` coordinated database-only writes on a managed brain: it checks the caller's durable write authority for the `from` page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits the edge inside `withCoordinatedWrite` holding both endpoint page keys. Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`.+- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 72aacbea87..4f9ee33dd8 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps (warn-once preserved when cap is unset); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math (`reservationCostUsd`, overrides, free local providers, unknown-price `null`) lives in the pure `src/core/budget/reservation-cost.ts`, shared with skillopt preflight's impossible-reservation check so the two cannot disagree. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases.-- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.+- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v189 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 2aca865a69..e7e664a0a8 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`.- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 0ea5851b84..58c8185db6 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -429,6 +429,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// ontology observations) and the per-stint ontology dedup key."src/core/persistence/database-write.ts": ["test/e2e/managed-ontology-propose-postgres.test.ts", "test/e2e/managed-writers-w3.test.ts"],"src/core/schema-migrations/v189-facts-ontology-stint-dedup.ts": ["test/e2e/ontology-merge-parity.test.ts", "test/e2e/schema-drift.test.ts"],+ "src/core/facts/meta-hook.ts": ["test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/facts-context-injection-postgres.test.ts", "test/e2e/serve-http-meta.test.ts"],+ "src/mcp/dispatch.ts": ["test/e2e/hot-memory-invalidation-postgres.test.ts"],// Schema source of truth: any change must pass the cross-engine drift gate."src/schema.sql": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.tsindex e271d1b347..bb7fdc3c46 100644--- a/src/core/facts/meta-hook.ts+++ b/src/core/facts/meta-hook.ts@@ -7,7 +7,11 @@* to no-_meta rather than failing the tool call.* - Cache key is (source_id, session_id, hash(takesHoldersAllowList sorted)).* Visibility-aware: cache entries don't bleed across token tiers.- * - 30s TTL per session. Refreshed on extraction event via `bumpCache`.+ * - 30s TTL per session. A successful mutating tool call on the engine+ * drops that engine's entries (`invalidateHotMemoryForEngine`, called by+ * dispatch on every MCP transport), and every hit revalidates the+ * source's withdrawal-ledger watermark, so a forget committed by any+ * process is never served from the cache.* - Cap at top-K facts per response so the injection stays lean.** Both stdio and HTTP MCP transports pass this hook into dispatchToolCall@@ -34,9 +38,34 @@ export const HOT_MEMORY_CACHE_MAX_ENTRIES = 1000;interface CacheEntry {expiresAt: number;payload: Record<string, unknown> | undefined;+ withdrawals?: string;}const _cache = new Map<string, CacheEntry>();+const _generations = new WeakMap<object, number>();++/**+ * Drop every cached payload built from `engine` and bump its generation, so+ * a build that read the database before the write cannot store its stale+ * result afterwards.+ */+export function invalidateHotMemoryForEngine(engine: object): void {+ _generations.set(engine, (_generations.get(engine) ?? 0) + 1);+ const key = ENGINE_KEYS.get(engine);+ if (!key) return;+ for (const k of _cache.keys()) if (k.split('::')[0] === key) _cache.delete(k);+}++/**+ * Changes whenever a withdrawal is recorded for the source, by any process.+ * Read-only embedder engines without raw SQL fall back to the TTL alone.+ */+async function withdrawalWatermark(engine: OperationContext['engine'], sourceId: string): Promise<string> {+ if (typeof engine.executeRaw !== 'function') return '';+ const [row] = await engine.executeRaw<{ n: number; at: string | null }>(+ 'SELECT count(*)::int AS n, max(withdrawn_at)::text AS at FROM fact_withdrawals WHERE source_id = $1', [sourceId]);+ return `${row?.n ?? 0}:${row?.at ?? ''}`;+}/** Bounded set: evict the oldest-expiry entry when inserting at capacity. */function cacheSet(key: string, entry: CacheEntry): void {@@ -101,15 +130,24 @@ export async function getBrainHotMemoryMeta(const ttl = Math.max(1000, opts.ttlMs ?? DEFAULT_TTL_MS);const topK = Math.max(1, Math.min(opts.topK ?? DEFAULT_TOP_K, 25));+ // The watermark is read before the rows, so a build that raced a forget+ // stores the older watermark and the next hit rebuilds.+ const generation = _generations.get(ctx.engine) ?? 0;+ const withdrawals = await withdrawalWatermark(ctx.engine, sourceId);+// Cache hit?const cached = _cache.get(cacheKey);if (cached) {- if (cached.expiresAt > Date.now()) return cached.payload;- // Expired: evict BEFORE the rebuild. If the rebuild below throws (the- // caller's try/catch absorbs it), the dead entry must not linger — with- // remote-influencable keys, lingering corpses defeat the size bound.+ if (cached.expiresAt > Date.now() && cached.withdrawals === withdrawals) return cached.payload;+ // Expired or withdrawn since: evict BEFORE the rebuild. If the rebuild+ // below throws (the caller's try/catch absorbs it), the dead entry must+ // not linger — with remote-influencable keys, lingering corpses defeat+ // the size bound._cache.delete(cacheKey);}+ const store = (entry: CacheEntry) => {+ if ((_generations.get(ctx.engine) ?? 0) === generation) cacheSet(cacheKey, { ...entry, withdrawals });+ };// Build a fresh payload. Visibility tier: remote → world-only;// local → all rows.@@ -128,7 +166,7 @@ export async function getBrainHotMemoryMeta(});}if (rows.length === 0) {- cacheSet(cacheKey, { expiresAt: Date.now() + ttl, payload: undefined });+ store({ expiresAt: Date.now() + ttl, payload: undefined });return undefined;}@@ -171,7 +209,7 @@ export async function getBrainHotMemoryMeta(const vu = r.valid_until?.getTime();if (vu !== undefined && Number.isFinite(vu) && vu < expiresAt) expiresAt = vu;}- cacheSet(cacheKey, { expiresAt, payload });+ store({ expiresAt, payload });return payload;}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 9e413b0d4e..244cc8b5c9 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -29,6 +29,7 @@ import {import { backupCheckDisabled, backupNagGate, backupNoticeText, loadBackupStatus } from '../core/backup/status-file.ts';import { maybeRefreshBackupStatusInProcess } from '../core/backup/coverage.ts';import { operationScopesAllowed } from '../core/scope.ts';+import { invalidateHotMemoryForEngine } from '../core/facts/meta-hook.ts';import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';// WP3: normalization + validation moved to validate-params.ts (direct unit@@ -706,6 +707,10 @@ export async function dispatchToolCall(return op.handler(ctx, safeParams);}): await op.handler(ctx, safeParams);+ // A committed write (forget, remember, any fact or page mutation) must not+ // be answered from hot memory built before it, on this response or later.+ // Every MCP transport dispatches here.+ if (op.mutating) invalidateHotMemoryForEngine(engine);// [E4] verb success metrics: budget drops + entity hit/miss when present.{const r = result as { dropped_count?: number; found?: boolean; status?: string } | null;@@ -766,6 +771,8 @@ export async function dispatchToolCall(return out;} catch (e: unknown) {logVerb(false);+ // A refused or failed write may still have committed part of its work.+ if (op.mutating) invalidateHotMemoryForEngine(engine);if (e instanceof OperationError) {return { content: [{ type: 'text', text: JSON.stringify(e.toJSON(), null, 2) }], isError: true };}diff --git a/test/e2e/hot-memory-invalidation-postgres.test.ts b/test/e2e/hot-memory-invalidation-postgres.test.tsnew file mode 100644index 0000000000..ad3233e678--- /dev/null+++ b/test/e2e/hot-memory-invalidation-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../hot-memory-invalidation.test.ts'));diff --git a/test/hot-memory-invalidation.test.ts b/test/hot-memory-invalidation.test.tsnew file mode 100644index 0000000000..eda6dfe613--- /dev/null+++ b/test/hot-memory-invalidation.test.ts@@ -0,0 +1,117 @@+/**+ * Hot memory never outlives a forget (eval wave N5-1).+ *+ * `_meta.brain_hot_memory` and context_pack's hot facts come from a 30 s+ * per-process cache. A mutating tool call through dispatch (every MCP+ * transport) drops the engine's entries, every hit revalidates the source's+ * withdrawal-ledger watermark (so a forget committed by another process is+ * not served either), and a build that raced an invalidation is not stored.+ * Both visibility tiers are checked.+ *+ * Synthetic data only.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import {+ getBrainHotMemoryMeta, invalidateHotMemoryForEngine, __hotMemoryCacheForTests, __resetHotMemoryCacheForTests,+} from '../src/core/facts/meta-hook.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-hot-memory-'));+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) await engine.disconnect();+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });+});+beforeEach(() => { __resetHotMemoryCacheForTests(); });++const ENTITY = 'people/alice-example';+let seq = 0;+async function seed(engine: BrainEngine): Promise<{ id: number; marker: string }> {+ const marker = `cnryhot${++seq}${Math.random().toString(36).slice(2, 8)}`;+ const { id } = await engine.insertFact(+ { fact: `Keeps bees ${marker}`, kind: 'fact', entity_slug: ENTITY, visibility: 'world', source: 'test' },+ { source_id: 'default' });+ return { id, marker };+}+const call = (engine: BrainEngine, name: string, params: Record<string, unknown>, remote: boolean) =>+ dispatchToolCall(engine, name, params, { remote, sourceId: 'default', transport: remote ? 'stdio' : undefined, metaHook: getBrainHotMemoryMeta });+const metaCarries = async (engine: BrainEngine, marker: string, remote: boolean) =>+ JSON.stringify((await call(engine, 'get_stats', {}, remote))._meta ?? null).includes(marker);+const packCarries = async (engine: BrainEngine, marker: string, remote: boolean) =>+ (await call(engine, 'context_pack', { entities: ENTITY }, remote)).content.map(c => c.text).join('\n').includes(marker);+const ctx = (engine: BrainEngine, remote: boolean): OperationContext =>+ ({ engine, remote, sourceId: 'default', config: {} as never, dryRun: false, logger: { info() {}, warn() {}, error() {} } });++test('a forget through dispatch clears hot memory for both tiers, in _meta and context_pack', async () => {+ for (const engine of engines) {+ const { id, marker } = await seed(engine);+ for (const remote of [true, false]) {+ expect(await metaCarries(engine, marker, remote)).toBe(true);+ expect(await packCarries(engine, marker, remote)).toBe(true);+ }+ const forgotten = await call(engine, 'forget', { id: String(id), reason: 'test' }, false);+ expect(forgotten.isError).toBeFalsy();+ for (const remote of [true, false]) {+ expect(await metaCarries(engine, marker, remote)).toBe(false);+ expect(await packCarries(engine, marker, remote)).toBe(false);+ }+ }+});++test('a withdrawal committed outside this dispatcher (another process) is not served from the cache', async () => {+ for (const engine of engines) {+ const { id, marker } = await seed(engine);+ for (const remote of [true, false]) {+ expect(JSON.stringify(await getBrainHotMemoryMeta('get_stats', ctx(engine, remote)))).toContain(marker);+ }+ expect((await recordFactWithdrawal(engine, id, 'default')).withdrawn).toBe(true);+ for (const remote of [true, false]) {+ expect(JSON.stringify(await getBrainHotMemoryMeta('get_stats', ctx(engine, remote)) ?? null)).not.toContain(marker);+ }+ }+});++test('a fact written through dispatch shows up on the next response', async () => {+ for (const engine of engines) {+ await seed(engine);+ expect(await metaCarries(engine, 'cnryfreshwrite', false)).toBe(false);+ const remembered = await call(engine, 'remember', { fact: 'Plays the oboe cnryfreshwrite', entity: ENTITY, provenance: 'test', visibility: 'world' }, false);+ expect(remembered.isError).toBeFalsy();+ expect(await metaCarries(engine, 'cnryfreshwrite', false)).toBe(true);+ expect(await metaCarries(engine, 'cnryfreshwrite', true)).toBe(true);+ }+});++test('a build that raced an invalidation is not cached', async () => {+ for (const engine of engines) {+ await seed(engine);+ const racing = Object.create(engine) as BrainEngine;+ racing.listFactsSince = async (...args: Parameters<BrainEngine['listFactsSince']>) => {+ invalidateHotMemoryForEngine(racing);+ return engine.listFactsSince(...args);+ };+ expect(await getBrainHotMemoryMeta('get_stats', ctx(racing, false))).toBeDefined();+ expect(__hotMemoryCacheForTests().size).toBe(0);+ }+});