Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(memory): readable writeback rule, admin-settable agent override, per-conversation switch (GBRA-219)

garrytan5cf5fd61f1fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 169b49e9df..12411b7b9e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Agents and settings screens can now read the memory-saving rule, an admin can change it remotely, and a user can say "save everything from here" or "stop saving" for one conversation.**
+
+Before, the rule for what an agent saves lived in the MCP instructions, and only the brain operator could see or change `memory.auto_writeback`, from a shell on the host. Three MCP tools change that. Every one keeps its state in the database, so a brain with no git repository gets all of them.
+
+### What changed
+
+| Tool | Who can call it | What it does |
+|---|---|---|
+| `get_memory_settings` | any connection | the mode agents follow, where it came from, the exact rule text, every mode's rule, background capture state, and why you can or can't change it |
+| `set_memory_writeback` | admin scope, after `gbrain config set mcp.publish_memory_settings true` (off by default) | changes `memory.agent_writeback` (inherit, off, salient, all) for the whole brain, with a dry run, an audit row in the same transaction, and a caution on team brains |
+| `memory_conversation_mode` | any connection that can call `remember` | returns the rule for the rest of this conversation: all, salient, off (only what the user asks to keep) or brain; stores nothing |
+
+The new `memory.agent_writeback` key changes only what agents are told. The host capture lanes (Stop hook, compaction harvest, SessionEnd transcripts) keep following the operator's `memory.auto_writeback`, so a remote "off" can't discard banked session text and a remote "all" can't start capture the operator never enabled. An unreadable or unrecognized override makes agents act as if saving is off and `get_memory_settings` reports `degraded`. The MCP instructions gain one line telling the agent to use the switch, after the governing rule, wherever the tool is served (starter and full surfaces). `gbrain config set|get memory.agent_writeback` works from the CLI.
+
+
+
## [0.60.473.0] - 2026-10-27
**A change you stage while a write is finishing is no longer overwritten.**
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index c5a85e00c9..f97923949e 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 162 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 165 tools across 26 areas. **Starter** marks membership in the ~41-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -145,6 +145,14 @@ Every non-localOnly operation on the MCP surface: 162 tools across 25 areas. **S
| `extract_facts` | Extract personal-knowledge facts (events, preferences, commitments, beliefs, ideas, and plain facts) from a conversation turn into the per-source hot memory. | write | | |
| `forget_fact` | Forget a fact by recording a durable withdrawal in its source and visibility. | write | | |
+## memory-settings
+
+| Tool | Description | Scope | Starter | Gate |
+|---|---|---|---|---|
+| `get_memory_settings` | Memory writeback settings: the mode agents follow, the exact rule text, every mode's rule, background capture state, and whether you may change it. | read | | |
+| `memory_conversation_mode` | Use when the user says "save everything from here" (all) or "stop saving" (off: explicit saves only): returns the memory rule for the rest of this conversation. | write | yes | |
+| `set_memory_writeback` | Change the brain-wide writeback mode agents are told to follow (inherit uses the operator's setting). | admin | | `mcp.publish_memory_settings` |
+
## memory-verbs
| Tool | Description | Scope | Starter | Gate |
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 8c94f86be4..7877db75ed 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -12,6 +12,8 @@
- `src/core/facts/ttl-parse.ts` — dependency-free TTL grammar leaf (`parseTtlShorthand` non-throwing typed results; `validateTtlConfig` — duration-shorthand-only, positive, ≤365d for the transient-TTL config). `ops/facts.ts`'s `parseTtlParam` wraps it with the byte-identical frozen verbError copy; the engine-free hook child shares the grammar without touching the gateway-reaching ops graph.
- `src/core/facts/writeback-config.ts` — config resolution, fail-closed OFF. `gbrain config set memory.*` DUAL-WRITES (file mirror first for the engine-free readers, then the AUTHORITATIVE DB plane; `src/commands/config.ts` MEMORY_DUAL_PLANE_KEYS branch, which also stamps the resolved `memory.visibility_posture` file mirror for the engine-free harness renderer — and a `facts.default_visibility` set/unset RE-STAMPS that mirror so installed blocks can always converge; a DB-write/delete failure on these keys exits NON-ZERO naming the unchanged runtime value, and `config get` reports them DB-first with a drift warn). MOUNT RULE: when the selected brain is not the host (`--brain`/GBRAIN_BRAIN_ID/.gbrain-mount), every dual-plane lane (set, unset, `unset --pattern`, the posture re-stamp) writes the DB row ONLY and says so — the machine-local mirror gates the HOST's Stop hook, and enabling a team mount must never opt the host's conversations into banking; an unresolvable brain selection also skips the mirror (fail toward not mutating host state). The engine path resolves mode/ttl from the DB ONLY — the machine-global file mirror never enables a per-brain gap (a mounted/selected brain can't inherit another brain's opt-in); a provided fileCfg serves drift detection (`plane_drift`: DB row ABSENT + file enabled; explicit DB 'off' is intent, never drift) and the LKG override (a file-mirror explicit 'off' beats a cached ENABLED bundle on read failure). `resolveWritebackConfig` caches a per-engine LAST-KNOWN-GOOD bundle ATOMICALLY (mode+ttl+visibility together; no LKG + read failure = OFF+`read_error`). `ambientOptsFrom(wb, {remember, extractFacts})` gates the section on the caller's ACTUAL callable set — no `remember` ⇒ no section (bound-client fences, clamped surfaces). `visibilityPostureFromRaw` owns the rule: unset → world, only explicit non-world → private.
- Capture gate (#6091): see [Ambient capture consent gate](ambient-capture.md).
+ - `src/core/facts/writeback-settings.ts` — GBRA-219: the DB-only `memory.agent_writeback` override (inherit | off | salient | all) of the mode AGENTS are told to follow. `resolveAgentWriteback` wraps the operator resolver and is what the three initialize transports render; an unreadable or invalid override, or an operator read failure with no last-known-good, fails closed to off (never inherits a wider mode). It never feeds `captureGateDecision`, so the capture lanes stay on `memory.auto_writeback`. `writeAgentWriteback` writes the setting and a `memory_setting_change` request-log row in one transaction under an advisory lock. Kept out of writeback-config.ts because the engine-free hook children import that file.
+ - `src/core/ops/memory-settings.ts` — `get_memory_settings` (read), `set_memory_writeback` (admin scope + `mcp.publish_memory_settings` publish gate; writes only the override), `memory_conversation_mode` (write scope, callable where `remember` is; stores nothing; no enum auto-repair because `mutating` is unset). Guide: `docs/guides/ambient-writeback.md#reading-and-changing-it-remotely`.
- `src/core/facts/writeback-instructions.ts` — the ONE ~15-line instruction-section builder feeding BOTH the MCP `instructions` composition and the bootstrap-managed harness blocks (surfaces structurally cannot drift). Mode-conditional candidate policy, literal resolved TTL, surface-honest extract_facts mention, visibility posture with the "world = agents on this brain, not the public internet / never widen" rule; the private posture states its consequence to the agent (it and every other MCP/HTTP session cannot recall or forget a fact it saves as private).
- `src/core/facts/writeback-gate.ts` — the engine-free zero-LLM Stop-hook salience gate: frozen skip-reason vocabulary (`empty`/`too_short` [CJK-aware 20→10 floor]/`ack_or_greeting`/`slash_command`/`question_only`/`quoted_or_tool_output`/`bulk_paste` >8KB/`pasted_content`), first hit wins; after the length checks every Claude Code paste block is stripped (`pasted-content.ts`) and the remaining rules plus the banked text see only the user's own words (a paste-only turn is `pasted_content`); ok returns the NFC/collapsed normalized text + sha256-hash24 — the turn's idempotency key (same turn ⇒ same `.wb-` filename ⇒ embedding-free dedup that works keyless).
- `src/core/facts/writeback-audience.ts` — personal-vs-shared classifier for the consent nudge. Declaration (`brain.audience`, stamped by company-brainify's Phase-5 handoff, the bootstrap interview's SURFACE_MULTIUSER answer — applied the moment `interview --set` records it, BEFORE the agent runs init — or the operator) BEATS the conservative heuristic (≥3 distinct non-automation MCP clients active 30d via `mcp-usage.ts`, `likely_automation` excluded); `reasons[]` always names the evidence. The machine-global file-mirror declaration speaks for the HOST brain only — a mounted/selected brain falls through to its own DB row or heuristic. Fail directions: config read failure → `unknown` (nudge stays silent), usage-read failure with a reachable DB → `personal` (missing multi-client infra is personal-shaped). Never enables anything.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index 8e491234a1..b09f84a286 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -501,6 +501,72 @@ files from gbrain's own claude-cli sessions, and `captured_facts_active`
counts facts captured before v0.60.30.0 from those sessions or from pasted
text (cleared by `gbrain repair captured-facts`).
+## Reading and changing it remotely
+
+Three MCP tools let a connected agent or a product settings screen read the
+rule, change the mode agents follow, and switch saving for one conversation.
+They keep everything in the brain's database (the config table and the
+request log), so a brain with no git repository gets all of them.
+
+| Tool | Who can call it | What it does |
+|---|---|---|
+| `get_memory_settings` | any connection (read scope) | the mode agents follow, where it came from, the exact rule text, every mode's rule, background capture state, and whether you may change it |
+| `set_memory_writeback` | admin scope, after the operator's grant | changes `memory.agent_writeback` for the whole brain; `dry_run: true` previews |
+| `memory_conversation_mode` | any connection that can call `remember` | returns the rule to follow for the rest of this conversation; stores nothing |
+
+**Two keys, two jobs.** `memory.auto_writeback` is the operator's setting: it
+drives the instruction section and the host capture lanes (Stop hook,
+compaction harvest, SessionEnd transcripts). `memory.agent_writeback`
+(`inherit` | `off` | `salient` | `all`, unset means inherit) changes only
+what agents are told over MCP. The capture lanes never read it, so a remote
+`off` can't retire the host's banked session text, and a remote `all` can't
+start capture the operator never turned on. Harness instruction blocks
+installed by `gbrain bootstrap harness` also keep following the operator's
+`memory.auto_writeback`; converge them with another bootstrap run if you
+change that. An unreadable or unrecognized `memory.agent_writeback` makes
+agents act as if writeback is off (never as if it inherited a wider mode), and
+`get_memory_settings` reports `status: degraded` with the reason instead of a
+plain `off`.
+
+**Turning on remote changes (operator, on the brain host):**
+
+```bash
+gbrain config set mcp.publish_memory_settings true # the grant; default off
+gbrain auth create settings-app --scopes read,write,admin # or: gbrain auth rescope --id TOKEN_ID --scopes read,write,admin
+# From an admin-scope connection:
+# set_memory_writeback {"mode": "salient", "dry_run": true} -> preview, writes nothing
+# set_memory_writeback {"mode": "salient"} -> applied, audited
+# get_memory_settings {} -> effective_mode: "salient", source: "agent_override"
+gbrain config get memory.agent_writeback # the same value from the CLI
+gbrain config set memory.agent_writeback inherit # back to the operator's mode
+```
+
+Admin scope also carries `sources_admin` and `users_admin`, so grant it only
+to a connection you'd trust with those. While the grant is off, the tool is
+hidden from network tool lists; `get_memory_settings` names why in
+`can_set.blocked_by` (`gate_off`, `scope`, `bound_client`, `surface`) and
+carries the grant command in `can_set.fix`.
+
+Each change writes the setting and a `memory_setting_change` row in
+`mcp_request_log` (client, transport, old, new) in one transaction. If the
+database write doesn't confirm, the call fails with
+`memory_setting_write_outcome_unknown`: read `get_memory_settings` before
+trying again, because a lost acknowledgement looks the same as a rollback.
+On a brain that looks like a team brain, enabling returns a `caution`.
+
+**When a change takes effect:** HTTP sessions on their next initialize; a
+stdio server after it restarts; the conversation switch immediately.
+
+**The conversation switch.** When the user says "save everything from here",
+the agent calls `memory_conversation_mode {"mode": "all"}` and follows the
+returned `rule_text` for the rest of the conversation. "Stop saving" is
+`{"mode": "off"}`: save only what the user explicitly asks to keep. `brain`
+returns the brain's own rule. Nothing is stored: a new conversation starts
+from the brain's mode, and after compaction the agent calls it again. Every
+save still goes through `remember` with the connection's own scope and the
+brain's visibility posture. The switch doesn't stop background capture from
+host session hooks, and its response says so.
+
## Enable / verify / disable
```bash
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6eafb98264..a0bd5b56dd 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2601,6 +2601,16 @@ More: [docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollm
More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+### memory_setting_write_outcome_unknown
+
+<a id="memory_setting_write_outcome_unknown"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A memory writeback setting change did not confirm, so it may or may not have been saved. | A database write that throws can be a rollback or a lost acknowledgement, and the two look the same to the caller. The setting and its audit row commit together, so a re-read shows which happened. | Call get_memory_settings to read the mode in effect, and change it again only if the change did not land. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/ambient-writeback.md#reading-and-changing-it-remotely](../../docs/guides/ambient-writeback.md#reading-and-changing-it-remotely)
+
### merge_recommended
<a id="merge_recommended"></a>
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index cd9d3682ed..e36c275d15 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -1118,6 +1118,16 @@ it; each change carries its `trust_tier`. The
CLI twin is `gbrain beliefs changes [<entity>...] [--since 7d]`. Design:
[BELIEF_LEDGER.md section 15](../designs/BELIEF_LEDGER.md#15-w4-as-built-the-weekly-change-diff).
+### Adjacent memory-settings ops (not verbs)
+
+Three ops sit next to `remember` without joining the frozen verb set, so
+`--surface verbs` does not serve them: `get_memory_settings` (read the
+writeback mode and rule text), `set_memory_writeback` (admin scope plus the
+operator's `mcp.publish_memory_settings` grant) and `memory_conversation_mode`
+(the per-conversation "save everything from here" / "stop saving" switch, on
+the starter surface). See
+[Reading and changing it remotely](../guides/ambient-writeback.md#reading-and-changing-it-remotely).
+
## Latency classes (per verb)
Published so harness authors place calls by cost, not by learning at timeout:
diff --git a/llms-full.txt b/llms-full.txt
index 76575d3143..c296211b42 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9669,6 +9669,16 @@ it; each change carries its `trust_tier`. The
CLI twin is `gbrain beliefs changes [<entity>...] [--since 7d]`. Design:
[BELIEF_LEDGER.md section 15](../designs/BELIEF_LEDGER.md#15-w4-as-built-the-weekly-change-diff).
+### Adjacent memory-settings ops (not verbs)
+
+Three ops sit next to `remember` without joining the frozen verb set, so
+`--surface verbs` does not serve them: `get_memory_settings` (read the
+writeback mode and rule text), `set_memory_writeback` (admin scope plus the
+operator's `mcp.publish_memory_settings` grant) and `memory_conversation_mode`
+(the per-conversation "save everything from here" / "stop saving" switch, on
+the starter surface). See
+[Reading and changing it remotely](../guides/ambient-writeback.md#reading-and-changing-it-remotely).
+
## Latency classes (per verb)
Published so harness authors place calls by cost, not by learning at timeout:
diff --git a/plugin/README.md b/plugin/README.md
index 87dfc0b390..67d2aa2ac2 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 183
+The plugin's MCP server runs `gbrain serve --surface full` — 186
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bfa01bceb3..58e3e8d785 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2866 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured)
src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 245 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line)
+src/core/operations.ts 246 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GBRA-219: memorySettingsOperations import (spread shares the facts line)
src/core/pglite-engine.ts 3097 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured)
src/core/postgres-engine.ts 3155 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
+src/core/config.ts 2014 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-219: memory.agent_writeback and mcp.publish_memory_settings KNOWN_CONFIG_KEYS rows (resolver in facts/writeback-settings.ts)
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/src/commands/config-agent-writeback.ts b/src/commands/config-agent-writeback.ts
new file mode 100644
index 0000000000..2ff9907afd
--- /dev/null
+++ b/src/commands/config-agent-writeback.ts
@@ -0,0 +1,42 @@
+/**
+ * `gbrain config set|get memory.agent_writeback` (GBRA-219). Kept out of
+ * runConfig, which sits at its function-size ceiling. DB-only: the setting and
+ * its audit row commit in one transaction; the capture lanes and the file
+ * mirror are never touched.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfig } from '../core/config.ts';
+import { AGENT_WRITEBACK_KEY, AGENT_WRITEBACK_VALUES, parseAgentWriteback, resolveAgentWriteback, writeAgentWriteback } from '../core/facts/writeback-settings.ts';
+
+export { AGENT_WRITEBACK_KEY };
+
+export async function setAgentWritebackFromCli(engine: BrainEngine, value: string): Promise<void> {
+ const mode = parseAgentWriteback(value);
+ if (!mode) {
+ console.error(`[config] ${AGENT_WRITEBACK_KEY} must be one of: ${AGENT_WRITEBACK_VALUES.join(' | ')}. Nothing was written.`);
+ process.exit(1);
+ }
+ try {
+ const { previous } = await writeAgentWriteback(engine, mode, { actor: 'operator', client_id: null, transport: 'cli' });
+ console.log(`Set ${AGENT_WRITEBACK_KEY} = ${mode} (db plane; was ${previous ?? 'inherit'})`);
+ console.log('This changes what agents are told to save. Background capture (session hooks) still follows memory.auto_writeback.');
+ } catch (e) {
+ console.error(`[config] ERROR: the write did not confirm (${e instanceof Error ? e.name : 'error'}), so it may or may not have landed.`);
+ console.error(`[config] Read it back with \`gbrain config get ${AGENT_WRITEBACK_KEY}\` before re-running.`);
+ process.exit(1);
+ }
+}
+
+/** Unset is a real value (inherit), not a missing key. */
+export async function printUnsetAgentWriteback(engine: BrainEngine): Promise<void> {
+ const agent = await resolveAgentWriteback(engine, loadConfig());
+ console.log('inherit');
+ console.error(`[config] source: unset (inherits memory.auto_writeback); agents are told: ${agent.bundle.mode}${agent.status === 'degraded' ? ` (degraded: ${agent.reasons.join(', ')})` : ''}`);
+}
+
+/** The `config get memory.auto_writeback` source-line suffix when agents are told something else. */
+export async function agentWritebackNote(engine: BrainEngine): Promise<string> {
+ const agent = await resolveAgentWriteback(engine, loadConfig());
+ if (agent.source === 'operator') return '';
+ return `; agents are told: ${agent.bundle.mode} (${AGENT_WRITEBACK_KEY} ${agent.source === 'fail_closed' ? 'unreadable or invalid, failing closed' : agent.override})`;
+}
diff --git a/src/commands/config.ts b/src/commands/config.ts
index ee213866a0..1ebefff6a7 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -944,6 +944,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
: fileOnly
? fileVal
: (fileVal !== undefined && fileVal !== null ? fileVal : dbVal);
+ if (key === 'memory.agent_writeback' && (val === null || val === undefined)) return (await import('./config-agent-writeback.ts')).printUnsetAgentWriteback(engine);
if (val !== null && val !== undefined) {
// #3943: redact by default like `show`/`set` — `get` output lands in
// agent transcripts and shell history; scripts opt out with the flag.
@@ -1008,10 +1009,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
// Ambient-writeback keys DUAL-WRITE (OV2-5): file mirror first (the
// engine-free readers' plane), then the authoritative DB row. A DB
// failure leaves the planes briefly diverged — reported, not hidden.
- if (key === EMBEDDING_DISABLED_KEY) {
- await setEmbeddingDisabled(engine, value);
- return;
- }
+ if (key === EMBEDDING_DISABLED_KEY) return setEmbeddingDisabled(engine, value);
if (key === BRAIN_AUDIENCE_KEY) {
// Dual-plane like memory.* (WP8): the engine-free harness lane gates
// its enable-nudge advisory on the file-plane declared audience.
@@ -1043,6 +1041,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.log(`Set ${key} = ${audience} (${hostPlane ? 'file + db planes' : 'db plane only — mounted brain'})`);
return;
}
+ if (key === 'memory.agent_writeback') return (await import('./config-agent-writeback.ts')).setAgentWritebackFromCli(engine, value);
if (MEMORY_DUAL_PLANE_KEYS.has(key)) {
const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as Parameters<typeof saveConfig>[0];
@@ -1520,5 +1519,5 @@ async function refuseSchemaSizingKey(key: 'embedding_model' | 'embedding_dimensi
async function writebackLanesNote(engine: BrainEngine, key: string): Promise<string> {
if (key !== 'memory.auto_writeback') return '';
const { captureLaneSummary, resolveWritebackConfig } = await import('../core/facts/writeback-config.ts');
- return `; capture lanes: ${captureLaneSummary(await resolveWritebackConfig(engine, loadConfig(), { gate: true }))}`;
+ return `; capture lanes: ${captureLaneSummary(await resolveWritebackConfig(engine, loadConfig(), { gate: true }))}${await (await import('./config-agent-writeback.ts')).agentWritebackNote(engine)}`;
}
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index d760c179a6..c552d6f40b 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -20,7 +20,8 @@ import { httpInstructionTools } from '../mcp/initialize-context.ts';
import { installCapabilitiesResource, mcpAdministrationGuidance } from '../mcp/capabilities.ts';
import { createSkillResources } from '../mcp/skill-resources.ts';
import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';
-import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
+import { ambientOptsFrom, type WritebackConfig } from '../core/facts/writeback-config.ts';
+import { resolveAgentWriteback } from '../core/facts/writeback-settings.ts';
import { hasScope, operationScopesAllowed } from '../core/scope.ts';
import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, type ToolResult } from '../mcp/dispatch.ts';
import { toAgentError } from '../core/agent-output.ts';
@@ -159,7 +160,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {
const canWrite = hasScope(authInfo.scopes, 'write');
const [{ ceiling: surfaceCeiling, effective: surface }, writeback, hostResultRows] = await Promise.all([
resolveEffectiveSurface(authInfo),
- canWrite ? resolveWritebackConfig(engine, config) : Promise.resolve(null),
+ canWrite ? resolveAgentWriteback(engine, config).then(r => r.bundle) : Promise.resolve(null),
resolveResultRowsMode(engine, config),
]);
// C1: gbrain's thin client keeps full rows. The header is unverified and
@@ -180,7 +181,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {
function createMcpRequestServer(
ctx: ServeHttpContext,
state: McpRequestState,
- writeback: Awaited<ReturnType<typeof resolveWritebackConfig>> | null,
+ writeback: WritebackConfig | null,
): Server {
const { engine, config, mcpResourceUrl } = ctx;
const { authInfo, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps } = state;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b441be94f8..adb6269812 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -25,13 +25,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
+ 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--admin-intent', '--brain', '--confirm-relocated-root', '--dir', '--expected-epoch', '--expected-state', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--manifest', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--path', '--probe', '--resume', '--save', '--self-transfer', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
- 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
+ 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--channel', '--exit-code', '--ff-only', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
@@ -52,12 +52,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
- 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
+ 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--only', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--request-id', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--timings', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],
@@ -97,12 +97,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
- 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
+ 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
@@ -139,7 +139,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
};
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
diff --git a/src/core/config.ts b/src/core/config.ts
index 0a95052dce..bfebbc9738 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1538,6 +1538,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Fire-once sentinel for the ambient-writeback consent nudge (WP8):
// stamped 'true' after the init/post-upgrade ask has been shown once.
'memory.auto_writeback_notice_shown',
+ 'memory.agent_writeback', // GBRA-219: DB-only override of what AGENTS are told (inherit|off|salient|all); never the capture lanes (facts/writeback-settings.ts)
// Always-loaded core memory + context-pressure notice (docs/guides/core-memory.md#configuration).
'memory.core.enabled', 'memory.core.max_chars', 'memory.core.remote_edit',
'memory.pressure.enabled', 'memory.pressure.warn_ratio', 'memory.pressure.context_window',
@@ -1651,6 +1652,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// the advisor exposes operational diagnostics (version/jobs/key presence),
// not prose skills. Default OFF; read-only over MCP.
'mcp.publish_advisor',
+ 'mcp.publish_memory_settings', // GBRA-219: operator grant for set_memory_writeback over MCP (admin scope too); default off
// WP3 — unknown tool-call argument posture ('warn' default | 'reject').
// Read dual-plane by src/mcp/validate-params.ts (DB > file > 'warn').
'mcp.strict_params',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c4d30ed271..67907b2e21 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -414,6 +414,7 @@ export const CODES = {
maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },
managed_failure_unsettled: { class: 'caller', summary: "The recorded managed sync failure is not settled by the imported state, so it was not acknowledged.", why: "Acknowledging removes a failure record only when the file it failed on is already imported unchanged (or deleted in both the commit and the brain); anything else would hide content that never reached the brain.", suggestion: 'Resume or retry the sync the failure names (gbrain sync status --source <id> --json shows it), then acknowledge again if the record remains.' },
managed_remedy_unavailable: { class: 'caller', summary: "gbrain repair rename-identity cannot carry a page identity on a managed source; nothing was written.", why: "On a managed brain page tables change only through coordinated publications, and the carry is a classic-source maintenance transaction, so on a managed source the remedy can only close the pair.", suggestion: 'Release the purge hold without carrying identity: preview gbrain repair rename-identity --source <id> --slug <new-slug> --close, then run the apply command it prints after the user agrees; or keep the old page as its own page with gbrain restore <old-slug> --source-id <id> --force.', docs: 'docs/guides/repair.md#rename-identity' },
+ memory_setting_write_outcome_unknown: { class: 'server', retryable: false, summary: "A memory writeback setting change did not confirm, so it may or may not have been saved.", why: "A database write that throws can be a rollback or a lost acknowledgement, and the two look the same to the caller. The setting and its audit row commit together, so a re-read shows which happened.", docs: 'docs/guides/ambient-writeback.md#reading-and-changing-it-remotely', suggestion: 'Call get_memory_settings to read the mode in effect, and change it again only if the change did not land.' },
merge_recommended: { class: 'caller', retryable: false, actor: 'user',
summary: "The content-repair model judged a held file and the page its frontmatter `slug:` names to be the same page, so gbrain recommends merging them instead of removing the slug line; nothing was written.",
why: "A `frontmatter_slug_conflict` hold whose two sides describe the same person, company or topic is a duplicate, and the deterministic repair (delete the `slug:` line) would mint a second page for it. gbrain does not merge pages by itself yet (a lossless merge needs a coordinated two-page write with both revisions, withdrawal and metadata preservation; it ships separately), so the lane records the recommendation on the hold as codes and slugs (`meta.content_repair`: the canonical slug that keeps the page), `gbrain sync status` renders a paragraph for a person, and nothing retries it until the file changes.",
diff --git a/src/core/facts/writeback-instructions.ts b/src/core/facts/writeback-instructions.ts
index 87b843f30a..45005d0b9b 100644
--- a/src/core/facts/writeback-instructions.ts
+++ b/src/core/facts/writeback-instructions.ts
@@ -32,6 +32,8 @@ export interface AmbientWritebackOpts {
* 'unknown' and gets HEDGED lines ("when it is in your tool list") that
* stay honest whether the serve is full-surface or clamped to verbs. */
extractFactsAvailable: boolean | 'unknown';
+ /** Who turned it on: the brain (default) or the user, for this conversation only (memory_conversation_mode). */
+ origin?: 'brain' | 'conversation';
}
export function buildAmbientWritebackSection(opts: AmbientWritebackOpts): string {
@@ -51,7 +53,10 @@ export function buildAmbientWritebackSection(opts: AmbientWritebackOpts): string
const visibilityLine = opts.visibility === 'world'
? 'Pass visibility: "world" explicitly on every save. "world" means readable by agents authorized on THIS brain — not the public internet. Never widen a private fact on your own.'
: 'Pass visibility: "private" explicitly on every save — this brain\'s operator keeps facts private by default (omitting visibility would silently widen: remember defaults to world). Private facts are readable by the local CLI only, not by remote sessions: you, and every other MCP or HTTP session, cannot recall or forget a fact you save as private. Never widen to world on your own.';
- return `Ambient memory writeback (enabled by this brain's operator — mode: ${opts.mode}):
+ const header = opts.origin === 'conversation'
+ ? `Memory writeback for the rest of this conversation (the user asked for it — mode: ${opts.mode}):`
+ : `Ambient memory writeback (enabled by this brain's operator — mode: ${opts.mode}):`;
+ return `${header}
1. Treat every substantive statement the user makes about themselves, their people, projects, or plans as a memory candidate. ${candidatePolicy}
2. Save with remember: ONE claim per call; set kind (event | preference | commitment | belief | fact) and set entity whenever a person, company, or project is the subject (e.g. people/alice-example, companies/acme-example).
3. ${multiFact}
diff --git a/src/core/facts/writeback-settings.ts b/src/core/facts/writeback-settings.ts
new file mode 100644
index 0000000000..8e5345b18e
--- /dev/null
+++ b/src/core/facts/writeback-settings.ts
@@ -0,0 +1,136 @@
+/**
+ * Agent-instruction writeback override (gbrain.io memory settings, GBRA-219).
+ *
+ * `memory.agent_writeback = inherit | off | salient | all` changes ONLY what
+ * agents are told to save: the ambient-writeback section and the short
+ * writeback line in the MCP initialize instructions, and what
+ * `get_memory_settings` renders. It is DB-only (no file mirror), so it works
+ * the same on a repo-less brain, and it never feeds the host capture lanes:
+ * the Stop hook, the compaction harvest and SessionEnd transcripts keep
+ * reading the operator's `memory.auto_writeback` through
+ * captureGateDecision (writeback-config.ts). That separation is the point: a
+ * remote `off` must never retire the operator's banked session text.
+ *
+ * Kept out of writeback-config.ts on purpose: the engine-free hook children
+ * import that module, and this one reads the audience classifier and the
+ * request log.
+ *
+ * Fail direction: an unreadable or unrecognized override resolves to `off`
+ * (never back to inherit, which would widen an `off` override on a brain
+ * whose operator mode is on), with status `degraded`. A read failure serves
+ * the engine's last-known-good override first, matching the operator
+ * resolver's mid-session posture.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { executeRawJsonb } from '../sql-query.ts';
+import { resolveWritebackConfig, type WritebackConfig, type WritebackMode } from './writeback-config.ts';
+
+export const AGENT_WRITEBACK_KEY = 'memory.agent_writeback';
+export const AGENT_WRITEBACK_VALUES = Object.freeze(['inherit', 'off', 'salient', 'all'] as const);
+export type AgentWritebackValue = (typeof AGENT_WRITEBACK_VALUES)[number];
+
+/** The request-log operation name of a settings change (a NON_OP_LOG_ROWS member). */
+export const MEMORY_SETTING_AUDIT_OP = 'memory_setting_change';
+
+export interface AgentWritebackResolution {
+ /** The operator bundle with mode/enabled replaced by the effective instruction mode. */
+ bundle: WritebackConfig;
+ /** The operator's own `memory.auto_writeback` resolution (also what the capture lanes follow). */
+ operator: WritebackConfig;
+ /** The stored override, normalized; null when unset. */
+ override: AgentWritebackValue | null;
+ /** Where the effective instruction mode came from. */
+ source: 'agent_override' | 'operator' | 'fail_closed';
+ status: 'ok' | 'degraded';
+ /** Machine-readable reasons for a degraded status. */
+ reasons: string[];
+}
+
+export function parseAgentWriteback(raw: unknown): AgentWritebackValue | null | undefined {
+ if (raw == null) return null;
+ const s = String(raw).trim().toLowerCase();
+ if (!s) return null;
+ return (AGENT_WRITEBACK_VALUES as readonly string[]).includes(s) ? s as AgentWritebackValue : undefined;
+}
+
+const overrideLkg = new WeakMap<BrainEngine, AgentWritebackValue | null>();
+
+/** Never throws. `fileCfg` is passed through to the operator resolver as drift/LKG input only. */
+export async function resolveAgentWriteback(engine: BrainEngine, fileCfg?: GBrainConfig | null): Promise<AgentWritebackResolution> {
+ const operator = await resolveWritebackConfig(engine, fileCfg);
+ const reasons: string[] = [];
+ if (operator.read_error) reasons.push('operator_mode_unreadable');
+ if (!operator.mode_valid) reasons.push('operator_mode_invalid');
+ if (operator.plane_drift) reasons.push('operator_plane_drift');
+ let override: AgentWritebackValue | null | undefined;
+ try {
+ override = parseAgentWriteback(await engine.getConfig(AGENT_WRITEBACK_KEY));
+ if (override !== undefined) overrideLkg.set(engine, override);
+ } catch {
+ override = overrideLkg.has(engine) ? overrideLkg.get(engine)! : undefined;
+ reasons.push(overrideLkg.has(engine) ? 'agent_override_last_known_good' : 'agent_override_unreadable');
+ }
+ let mode: WritebackMode;
+ let source: AgentWritebackResolution['source'];
+ if (operator.read_error) {
+ // The operator read failed with no last-known-good, so the visibility and
+ // TTL posture are defaults, not this brain's: never emit an enabled rule on them.
+ mode = 'off';
+ source = 'fail_closed';
+ } else if (override === undefined) {
+ if (!reasons.includes('agent_override_unreadable')) reasons.push('agent_override_invalid');
+ mode = 'off';
+ source = 'fail_closed';
+ } else if (override === null || override === 'inherit') {
+ mode = operator.mode;
+ source = 'operator';
+ } else {
+ mode = override;
+ source = 'agent_override';
+ }
+ return {
+ bundle: { ...operator, mode, enabled: mode !== 'off' },
+ operator,
+ override: override ?? null,
+ source,
+ status: reasons.length ? 'degraded' : 'ok',
+ reasons,
+ };
+}
+
+export interface AgentWritebackChange {
+ actor: string;
+ client_id: string | null;
+ transport: 'cli' | 'stdio' | 'http';
+}
+
+/**
+ * Write the override and its audit row in ONE transaction: either both land
+ * or neither does. Returns the previous stored value. A throw means the
+ * outcome is unknown to the caller (a lost acknowledgement looks the same as
+ * a rollback), so callers re-read before any retry.
+ */
+export async function writeAgentWriteback(
+ engine: BrainEngine,
+ value: AgentWritebackValue,
+ change: AgentWritebackChange,
+): Promise<{ previous: AgentWritebackValue | null }> {
+ const result = await engine.transaction(async (tx) => {
+ // Serialize concurrent changes so each audit row's `old` is the value it replaced.
+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1))', [AGENT_WRITEBACK_KEY]);
+ const previous = parseAgentWriteback(await tx.getConfig(AGENT_WRITEBACK_KEY)) ?? null;
+ await tx.setConfig(AGENT_WRITEBACK_KEY, value);
+ await executeRawJsonb(
+ tx,
+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, params)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,
+ [change.actor, change.actor, MEMORY_SETTING_AUDIT_OP, 0, 'success'],
+ [{ key: AGENT_WRITEBACK_KEY, actor: change.actor, client_id: change.client_id, transport: change.transport, old: previous, new: value }],
+ );
+ return { previous };
+ });
+ overrideLkg.set(engine, value);
+ return result;
+}
diff --git a/src/core/mcp-usage.ts b/src/core/mcp-usage.ts
index 4baf53469b..a526193a03 100644
--- a/src/core/mcp-usage.ts
+++ b/src/core/mcp-usage.ts
@@ -51,6 +51,8 @@ export const NON_OP_LOG_ROWS: ReadonlySet<string> = new Set([
'ping',
// ENG-8 surface-change audit rows (src/core/surface-audit.ts).
'surface_change',
+ // GBRA-219 memory settings audit rows (src/core/facts/writeback-settings.ts).
+ 'memory_setting_change',
]);
/** Legacy bearer transport row prefix — 'tools/call:query' means op 'query'. */
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index f824bdb4f6..60007174db 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -28,6 +28,7 @@ const load_insights = () => import('./ops/insights.ts') as Promise<Record<string
const load_jobs = () => import('./ops/jobs.ts') as Promise<Record<string, unknown>>;
const load_links = () => import('./ops/links.ts') as Promise<Record<string, unknown>>;
const load_loops = () => import('./ops/loops.ts') as Promise<Record<string, unknown>>;
+const load_memory_settings = () => import('./ops/memory-settings.ts') as Promise<Record<string, unknown>>;
const load_notices = () => import('./ops/notices.ts') as Promise<Record<string, unknown>>;
const load_orphans = () => import('./ops/orphans.ts') as Promise<Record<string, unknown>>;
const load_page_append = () => import('./ops/page-append.ts') as Promise<Record<string, unknown>>;
@@ -209,6 +210,9 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"purge_fact": [load_purge, "purgeOperations"],
"list_page_purges": [load_purge, "purgeOperations"],
"unpurge_page": [load_purge, "purgeOperations"],
+ "get_memory_settings": [load_memory_settings, "memorySettingsOperations"],
+ "set_memory_writeback": [load_memory_settings, "memorySettingsOperations"],
+ "memory_conversation_mode": [load_memory_settings, "memorySettingsOperations"],
"find_contradictions": [load_insights, "find_contradictions"],
"find_experts": [load_insights, "find_experts"],
"find_trajectory": [load_insights, "find_trajectory"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index abb2c1a536..cdb3a1783c 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -6111,6 +6111,65 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"hidden": true
}
},
+ {
+ "name": "get_memory_settings",
+ "mutating": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Memory writeback settings: the mode agents follow, the exact rule text, every mode's rule, background capture state, and whether you may change it.",
+ "params": {},
+ "scope": "read",
+ "area": "memory-settings",
+ "cliHints": {
+ "name": "memory-settings"
+ }
+ },
+ {
+ "name": "set_memory_writeback",
+ "mutating": true,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Change the brain-wide writeback mode agents are told to follow (inherit uses the operator's setting). Admin scope and the operator's grant required; background capture is not changed.",
+ "params": {
+ "mode": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "inherit",
+ "off",
+ "salient",
+ "all"
+ ],
+ "description": "inherit | off | salient | all."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Preview the change; writes nothing."
+ }
+ },
+ "scope": "admin",
+ "area": "memory-settings",
+ "publishGateKey": "mcp.publish_memory_settings"
+ },
+ {
+ "name": "memory_conversation_mode",
+ "outputRedaction": "no_stored_text",
+ "description": "Use when the user says \"save everything from here\" (all) or \"stop saving\" (off: explicit saves only): returns the memory rule for the rest of this conversation. Stores nothing.",
+ "params": {
+ "mode": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "brain",
+ "off",
+ "salient",
+ "all"
+ ],
+ "description": "all | salient | off (only what the user explicitly asks to keep) | brain (this brain's mode)."
+ }
+ },
+ "scope": "write",
+ "area": "memory-settings"
+ },
{
"name": "find_contradictions",
"mutating": false,
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 5a5970c8cc..5e1edeebf4 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -123,6 +123,7 @@ import { extractionOperations } from './ops/extraction.ts';
import { entityIdentityOperations } from './ops/entity-identity.ts';
import { requestToolsOperations } from './ops/request-tools.ts';
import { noticesOperations } from './ops/notices.ts';
+import { memorySettingsOperations } from './ops/memory-settings.ts';
import { pageEditOperations } from './ops/page-edit.ts';
import { pageAppendOperations } from './ops/page-append.ts';
import { pageBatchOperations } from './ops/page-batch.ts';
@@ -212,7 +213,7 @@ export const operations: Operation[] = [
...entityIdentityOperations,
// v0.31: hot memory (extract_facts, recall, context_pack, delta,
// forget_fact) — ops/facts.ts
- ...factsOperations, ...purgeOperations,
+ ...factsOperations, ...purgeOperations, ...memorySettingsOperations, // + GBRA-219 memory settings — ops/memory-settings.ts
// v0.32.6: contradiction probe MCP surface (M3) — ops/insights.ts
find_contradictions,
// v0.33: expertise + relationship-proximity routing — ops/insights.ts
diff --git a/src/core/ops/cli-equivalent.ts b/src/core/ops/cli-equivalent.ts
index c05935c29b..20d50521eb 100644
--- a/src/core/ops/cli-equivalent.ts
+++ b/src/core/ops/cli-equivalent.ts
@@ -9,6 +9,7 @@ import type { Operation } from './contract.ts';
const OVERRIDES: Readonly<Record<string, readonly string[]>> = {
get_health: ['gbrain', 'doctor', '--json'],
+ set_memory_writeback: ['gbrain', 'config', 'set', 'memory.agent_writeback', '<mode>'],
sync_brain: ['gbrain', 'sync'],
submit_job: ['gbrain', 'jobs', 'submit'],
get_job: ['gbrain', 'jobs', 'get'],
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 124bec4f4a..56d4c184de 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -790,7 +790,7 @@ export interface Operation {
* fail-closed call-time backstop; stdio (local pipe) bypasses publish
* gates entirely. Resolution lives in src/mcp/publish-gates.ts.
*/
- publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor';
+ publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor' | 'mcp.publish_memory_settings';
/**
* MEMORY_VERBS v1: marks the seven frozen protocol verbs (recall, remember,
* entity, synthesize, forget, context_pack, delta). `gbrain serve --surface
diff --git a/src/core/ops/memory-settings.ts b/src/core/ops/memory-settings.ts
new file mode 100644
index 0000000000..c3349d3770
--- /dev/null
+++ b/src/core/ops/memory-settings.ts
@@ -0,0 +1,237 @@
+/**
+ * Memory settings over MCP (gbrain.io memory issue, GBRA-219): read the
+ * writeback mode and the exact rule text, change the agent-instruction mode
+ * (admin scope + the operator's `mcp.publish_memory_settings` grant), and a
+ * per-conversation switch that returns the rule to follow for the rest of a
+ * conversation. Everything here is database-backed (config table + request
+ * log), so a repo-less brain gets all of it.
+ *
+ * The capture lanes stay operator-only: set_memory_writeback writes
+ * `memory.agent_writeback` (src/core/facts/writeback-settings.ts), never
+ * `memory.auto_writeback`, and never the host file mirror.
+ */
+import type { Operation, OperationContext } from './contract.ts';
+import { opError, OperationError } from './contract.ts';
+import { hostFix } from './op-fix.ts';
+import { opAllowedForBoundClient } from './context.ts';
+import { hasScope } from '../scope.ts';
+import { buildAmbientWritebackSection } from '../facts/writeback-instructions.ts';
+import { CAPTURE_GATE_LANES, CAPTURE_LANE_LABELS, captureGateDecision, resolveWritebackConfig, type WritebackMode } from '../facts/writeback-config.ts';
+import {
+ AGENT_WRITEBACK_KEY, AGENT_WRITEBACK_VALUES, parseAgentWriteback, resolveAgentWriteback, writeAgentWriteback,
+ type AgentWritebackResolution, type AgentWritebackValue,
+} from '../facts/writeback-settings.ts';
+
+export const MEMORY_SETTINGS_GATE_KEY = 'mcp.publish_memory_settings' as const;
+const CONVERSATION_MODES = ['brain', 'off', 'salient', 'all'] as const;
+const SET_OP = { name: 'set_memory_writeback', scope: 'admin', mutating: true } as const;
+const REMEMBER_OP = { name: 'remember', scope: 'write', mutating: true } as const;
+const EXTRACT_FACTS_OP = { name: 'extract_facts', scope: 'write', mutating: true } as const;
+const SWITCH_OP = { name: 'memory_conversation_mode', scope: 'write', mutating: false } as const;
+
+const BLOCKER_WHY = {
+ gate_off: `The brain operator has not granted remote changes (${MEMORY_SETTINGS_GATE_KEY} is off).`,
+ scope: 'Changing the brain-wide mode needs an admin-scope connection.',
+ bound_client: 'This connection is bound to specific pages or tools, so it cannot change brain settings.',
+ surface: 'This server\'s tool surface does not include set_memory_writeback.',
+} as const;
+
+const TAKES_EFFECT = {
+ http: 'the next initialize (a new MCP session)',
+ stdio: 'after the stdio server restarts',
+ conversation_switch: 'immediately, for the rest of the conversation that called it',
+};
+
+const EXPLICIT_ONLY_RULE =
+ 'Memory for the rest of this conversation (the user asked): save only what the user explicitly asks you to keep, with remember and concise provenance. ' +
+ 'Do not save anything unprompted, even if this brain would otherwise ask you to. ' +
+ 'This does not stop background capture the brain host runs from session hooks; if the user asks whether this conversation is off the record, say so.';
+
+/** May this caller run `op`? Same predicates dispatch applies: trusted CLI, stdio read-only, token scopes, bound-client fence. */
+function callerCan(ctx: OperationContext, op: { name: string; scope: string; mutating: boolean }): boolean {
+ if (ctx.remote === false) return true;
+ if (ctx.stdioSurface?.readOnly && op.mutating) return false;
+ if (ctx.auth && !hasScope(ctx.auth.scopes ?? [], op.scope)) return false;
+ return opAllowedForBoundClient(ctx.auth, op as never);
+}
+
+async function gateOn(ctx: OperationContext): Promise<boolean> {
+ if (ctx.remote === false) return true;
+ const { readPublishGate } = await import('../../mcp/publish-gates.ts');
+ return readPublishGate(ctx.engine, ctx.config, MEMORY_SETTINGS_GATE_KEY, ctx.transport);
+}
+
+function grantFix(ctx: OperationContext) {
+ return hostFix(ctx, ['gbrain', 'config', 'set', MEMORY_SETTINGS_GATE_KEY, 'true'],
+ 'Lets admin-scope connections change the memory writeback mode agents are told to follow. The host capture lanes stay on the operator\'s memory.auto_writeback.');
+}
+
+function ruleFor(res: AgentWritebackResolution, mode: WritebackMode, ctx: OperationContext, origin: 'brain' | 'conversation'): string | null {
+ if (mode === 'off') return null;
+ return buildAmbientWritebackSection({
+ mode,
+ transientTtl: res.operator.transient_ttl,
+ visibility: res.operator.visibility,
+ extractFactsAvailable: callerCan(ctx, EXTRACT_FACTS_OP),
+ origin,
+ });
+}
+
+function degradedNote(res: AgentWritebackResolution): string | undefined {
+ if (res.status === 'ok') return undefined;
+ return `The memory settings could not be read cleanly (${res.reasons.join(', ')}), so agents are told the most conservative mode that applies. This is not proof that writeback is off on purpose; the brain host can check with \`gbrain doctor --only memory_writeback\`.`;
+}
+
+const get_memory_settings: Operation = {
+ name: 'get_memory_settings',
+ mutating: false,
+ outputRedaction: 'no_stored_text',
+ description: 'Memory writeback settings: the mode agents follow, the exact rule text, every mode\'s rule, background capture state, and whether you may change it.',
+ params: {},
+ scope: 'read',
+ area: 'memory-settings',
+ cliHints: { name: 'memory-settings' },
+ handler: async (ctx) => {
+ const res = await resolveAgentWriteback(ctx.engine, ctx.config);
+ const capture = await resolveWritebackConfig(ctx.engine, ctx.config, { gate: true });
+ const canRemember = callerCan(ctx, REMEMBER_OP);
+ const gate = await gateOn(ctx);
+ const bound = Boolean(ctx.auth?.boundSlugPrefixes || ctx.auth?.allowedOperations);
+ const blockers: Array<'gate_off' | 'scope' | 'bound_client' | 'surface'> = [];
+ if (!gate) blockers.push('gate_off');
+ if (ctx.remote !== false && ctx.auth && !hasScope(ctx.auth.scopes ?? [], 'admin')) blockers.push('scope');
+ if (ctx.remote !== false && bound && !opAllowedForBoundClient(ctx.auth, SET_OP as never)) blockers.push('bound_client');
+ if (ctx.surfaceCeiling && ctx.surfaceCeiling !== 'full') blockers.push('surface');
+ const canSwitch = canRemember && callerCan(ctx, SWITCH_OP);
+ const note = degradedNote(res);
+ return {
+ status: res.status,
+ ...(res.reasons.length ? { reasons: res.reasons } : {}),
+ effective_mode: res.bundle.mode,
+ source: res.source,
+ operator_mode: { mode: res.operator.mode, explicit: res.operator.raw_mode != null },
+ agent_override: res.override ?? 'inherit',
+ transient_ttl: res.operator.transient_ttl,
+ visibility: res.operator.visibility,
+ rule_text: canRemember ? ruleFor(res, res.bundle.mode, ctx, 'brain') : null,
+ ...(canRemember ? {} : { rule_text_note: 'This connection cannot call remember, so its instructions carry no writeback rule.' }),
+ rule_texts: { salient: ruleFor(res, 'salient', ctx, 'brain'), all: ruleFor(res, 'all', ctx, 'brain') },
+ background_capture: Object.fromEntries(CAPTURE_GATE_LANES.map(lane => [lane, {
+ label: CAPTURE_LANE_LABELS[lane],
+ state: captureGateDecision(capture, lane).action === 'extract' ? 'on' : captureGateDecision(capture, lane).action === 'retire' ? 'off' : 'held',
+ }])),
+ background_capture_note: 'Background capture runs only where the brain host installed session hooks, and follows the operator\'s memory.auto_writeback; the agent override does not change it.',
+ takes_effect: TAKES_EFFECT,
+ can_set: blockers.length === 0
+ ? { allowed: true }
+ : { allowed: false, blocked_by: blockers, ...(blockers.includes('gate_off') ? { fix: grantFix(ctx) } : {}),
+ why: blockers.map(b => BLOCKER_WHY[b]).join(' ') },
+ conversation_switch: canSwitch ? { available: true } : { available: false, why: 'memory_conversation_mode needs a connection that can call remember and is not bound to specific pages or tools.' },
+ ...(note ? { note } : {}),
+ };
+ },
+};
+
+const set_memory_writeback: Operation = {
+ name: 'set_memory_writeback',
+ mutating: true,
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description: 'Change the brain-wide writeback mode agents are told to follow (inherit uses the operator\'s setting). Admin scope and the operator\'s grant required; background capture is not changed.',
+ params: {
+ mode: { type: 'string', required: true, enum: [...AGENT_WRITEBACK_VALUES], description: 'inherit | off | salient | all.' },
+ dry_run: { type: 'boolean', description: 'Preview the change; writes nothing.' },
+ },
+ scope: 'admin',
+ area: 'memory-settings',
+ publishGateKey: MEMORY_SETTINGS_GATE_KEY,
+ handler: async (ctx, p) => {
+ if (!(await gateOn(ctx))) {
+ const err = opError('permission_denied',
+ 'The brain operator has not granted remote changes to the memory writeback mode, so this tool is hidden from your catalog.',
+ `Ask whoever runs this brain to enable it with \`gbrain config set ${MEMORY_SETTINGS_GATE_KEY} true\`. Nothing was changed.`,
+ { fix: grantFix(ctx) });
+ err.detail = `config_key=${MEMORY_SETTINGS_GATE_KEY}`;
+ throw err;
+ }
+ if (!callerCan(ctx, SET_OP)) {
+ throw opError('permission_denied', 'Changing the brain-wide memory writeback mode needs an admin-scope connection that is not bound to specific pages or tools.',
+ 'Ask the brain\'s administrator to make the change. Nothing was changed.');
+ }
+ const mode = parseAgentWriteback(p.mode);
+ if (!mode) throw opError('invalid_params', `mode must be one of: ${AGENT_WRITEBACK_VALUES.join(', ')}.`, 'Pass the mode the user chose. Nothing was changed.');
+ const before = await resolveAgentWriteback(ctx.engine, ctx.config);
+ const effective: WritebackMode = mode === 'inherit' ? before.operator.mode : mode;
+ let caution: string | undefined;
+ if (effective !== 'off') {
+ try {
+ const { classifyBrainAudience } = await import('../facts/writeback-audience.ts');
+ const audience = await classifyBrainAudience(ctx.engine, ctx.config);
+ if (audience.audience === 'shared') {
+ caution = `This brain looks like a team brain (${audience.reasons.join('; ')}): agents on every member's connection will save what people tell them into a store other authorized agents can read.`;
+ }
+ } catch { /* advisory only */ }
+ }
+ const common = {
+ requested: mode,
+ effective_mode: effective,
+ background_capture_unchanged: true,
+ takes_effect: TAKES_EFFECT,
+ ...(effective === 'off' && before.operator.enabled ? { note: 'Agents will stop saving unprompted, but background capture from host session hooks follows the operator\'s memory.auto_writeback and keeps running.' } : {}),
+ ...(caution ? { caution } : {}),
+ };
+ if (ctx.dryRun || p.dry_run === true) return { applied: false, dry_run: true, previous: before.override ?? 'inherit', ...common };
+ const transport = ctx.remote === false ? 'cli' as const : ctx.transport ?? 'stdio';
+ const actor = ctx.remote === false ? 'operator' : ctx.auth?.clientId ?? 'stdio';
+ try {
+ const { previous } = await writeAgentWriteback(ctx.engine, mode, { actor, client_id: ctx.auth?.clientId ?? null, transport });
+ return { applied: true, previous: previous ?? 'inherit', ...common };
+ } catch (e) {
+ if (e instanceof OperationError) throw e;
+ const cause = ctx.remote === false ? ` (${e instanceof Error ? e.message : String(e)})` : '';
+ throw opError('memory_setting_write_outcome_unknown',
+ `The change to ${mode} may or may not have been saved: the database write did not confirm${cause}.`,
+ 'Call get_memory_settings to read the current mode before trying again; do not repeat the change blindly.',
+ { fix: { mcp: { tool: 'get_memory_settings', arguments: {} }, consent: [], actor: 'agent', requires_exclusive: false, why: 'Reads the mode actually in effect, so a retry only happens if the change did not land.' } });
+ }
+ },
+};
+
+const memory_conversation_mode: Operation = {
+ name: 'memory_conversation_mode',
+ outputRedaction: 'no_stored_text',
+ description: 'Use when the user says "save everything from here" (all) or "stop saving" (off: explicit saves only): returns the memory rule for the rest of this conversation. Stores nothing.',
+ params: {
+ mode: { type: 'string', required: true, enum: [...CONVERSATION_MODES], description: 'all | salient | off (only what the user explicitly asks to keep) | brain (this brain\'s mode).' },
+ },
+ scope: 'write',
+ area: 'memory-settings',
+ handler: async (ctx, p) => {
+ if (!callerCan(ctx, REMEMBER_OP) || !callerCan(ctx, SWITCH_OP)) {
+ throw opError('permission_denied', 'memory_conversation_mode needs a connection that can call remember, and this one cannot.',
+ 'Tell the user this connection cannot save memory; nothing was changed.');
+ }
+ const mode = String(p.mode ?? '');
+ if (!(CONVERSATION_MODES as readonly string[]).includes(mode)) {
+ throw opError('invalid_params', `mode must be one of: ${CONVERSATION_MODES.join(', ')}.`, 'Ask the user which they meant; do not pick a mode for them.');
+ }
+ const res = await resolveAgentWriteback(ctx.engine, ctx.config);
+ const effective: WritebackMode = mode === 'brain' ? res.bundle.mode : mode as WritebackMode;
+ const rule = mode === 'off' || effective === 'off' ? EXPLICIT_ONLY_RULE : ruleFor(res, effective, ctx, mode === 'brain' ? 'brain' : 'conversation')!;
+ const note = degradedNote(res);
+ return {
+ mode,
+ effective_mode: mode === 'off' ? 'off' : effective,
+ applies_to: 'this_conversation',
+ persisted: false,
+ rule_text: rule,
+ background_capture_unchanged: true,
+ note: 'Follow rule_text for the rest of this conversation. Nothing was stored: a new conversation starts from the brain\'s mode, and if the conversation is compacted, call this again.',
+ ...(note ? { degraded_note: note } : {}),
+ };
+ },
+};
+
+export const memorySettingsOperations: Operation[] = [get_memory_settings, set_memory_writeback, memory_conversation_mode];
+export const MEMORY_SETTINGS_KEYS = [AGENT_WRITEBACK_KEY, MEMORY_SETTINGS_GATE_KEY] as const;
+export type { AgentWritebackValue };
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 22aa9004cb..8e61ec849a 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -34,7 +34,8 @@ import type { BrainEngine } from '../core/engine.ts';
import { buildToolDefs } from './tool-defs.ts';
import { readInstructionContent, resolveMcpInstructions } from './instructions.ts';
import { httpInstructionTools } from './initialize-context.ts';
-import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
+import { ambientOptsFrom } from '../core/facts/writeback-config.ts';
+import { resolveAgentWriteback } from '../core/facts/writeback-settings.ts';
import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';
import { scopeDeniedError } from '../core/ops/op-fix.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
@@ -436,7 +437,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// extract_facts is advertised only when the resolved surface can
// actually call it (OV2-14; a verbs/starter-pinned serve must not
// order agents to call a tool dispatch will deny).
- const writeback = await resolveWritebackConfig(engine, fileConfig);
+ const writeback = (await resolveAgentWriteback(engine, fileConfig)).bundle;
const canWriteOp = (name: string) => hasScope(auth.auth!.scopes, 'write') && (!surfaceAllowedOps || surfaceAllowedOps.has(name));
return Response.json(
{
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index d5e559f535..51b7040340 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -131,6 +131,8 @@ function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOpts
}
out.push('Preserve the caller\'s brain and source scope. Do not broaden access, invent missing content, or write outside the requested task.');
if (c('forget')) out.push('`forget` withdraws active memory; it does not promise erasure of source material, history, or backups.');
+ // GBRA-219: after the governing rule, so it never pushes that rule past the 2,048 characters capped harnesses read; the tool's description carries the trigger phrases too.
+ if (c('memory_conversation_mode')) out.push('When the user asks to save everything from here, or to stop saving, call `memory_conversation_mode` and follow its rule for the rest of the conversation.');
out.push(`When you need this connection's effective permissions or setup readiness, read gbrain://capabilities${c('whoami') ? ' (or `whoami`)' : ''}. A full tool surface does not imply administrative or delegation authority. Missing capabilities require an explicit host grant.`);
out.push('MCP admin scope does not authorize the owner dashboard or client management. For an admin login link, client registration, setup instructions, permission edits, token invalidation, revocation, or deletion, use the mcp-access skill when available, or https://github.com/garrytan/gbrain/blob/master/docs/mcp/ADMIN.md directly. Ask the server-hosting harness or a separately authorized administrator to use gbrain mcp admin with the configured server URL and its protected owner credential. Native OAuth clients initiate their own PKCE connection; preserve oauth_request when requesting a login link, and never fetch a generated single-use login link before delivering it to the owner.');
if (c('join_brain') && c('sync_brain_skills')) {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 66e4930b0f..fa83127dcd 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -24,7 +24,8 @@ import { STATUS_TOOL_DEF, STATUS_TOOL_NAME, attemptStatusRecovery, statusHeadlin
import { installCapabilitiesResource, mcpAdministrationGuidance } from './capabilities.ts';
import { createSkillResources, type SkillResources } from './skill-resources.ts';
import { readLocalWriter, verifyLocalWriter } from '../core/persistence/identity.ts';
-import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
+import { ambientOptsFrom } from '../core/facts/writeback-config.ts';
+import { resolveAgentWriteback } from '../core/facts/writeback-settings.ts';
import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';
import { assertStdioSourceBindable } from './source-preflight.ts';
import { readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';
@@ -362,7 +363,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// F4 status-only mode: never touch the lazy engine at boot (its gated
// reconnect belongs to tool calls).
const statusMode = statusModeOf(engine);
- const writeback = statusMode ? null : await resolveWritebackConfig(engine, config);
+ const writeback = statusMode ? null : (await resolveAgentWriteback(engine, config)).bundle;
const writebackOpts = writeback ? ambientOptsFrom(writeback, {
remember: session.allowedOps ? session.allowedOps.has('remember') : true,
extractFacts: session.allowedOps ? session.allowedOps.has('extract_facts') : true,
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index b55529535e..76a1922ecd 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -109,6 +109,8 @@ export const STARTER_OPS: ReadonlySet<string> = new Set([
'join_brain', 'sync_brain_skills', 'leave_brain', 'put_skill', 'delete_skill',
// The dismissal for the coaching notices starter sessions receive (onboarding, features).
'mute_notice',
+ // GBRA-219: the per-conversation memory switch rides next to remember.
+ 'memory_conversation_mode',
]);
/**
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 0f55a875dc..e9edc96e3e 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 264473,
- "stdoutSha256": "f5647f0a0d45a36ed8685afa000792cef233379d012eeceec6fa2f9366d1b0ee",
+ "stdoutBytes": 266680,
+ "stdoutSha256": "6852cc9ef243f970c7620122d098f07e6b231a8ac6396c7ce3c8fd094e9bf121",
"toolNames": [
"remember",
"entity",
@@ -156,6 +156,9 @@
"purge_fact",
"list_page_purges",
"unpurge_page",
+ "get_memory_settings",
+ "set_memory_writeback",
+ "memory_conversation_mode",
"find_contradictions",
"find_experts",
"find_trajectory",
@@ -7089,6 +7092,86 @@
},
"scope": "admin"
},
+ {
+ "description": "Memory writeback settings: the mode agents follow, the exact rule text, every mode's rule, background capture state, and whether you may change it.",
+ "idempotent": false,
+ "local_only": false,
+ "mutating": false,
+ "name": "get_memory_settings",
+ "parameters": {},
+ "required_scopes": [],
+ "schema": {
+ "properties": {},
+ "required": [],
+ "type": "object"
+ },
+ "scope": "read"
+ },
+ {
+ "description": "Change the brain-wide writeback mode agents are told to follow (inherit uses the operator's setting). Admin scope and the operator's grant required; background capture is not changed.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
+ "name": "set_memory_writeback",
+ "parameters": {
+ "dry_run": "boolean?",
+ "mode": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "dry_run": {
+ "description": "Preview the change; writes nothing.",
+ "type": "boolean"
+ },
+ "mode": {
+ "description": "inherit | off | salient | all.",
+ "enum": [
+ "inherit",
+ "off",
+ "salient",
+ "all"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "mode"
+ ],
+ "type": "object"
+ },
+ "scope": "admin"
+ },
+ {
+ "description": "Use when the user says \"save everything from here\" (all) or \"stop saving\" (off: explicit saves only): returns the memory rule for the rest of this conversation. Stores nothing.",
+ "idempotent": false,
+ "local_only": false,
+ "mutating": false,
+ "name": "memory_conversation_mode",
+ "parameters": {
+ "mode": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "mode": {
+ "description": "all | salient | off (only what the user explicitly asks to keep) | brain (this brain's mode).",
+ "enum": [
+ "brain",
+ "off",
+ "salient",
+ "all"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "mode"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
{
"description": "Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. Remote, source-scoped or min_trust callers get only findings whose two sides they can read now (each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. Reads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",
"idempotent": true,
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 2e3df1bd62..ee05241d77 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6429,7 +6429,7 @@
"name: string",
"outputRedaction: OutputRedactionPolicy",
"params: Record<string, ParamDef>",
- "publishGateKey?: \"mcp.publish_skills\" | \"mcp.publish_advisor\" | undefined",
+ "publishGateKey?: \"mcp.publish_skills\" | \"mcp.publish_advisor\" | \"mcp.publish_memory_settings\" | undefined",
"requiredScopes?: readonly string[] | undefined",
"scope?: \"agent\" | \"read\" | \"write\" | \"admin\" | \"sources_admin\" | \"users_admin\" | undefined",
"verb?: boolean | undefined",
@@ -6478,7 +6478,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/mcp-initialize-instructions.test.ts b/test/mcp-initialize-instructions.test.ts
index 2d1a7749be..3edc76f4c4 100644
--- a/test/mcp-initialize-instructions.test.ts
+++ b/test/mcp-initialize-instructions.test.ts
@@ -49,7 +49,13 @@ const BATCHING_CLAUSE_BYTES = 200;
* `entity names` rows carry on this brain (`next`, and `records` when record types are enrolled); 70 bytes at most.
*/
const NAMES_ROW_REFERENCES_BYTES = 70;
-const LANE_I_CEILING = Math.floor(PRE_F1_BYTES * 1.15) + WRITING_CLAUSE_BYTES + BATCHING_CLAUSE_BYTES + NAMES_ROW_REFERENCES_BYTES;
+/**
+ * GBRA-219: the per-conversation memory switch clause ("save everything from here" / "stop saving" →
+ * memory_conversation_mode), 146 bytes on every surface serving the tool (starter and full), placed after the
+ * governing rule so that rule's offsets do not move (test/mcp-instructions-governing-rule.test.ts).
+ */
+const CONVERSATION_SWITCH_CLAUSE_BYTES = 150;
+const LANE_I_CEILING = Math.floor(PRE_F1_BYTES * 1.15) + WRITING_CLAUSE_BYTES + BATCHING_CLAUSE_BYTES + NAMES_ROW_REFERENCES_BYTES + CONVERSATION_SWITCH_CLAUSE_BYTES;
/** Claude Code reads only the first 2,048 characters of a server's initialize instructions. */
const HARNESS_READ_LIMIT = 2_048;
@@ -102,8 +108,9 @@ describe('F1 generated instructions', () => {
// d5b: the brief names the fields compact `entity names` rows carry (NAMES_ROW_REFERENCES_BYTES): +39 at the default
// (names-row references on, no records) on every surface serving entity; +70 with records enrolled (maximal).
// F4: instruction 7's governing rule (in effect on the date asked about), +63 on starter and full; verbs serves no clause 7.
- const recorded = { verbs: 2_225, starter: 4_926, full: 5_077 };
- const maximal = { verbs: 2_256, starter: 4_957, full: 5_108 };
+ // GBRA-219: the conversation-switch clause (CONVERSATION_SWITCH_CLAUSE_BYTES), +145 on starter and full; verbs does not serve the tool.
+ const recorded = { verbs: 2_225, starter: 5_071, full: 5_223 };
+ const maximal = { verbs: 2_256, starter: 5_102, full: 5_254 };
for (const surface of SURFACES) {
const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));
const size = buildMcpInstructions({ tools: { callable: n => listed.has(n) } }).length;
@@ -127,7 +134,7 @@ describe('F1 generated instructions', () => {
expect(text).toContain('worker missing: 3 jobs');
expect(text).not.toContain('keyless by choice');
expect(text).not.toContain('Schema is behind');
- expect(Buffer.byteLength(text) - PRE_F1_BYTES).toBeLessThanOrEqual(1200 + WRITING_CLAUSE_BYTES);
+ expect(Buffer.byteLength(text) - PRE_F1_BYTES).toBeLessThanOrEqual(1200 + WRITING_CLAUSE_BYTES + CONVERSATION_SWITCH_CLAUSE_BYTES);
});
for (const surface of SURFACES) {
diff --git a/test/memory-settings.test.ts b/test/memory-settings.test.ts
new file mode 100644
index 0000000000..e77524ab7d
--- /dev/null
+++ b/test/memory-settings.test.ts
@@ -0,0 +1,301 @@
+/**
+ * GBRA-219: memory writeback settings over MCP. Every case runs on a keyless,
+ * in-memory PGLite brain with no git repository (repo-less brains are first
+ * class): the settings live in the config table and the audit row in the
+ * request log.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { operations } from '../src/core/operations.ts';
+import { disabledOpsForPublishGates } from '../src/mcp/publish-gates.ts';
+import { isCallable } from '../src/core/ops/callable.ts';
+import { buildMcpInstructions } from '../src/mcp/instructions.ts';
+import { buildAmbientWritebackSection } from '../src/core/facts/writeback-instructions.ts';
+import { ambientOptsFrom, captureLaneStates, resolveWritebackConfig } from '../src/core/facts/writeback-config.ts';
+import { resolveAgentWriteback } from '../src/core/facts/writeback-settings.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+const CONFIG = { engine: 'pglite' } as GBrainConfig;
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const auth = (scopes: string[], extra: Partial<AuthInfo> = {}): AuthInfo => ({ token: 't', clientId: 'client-a', scopes, ...extra }) as AuthInfo;
+
+async function call(name: string, params: Record<string, unknown>, opts: { scopes?: string[]; auth?: AuthInfo; remote?: boolean } = {}) {
+ const res = await dispatchToolCall(engine, name, params, {
+ remote: opts.remote ?? true,
+ transport: 'http',
+ config: CONFIG,
+ auth: opts.auth ?? auth(opts.scopes ?? ['admin']),
+ sourceId: 'default',
+ });
+ return { isError: res.isError === true, body: JSON.parse(res.content[0].text) as Record<string, any> };
+}
+
+async function auditRows(): Promise<Array<{ params: Record<string, unknown> }>> {
+ return engine.executeRaw(`SELECT params FROM mcp_request_log WHERE operation = 'memory_setting_change' ORDER BY id`) as never;
+}
+
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+describe('set_memory_writeback: operator grant + admin scope', () => {
+ test('gate unset: hidden from the catalog and refused at call time; nothing written', async () => {
+ const disabled = await disabledOpsForPublishGates(engine, CONFIG);
+ expect(disabled.has('set_memory_writeback')).toBe(true);
+ const gates = { 'mcp.publish_memory_settings': false };
+ expect(isCallable(op('set_memory_writeback'), { transport: 'http', surface: 'full', scopes: ['admin'], publishGates: gates })).toBe(false);
+ const res = await call('set_memory_writeback', { mode: 'all' });
+ expect(res.isError).toBe(true);
+ expect(JSON.stringify(res.body)).toContain('mcp.publish_memory_settings');
+ expect(await engine.getConfig('memory.agent_writeback')).toBeNull();
+ expect(await auditRows()).toHaveLength(0);
+ });
+
+ test('gate on: write scope is not enough, admin scope changes only the agent override', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ expect(isCallable(op('set_memory_writeback'), { transport: 'http', surface: 'full', scopes: ['read', 'write'], publishGates: { 'mcp.publish_memory_settings': true } })).toBe(false);
+ const denied = await call('set_memory_writeback', { mode: 'all' }, { scopes: ['read', 'write'] });
+ expect(denied.isError).toBe(true);
+ expect(await engine.getConfig('memory.agent_writeback')).toBeNull();
+
+ const ok = await call('set_memory_writeback', { mode: 'salient' });
+ expect(ok.isError).toBe(false);
+ expect(ok.body.applied).toBe(true);
+ expect(ok.body.background_capture_unchanged).toBe(true);
+ expect(await engine.getConfig('memory.agent_writeback')).toBe('salient');
+ expect(await engine.getConfig('memory.auto_writeback')).toBeNull();
+ const rows = await auditRows();
+ expect(rows).toHaveLength(1);
+ expect(rows[0].params).toMatchObject({ key: 'memory.agent_writeback', actor: 'client-a', old: null, new: 'salient', transport: 'http' });
+ });
+
+ test('remote off then remote salient never moves the host capture lanes', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ const before = captureLaneStates(await resolveWritebackConfig(engine, CONFIG, { gate: true }));
+ expect((await call('set_memory_writeback', { mode: 'off' })).isError).toBe(false);
+ expect(captureLaneStates(await resolveWritebackConfig(engine, CONFIG, { gate: true }))).toEqual(before);
+ expect((await call('set_memory_writeback', { mode: 'salient' })).isError).toBe(false);
+ expect(captureLaneStates(await resolveWritebackConfig(engine, CONFIG, { gate: true }))).toEqual(before);
+ expect(await engine.getConfig('memory.auto_writeback')).toBe('salient');
+ });
+
+ test('a restrictive override says background capture keeps running', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ await engine.setConfig('memory.auto_writeback', 'all');
+ const res = await call('set_memory_writeback', { mode: 'off' });
+ expect(res.body.effective_mode).toBe('off');
+ expect(res.body.note).toContain('keeps running');
+ });
+
+ test('dry_run writes neither the setting nor an audit row', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ const res = await call('set_memory_writeback', { mode: 'all', dry_run: true });
+ expect(res.body).toMatchObject({ applied: false, dry_run: true, requested: 'all', previous: 'inherit' });
+ expect(await engine.getConfig('memory.agent_writeback')).toBeNull();
+ expect(await auditRows()).toHaveLength(0);
+ });
+
+ test('setting and audit commit together: a failed audit insert leaves the setting unchanged and says the outcome is unknown', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ await engine.executeRaw('ALTER TABLE mcp_request_log RENAME TO mcp_request_log_gone');
+ let res: Awaited<ReturnType<typeof call>>;
+ try {
+ res = await call('set_memory_writeback', { mode: 'all' });
+ } finally {
+ await engine.executeRaw('ALTER TABLE mcp_request_log_gone RENAME TO mcp_request_log');
+ }
+ expect(res.isError).toBe(true);
+ expect(JSON.stringify(res.body)).toContain('memory_setting_write_outcome_unknown');
+ expect(JSON.stringify(res.body)).toContain('get_memory_settings');
+ expect(await engine.getConfig('memory.agent_writeback')).toBeNull();
+ });
+
+ test('the trusted local CLI needs no grant', async () => {
+ const res = await call('set_memory_writeback', { mode: 'all' }, { remote: false });
+ expect(res.isError).toBe(false);
+ expect(await engine.getConfig('memory.agent_writeback')).toBe('all');
+ });
+});
+
+describe('resolveAgentWriteback: the override never widens on doubt', () => {
+ test('inherit and unset follow the operator; a valid override wins', async () => {
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ expect((await resolveAgentWriteback(engine, CONFIG)).bundle.mode).toBe('salient');
+ await engine.setConfig('memory.agent_writeback', 'inherit');
+ expect((await resolveAgentWriteback(engine, CONFIG)).bundle.mode).toBe('salient');
+ await engine.setConfig('memory.agent_writeback', 'off');
+ const off = await resolveAgentWriteback(engine, CONFIG);
+ expect(off.bundle).toMatchObject({ mode: 'off', enabled: false });
+ expect(off.operator.mode).toBe('salient');
+ expect(off.status).toBe('ok');
+ });
+
+ test('an unrecognized override fails closed to off, degraded', async () => {
+ await engine.setConfig('memory.auto_writeback', 'all');
+ await engine.setConfig('memory.agent_writeback', 'everything');
+ const r = await resolveAgentWriteback(engine, CONFIG);
+ expect(r).toMatchObject({ source: 'fail_closed', status: 'degraded' });
+ expect(r.bundle.mode).toBe('off');
+ expect(r.reasons).toContain('agent_override_invalid');
+ });
+
+ test('an unreadable override with no last-known-good fails closed to off', async () => {
+ const real = engine.getConfig.bind(engine);
+ const flaky = Object.create(engine) as PGLiteEngine;
+ flaky.getConfig = async (key: string) => {
+ if (key === 'memory.agent_writeback') throw new Error('config read failed');
+ return key === 'memory.auto_writeback' ? 'all' : real(key);
+ };
+ const r = await resolveAgentWriteback(flaky, CONFIG);
+ expect(r.bundle.mode).toBe('off');
+ expect(r.reasons).toContain('agent_override_unreadable');
+ });
+});
+
+describe('resolveAgentWriteback: cold failures', () => {
+ test('an operator read failure with no last-known-good never emits an enabled rule on default posture', async () => {
+ await engine.setConfig('memory.agent_writeback', 'all');
+ await engine.setConfig('facts.default_visibility', 'private');
+ const real = engine.getConfig.bind(engine);
+ const cold = Object.create(engine) as PGLiteEngine;
+ cold.getConfig = async (key: string) => {
+ if (key === 'facts.default_visibility' || key === 'memory.auto_writeback') throw new Error('config read failed');
+ return real(key);
+ };
+ const r = await resolveAgentWriteback(cold, CONFIG);
+ expect(r.bundle.enabled).toBe(false);
+ expect(r).toMatchObject({ source: 'fail_closed', status: 'degraded' });
+ });
+
+ test('a confirmed restrictive write replaces the cached override, so a later read failure cannot revive the old one', async () => {
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ await call('set_memory_writeback', { mode: 'all' });
+ expect((await resolveAgentWriteback(engine, CONFIG)).bundle.mode).toBe('all');
+ await call('set_memory_writeback', { mode: 'off' }, { remote: false });
+ const real = engine.getConfig;
+ engine.getConfig = async (key: string) => {
+ if (key === 'memory.agent_writeback') throw new Error('config read failed');
+ return real.call(engine, key);
+ };
+ try {
+ expect((await resolveAgentWriteback(engine, CONFIG)).bundle.mode).toBe('off');
+ } finally {
+ engine.getConfig = real;
+ }
+ });
+});
+
+describe('get_memory_settings', () => {
+ test('rule text matches what initialize renders; off has none; every mode is previewable', async () => {
+ const off = await call('get_memory_settings', {}, { scopes: ['read', 'write'] });
+ expect(off.body.effective_mode).toBe('off');
+ expect(off.body.rule_text).toBeNull();
+ expect(off.body.rule_texts.salient).toContain('mode: salient');
+ expect(off.body.rule_texts.all).toContain('mode: all');
+ expect(off.body.operator_mode).toEqual({ mode: 'off', explicit: false });
+
+ await engine.setConfig('memory.agent_writeback', 'salient');
+ const on = await call('get_memory_settings', {}, { scopes: ['read', 'write'] });
+ const bundle = (await resolveAgentWriteback(engine, CONFIG)).bundle;
+ const rendered = buildMcpInstructions({ writeback: ambientOptsFrom(bundle, { remember: true, extractFacts: true }) });
+ expect(on.body.rule_text).toBe(buildAmbientWritebackSection({ mode: 'salient', transientTtl: '3d', visibility: 'world', extractFactsAvailable: true }));
+ expect(rendered).toContain(on.body.rule_text);
+ expect(on.body.source).toBe('agent_override');
+ });
+
+ test('can_set names the missing grant with the operator command; conversation switch needs remember', async () => {
+ const reader = await call('get_memory_settings', {}, { scopes: ['read'] });
+ expect(reader.body.can_set).toMatchObject({ allowed: false, blocked_by: ['gate_off', 'scope'] });
+ expect(JSON.stringify(reader.body.can_set.fix)).toContain('mcp.publish_memory_settings');
+ expect(reader.body.conversation_switch.available).toBe(false);
+ expect(reader.body.rule_text).toBeNull();
+
+ await engine.setConfig('mcp.publish_memory_settings', 'true');
+ const writer = (await call('get_memory_settings', {}, { scopes: ['read', 'write'] })).body.can_set;
+ expect(writer).toMatchObject({ allowed: false, blocked_by: ['scope'] });
+ expect(writer.fix).toBeUndefined();
+ expect((await call('get_memory_settings', {})).body.can_set).toEqual({ allowed: true });
+ });
+
+ test('a degraded read says so instead of reporting a plain off', async () => {
+ await engine.setConfig('memory.agent_writeback', 'bogus');
+ const res = await call('get_memory_settings', {}, { scopes: ['read'] });
+ expect(res.body.status).toBe('degraded');
+ expect(res.body.note).toContain('not proof');
+ });
+});
+
+describe('memory_conversation_mode', () => {
+ test('all returns a conversation rule with the brain\'s private posture, even when the operator set off; nothing is stored', async () => {
+ await engine.setConfig('memory.auto_writeback', 'off');
+ await engine.setConfig('facts.default_visibility', 'private');
+ const before = await engine.executeRaw('SELECT key, value FROM config ORDER BY key');
+ const res = await call('memory_conversation_mode', { mode: 'all' }, { scopes: ['read', 'write'] });
+ expect(res.isError).toBe(false);
+ expect(res.body).toMatchObject({ mode: 'all', persisted: false, applies_to: 'this_conversation', background_capture_unchanged: true });
+ expect(res.body.rule_text).toContain('for the rest of this conversation');
+ expect(res.body.rule_text).toContain('visibility: "private"');
+ expect(await engine.executeRaw('SELECT key, value FROM config ORDER BY key')).toEqual(before);
+ });
+
+ test('off returns the explicit-only rule and is honest about host capture', async () => {
+ await engine.setConfig('memory.agent_writeback', 'all');
+ const res = await call('memory_conversation_mode', { mode: 'off' }, { scopes: ['write'] });
+ expect(res.body.effective_mode).toBe('off');
+ expect(res.body.rule_text).toContain('only what the user explicitly asks you to keep');
+ expect(res.body.rule_text).toContain('background capture');
+ });
+
+ test('brain returns the brain\'s effective rule', async () => {
+ await engine.setConfig('memory.agent_writeback', 'salient');
+ const res = await call('memory_conversation_mode', { mode: 'brain' }, { scopes: ['write'] });
+ expect(res.body.effective_mode).toBe('salient');
+ expect(res.body.rule_text).toContain('enabled by this brain');
+ });
+
+ test('a read-only connection is refused; an invalid mode is never repaired into another mode', async () => {
+ const ro = await call('memory_conversation_mode', { mode: 'all' }, { scopes: ['read'] });
+ expect(ro.isError).toBe(true);
+ const bound = await call('memory_conversation_mode', { mode: 'all' }, { auth: auth(['read', 'write'], { boundSlugPrefixes: ['people/alice-example'] } as Partial<AuthInfo>) });
+ expect(bound.isError).toBe(true);
+ const bad = await call('memory_conversation_mode', { mode: 'pause' }, { scopes: ['write'] });
+ expect(bad.isError).toBe(true);
+ expect(JSON.stringify(bad.body)).not.toContain('"tool":"memory_conversation_mode"');
+ });
+});
+
+describe('initialize instructions', () => {
+ test('the switch clause appears only when the tool is callable, after the governing rule', () => {
+ const withIt = buildMcpInstructions({ tools: { callable: () => true } });
+ const at = withIt.indexOf('memory_conversation_mode');
+ expect(at).toBeGreaterThan(withIt.indexOf('The record whose terms are in effect'));
+ expect(withIt).toContain('save everything from here, or to stop saving');
+ const without = buildMcpInstructions({ tools: { callable: n => n !== 'memory_conversation_mode' } });
+ expect(without).not.toContain('memory_conversation_mode');
+ });
+
+ test('an agent override turns the ambient section on even while the operator mode is unset', async () => {
+ await engine.setConfig('memory.agent_writeback', 'all');
+ const bundle = (await resolveAgentWriteback(engine, CONFIG)).bundle;
+ const text = buildMcpInstructions({ writeback: ambientOptsFrom(bundle, { remember: true, extractFacts: true }) });
+ expect(text).toContain('Ambient memory writeback (enabled by this brain');
+ expect(captureLaneStates(await resolveWritebackConfig(engine, CONFIG, { gate: true })).writeback).toBe('retire');
+ });
+});
diff --git a/test/publish-gates.test.ts b/test/publish-gates.test.ts
index 49c0e13779..e7d63cd4bb 100644
--- a/test/publish-gates.test.ts
+++ b/test/publish-gates.test.ts
@@ -11,7 +11,7 @@ import { operations, opAllowedForBoundClient, CLIENT_FENCED_WRITE_OPS } from '..
import type { BrainEngine } from '../src/core/engine.ts';
import type { GBrainConfig } from '../src/core/config.ts';
-const GATED_OPS = ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack', 'advisor'];
+const GATED_OPS = ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack', 'advisor', 'set_memory_writeback'];
function engineWithConfig(values: Record<string, string | null> | 'throws'): BrainEngine {
return {
@@ -23,7 +23,7 @@ function engineWithConfig(values: Record<string, string | null> | 'throws'): Bra
}
describe('publish-gates: gate declaration', () => {
- test('exactly the four gated ops carry publishGateKey', () => {
+ test('exactly the gated ops carry publishGateKey', () => {
const declared = operations.filter(o => o.publishGateKey).map(o => o.name).sort();
expect(declared).toEqual([...GATED_OPS].sort());
});