Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
storage manifest: managed storage source, validated cards and find/get/list/register/update verbs (GBRA-387 PR 1)
garrytanae62eb74f02c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f00d5b0f5c..8882a9b8ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**A storage manifest: agents can register what they archived to object storage and find it again later.** A new `storage` source holds one validated card per archived item: what it is, where every copy lives (store, bucket, path, restic repository and snapshot, size, file count, hash and its kind, when it was verified), where it came from and which skill restores it. `gbrain storage-register` adds a card (from stdin or `--card`) and never overwrites one; `gbrain storage-update <id> --expected-revision <rev>` patches a card bound to the revision it read and records restores newest first; `gbrain storage-find "<words>"` ranks the exact id, then an exact alias, then the cards holding most of the words, and a miss lists the closest cards; `gbrain storage-get` and `gbrain storage-list` read. On a brain with a Git checkout, `gbrain storage init` hosts the shelf in its own repository first (preview, then `--expect <plan_hash>`; it needs managed persistence), so each card is a commit before it is indexed. A repo-less brain gets a database-only shelf on the first register.++Cards never carry credentials or commands. A card is refused when any field looks like a secret, an environment assignment, a credential variable, a URL with user info or a presigned URL, or when any key is named `command`, `cmd`, `script`, `exec`, `shell` or `instructions`; the refusal never echoes the value. A restore is `{ skill, args }` with flat scalar arguments. gbrain stamps `registered_by` and `origin` itself, and holds no store credentials.++The shelf is written only through the storage verbs. `put_page`, `remember` and every other page writer are refused `storage_source_managed` there, a request parameter cannot open the door, register and update run only from the trusted local CLI, and a dream cycle or enrichment run scoped to the shelf skips it. The source is not federated: a remote connection reads cards only when its grant names `storage`.++### Itemized changes++- `src/core/storage-manifest/` (`schema.ts`, `door.ts`, `source.ts`, `find.ts`) and `src/core/ops/storage-manifest.ts`: the card schema and secret checks, the write door, the source lifecycle (`storage init`), keyless ranked lookup (exact id, `page_aliases`, word matches, `pg_trgm` closest cards) and the five ops `storage_find`, `storage_get`, `storage_list`, `storage_register`, `storage_update`.+- `src/core/persistence/page-mutations.ts`, `src/core/persistence/memory-mutations.ts`: the page door and `remember`/`forget` refuse writers other than the storage verbs on a source with `role: storage_manifest`; the owner's import of commits already in the hosted repository still syncs.+- `src/core/cycle.ts`, `src/commands/enrich.ts`: a cycle scoped to the storage source returns `skipped` with reason `storage_manifest_source`; enrichment considers no card there.+- `src/core/error-registry.ts`, `docs/guides/write-refusals.md`, `docs/guides/error-codes.md`: `storage_source_managed`, `storage_manifest_missing`, `storage_record_invalid`, `storage_record_secret`, `storage_card_exists` and `storage_revision_conflict`, each with its recovery path. Remote register and update refuse with the shared `trusted_local_only`.+- `src/commands/storage.ts`: `gbrain storage init`; the help separates the tiers report (`status`) from the shelf verbs.+- Goldens: `test/fixtures/goldens/cli/tools-json.json` gains the three read tools; `test/fixtures/goldens/exports/types.json` gains the new error codes in the `canonical` union and lists `ThinkSynthesisStatus` in a new order (the new schema module declares the `not_json` literal first; the type is unchanged).+- Tests: `test/storage-manifest.test.ts` (PGLite, repo-less) and `test/storage-manifest-hosted.serial.test.ts` (managed PGLite with a Git checkout).+## [0.60.617.0] - 2026-11-08**Older URL sources can get the same reclone settings as new ones remote callers add.** URL sources added before gbrain recorded who added them carry no record, and nothing stored tells a remote caller's add from the local operator's, so their reclones used the clone settings of a local add. The new doctor check `url_source_origin` lists them and asks the user who added each one. `gbrain sources record-origin <id>... --remote|--local` records that answer, as a preview until `--apply`. A URL source the local operator adds from now on records that it was a local add, so doctor never asks about it. With `--remote`, every later reclone of the source clones with git-lfs downloads and hooks off, like a source a remote caller adds today. A checkout that tracks git-lfs files is refused, because changing its settings would make the next reclone fail to match its canonical content. Nothing changes on upgrade.diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 06983e1c48..d258aacfe6 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: 171 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.+Every non-localOnly operation on the MCP surface: 174 tools across 27 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@@ -278,6 +278,14 @@ Every non-localOnly operation on the MCP surface: 171 tools across 26 areas. **S| `sources_resolve_path` | Read-only: what gbrain did with each file path of a source, by its own rules. | read | | || `sources_status` | Per-source diagnostic. | read | | |+## storage++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `storage_find` | Find archived items on the storage shelf (files moved to B2, Supabase Storage, S3 and similar) by a plain phrase, such as "the October Gmail dataset". | read | | |+| `storage_get` | Read one card from the storage shelf by id: what the item is, every stored copy (store, bucket, path, restic repository and snapshot, size, hash, when verified), the original path, why it was archived, the restore form (restore.skill and restore.args, run by the agent's own restore skill; cards carry no commands or credentials), past restores, who registered it, and its revision. | read | | |+| `storage_list` | List cards on the storage shelf, sorted by id, optionally filtered by store, status or whether a copy is still on the source machine. | read | | |+## tags| Tool | Description | Scope | Starter | Gate |diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 3038d6c9c0..b1b9b0ba62 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4702,6 +4702,16 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### storage_card_exists++<a id="storage_card_exists"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A storage card with this id is already on the storage shelf; nothing was written. | Registering never overwrites a card, so two archives cannot silently share one id; a change to an existing card names the revision it read. | Change the card with gbrain storage-update <id> --expected-revision <revision from storage_get>, or register the new item under another id. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)+### storage_error<a id="storage_error"></a>@@ -4714,6 +4724,60 @@ Reasons: `database_contention`.Override: reason `database_contention`: retryable, exit 1, retryable.+### storage_manifest_missing++<a id="storage_manifest_missing"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This brain has no storage shelf to write to (or the storage source ID belongs to another source); nothing was written. | On a brain with a Git checkout the shelf is a hosted git-canonical repository, created only after the user previews it, and hosting needs managed persistence. A repo-less brain gets its database-only shelf on the first register. | Preview gbrain storage init --dir <absolute path> --dry-run and apply the command it prints after the user agrees. | user | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)++### storage_record_invalid++<a id="storage_record_invalid"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A storage card failed validation (a missing or malformed field, a command field, or a field gbrain stamps itself); nothing was written. | Every card must say where the item is, how big it is and how to restore it, and carries no commands, so a card is complete and safe to act on when it is found months later. | Fix the field the message names and send the card again; gbrain storage-register --help lists the card fields. | agent | `repeat the read that failed` | 1 | no |++Reasons: `schema`, `command_field`, `stamped_field`, `not_json`, `not_object`, `too_large`, `id_change`.++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)++### storage_record_secret++<a id="storage_record_secret"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A storage card field looks like a secret or has a credential shape; nothing was written and the value is not echoed. | Cards are read by agents and copied into the stores; credentials stay in the environment of the skill that restores an item. | Remove the secret, environment assignment, credential variable, URL password or signed-URL parameter from the named field. | agent | `repeat the read that failed` | 1 | no |++Reasons: `secret_scanner`, `env_assignment`, `credential_variable`, `url_userinfo`, `presigned_url`.++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)++### storage_revision_conflict++<a id="storage_revision_conflict"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A storage card changed since the revision the update named was read; nothing was written. | Updates bind to the revision they read, so two writers never silently overwrite each other; the refusal carries the current revision in detail. | Read the card again with storage_get, apply the change to what it says now, and update once with its revision. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)++### storage_source_managed++<a id="storage_source_managed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A page write targeted the storage shelf outside the storage verbs; nothing was written. | The storage source holds only validated cards, so put_page, remember and the other page writers are refused there. | Register cards with gbrain storage-register and change them with gbrain storage-update. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#storage-manifest-refusals](../../docs/guides/write-refusals.md#storage-manifest-refusals)+### store_unavailable<a id="store_unavailable"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 3ca4d90688..1daf57b496 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1074,6 +1074,20 @@ Links and the right live in the database, so they are the same on a repo-less br| <a id="source_not_attested"></a>`permission_denied` reason `source_not_attested` / `scope_page_not_shared`, `invalid_params` reason `source_is_member_source` | A scope `memory_write` (`source_id`, contract v2) named a source that is not in the credential's `--attest-sources` or not a marked scope source (also when a queued write publishes after the source was dropped), or its own write source; or the scope's `memory/scope` page names readers, is private or sits under a folder rule. Nothing was written. | The operator lists the source with `gbrain auth rescope --client <id> --attest-sources <list>`, or removes `readable_by` / `visibility: private` / the folder rule from `memory/scope`. For the person's own page, leave `source_id` out. See [shared scopes](qm.md#shared-scopes-projects-channels-teams). || <a id="actor_unlinked"></a>`actor_unlinked` | The id is not linked to an enabled member: never linked, unlinked, or the member is disabled or removed. Ids compare exactly, with no case folding. Nothing was read or written. A queued write or agent job made for the person is refused the same way when its link is gone or now names another member. `memory_recall` answers it as an empty success instead (`structuredContent: {facts: [], truncated: false, code: "actor_unlinked"}`), so a person not yet linked reads nothing. | The brain operator links it: `gbrain access member link <member> --qm <id>` (or `gbrain access member enable <member>`). |+## Storage manifest refusals++The storage shelf (source `storage`) holds one validated card per item an agent archived to object storage.+Only `gbrain storage-register` and `gbrain storage-update` write it, from the trusted local CLI.++| Code | What happened | What to do |+|---|---|---|+| `storage_source_managed` | `put_page`, `remember` or another page writer targeted the shelf. | Register with `gbrain storage-register`, change with `gbrain storage-update`. |+| `storage_record_invalid` | A card field is missing or malformed, names a command (`command`, `script`, `exec` and similar), or is one gbrain sets itself (`registered_by`, `origin`). | Fix the field the message names. Restore runs through `restore.skill` and `restore.args`. |+| `storage_record_secret` | A field looks like a secret or has a credential shape: an environment assignment, a credential-named variable, a URL password or a signed-URL parameter. The value is not echoed. | Remove it; the restore skill reads credentials from its own environment. |+| `storage_card_exists` | A card with that id is already registered. | Update it with the revision `storage_get` returns, or use another id. |+| `storage_revision_conflict` | The card changed since its revision was read; `detail` holds the current revision. | Read it again, apply the change, update once. |+| `storage_manifest_missing` | No shelf yet on a brain with a Git checkout, or the `storage` source ID belongs to another source. | Preview `gbrain storage init --dir <path> --dry-run` and apply it after the user agrees (it needs managed persistence). |+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/plugin/README.md b/plugin/README.mdindex f787d7de44..a744d36552 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` — 194+The plugin's MCP server runs `gbrain serve --surface full` — 199operations, the same surface every stdio registration gbrain writes pins.Every gbrain operation the bundled skills name is on it. A harness that capsits tool count can narrow this machine's plugin surface withdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bf60517f18..66eacd1db2 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,13 +13,13 @@ src/commands/jobs.ts 693 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 947 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts); +4 GBRA-199: serve --http --advertise parse, help line and pass-through (logic in mcp/surface.ts parseAdvertiseFlag); +6 GBRA-283 B3a: runServeHttp enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot movesrc/core/ai/gateway.ts 4571 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts); +7 GBRA-283 B3a: every embed/chat/expand/rerank/toolLoop entry and requireConfig/configFor call refuseUnscoped (predicate and refusal in ai/engine-gateway.ts), the unscoped state, and the shrink/no_key/structured-output memory read through gw() (state in ai/engine-gateway.ts GatewayState)src/commands/sync.ts 566 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts); +2 #7866: SyncOpts.fullRound interface field and its doc comment (internal: the conversion strict passes in persistence/git-conversion.ts set it; read in persistence/sync-pass-run.ts); +1 #8007: SyncResult.storage_invalid_kept interface field (the keep lives in persistence/sync-discovery.ts); +2 GBRA-287: SyncResult.reexport_failures interface field (the re-export lives in commands/sync/full.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (564 measured); +2 convergence PR A: SyncOpts.conversionBinding interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-pass.ts bindConversion)-src/core/cycle.ts 3351 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures)+src/core/cycle.ts 3353 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures); +2 GBRA-387 storage manifest: dream skips a cycle scoped to the storage shelf (check in storage-manifest/door.ts)src/core/cycle/synthesize.ts 3244 ratchet +3 #7805: each captured session synthesizes only into its own frozen source (routing import, the outer wrapper, the routing parameter; logic in cycle/synthesize-source-routing.ts); +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guardsrc/core/engine.ts 2874 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); 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); 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); re-summed at the memory train #8481 merge with v0.60.576.0 (2874 measured)src/core/import-file.ts 2088 ratchet +2 #7880: importFromContent's holdNoncanonicalPrivate option (interface field; the hold is screenImportContent's); +2 #7848: importFromFile holds a non-canonical private request (predicate and hold in persistence/visibility-request.ts); +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; +7 GBRA-283 B3a (#8523): the three file import entry points re-enter an embedded engine's scope (needsEngineScope in core/engine-scope.ts), importFromContent runs its screened body in that scope as a closure, and the deferred embed resumes the import's scope; re-summed at the memory train #8481 merge with v0.60.576.0 (2088 measured)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 249 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 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line)+src/core/operations.ts 250 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 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line); +1 GBRA-387 storage manifest: storageManifestOperations import (ops/storage-manifest.ts; its spread shares the files line)src/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.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); +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); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +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); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4src/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.tsdiff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex bd03e11ed4..41a3919d7a 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -512,6 +512,7 @@ export async function runEnrichCore(pages_failed: 0,};+ if (await (await import('../core/storage-manifest/door.ts')).isStorageManifestSource(engine, opts.sourceId)) return result;const sourceId = opts.sourceId;const types = opts.types && opts.types.length > 0 ? opts.types : DEFAULT_TYPES;const order: EnrichOrder = ENRICH_ORDERS.includes(opts.order as EnrichOrder)diff --git a/src/commands/storage.ts b/src/commands/storage.tsindex 1270b387b9..ab4587a028 100644--- a/src/commands/storage.ts+++ b/src/commands/storage.ts@@ -49,15 +49,30 @@ export interface StorageStatusResult {// #3686: real usage, reachable via `gbrain storage --help` (the generic// one-line CLI_ONLY stub used to shadow this surface entirely).-const STORAGE_HELP = `gbrain storage — storage-tier status for the brain repo+const STORAGE_HELP = `gbrain storage — storage tiers of the brain repo, and the storage shelfUSAGEgbrain storage [status] [--repo <path>] [--json]+ gbrain storage init [--dir <path>] [--push-remote <url>] [--dry-run | --expect <plan_hash>] [--json]SUBCOMMANDSstatus (default) Report page counts and disk usage per storagetier, list DB pages whose repo file is missing, andvalidate the storage config.+ init Create the storage shelf: the source that holds one card+ per item archived to object storage (B2, Supabase Storage,+ S3). A repo-less brain gets a database-only source (the+ first storage-register also creates it). A brain with a+ Git checkout gets a hosted git-canonical repository under+ --dir, which needs managed persistence; preview first and+ apply the printed command after the user agrees.++THE STORAGE SHELF (separate commands)+ gbrain storage-find "<phrase>" Find a card; closest cards when none match+ gbrain storage-get <id> One card: copies, restore form, revision+ gbrain storage-list Cards, filtered by --store / --status+ gbrain storage-register --card <json> Register a verified archive (local only)+ gbrain storage-update <id> --expected-revision <rev> [--patch <json>] [--restored-to <path>]OPTIONS--repo <path> Brain repo to walk (default: resolved from the storage@@ -78,8 +93,16 @@ export async function runStorage(engine: BrainEngine, args: string[]): Promise<vawait runStorageStatus(engine, args.slice(1));return;}+ if (subcommand === 'init') {+ await runStorageInit(engine, args.slice(1));+ return;+ }+ if (['find', 'get', 'list', 'register', 'update'].includes(subcommand)) {+ console.error(`The storage manifest verbs are their own commands: run gbrain storage-${subcommand} (see gbrain storage-${subcommand} --help).`);+ process.exit(1);+ }console.error(`Unknown storage subcommand: ${subcommand}`);- console.error('Available subcommands: status');+ console.error('Available subcommands: status, init');process.exit(1);}@@ -413,3 +436,24 @@ function formatBytes(bytes: number): string {const i = Math.floor(Math.log(bytes) / Math.log(k));return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];}++// ── storage init (GST-1943) ───────────────────────────────++async function runStorageInit(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ const value = (flag: string): string | undefined => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : undefined; };+ const { initStorageSource } = await import('../core/storage-manifest/source.ts');+ try {+ const expect = value('--expect');+ const result = await initStorageSource(engine, { dir: value('--dir'), pushRemote: value('--push-remote'), dryRun: args.includes('--dry-run') || expect === undefined && args.includes('--dir'), expect });+ if (json) { console.log(JSON.stringify(result)); return; }+ for (const line of result.summary) console.log(line);+ if (result.dry_run && result.apply) console.log(`Apply (after the user agrees): ${result.apply.join(' ')}`);+ else if (!result.dry_run && result.action !== 'none') console.log('Done: the storage shelf exists.');+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ console.log(json ? JSON.stringify({ error: error.code, message: error.message, suggestion: error.suggestion }) : `Refused (${error.code}): ${error.message}+Fix: ${error.suggestion ?? ''}`);+ process.exitCode = error.code === 'invalid_params' ? 2 : 1;+ }+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex fadba17dbe..e8bb6942fa 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -26,14 +26,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backup': ['--accept-pending', '--as', '--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', '--as', '--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', '--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', '--of', '--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'],+ 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--card', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--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', '--of', '--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', '--advertise', '--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-instructions', '--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', '--skill-loading', '--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'],'bundled-skill': ['--asset', '--brain', '--help', '--json', '--source'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],- 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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'],+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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', '--as', '--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', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--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'],+ 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--card', '--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', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--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', '--as', '--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', '--check-only', '--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'],@@ -51,15 +51,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--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'],+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--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', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--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', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--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', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--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', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--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', '--ignore-missing', '--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', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--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', '--may-act-for', '--mcp-only', '--member', '--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-instructions', '--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', '--of', '--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', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--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', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--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', '--source-ids', '--sources', '--squash', '--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', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--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', '--worktree', '--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', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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'],+ 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--gbrain-bin', '--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', '--as', '--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', '--as', '--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', '--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', '--of', '--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'],+ 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--expected-revision', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--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', '--of', '--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', '--as', '--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', '--access-policy', '--as', '--background', '--body', '--brain', '--dir', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],@@ -81,7 +81,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--card', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-revision', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -92,19 +92,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],'notices': ['--brain', '--help', '--json', '--source'],- 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],+ 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--card', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'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', '--check-only', '--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', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--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', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--advertise', '--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', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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'],+ 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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', '--as', '--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', '--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', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--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', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--card', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--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', '--as', '--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', '--as', '--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', '--as', '--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'],@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'smoke-test': ['--brain', '--help', '--json', '--source'],'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--record', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],- 'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],+ 'storage': ['--brain', '--card', '--dir', '--dry-run', '--expect', '--expected-revision', '--help', '--json', '--patch', '--plan', '--push-remote', '--repo', '--restore-only', '--restored-to', '--source', '--status', '--store', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],@@ -142,7 +142,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--non-interactive', '--source', '--trust', '--url', '--yes'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],- 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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'],+ 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--of', '--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/cycle.ts b/src/core/cycle.tsindex d4d8b785ac..4a8c7033fd 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -423,7 +423,7 @@ export interface CycleReport {* - 'failed' : lock acquired but all attempted phases failed*/status: CycleStatus;- /** Present when status = 'skipped'. E.g., 'cycle_already_running' or 'no_database'. Also 'aborted' when the cycle was cancelled mid-flight (#1972), or 'stamp_write_failed' (#3504). */+ /** Present when status = 'skipped'. E.g., 'cycle_already_running' or 'no_database'. Also 'aborted' when the cycle was cancelled mid-flight (#1972), or 'stamp_write_failed' (#3504), or 'storage_manifest_source' when the cycle's source is the storage shelf (GST-1943). */reason?: string;/** `cycle_already_running` on the DB lock: who holds it and for how long (best effort). */lock_holder?: { id: string; holder_pid: number; holder_host: string; age_ms: number };@@ -2000,6 +2000,8 @@ async function runCycleUnscoped(? (opts.sourceId ?? (await resolveSourceForDir(engine, brainDir))): opts.sourceId;const orphansSourceId = opts.forceGlobalOrphans ? undefined : cycleSourceId;+ const storageShelf = engine && cycleSourceId ? await (await import('./storage-manifest/door.ts')).isStorageManifestSource(engine, cycleSourceId) : false;+ if (storageShelf) return { schema_version: '1', timestamp, duration_ms: Math.round(performance.now() - start), status: 'skipped', reason: 'storage_manifest_source', brain_dir: opts.brainDir, phases: [], totals: emptyTotals() };let sourceWindow: SourceCycleWindow | undefined;const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));diff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.tsindex a1852a4bf1..3c9404c7b1 100644--- a/src/core/eligibility/registry.ts+++ b/src/core/eligibility/registry.ts@@ -38,6 +38,7 @@ export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {chronicle_day: 'labeled', chronicle_on_this_day: 'labeled', chronicle_since: 'labeled', chronicle_last_seen: 'labeled',ontology_get: 'labeled', ontology_dimensions: 'labeled', ontology_conflicts: 'labeled', volunteer_chronicle: 'labeled',extraction_pending: 'labeled', entity_identity_list: 'labeled', find_contradictions: 'filtered',+ storage_find: 'labeled', storage_get: 'labeled', storage_list: 'labeled',find_experts: 'labeled', find_trajectory: 'labeled', takes_scorecard: 'labeled', takes_calibration: 'labeled',open_loops: 'labeled', schema_review_orphans: 'labeled',questions_list: 'labeled', questions_status: 'labeled',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 24093bca22..525e0d4521 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -766,6 +766,12 @@ export const CODES = {stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },store_unavailable: { class: 'retryable', summary: "The object store an engine opened from settings names did not answer a file check (file_register, file_verify, file_url), so nothing was recorded and no file was reported missing.", why: 'A failed read says nothing about whether the object exists; reporting it missing could lead a host to re-upload or delete a file that is still there.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Check the store named in settings.storage (its path, or its endpoint, bucket and keys), then call again." },+ storage_card_exists: { class: 'caller', summary: "A storage card with this id is already on the storage shelf; nothing was written.", why: 'Registering never overwrites a card, so two archives cannot silently share one id; a change to an existing card names the revision it read.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Change the card with gbrain storage-update <id> --expected-revision <revision from storage_get>, or register the new item under another id.' },+ storage_manifest_missing: { class: 'consent', actor: 'user', summary: "This brain has no storage shelf to write to (or the storage source ID belongs to another source); nothing was written.", why: 'On a brain with a Git checkout the shelf is a hosted git-canonical repository, created only after the user previews it, and hosting needs managed persistence. A repo-less brain gets its database-only shelf on the first register.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Preview gbrain storage init --dir <absolute path> --dry-run and apply the command it prints after the user agrees.' },+ storage_record_invalid: { class: 'caller', summary: "A storage card failed validation (a missing or malformed field, a command field, or a field gbrain stamps itself); nothing was written.", why: 'Every card must say where the item is, how big it is and how to restore it, and carries no commands, so a card is complete and safe to act on when it is found months later.', reasons: ['schema', 'command_field', 'stamped_field', 'not_json', 'not_object', 'too_large', 'id_change'], docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Fix the field the message names and send the card again; gbrain storage-register --help lists the card fields.' },+ storage_record_secret: { class: 'caller', summary: "A storage card field looks like a secret or has a credential shape; nothing was written and the value is not echoed.", why: 'Cards are read by agents and copied into the stores; credentials stay in the environment of the skill that restores an item.', reasons: ['secret_scanner', 'env_assignment', 'credential_variable', 'url_userinfo', 'presigned_url'], docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Remove the secret, environment assignment, credential variable, URL password or signed-URL parameter from the named field.' },+ storage_revision_conflict: { class: 'caller', summary: "A storage card changed since the revision the update named was read; nothing was written.", why: 'Updates bind to the revision they read, so two writers never silently overwrite each other; the refusal carries the current revision in detail.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Read the card again with storage_get, apply the change to what it says now, and update once with its revision.' },+ storage_source_managed: { class: 'caller', summary: "A page write targeted the storage shelf outside the storage verbs; nothing was written.", why: 'The storage source holds only validated cards, so put_page, remember and the other page writers are refused there.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Register cards with gbrain storage-register and change them with gbrain storage-update.' },storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",reasons: ['database_contention'], reason_overrides: { database_contention: { class: 'retryable' } },why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",diff --git a/src/core/operation-load.ts b/src/core/operation-load.tsindex 1696485200..4f0581bd38 100644--- a/src/core/operation-load.ts+++ b/src/core/operation-load.ts@@ -79,6 +79,7 @@ const OP_AREAS: Record<string, string> = {log_ingest: 'ingest', get_ingest_log: 'ingest',get_usage: 'admin',// files (localOnly)+ storage_find: 'storage', storage_get: 'storage', storage_list: 'storage',file_list: 'files', file_upload: 'files', file_url: 'files', file_register: 'files', file_verify: 'files',// jobs (Minions + agent lane)submit_job: 'jobs', get_job: 'jobs', wait_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.tsindex 299e92d5b3..7993310bb5 100644--- a/src/core/operation-loaders.generated.ts+++ b/src/core/operation-loaders.generated.ts@@ -50,6 +50,7 @@ const load_search = () => import('./ops/search.ts') as Promise<Record<string, unconst load_skillopt = () => import('./ops/skillopt.ts') as Promise<Record<string, unknown>>;const load_skills_catalog = () => import('./ops/skills-catalog.ts') as Promise<Record<string, unknown>>;const load_sources = () => import('./ops/sources.ts') as Promise<Record<string, unknown>>;+const load_storage_manifest = () => import('./ops/storage-manifest.ts') as Promise<Record<string, unknown>>;const load_sync_status = () => import('./ops/sync-status.ts') as Promise<Record<string, unknown>>;const load_tags = () => import('./ops/tags.ts') as Promise<Record<string, unknown>>;const load_takes = () => import('./ops/takes.ts') as Promise<Record<string, unknown>>;@@ -150,6 +151,11 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st"file_url": [load_files, "filesOperations"],"file_register": [load_files, "filesOperations"],"file_verify": [load_files, "filesOperations"],+ "storage_find": [load_storage_manifest, "storageManifestOperations"],+ "storage_get": [load_storage_manifest, "storageManifestOperations"],+ "storage_list": [load_storage_manifest, "storageManifestOperations"],+ "storage_register": [load_storage_manifest, "storageManifestOperations"],+ "storage_update": [load_storage_manifest, "storageManifestOperations"],"submit_job": [load_jobs, "jobsOperations"],"get_job": [load_jobs, "jobsOperations"],"wait_job": [load_jobs, "jobsOperations"],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 4f3cba05e1..b952c45876 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -3853,6 +3853,202 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"area": "files"},+ {+ "name": "storage_find",+ "mutating": false,+ "idempotent": true,+ "outputRedaction": "retrieval",+ "description": "Find archived items on the storage shelf (files moved to B2, Supabase Storage, S3 and similar) by a plain phrase, such as \"the October Gmail dataset\". Ranks exact id, then exact alias, then cards matching most of the phrase's words in title, aliases and description. When nothing matches, not_found is true and closest lists the nearest cards. Then call storage_get with the id for where it is stored and how to restore it.",+ "params": {+ "query": {+ "type": "string",+ "required": true,+ "description": "The phrase, id or alias."+ },+ "store": {+ "type": "string",+ "enum": [+ "b2",+ "supabase",+ "s3",+ "r2",+ "gcs",+ "other"+ ],+ "description": "Only cards with a copy in this store."+ },+ "status": {+ "type": "string",+ "enum": [+ "archived",+ "restored",+ "missing",+ "retired"+ ],+ "description": "Only cards with this status."+ },+ "limit": {+ "type": "number",+ "description": "Max hits (default 10, max 50)."+ }+ },+ "scope": "read",+ "cliHints": {+ "name": "storage-find",+ "positional": [+ "query"+ ]+ },+ "area": "storage"+ },+ {+ "name": "storage_get",+ "mutating": false,+ "idempotent": true,+ "outputRedaction": "retrieval",+ "description": "Read one card from the storage shelf by id: what the item is, every stored copy (store, bucket, path, restic repository and snapshot, size, hash, when verified), the original path, why it was archived, the restore form (restore.skill and restore.args, run by the agent's own restore skill; cards carry no commands or credentials), past restores, who registered it, and its revision.",+ "params": {+ "id": {+ "type": "string",+ "required": true,+ "description": "Card id (storage_find returns it)."+ }+ },+ "scope": "read",+ "cliHints": {+ "name": "storage-get",+ "positional": [+ "id"+ ]+ },+ "area": "storage"+ },+ {+ "name": "storage_list",+ "mutating": false,+ "idempotent": true,+ "outputRedaction": "retrieval",+ "description": "List cards on the storage shelf, sorted by id, optionally filtered by store, status or whether a copy is still on the source machine. Returns id, title, status, kind, stores and original path per card, and total.",+ "params": {+ "store": {+ "type": "string",+ "enum": [+ "b2",+ "supabase",+ "s3",+ "r2",+ "gcs",+ "other"+ ],+ "description": "Only cards with a copy in this store."+ },+ "status": {+ "type": "string",+ "enum": [+ "archived",+ "restored",+ "missing",+ "retired"+ ],+ "description": "Only cards with this status."+ },+ "on_source_machine": {+ "type": "boolean",+ "description": "Only cards whose item is (true) or is not (false) still on the machine it came from."+ },+ "limit": {+ "type": "number",+ "description": "Max rows (default 50; max 500, remote 100)."+ },+ "offset": {+ "type": "number",+ "description": "Rows to skip, for paging."+ }+ },+ "scope": "read",+ "cliHints": {+ "name": "storage-list"+ },+ "area": "storage"+ },+ {+ "name": "storage_register",+ "mutating": true,+ "writeInference": "none",+ "idempotent": false,+ "outputRedaction": "no_stored_text",+ "description": "Register a new card on the storage shelf after an archive is verified. card is a JSON object: id, title, aliases, description, kind, status, locations (store, bucket, path, tool, repository, snapshot, size_bytes, file_count, sha256, hash_kind, verified_at), original_path, on_source_machine, source_machine, archived_at, archived_by, reason, restore {skill, args}, restores, details. Credentials, credential-shaped values and command fields are refused. Trusted local CLI only.",+ "params": {+ "card": {+ "type": "object",+ "required": true,+ "description": "The card (JSON)."+ }+ },+ "scope": "write",+ "localOnly": true,+ "cliOnly": {+ "argv": [+ "gbrain",+ "storage-register",+ "--card",+ "<card json>"+ ]+ },+ "cliHints": {+ "name": "storage-register",+ "stdin": "card"+ }+ },+ {+ "name": "storage_update",+ "mutating": true,+ "writeInference": "none",+ "idempotent": false,+ "outputRedaction": "no_stored_text",+ "description": "Change a card on the storage shelf: patch replaces the named top-level fields (validated like a new card), and restored_to records a restore (newest first; status becomes restored). expected_revision is the revision storage_get returned; a stale one is refused storage_revision_conflict with the current revision. Trusted local CLI only.",+ "params": {+ "id": {+ "type": "string",+ "required": true,+ "description": "Card id."+ },+ "expected_revision": {+ "type": "string",+ "required": true,+ "description": "The revision storage_get returned."+ },+ "patch": {+ "type": "object",+ "description": "Top-level fields to replace (JSON)."+ },+ "restored_to": {+ "type": "string",+ "description": "Path the item was restored to; adds a restores entry."+ },+ "restored_verified": {+ "type": "boolean",+ "description": "With restored_to: the checksums matched."+ }+ },+ "scope": "write",+ "localOnly": true,+ "cliOnly": {+ "argv": [+ "gbrain",+ "storage-update",+ "<id>",+ "--expected-revision",+ "<revision>"+ ]+ },+ "cliHints": {+ "name": "storage-update",+ "positional": [+ "id"+ ]+ }+ },{"name": "submit_job","idempotent": false,diff --git a/src/core/operations.ts b/src/core/operations.tsindex a542507ca0..b2a5116403 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -133,6 +133,7 @@ import { feedbackOperations } from './ops/feedback.ts';import { trustOperations } from './ops/trust.ts';import { wakeshiftOperations } from './ops/wakeshift.ts';import { findPagesOperations } from './ops/find-pages.ts';+import { storageManifestOperations } from './ops/storage-manifest.ts';// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`// verb (verbs.ts) loads it from THIS module at runtime — re-exported so every@@ -182,7 +183,7 @@ export const operations: Operation[] = [// Usage accounting (get_usage, #4218) — ops/usage.ts...usageOperations,// Files (file_list, file_upload, file_url) — ops/files.ts- ...filesOperations,+ ...filesOperations, ...storageManifestOperations,// Jobs (Minions: submit_job, get_job, list_jobs, cancel_job, retry_job,// get_job_progress, pause_job, resume_job, replay_job, send_job_message)// + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts; Wakeshift watches (watch_job, list_watches, unwatch) — ops/wakeshift.tsdiff --git a/src/core/ops/storage-manifest.ts b/src/core/ops/storage-manifest.tsnew file mode 100644index 0000000000..19a536f93e--- /dev/null+++ b/src/core/ops/storage-manifest.ts@@ -0,0 +1,255 @@+/**+ * Storage manifest verbs (GST-1943): `storage_find`, `storage_get` and `storage_list` read the storage shelf (the+ * `storage` source) under the caller's ordinary read authority; `storage_register` and `storage_update` write it and+ * are trusted-local only (v1: remote write grants are a later plan). Writes go through the page door with the storage+ * door mark, so the card is committed to the hosted repository first on a repo brain and the database is the record on+ * a repo-less one. Cards and shapes: src/core/storage-manifest/schema.ts.+ */+import { clampSearchLimit } from '../engine.ts';+import { dataFrontmatter } from '../data-frontmatter.ts';+import type { Operation, OperationContext } from './contract.ts';+import { opError, OperationError } from './contract.ts';+import { federatedSearchScope, readPolicyOpts } from './context.ts';+import { readFix } from './op-fix.ts';+import { cliOnlyRefusal } from './callable.ts';+import type { PageReadScope } from '../types.ts';+import { initializeLocalPersistence, submitPageMutation, requestPrincipalForContext } from '../persistence/page-mutations.ts';++async function principalLabel(ctx: OperationContext): Promise<string> {+ await initializeLocalPersistence(ctx);+ const principal = await requestPrincipalForContext(ctx);+ return `${principal.kind}:${principal.id}`;+}+import { cardFromPage, cardPage, parseCardInput, STATUSES, STORES, withRestore, type Card, type CardInput, ORIGINS } from '../storage-manifest/schema.ts';+import { ensureStorageSource, storageDoorContext, STORAGE_SOURCE_ID } from '../storage-manifest/source.ts';+import { findCards, listCards, type CardFilters } from '../storage-manifest/find.ts';++const FIND_DEFAULT = 10, FIND_MAX = 50;+const LIST_DEFAULT = 50, LIST_LOCAL_MAX = 500, LIST_REMOTE_MAX = 100;++function getFix(id: string) {+ return readFix('Reads the card with its restore form and current revision.', { argv: ['gbrain', 'storage-get', id, '--json'], mcp: { tool: 'storage_get', arguments: { id } } });+}++async function shelfExists(ctx: OperationContext): Promise<boolean> {+ const rows = await ctx.engine.executeRaw<{ ok: number }>('SELECT 1 AS ok FROM sources WHERE id=$1 AND archived IS NOT TRUE', [STORAGE_SOURCE_ID]);+ return rows.length > 0;+}++/** The read policy for the shelf: the caller's grant must allow the storage source (federatedSearchScope refuses otherwise). */+async function shelfPolicy(ctx: OperationContext): Promise<PageReadScope | undefined> {+ const scope = federatedSearchScope(ctx, STORAGE_SOURCE_ID);+ return ctx.remote === false && !ctx.applyRemoteReadPolicy ? scope : await readPolicyOpts(ctx, scope);+}++function filtersOf(p: Record<string, unknown>): CardFilters {+ const filters: CardFilters = {};+ if (p.store !== undefined) {+ if (typeof p.store !== 'string' || !(STORES as readonly string[]).includes(p.store)) throw opError('invalid_params', `store must be one of ${STORES.join(', ')}.`, 'Pass a store name, or omit store.');+ filters.store = p.store;+ }+ if (p.status !== undefined) {+ if (typeof p.status !== 'string' || !(STATUSES as readonly string[]).includes(p.status)) throw opError('invalid_params', `status must be one of ${STATUSES.join(', ')}.`, 'Pass a status, or omit status.');+ filters.status = p.status;+ }+ if (p.on_source_machine !== undefined) filters.onSourceMachine = p.on_source_machine === true || p.on_source_machine === 'true';+ return filters;+}++const NO_SHELF = 'This brain has no storage shelf yet: nothing has been registered. The archiving agent registers each item with gbrain storage-register after it verifies the archive.';++async function readCard(ctx: OperationContext, id: string): Promise<{ card: Card; revision: string; updated_at: string } | null> {+ if (!await shelfExists(ctx)) return null;+ const policy = await shelfPolicy(ctx);+ const params: unknown[] = [STORAGE_SOURCE_ID, id];+ const { pageReadFilter } = await import('../search/read-policy-sql.ts');+ const visible = await ctx.engine.executeRaw<{ ok: number }>(`SELECT 1 AS ok FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ${pageReadFilter('p', policy, params, true)}`, params);+ if (!visible.length) return null;+ const snapshot = await ctx.engine.readPageSnapshot(id, { sourceId: STORAGE_SOURCE_ID });+ if (!snapshot) return null;+ const card = cardFromPage({ slug: snapshot.page.slug, title: snapshot.page.title, frontmatter: (snapshot.page.frontmatter ?? {}) as Record<string, unknown> });+ return card ? { card, revision: snapshot.revision, updated_at: String(snapshot.page.updated_at ?? '') } : null;+}++async function writeCard(ctx: OperationContext, card: Card, opts: { expectedRevision?: string; requestId?: string }): Promise<Record<string, unknown>> {+ const { frontmatter, body } = cardPage(card);+ const content = dataFrontmatter.stringify(body, frontmatter);+ try {+ const response = await submitPageMutation(storageDoorContext(ctx), { operation: 'put_page', params: {+ slug: card.id, source_id: STORAGE_SOURCE_ID, content,+ ...(opts.expectedRevision ? { expected_revision: opts.expectedRevision } : {}),+ ...(opts.requestId ? { request_id: opts.requestId } : {}) } });+ return response;+ } catch (error) {+ if (error instanceof OperationError && error.code === 'revision_conflict') {+ const current = await ctx.engine.readPageSnapshot(card.id, { sourceId: STORAGE_SOURCE_ID });+ throw opError('storage_revision_conflict', `Card ${card.id} changed since revision ${opts.expectedRevision} was read; nothing was written.`,+ `Read the card again (its current revision is ${current?.revision ?? 'unknown'}), apply the change to what it says now, and update once with that revision.`,+ { fix: getFix(card.id), detail: current?.revision });+ }+ throw error;+ }+}++/** Register a new card. Exported for `storage adopt` and `storage import` (origin adopt / import). */+export async function registerCard(ctx: OperationContext, input: CardInput, origin: (typeof ORIGINS)[number], requestId?: string): Promise<Record<string, unknown>> {+ await ensureStorageSource(ctx.engine);+ const existing = await ctx.engine.readPageSnapshot(input.id, { sourceId: STORAGE_SOURCE_ID });+ if (existing) throw opError('storage_card_exists', `A card with id ${input.id} is already on the storage shelf; nothing was written.`,+ `Change it with gbrain storage-update ${input.id} --expected-revision ${existing.revision}, or register the new item under another id.`,+ { fix: getFix(input.id), detail: existing.revision });+ const card: Card = { ...input, registered_by: await principalLabel(ctx), origin };+ const response = await writeCard(ctx, card, { requestId });+ return { id: card.id, source_id: STORAGE_SOURCE_ID, origin, write: response };+}++function parsePatch(raw: unknown): Record<string, unknown> {+ let value = raw;+ if (typeof value === 'string') {+ try { value = JSON.parse(value); } catch { throw opError('storage_record_invalid', 'patch must be a JSON object; nothing was written.', 'Pass the fields to change as a JSON object, e.g. {"status":"retired"}.', { reason: 'not_json' }); }+ }+ if (value === undefined || value === null) return {};+ if (typeof value !== 'object' || Array.isArray(value)) throw opError('storage_record_invalid', 'patch must be a JSON object; nothing was written.', 'Pass the fields to change as a JSON object.', { reason: 'not_object' });+ if (Object.hasOwn(value, 'id')) throw opError('storage_record_invalid', 'A card keeps its id; nothing was written.', 'Drop id from the patch, or register the item under a new id.', { reason: 'id_change' });+ return value as Record<string, unknown>;+}++const storage_find: Operation = {+ name: 'storage_find',+ mutating: false,+ idempotent: true,+ outputRedaction: 'retrieval',+ description: 'Find archived items on the storage shelf (files moved to B2, Supabase Storage, S3 and similar) by a plain phrase, such as "the October Gmail dataset". ' ++ 'Ranks exact id, then exact alias, then cards matching most of the phrase\'s words in title, aliases and description. When nothing matches, not_found is true and closest lists the nearest cards. ' ++ 'Then call storage_get with the id for where it is stored and how to restore it.',+ params: {+ query: { type: 'string', required: true, description: 'The phrase, id or alias.' },+ store: { type: 'string', enum: [...STORES], description: 'Only cards with a copy in this store.' },+ status: { type: 'string', enum: [...STATUSES], description: 'Only cards with this status.' },+ limit: { type: 'number', description: `Max hits (default ${FIND_DEFAULT}, max ${FIND_MAX}).` },+ },+ handler: async (ctx, p) => {+ const query = typeof p.query === 'string' ? p.query.trim() : '';+ if (!query) throw opError('invalid_params', 'storage_find needs a query.', 'Pass the phrase people would use for the item, e.g. "october gmail dataset".');+ const filters = filtersOf(p);+ if (!await shelfExists(ctx)) return { query, terms: [], hits: [], not_found: true, closest: [], shelf: false, note: NO_SHELF };+ const limit = clampSearchLimit(typeof p.limit === 'number' ? p.limit : undefined, FIND_DEFAULT, FIND_MAX);+ const result = await findCards(ctx.engine, query, { limit, filters, policy: await shelfPolicy(ctx) });+ const top = result.hits[0] ?? result.closest[0];+ return { ...result, shelf: true, ...(top ? { next: getFix(top.id) } : {}) };+ },+ scope: 'read',+ cliHints: { name: 'storage-find', positional: ['query'] },+};++const storage_get: Operation = {+ name: 'storage_get',+ mutating: false,+ idempotent: true,+ outputRedaction: 'retrieval',+ description: 'Read one card from the storage shelf by id: what the item is, every stored copy (store, bucket, path, restic repository and snapshot, size, hash, when verified), ' ++ 'the original path, why it was archived, the restore form (restore.skill and restore.args, run by the agent\'s own restore skill; cards carry no commands or credentials), past restores, who registered it, and its revision.',+ params: { id: { type: 'string', required: true, description: 'Card id (storage_find returns it).' } },+ handler: async (ctx, p) => {+ const id = typeof p.id === 'string' ? p.id.trim().toLowerCase() : '';+ if (!id) throw opError('invalid_params', 'storage_get needs an id.', 'Pass the id storage_find returned.');+ const found = await readCard(ctx, id);+ if (!found) {+ throw opError('not_found', `No card ${id} on the storage shelf.`, 'Search with storage_find and the words people would use for the item; it lists the closest cards when nothing matches.',+ { fix: readFix('Finds cards by phrase, with the closest cards when nothing matches.', { argv: ['gbrain', 'storage-find', id, '--json'], mcp: { tool: 'storage_find', arguments: { query: id } } }) });+ }+ return { card: found.card, revision: found.revision, updated_at: found.updated_at, source_id: STORAGE_SOURCE_ID, registered_by: found.card.registered_by, origin: found.card.origin };+ },+ scope: 'read',+ cliHints: { name: 'storage-get', positional: ['id'] },+};++const storage_list: Operation = {+ name: 'storage_list',+ mutating: false,+ idempotent: true,+ outputRedaction: 'retrieval',+ description: 'List cards on the storage shelf, sorted by id, optionally filtered by store, status or whether a copy is still on the source machine. Returns id, title, status, kind, stores and original path per card, and total.',+ params: {+ store: { type: 'string', enum: [...STORES], description: 'Only cards with a copy in this store.' },+ status: { type: 'string', enum: [...STATUSES], description: 'Only cards with this status.' },+ on_source_machine: { type: 'boolean', description: 'Only cards whose item is (true) or is not (false) still on the machine it came from.' },+ limit: { type: 'number', description: `Max rows (default ${LIST_DEFAULT}; max ${LIST_LOCAL_MAX}, remote ${LIST_REMOTE_MAX}).` },+ offset: { type: 'number', description: 'Rows to skip, for paging.' },+ },+ handler: async (ctx, p) => {+ const filters = filtersOf(p);+ if (!await shelfExists(ctx)) return { cards: [], total: 0, shelf: false, note: NO_SHELF };+ const limit = clampSearchLimit(typeof p.limit === 'number' ? p.limit : undefined, LIST_DEFAULT, ctx.remote === false ? LIST_LOCAL_MAX : LIST_REMOTE_MAX);+ const offset = typeof p.offset === 'number' && p.offset > 0 ? Math.floor(p.offset) : 0;+ const { cards, total } = await listCards(ctx.engine, { limit, offset, filters, policy: await shelfPolicy(ctx) });+ return { cards, total, limit, offset, complete: offset + cards.length >= total, shelf: true };+ },+ scope: 'read',+ cliHints: { name: 'storage-list' },+};++const storage_register: Operation = {+ name: 'storage_register',+ mutating: true,+ writeInference: 'none',+ idempotent: false,+ outputRedaction: 'no_stored_text',+ description: 'Register a new card on the storage shelf after an archive is verified. card is a JSON object: id, title, aliases, description, kind, status, locations (store, bucket, path, tool, repository, snapshot, size_bytes, file_count, sha256, hash_kind, verified_at), ' ++ 'original_path, on_source_machine, source_machine, archived_at, archived_by, reason, restore {skill, args}, restores, details. Credentials, credential-shaped values and command fields are refused. Trusted local CLI only.',+ params: { card: { type: 'object', required: true, description: 'The card (JSON).' } },+ scope: 'write',+ localOnly: true,+ cliOnly: { argv: ['gbrain', 'storage-register', '--card', '<card json>'] },+ handler: async (ctx, p) => {+ if (ctx.remote !== false) throw cliOnlyRefusal(storage_register);+ return registerCard(ctx, parseCardInput(p.card), 'local');+ },+ cliHints: { name: 'storage-register', stdin: 'card' },+};++const storage_update: Operation = {+ name: 'storage_update',+ mutating: true,+ writeInference: 'none',+ idempotent: false,+ outputRedaction: 'no_stored_text',+ description: 'Change a card on the storage shelf: patch replaces the named top-level fields (validated like a new card), and restored_to records a restore (newest first; status becomes restored). ' ++ 'expected_revision is the revision storage_get returned; a stale one is refused storage_revision_conflict with the current revision. Trusted local CLI only.',+ params: {+ id: { type: 'string', required: true, description: 'Card id.' },+ expected_revision: { type: 'string', required: true, description: 'The revision storage_get returned.' },+ patch: { type: 'object', description: 'Top-level fields to replace (JSON).' },+ restored_to: { type: 'string', description: 'Path the item was restored to; adds a restores entry.' },+ restored_verified: { type: 'boolean', description: 'With restored_to: the checksums matched.' },+ },+ scope: 'write',+ localOnly: true,+ cliOnly: { argv: ['gbrain', 'storage-update', '<id>', '--expected-revision', '<revision>'] },+ handler: async (ctx, p) => {+ if (ctx.remote !== false) throw cliOnlyRefusal(storage_update);+ const id = typeof p.id === 'string' ? p.id.trim().toLowerCase() : '';+ const expected = typeof p.expected_revision === 'string' ? p.expected_revision : '';+ if (!id || !expected) throw opError('invalid_params', 'storage_update needs id and expected_revision.', 'Read the card with storage_get and pass its id and revision.');+ const found = await readCard(ctx, id);+ if (!found) throw opError('not_found', `No card ${id} on the storage shelf; nothing was written.`, 'Register it with gbrain storage-register, or find the right id with storage_find.');+ if (found.revision !== expected) {+ throw opError('storage_revision_conflict', `Card ${id} changed since revision ${expected} was read; nothing was written.`,+ `Read the card again (its current revision is ${found.revision}), apply the change to what it says now, and update once with that revision.`, { fix: getFix(id), detail: found.revision });+ }+ const patch = parsePatch(p.patch);+ const { registered_by, origin, ...current } = found.card;+ const input = parseCardInput({ ...current, ...patch, id });+ let card: Card = { ...input, registered_by, origin };+ if (typeof p.restored_to === 'string' && p.restored_to.trim()) {+ card = withRestore(card, { at: new Date().toISOString(), to: p.restored_to.trim(), by: await principalLabel(ctx), verified: p.restored_verified === true });+ const { registered_by: _stampedBy, origin: _stampedOrigin, ...unstamped } = card;+ parseCardInput(unstamped);+ }+ const response = await writeCard(ctx, card, { expectedRevision: expected });+ return { id, source_id: STORAGE_SOURCE_ID, status: card.status, write: response };+ },+ cliHints: { name: 'storage-update', positional: ['id'] },+};++export const storageManifestOperations: Operation[] = [storage_find, storage_get, storage_list, storage_register, storage_update];diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 9e011923b7..348c7ab35d 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -1,4 +1,5 @@import { throwIfHeld } from '../trust/gate-outcomes.ts';+import { assertStorageSourceWriter } from '../storage-manifest/door.ts';import { guardRemoteForget, remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';import { randomUUID } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';@@ -192,9 +193,10 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoconst sub = await submission(ctx, 'remember', params, opts.visibilityDefaulted ? withoutDefault : params);if (sub.prior) { const prior = sub.prior; const settled = await waitForWrite(ctx.engine, prior, ctx.config, waitMs ?? ctx.writeWaitMs); return throwIfHeld(withRememberTarget(prior, () => writeResponse(settled))); }const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;- const [source] = await ctx.engine.executeRaw<RememberSource>(- "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ const [source] = await ctx.engine.executeRaw<RememberSource & { role: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw sourceInactive(sourceId);+ assertStorageSourceWriter(ctx, sourceId, source.role, {});const { parseTtlParam } = await import('../ops/facts.ts');const validUntil = parseTtlParam(p.ttl);const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;@@ -316,9 +318,10 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foif (ownPage && !(await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${memberFactAdmitSql('facts')}`, [id, sourceId])).length) throw missing();// #5575 I3: a remote caller cannot forget a fact more trusted than its own writes; the owner is asked instead.if (remote) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });- const [source] = await ctx.engine.executeRaw<RememberSource>(- "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ const [source] = await ctx.engine.executeRaw<RememberSource & { role: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw sourceInactive(sourceId);+ assertStorageSourceWriter(ctx, sourceId, source.role, {});const fact = await readForgetTarget(ctx.engine, id, sourceId, remote, excludePrivate, false, ownPage);if (!fact) throw missing();if (remote && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 1ec79103d5..72cc40e874 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -51,6 +51,7 @@ import { holdsSummarizedToolCalls, isQuotedPageType, quotesTier, unquoteTranscriimport { readStoredBody } from '../facts/file-body-guard.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { perCallWriteSource } from '../access/attest-sources.ts';+import { assertStorageSourceWriter } from '../storage-manifest/door.ts';export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {// #5994: a failed-writes replay is admitted under the original writer.@@ -75,7 +76,7 @@ const flatSql = (sql: string) => sql.replace(/\s+/g, ' ').trim();* under lock by the admission transaction or by publication.*/const BATCH_SHARED_READS = new Set([- "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1",+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1",'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1','SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid','SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',@@ -423,12 +424,14 @@ export async function preparePageAdmission(ctx: OperationContext,return { prior };}if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(- "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null; role: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) {throw new OperationError('source_changed', 'The write source is not active.',`Source ${sourceId} is archived or not registered, so nothing was written. Write to an active source (sources_list shows them).`);}+ // GST-1943: the storage manifest takes page writes only from the storage verbs (and the owner's import of its own commits).+ assertStorageSourceWriter(ctx, sourceId, source.role, { managedFileImport: input.managedFileImport });// After the replay check: the request digest covers what the caller sent, so a retry matches whatever the page's type is by then.if (input.operation === 'put_page' && ctx.remote !== false && typeof p.content === 'string' && typeof p.slug === 'string') {p.content = await unquotedPutContent(ctx.engine, sourceId, p.slug.toLowerCase(), p.content);diff --git a/src/core/storage-manifest/door.ts b/src/core/storage-manifest/door.tsnew file mode 100644index 0000000000..09faca6af0--- /dev/null+++ b/src/core/storage-manifest/door.ts@@ -0,0 +1,37 @@+/**+ * The storage manifest's write door (GST-1943), kept free of heavy imports because the page door imports it: the+ * storage verbs mark the context they write through with a symbol no request parameter can carry, and a source with+ * the storage role refuses every other page writer.+ */+import { opError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { BrainEngine } from '../engine.ts';++export const STORAGE_SOURCE_ID = 'storage';+export const STORAGE_ROLE = 'storage_manifest';++/** Set by the storage verbs on the context they write through; a symbol, so no request parameter can carry it. */+export const STORAGE_DOOR: unique symbol = Symbol('gbrain.storage_door');+export function storageDoorContext(ctx: OperationContext): OperationContext {+ return Object.assign({ ...ctx }, { [STORAGE_DOOR]: true });+}+export function isStorageDoor(ctx: OperationContext): boolean {+ return (ctx as unknown as Record<symbol, unknown>)[STORAGE_DOOR] === true;+}++/**+ * The page door's check: a source with the storage role takes page writes only from the storage verbs and from the+ * owner's import of commits already in its hosted repository. Everything else is refused with the verb to use.+ */+export function assertStorageSourceWriter(ctx: OperationContext, sourceId: string, role: string | null, opts: { managedFileImport?: boolean }): void {+ if (role !== STORAGE_ROLE || isStorageDoor(ctx) || opts.managedFileImport === true) return;+ throw opError('storage_source_managed', `Source ${sourceId} is the storage manifest; only the storage verbs write it, so nothing was written.`,+ 'Register a card with gbrain storage-register, or change one with gbrain storage-update and the card\'s current revision from storage_get.',+ { fix: readFix('Lists the cards on the storage shelf, read-only.', { argv: ['gbrain', 'storage-list', '--json'], mcp: { tool: 'storage_list', arguments: {} } }) });+}+++/** Derived writers (dream's phases, enrichment) skip the storage shelf: only the storage verbs change a card. */+export async function isStorageManifestSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {+ return (await engine.executeRaw('SELECT 1 FROM sources WHERE id = $1 AND config->>\'role\' = $2', [sourceId, STORAGE_ROLE])).length > 0;+}diff --git a/src/core/storage-manifest/find.ts b/src/core/storage-manifest/find.tsnew file mode 100644index 0000000000..ebfa89efae--- /dev/null+++ b/src/core/storage-manifest/find.ts@@ -0,0 +1,81 @@+/**+ * Ranked lookup on the storage shelf (GST-1943), keyless: exact id, exact alias (page_aliases), then the words of the+ * phrase over each card's title, aliases and body, then pg_trgm similarity on title and aliases for the closest cards+ * when nothing matches. One statement; the shelf is small (hundreds to thousands of cards).+ */+import type { BrainEngine } from '../engine.ts';+import type { PageReadScope } from '../types.ts';+import { pageReadFilter } from '../search/read-policy-sql.ts';+import { normalizeAlias } from '../search/alias-normalize.ts';+import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';+import { STORAGE_SOURCE_ID } from './door.ts';+import { STORED_OBJECT_TYPE } from './schema.ts';++const STOPWORDS = new Set(['a', 'an', 'and', 'the', 'of', 'to', 'in', 'on', 'for', 'from', 'my', 'our', 'it', 'that', 'this', 'back', 'bring', 'restore', 'find', 'where', 'is', 'was', 'what', 'did', 'go', 'with', 'please']);+const CLOSEST_FLOOR = 0.1;++export interface CardFilters { store?: string; status?: string; onSourceMachine?: boolean }+export interface CardRow { id: string; title: string; status: string | null; kind: string | null; stores: string[]; original_path: string | null; on_source_machine: boolean | null; updated_at: string }+export interface FindHit extends CardRow { match: 'id' | 'alias' | 'words'; matched_terms: number; similarity: number }+export interface FindResult { query: string; terms: string[]; hits: FindHit[]; not_found: boolean; closest: Array<CardRow & { similarity: number }> }++export function queryTerms(query: string): string[] {+ const words = query.toLowerCase().normalize('NFKC').split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 1 && !STOPWORDS.has(w));+ return [...new Set(words)].slice(0, 12);+}++/** Filters on the card's frontmatter, appended to `where` with bound params. */+export function cardFilterSql(alias: string, filters: CardFilters, params: unknown[]): string {+ const clauses: string[] = [];+ if (filters.status) { params.push(filters.status); clauses.push(`${alias}.frontmatter->'storage'->>'status' = $${params.length}`); }+ if (filters.store) { params.push(filters.store); clauses.push(`EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(${alias}.frontmatter->'storage'->'locations') = 'array' THEN ${alias}.frontmatter->'storage'->'locations' ELSE '[]'::jsonb END) loc WHERE loc->>'store' = $${params.length})`); }+ if (filters.onSourceMachine !== undefined) { params.push(String(filters.onSourceMachine)); clauses.push(`${alias}.frontmatter->'storage'->>'on_source_machine' = $${params.length}`); }+ return clauses.length ? ` AND ${clauses.join(' AND ')}` : '';+}++export const CARD_COLUMNS = `p.slug AS id, p.title, p.frontmatter->'storage'->>'status' AS status, p.frontmatter->'storage'->>'kind' AS kind,+ COALESCE((SELECT array_agg(DISTINCT loc->>'store') FROM jsonb_array_elements(CASE WHEN jsonb_typeof(p.frontmatter->'storage'->'locations') = 'array' THEN p.frontmatter->'storage'->'locations' ELSE '[]'::jsonb END) loc), ARRAY[]::text[]) AS stores,+ p.frontmatter->'storage'->>'original_path' AS original_path,+ CASE p.frontmatter->'storage'->>'on_source_machine' WHEN 'true' THEN true WHEN 'false' THEN false END AS on_source_machine,+ p.updated_at::text AS updated_at`;++export async function findCards(engine: BrainEngine, query: string, opts: { limit: number; filters: CardFilters; policy?: PageReadScope }): Promise<FindResult> {+ const terms = queryTerms(query);+ const params: unknown[] = [STORAGE_SOURCE_ID, STORED_OBJECT_TYPE, query.trim().toLowerCase(), normalizeAlias(query), terms];+ const policy = pageReadFilter('p', opts.policy, params, true);+ const filters = cardFilterSql('p', opts.filters, params);+ const rows = await engine.executeRaw<CardRow & { exact_id: boolean; exact_alias: boolean; matched: number; rank: number; similarity: number }>(`+ SELECT ${CARD_COLUMNS},+ p.slug = $3 AS exact_id,+ EXISTS (SELECT 1 FROM page_aliases a WHERE a.source_id = p.source_id AND a.slug = p.slug AND a.alias_norm = $4) AS exact_alias,+ (SELECT count(*) FROM unnest($5::text[]) t WHERE d.doc @@ plainto_tsquery('simple', t))::int AS matched,+ GREATEST(word_similarity($3, lower(p.title)),+ COALESCE((SELECT max(word_similarity($3, a.alias_norm)) FROM page_aliases a WHERE a.source_id = p.source_id AND a.slug = p.slug), 0))::float8 AS similarity+ FROM pages p+ CROSS JOIN LATERAL (SELECT to_tsvector('simple', p.title || ' ' || COALESCE((SELECT string_agg(a.alias_norm, ' ') FROM page_aliases a WHERE a.source_id = p.source_id AND a.slug = p.slug), '')+ || ' ' || p.slug || ' ' || ${boundedBodyPrefixSql('p')}) AS doc) d+ WHERE p.source_id = $1 AND p.type = $2 AND ${policy}${filters}+ ORDER BY exact_id DESC, exact_alias DESC, matched DESC, similarity DESC, p.slug+ LIMIT 500`, params);+ const needed = Math.max(1, Math.ceil(terms.length / 2));+ const strip = ({ exact_id: _e, exact_alias: _a, matched: _m, rank: _r, similarity: _s, ...card }: (typeof rows)[number]): CardRow => ({ ...card, stores: card.stores ?? [] });+ const hits: FindHit[] = [];+ for (const row of rows) {+ const match = row.exact_id ? 'id' : row.exact_alias ? 'alias' : terms.length && row.matched >= needed ? 'words' : null;+ if (match) hits.push({ ...strip(row), match, matched_terms: Number(row.matched), similarity: Number(row.similarity) });+ }+ const shown = hits.slice(0, opts.limit);+ const closest = shown.length ? [] : rows.filter((row) => Number(row.similarity) >= CLOSEST_FLOOR || Number(row.matched) > 0)+ .sort((a, b) => Number(b.similarity) - Number(a.similarity) || Number(b.matched) - Number(a.matched))+ .slice(0, 5).map((row) => ({ ...strip(row), similarity: Number(row.similarity) }));+ return { query, terms, hits: shown, not_found: shown.length === 0, closest };+}++export async function listCards(engine: BrainEngine, opts: { limit: number; offset: number; filters: CardFilters; policy?: PageReadScope }): Promise<{ cards: CardRow[]; total: number }> {+ const params: unknown[] = [STORAGE_SOURCE_ID, STORED_OBJECT_TYPE];+ const where = `p.source_id = $1 AND p.type = $2 AND ${pageReadFilter('p', opts.policy, params, true)}${cardFilterSql('p', opts.filters, params)}`;+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p WHERE ${where}`, params);+ params.push(opts.limit, opts.offset);+ const cards = await engine.executeRaw<CardRow>(`SELECT ${CARD_COLUMNS} FROM pages p WHERE ${where} ORDER BY p.slug LIMIT $${params.length - 1} OFFSET $${params.length}`, params);+ return { cards: cards.map((c) => ({ ...c, stores: c.stores ?? [] })), total: Number(n) };+}diff --git a/src/core/storage-manifest/schema.ts b/src/core/storage-manifest/schema.tsnew file mode 100644index 0000000000..82a6c2746c--- /dev/null+++ b/src/core/storage-manifest/schema.ts@@ -0,0 +1,183 @@+/**+ * Storage manifest cards (GST-1943): one page per item an agent archived to object storage (B2, Supabase Storage, S3 and+ * similar), validated on every storage write. The card lives under the page's `storage` frontmatter key; `title` and+ * `aliases` are the page's own, so search and alias lookup index them like any page.+ *+ * A card never carries a credential or a command: string fields are secret-scanned and shape-checked (env assignments,+ * credential-named variables, URL userinfo, presigned-URL parameters), keys that name a command are refused anywhere in+ * the card, and `restore` is a structured `{ skill, args }` the agent's own restore skill runs. gbrain itself never+ * contacts a store.+ */+import { z } from 'zod';+import { opError, type OperationError } from '../ops/contract.ts';+import { scanTextSpans } from '../secret-scan.ts';++export const STORED_OBJECT_TYPE = 'stored-object';+export const CARD_ID_RE = /^[a-z0-9][a-z0-9-]{1,79}$/;+export const STORES = ['b2', 'supabase', 's3', 'r2', 'gcs', 'other'] as const;+export const TOOLS = ['restic', 'object', 'rclone', 'other'] as const;+export const HASH_KINDS = ['sha256', 'sha256-tree-v1', 'b2-listing-sha1-v1', 'supabase-listing-etag-v1'] as const;+export const KINDS = ['directory', 'file', 'git-bundle', 'dataset', 'other'] as const;+export const STATUSES = ['archived', 'restored', 'missing', 'retired'] as const;+export const ORIGINS = ['local', 'adopt', 'import'] as const;+const RESTORES_KEPT = 20;+const DETAILS_MAX_BYTES = 64 * 1024;++const iso = z.string().min(1).max(64);+const text = (max: number) => z.string().max(max);+const count = z.number().int().nonnegative();++const LocationSchema = z.object({+ store: z.enum(STORES),+ bucket: text(200).nullish(),+ path: text(2000).min(1),+ tool: z.enum(TOOLS),+ repository: text(2000).nullish(),+ snapshot: text(200).nullish(),+ size_bytes: count,+ file_count: count.nullish(),+ sha256: z.string().regex(/^[a-f0-9]{64}$/).nullish(),+ hash_kind: z.enum(HASH_KINDS).nullish(),+ verified_at: iso.nullish(),+}).strict();++const RestoreSchema = z.object({+ skill: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),+ args: z.record(z.string().regex(/^[a-z0-9_][a-z0-9_-]{0,63}$/i), z.union([text(2000), z.number(), z.boolean()])).optional(),+}).strict();++const RestoreEventSchema = z.object({+ at: iso,+ to: text(2000).min(1),+ by: text(200).nullish(),+ verified: z.boolean(),+}).strict();++/** What a caller sends: every card field except the ones gbrain stamps. */+export const CardInputSchema = z.object({+ id: z.string().regex(CARD_ID_RE),+ title: text(300).min(1),+ aliases: z.array(text(200).min(1)).max(50).default([]),+ description: text(20_000).nullish(),+ kind: z.enum(KINDS),+ status: z.enum(STATUSES).default('archived'),+ locations: z.array(LocationSchema).min(1).max(20),+ original_path: text(2000).nullish(),+ on_source_machine: z.boolean().nullish(),+ source_machine: text(200).nullish(),+ archived_at: iso.nullish(),+ archived_by: text(200).nullish(),+ reason: text(2000).nullish(),+ restore: RestoreSchema,+ restores: z.array(RestoreEventSchema).max(RESTORES_KEPT).default([]),+ details: z.record(z.string(), z.unknown()).nullish(),+}).strict();++export type CardInput = z.infer<typeof CardInputSchema>;+export type Card = CardInput & { registered_by: string; origin: (typeof ORIGINS)[number] };++const COMMAND_KEYS = new Set(['command', 'cmd', 'script', 'exec', 'shell', 'instructions']);+const STAMPED_KEYS = ['registered_by', 'origin'] as const;+const CREDENTIAL_NAME = /(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|PASS|CRED|AUTH)/i;+const ENV_ASSIGNMENT = /(?:^|[\s;&|(])[A-Za-z_][A-Za-z0-9_]{1,}=\S/;+const VAR_REFERENCE = /\$\{?([A-Za-z_][A-Za-z0-9_]*)/g;+const URL_USERINFO = /[a-z][a-z0-9+.-]*:\/\/[^/\s@]*:[^/\s@]*@/i;+const PRESIGNED = /(?:X-Amz-Signature|X-Amz-Credential|X-Goog-Signature|Authorization=|[?&](?:token|sig|signature|access_token)=)/i;++function invalid(path: string, message: string, reason: string): OperationError {+ return opError('storage_record_invalid', `Storage card field ${path || '(card)'}: ${message}; nothing was written.`,+ 'Fix that field and send the card again; gbrain storage-register --help shows the card fields.', { reason });+}++/** Every string in `value` with its path, and every object key (command keys are refused wherever they appear). */+function walk(value: unknown, path: string, visit: (path: string, text: string) => void): void {+ if (typeof value === 'string') { visit(path, value); return; }+ if (Array.isArray(value)) { value.forEach((item, i) => walk(item, `${path}[${i}]`, visit)); return; }+ if (value && typeof value === 'object') {+ for (const [key, item] of Object.entries(value)) {+ const at = path ? `${path}.${key}` : key;+ if (COMMAND_KEYS.has(key.toLowerCase())) throw invalid(at, 'a card carries no commands; restore runs through restore.skill and restore.args', 'command_field');+ walk(item, at, visit);+ }+ }+}++/** The credential-shape rules over one string. Throws without echoing the value. */+function assertNoCredential(path: string, value: string): void {+ if (scanTextSpans(value).some((span) => span.finding !== null)) {+ throw opError('storage_record_secret', `Storage card field ${path} looks like it holds a secret; nothing was written.`,+ 'Remove the secret from that field. Cards name where an item is and how to restore it; credentials stay in the environment of the skill that restores it.',+ { reason: 'secret_scanner' });+ }+ const shape = ENV_ASSIGNMENT.test(value) ? 'env_assignment'+ : URL_USERINFO.test(value) ? 'url_userinfo'+ : PRESIGNED.test(value) ? 'presigned_url'+ : [...value.matchAll(VAR_REFERENCE)].some((m) => CREDENTIAL_NAME.test(m[1]!)) ? 'credential_variable' : null;+ if (shape) {+ throw opError('storage_record_secret', `Storage card field ${path} has a credential shape (${shape}); nothing was written.`,+ 'Drop the environment assignment, credential variable, URL password or signed-URL parameter from that field; the restore skill reads credentials from its own environment.',+ { reason: shape });+ }+}++/** Validate a caller's card. Returns the parsed card; throws storage_record_invalid or storage_record_secret. */+export function parseCardInput(raw: unknown): CardInput {+ let value = raw;+ if (typeof value === 'string') {+ try { value = JSON.parse(value); } catch { throw invalid('', 'the card must be a JSON object', 'not_json'); }+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid('', 'the card must be a JSON object', 'not_object');+ for (const key of STAMPED_KEYS) {+ if (Object.hasOwn(value, key)) throw invalid(key, 'gbrain sets this field itself', 'stamped_field');+ }+ walk(value, '', assertNoCredential);+ const details = (value as { details?: unknown }).details;+ if (details !== undefined && details !== null && Buffer.byteLength(JSON.stringify(details), 'utf8') > DETAILS_MAX_BYTES) {+ throw invalid('details', `details is over ${DETAILS_MAX_BYTES} bytes`, 'too_large');+ }+ const parsed = CardInputSchema.safeParse(value);+ if (!parsed.success) {+ const issue = parsed.error.issues[0]!;+ throw invalid(issue.path.map(String).join('.'), issue.message, 'schema');+ }+ return parsed.data;+}++/** The card stored on a page: `title` and `aliases` from the page, the rest from its `storage` frontmatter key. */+export function cardFromPage(page: { slug: string; title: string; frontmatter: Record<string, unknown> }): Card | null {+ const stored = page.frontmatter.storage;+ if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return null;+ const aliases = Array.isArray(page.frontmatter.aliases) ? page.frontmatter.aliases.filter((a): a is string => typeof a === 'string') : [];+ return { ...(stored as Card), id: page.slug, title: page.title, aliases };+}++function summary(card: Card): string {+ const lines: string[] = [];+ if (card.description) lines.push(card.description.trim(), '');+ lines.push('## Where it is', '');+ for (const loc of card.locations) {+ const parts = [`${loc.store}${loc.bucket ? ` bucket ${loc.bucket}` : ''}`, `path ${loc.path}`];+ if (loc.repository) parts.push(`${loc.tool} repository ${loc.repository}`);+ if (loc.snapshot) parts.push(`snapshot ${loc.snapshot}`);+ parts.push(`${loc.size_bytes} bytes${loc.file_count != null ? `, ${loc.file_count} files` : ''}`);+ if (loc.verified_at) parts.push(`verified ${loc.verified_at}`);+ lines.push(`- ${parts.join(', ')}`);+ }+ lines.push('');+ if (card.original_path) lines.push(`Original path: ${card.original_path}`);+ if (card.reason) lines.push(`Reason: ${card.reason}`);+ if (card.archived_at) lines.push(`Archived: ${card.archived_at}${card.archived_by ? ` by ${card.archived_by}` : ''}`);+ lines.push(`Restore: ${card.restore.skill}${card.restore.args ? ` with ${Object.entries(card.restore.args).map(([k, v]) => `${k}=${String(v)}`).join(', ')}` : ''}`);+ return lines.join('\n') + '\n';+}++/** Frontmatter and body for a card's page. */+export function cardPage(card: Card): { frontmatter: Record<string, unknown>; body: string } {+ const { id: _id, title, aliases, ...rest } = card;+ return { frontmatter: { type: STORED_OBJECT_TYPE, title, ...(aliases.length ? { aliases } : {}), storage: rest }, body: summary(card) };+}++/** Newest first, capped. */+export function withRestore(card: Card, event: z.infer<typeof RestoreEventSchema>): Card {+ return { ...card, status: 'restored', restores: [event, ...card.restores].slice(0, RESTORES_KEPT) };+}diff --git a/src/core/storage-manifest/source.ts b/src/core/storage-manifest/source.tsnew file mode 100644index 0000000000..7d65b82795--- /dev/null+++ b/src/core/storage-manifest/source.ts@@ -0,0 +1,92 @@+/**+ * The storage manifest source (GST-1943): one source, `storage`, holding a card per archived item. It is never+ * federated, so ordinary search and bound remote clients without a grant naming it never see cards, and only the+ * storage verbs write it (the page door refuses every other writer, see `assertStorageSourceWriter`).+ *+ * Repo-less brain: a database-only source, created by the first `storage_register`; the database is the record.+ * Repo brain (any active source with a directory): git stays the parent, so the shelf is a hosted git-canonical+ * repository (`hostRepo`), created only by `gbrain storage init` after its preview, which needs managed persistence.+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { STORAGE_ROLE, STORAGE_SOURCE_ID } from './door.ts';+import { readFix } from '../ops/op-fix.ts';+import { normalizeSourceConfig, parseSourceConfig } from '../sources-load.ts';+import { addSource } from '../sources-ops.ts';+import { hostRepo, type HostRepoPlan } from '../persistence/hosted-repo.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';++export { STORAGE_ROLE, STORAGE_SOURCE_ID, storageDoorContext, isStorageDoor, assertStorageSourceWriter } from './door.ts';++export function isStorageRole(config: unknown): boolean {+ return parseSourceConfig(config).role === STORAGE_ROLE;+}++export interface StorageSourceState { exists: boolean; repoBrain: boolean; role: boolean; hosted: boolean }++/** A repo brain is one with any active source that has a directory (or the legacy sync.repo_path of default); mixed brains count. */+export async function isRepoBrain(engine: BrainEngine): Promise<boolean> {+ const rows = await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL AND id <> $1 LIMIT 1', [STORAGE_SOURCE_ID]);+ return rows.length > 0 || !!(await engine.getConfig('sync.repo_path'));+}++export async function storageSourceState(engine: BrainEngine): Promise<StorageSourceState> {+ const [row] = await engine.executeRaw<{ config: unknown; archived: boolean }>('SELECT config, archived FROM sources WHERE id=$1', [STORAGE_SOURCE_ID]);+ const config = row ? parseSourceConfig(row.config) : {};+ return { exists: !!row && !row.archived, repoBrain: await isRepoBrain(engine), role: config.role === STORAGE_ROLE, hosted: !!config.hosted_repo };+}++function initFix() {+ return readFix('Previews creating the storage shelf on this brain; changes nothing.', { argv: ['gbrain', 'storage', 'init', '--dry-run'] });+}++async function markRole(engine: BrainEngine): Promise<void> {+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [STORAGE_SOURCE_ID]);+ const config = parseSourceConfig(row?.config);+ config.role = STORAGE_ROLE;+ config.federated = false;+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(config)), STORAGE_SOURCE_ID]);+}++/**+ * The shelf a storage write lands in. A repo-less brain gets its database-only source on first use; a repo brain+ * must run `gbrain storage init` first. A `storage` source that exists without the role is someone else's, refused.+ */+export async function ensureStorageSource(engine: BrainEngine): Promise<void> {+ const state = await storageSourceState(engine);+ if (state.exists && state.role) return;+ if (state.exists) throw opError('storage_manifest_missing', `Source ${STORAGE_SOURCE_ID} exists but is not a storage manifest; nothing was written.`,+ `The storage shelf needs the source ID ${STORAGE_SOURCE_ID}. Rename or remove the existing source (gbrain sources list shows it), then register again.`);+ if (state.repoBrain) throw opError('storage_manifest_missing', 'This brain keeps its pages in Git, so the storage shelf is a hosted Git repository that gbrain storage init creates; nothing was written.',+ 'Preview it with gbrain storage init --dir <absolute path> --dry-run, and apply the command it prints after the user agrees. It needs managed persistence (gbrain sources writer activate).',+ { fix: initFix() });+ await addSource(engine, { id: STORAGE_SOURCE_ID, name: 'Storage manifest', federated: false });+ await markRole(engine);+}++export interface StorageInitResult { action: 'none' | 'create_database_source' | 'host_repo'; dry_run: boolean; repo_brain: boolean; summary: string[]; apply?: string[]; plan?: HostRepoPlan }++/** `gbrain storage init`: preview, then apply. Repo-less: a database-only source. Repo brain: hostRepo, then the role. */+export async function initStorageSource(engine: BrainEngine, opts: { dir?: string; pushRemote?: string; dryRun: boolean; expect?: string }): Promise<StorageInitResult> {+ const state = await storageSourceState(engine);+ if (state.exists && state.role && (!state.repoBrain || state.hosted)) {+ return { action: 'none', dry_run: opts.dryRun, repo_brain: state.repoBrain, summary: [`The storage shelf (source ${STORAGE_SOURCE_ID}) already exists${state.hosted ? ' as a hosted Git repository' : ''}.`] };+ }+ if (state.exists && !state.role) throw opError('storage_manifest_missing', `Source ${STORAGE_SOURCE_ID} exists but is not a storage manifest.`,+ `Rename or remove the existing source first (gbrain sources list shows it); nothing was changed.`);+ if (!state.repoBrain) {+ const summary = [`Creates source ${STORAGE_SOURCE_ID}, database-only and not federated, as the storage shelf. This brain has no Git checkout, so the database is the record.`];+ if (opts.dryRun) return { action: 'create_database_source', dry_run: true, repo_brain: false, summary, apply: ['gbrain', 'storage', 'init'] };+ await ensureStorageSource(engine);+ return { action: 'create_database_source', dry_run: false, repo_brain: false, summary };+ }+ if (!opts.dir) throw opError('invalid_params', 'This brain keeps its pages in Git, so the storage shelf needs a directory for its hosted repository.',+ 'Pass --dir <absolute path outside every checkout>; nothing was changed.', { fix: initFix() });+ if (!await managedPersistenceEnabled(engine)) throw opError('strict_requires_managed',+ 'The storage shelf on a brain with a Git checkout is a git-canonical hosted repository, which needs managed persistence; nothing was created.',+ 'Ask the user whether to turn on managed persistence for this brain (gbrain sources writer activate), then preview gbrain storage init again.');+ const plan = await hostRepo(engine, { sourceId: STORAGE_SOURCE_ID, dir: opts.dir, dryRun: opts.dryRun, ...(opts.pushRemote ? { pushRemote: opts.pushRemote } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });+ const apply = plan.apply ? ['gbrain', 'storage', 'init', '--dir', opts.dir, ...(opts.pushRemote ? ['--push-remote', opts.pushRemote] : []), '--expect', plan.plan_hash] : undefined;+ if (!plan.dry_run) await markRole(engine);+ return { action: 'host_repo', dry_run: plan.dry_run, repo_brain: true, summary: [...plan.summary, 'The source is not federated and only the storage verbs write it.'], ...(apply ? { apply } : {}), plan };+}diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c742bbcd5b..d22ea79b88 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": 282967,- "stdoutSha256": "73f135de04ba7cceced4d9fd952b23aaefd7fb4cad5ebdf3dce1aca953c70f84",+ "stdoutBytes": 289409,+ "stdoutSha256": "7f40980027920edb253fe8d06964fd3ecbc425575357839782668fd67d6198ea","toolNames": ["remember","entity",@@ -93,6 +93,11 @@"file_url","file_register","file_verify",+ "storage_find",+ "storage_get",+ "storage_list",+ "storage_register",+ "storage_update","submit_job","get_job","wait_job",@@ -4485,6 +4490,208 @@},"scope": "admin"},+ {+ "description": "Find archived items on the storage shelf (files moved to B2, Supabase Storage, S3 and similar) by a plain phrase, such as \"the October Gmail dataset\". Ranks exact id, then exact alias, then cards matching most of the phrase's words in title, aliases and description. When nothing matches, not_found is true and closest lists the nearest cards. Then call storage_get with the id for where it is stored and how to restore it.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "storage_find",+ "parameters": {+ "limit": "number?",+ "query": "string",+ "status": "string?",+ "store": "string?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "limit": {+ "description": "Max hits (default 10, max 50).",+ "type": "number"+ },+ "query": {+ "description": "The phrase, id or alias.",+ "type": "string"+ },+ "status": {+ "description": "Only cards with this status.",+ "enum": [+ "archived",+ "restored",+ "missing",+ "retired"+ ],+ "type": "string"+ },+ "store": {+ "description": "Only cards with a copy in this store.",+ "enum": [+ "b2",+ "supabase",+ "s3",+ "r2",+ "gcs",+ "other"+ ],+ "type": "string"+ }+ },+ "required": [+ "query"+ ],+ "type": "object"+ },+ "scope": "read"+ },+ {+ "description": "Read one card from the storage shelf by id: what the item is, every stored copy (store, bucket, path, restic repository and snapshot, size, hash, when verified), the original path, why it was archived, the restore form (restore.skill and restore.args, run by the agent's own restore skill; cards carry no commands or credentials), past restores, who registered it, and its revision.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "storage_get",+ "parameters": {+ "id": "string"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "id": {+ "description": "Card id (storage_find returns it).",+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "type": "object"+ },+ "scope": "read"+ },+ {+ "description": "List cards on the storage shelf, sorted by id, optionally filtered by store, status or whether a copy is still on the source machine. Returns id, title, status, kind, stores and original path per card, and total.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "storage_list",+ "parameters": {+ "limit": "number?",+ "offset": "number?",+ "on_source_machine": "boolean?",+ "status": "string?",+ "store": "string?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "limit": {+ "description": "Max rows (default 50; max 500, remote 100).",+ "type": "number"+ },+ "offset": {+ "description": "Rows to skip, for paging.",+ "type": "number"+ },+ "on_source_machine": {+ "description": "Only cards whose item is (true) or is not (false) still on the machine it came from.",+ "type": "boolean"+ },+ "status": {+ "description": "Only cards with this status.",+ "enum": [+ "archived",+ "restored",+ "missing",+ "retired"+ ],+ "type": "string"+ },+ "store": {+ "description": "Only cards with a copy in this store.",+ "enum": [+ "b2",+ "supabase",+ "s3",+ "r2",+ "gcs",+ "other"+ ],+ "type": "string"+ }+ },+ "required": [],+ "type": "object"+ },+ "scope": "read"+ },+ {+ "description": "Register a new card on the storage shelf after an archive is verified. card is a JSON object: id, title, aliases, description, kind, status, locations (store, bucket, path, tool, repository, snapshot, size_bytes, file_count, sha256, hash_kind, verified_at), original_path, on_source_machine, source_machine, archived_at, archived_by, reason, restore {skill, args}, restores, details. Credentials, credential-shaped values and command fields are refused. Trusted local CLI only.",+ "idempotent": false,+ "local_only": true,+ "mutating": true,+ "name": "storage_register",+ "parameters": {+ "card": "object"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "card": {+ "description": "The card (JSON).",+ "type": "object"+ }+ },+ "required": [+ "card"+ ],+ "type": "object"+ },+ "scope": "write"+ },+ {+ "description": "Change a card on the storage shelf: patch replaces the named top-level fields (validated like a new card), and restored_to records a restore (newest first; status becomes restored). expected_revision is the revision storage_get returned; a stale one is refused storage_revision_conflict with the current revision. Trusted local CLI only.",+ "idempotent": false,+ "local_only": true,+ "mutating": true,+ "name": "storage_update",+ "parameters": {+ "expected_revision": "string",+ "id": "string",+ "patch": "object?",+ "restored_to": "string?",+ "restored_verified": "boolean?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "expected_revision": {+ "description": "The revision storage_get returned.",+ "type": "string"+ },+ "id": {+ "description": "Card id.",+ "type": "string"+ },+ "patch": {+ "description": "Top-level fields to replace (JSON).",+ "type": "object"+ },+ "restored_to": {+ "description": "Path the item was restored to; adds a restores entry.",+ "type": "string"+ },+ "restored_verified": {+ "description": "With restored_to: the checksums matched.",+ "type": "boolean"+ }+ },+ "required": [+ "id",+ "expected_revision"+ ],+ "type": "object"+ },+ "scope": "write"+ },{"description": "Submit a background job. Remote callers may submit sync, import, lint or lint-fix for their authenticated filesystem source. Other kinds require local CLI or a dedicated operation.","idempotent": false,diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex ea91f74979..b5f53550c6 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6840,7 +6840,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"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\" | \"owner_marker_missing\" | \"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_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"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\" | \"valid_time_undeclared\" | \"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\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"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_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"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\" | \"downgrade_blocked_deferred_writes\" | \"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\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"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_wins_rewrite\" | \"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_delta\" | \"conversion_file_in_source_root\" | \"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\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"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_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"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_backfill_pending\" | \"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\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"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\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"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\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"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\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"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\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"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\" | \"owner_marker_missing\" | \"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_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"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\" | \"valid_time_undeclared\" | \"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\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"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_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"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\" | \"downgrade_blocked_deferred_writes\" | \"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\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"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_wins_rewrite\" | \"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_delta\" | \"conversion_file_in_source_root\" | \"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\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"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_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"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_backfill_pending\" | \"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\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"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\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"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\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"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\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"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",@@ -8804,7 +8804,7 @@"kind": "type","name": "ThinkSynthesisStatus","signature": [- "\"ok\" | \"empty_answer\" | \"not_json\" | \"output_truncated\" | \"no_llm\" | \"model_unusable\" | \"llm_error\""+ "\"not_json\" | \"ok\" | \"empty_answer\" | \"output_truncated\" | \"no_llm\" | \"model_unusable\" | \"llm_error\""]},{diff --git a/test/storage-manifest-hosted.serial.test.ts b/test/storage-manifest-hosted.serial.test.tsnew file mode 100644index 0000000000..bc94dca409--- /dev/null+++ b/test/storage-manifest-hosted.serial.test.ts@@ -0,0 +1,62 @@+/**+ * GST-1943: the storage shelf on a brain with a Git checkout (managed persistence, PGLite). Git stays the parent: the+ * shelf is a hosted git-canonical repository that `gbrain storage init` creates after its preview, and every card is+ * committed there before the database indexes it. Protects:+ * - register refuses storage_manifest_missing until init runs; init previews without creating anything, a stale+ * plan_hash refuses, and the apply hosts the repository and marks the source with the storage role, not federated;+ * - a registered card is one commit on the hosted branch, and its file holds the card;+ * - put_page into the hosted shelf is refused storage_source_managed;+ * - an update with its revision commits again.+ * .serial: real git subprocesses and a GBRAIN_HOME swap.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { initStorageSource } from '../src/core/storage-manifest/source.ts';+import { git } from './helpers/git-publication.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) => operationsByName[name]!.handler(ctx, params) as Promise<Record<string, any>>;+const refusal = (promise: Promise<unknown>) => promise.then(() => null, (e: { code?: string; canonical?: string }) => e.canonical ?? e.code ?? 'error');+const card = (id: string) => ({ id, title: `Archive ${id}`, aliases: ['old research runs'], kind: 'directory',+ locations: [{ store: 'b2', bucket: 'bucket-a', path: `/archive/${id}`, tool: 'restic', repository: 'archive/restic', snapshot: 'c'.repeat(64), size_bytes: 4096 }],+ original_path: `/srv/data/${id}`, restore: { skill: 'restore-data', args: { id } } });++describe('storage shelf on a brain with a Git checkout', () => {+ test('init hosts the shelf after its preview; cards are committed before they are indexed; other writers are refused', () => managedBrain(async ({ engine, ctx, root }) => {+ expect(await refusal(call(ctx, 'storage_register', { card: card('runs-2026') }))).toBe('storage_manifest_missing');+ const dir = join(dirname(root), 'shelf');+ const preview = await initStorageSource(engine, { dir, dryRun: true });+ expect(preview).toMatchObject({ action: 'host_repo', dry_run: true, repo_brain: true });+ expect(preview.apply).toEqual(['gbrain', 'storage', 'init', '--dir', dir, '--expect', preview.plan!.plan_hash]);+ expect(await engine.executeRaw("SELECT 1 FROM sources WHERE id='storage'")).toEqual([]);+ expect(await refusal(initStorageSource(engine, { dir, dryRun: false, expect: 'f'.repeat(64) }))).toBe('preview_changed');++ const applied = await initStorageSource(engine, { dir, dryRun: false, expect: preview.plan!.plan_hash });+ expect(applied).toMatchObject({ action: 'host_repo', dry_run: false });+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string }>("SELECT config FROM sources WHERE id='storage'");+ const config = typeof source!.config === 'string' ? JSON.parse(source!.config) : source!.config;+ expect(config).toMatchObject({ role: 'storage_manifest', federated: false, canonical: 'git' });++ const repository = join(dir, 'repo.git');+ const before = git(repository, 'rev-list', '--count', 'main');+ await call(ctx, 'storage_register', { card: card('runs-2026') });+ expect(Number(git(repository, 'rev-list', '--count', 'main'))).toBe(Number(before) + 1);+ const file = git(repository, 'ls-tree', '-r', '--name-only', 'main').split('\n').find((path) => path.includes('runs-2026'));+ expect(file).toBeTruthy();+ const committed = git(repository, 'show', `main:${file}`);+ expect(committed).toContain('type: stored-object');+ expect(committed).toContain('restore-data');+ expect(readFileSync(join(dir, 'worktree', file!), 'utf8')).toBe(committed.endsWith('\n') ? committed : `${committed}\n`);++ expect(await refusal(call(ctx, 'put_page', { slug: 'runs-2026', source_id: 'storage', content: '---\ntype: note\ntitle: x\n---\nx\n', request_id: randomUUID() }))).toBe('storage_source_managed');++ const got = await call(ctx, 'storage_get', { id: 'runs-2026' });+ await call(ctx, 'storage_update', { id: 'runs-2026', expected_revision: got.revision, restored_to: '/scratch/runs-2026', restored_verified: true });+ expect(Number(git(repository, 'rev-list', '--count', 'main'))).toBe(Number(before) + 2);+ expect((await call(ctx, 'storage_find', { query: 'old research runs' })).hits[0]).toMatchObject({ id: 'runs-2026', match: 'alias' });+ }), 60_000);+});diff --git a/test/storage-manifest.test.ts b/test/storage-manifest.test.tsnew file mode 100644index 0000000000..f45a8c639e--- /dev/null+++ b/test/storage-manifest.test.ts@@ -0,0 +1,215 @@+/**+ * GST-1943: the storage shelf on a repo-less brain (PGLite; the database is the record). Protects:+ * - the first storage_register creates the database-only, non-federated storage source with its role, and the card+ * round-trips through storage_get with registered_by and origin stamped by gbrain;+ * - storage_find ranks exact id, then exact alias, then most of the phrase's words; a miss says not_found and lists+ * the closest cards; storage_list filters by store and status;+ * - validation refuses a missing field, a command field, a stamped field, a scanner secret and every credential shape+ * (env assignment, credential variable, URL userinfo, presigned URL), without echoing the value;+ * - the write guard: put_page and remember into the shelf are refused storage_source_managed, a forged parameter+ * does not open it, and the storage verbs still write;+ * - register never overwrites (storage_card_exists); update binds to the revision it read (storage_revision_conflict+ * carries the current one) and records a restore newest first;+ * - register and update refuse remote callers; the shelf is not federated, so a remote connection reads cards only+ * when its grant names the storage source (an ungranted bound client and an unbound stdio connection are refused);+ * - derived writers skip the shelf: a dream cycle scoped to the storage source runs no phase, and enrichment+ * considers no card there (no model call, no page write).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { runCycle } from '../src/core/cycle.ts';+import { runEnrichCore } from '../src/commands/enrich.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ home = mkdtempSync(join(tmpdir(), 'gbrain-storage-manifest-'));+}, 60_000);+afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+}, 60_000);+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ await engine.unsetConfig('sync.repo_path');+});++const ctx = (over: Partial<OperationContext> = {}): OperationContext => ({+ engine, config: { engine: engine.kind, embedding_disabled: true } as OperationContext['config'],+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default', ...over,+}) as OperationContext;+const call = (name: string, params: Record<string, unknown>, c: OperationContext = ctx()) =>+ operationsByName[name]!.handler(c, params) as Promise<Record<string, any>>;+const refusal = (promise: Promise<unknown>) => promise.then(() => null, (e: { code?: string; canonical?: string; reason?: string; message?: string }) => ({ code: e.canonical ?? e.code, reason: e.reason ?? null, message: e.message ?? '' }));++function card(id: string, over: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ id, title: `Dataset ${id}`, aliases: [], kind: 'directory', status: 'archived',+ description: 'Example archive used by the storage manifest tests.',+ locations: [{ store: 'b2', bucket: 'bucket-a', path: `/archive/${id}`, tool: 'restic', repository: 'archive/restic', snapshot: 'a'.repeat(64),+ size_bytes: 1024, file_count: 3, sha256: 'b'.repeat(64), hash_kind: 'sha256-tree-v1', verified_at: '2026-11-08T00:00:00Z' }],+ original_path: `/srv/data/${id}`, on_source_machine: false, archived_at: '2026-11-08T00:00:00Z', archived_by: 'archive-agent', reason: 'disk space',+ restore: { skill: 'restore-data', args: { id } },+ ...over,+ };+}++describe('storage shelf on a repo-less brain', () => {+ test('the first register creates the non-federated storage source; get round-trips the card with stamped fields', async () => {+ const out = await call('storage_register', { card: card('mail-export-oct', { aliases: ['october gmail dataset'] }) });+ expect(out).toMatchObject({ id: 'mail-export-oct', source_id: 'storage', origin: 'local' });+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string; local_path: string | null }>("SELECT config, local_path FROM sources WHERE id='storage'");+ const config = typeof source!.config === 'string' ? JSON.parse(source!.config) : source!.config;+ expect(config).toMatchObject({ role: 'storage_manifest', federated: false });+ expect(source!.local_path).toBeNull();+ const got = await call('storage_get', { id: 'mail-export-oct' });+ expect(got.card).toMatchObject({ id: 'mail-export-oct', title: 'Dataset mail-export-oct', aliases: ['october gmail dataset'], kind: 'directory',+ locations: [{ store: 'b2', snapshot: 'a'.repeat(64), size_bytes: 1024 }], restore: { skill: 'restore-data', args: { id: 'mail-export-oct' } }, origin: 'local' });+ expect(got.registered_by).toMatch(/^local_cli:/);+ expect(typeof got.revision).toBe('string');+ }, 30_000);++ test('find ranks id, alias and words; a miss lists the closest cards; list filters', async () => {+ await call('storage_register', { card: card('mail-export-oct', { title: 'October mail and web export', aliases: ['october gmail dataset'] }) });+ await call('storage_register', { card: card('model-weights-a', { title: 'Merged model weights', aliases: ['the big model'], kind: 'file' }) });+ await call('storage_register', { card: card('family-media', { title: 'Family media library', status: 'restored',+ locations: [{ store: 'supabase', bucket: 'bucket-b', path: 'items/family-media/', tool: 'object', size_bytes: 2048 }] }) });++ expect((await call('storage_find', { query: 'model-weights-a' })).hits[0]).toMatchObject({ id: 'model-weights-a', match: 'id' });+ expect((await call('storage_find', { query: 'October Gmail Dataset' })).hits[0]).toMatchObject({ id: 'mail-export-oct', match: 'alias' });+ const words = await call('storage_find', { query: 'bring back the merged model weights' });+ expect(words.hits[0]).toMatchObject({ id: 'model-weights-a', match: 'words' });+ expect(words.next.argv).toEqual(['gbrain', 'storage-get', 'model-weights-a', '--json']);++ const miss = await call('storage_find', { query: 'famly medai' });+ expect(miss.not_found).toBe(true);+ expect(miss.hits).toEqual([]);+ expect(miss.closest[0].id).toBe('family-media');++ const nothing = await call('storage_find', { query: 'zzqx quarterly invoices' });+ expect(nothing).toMatchObject({ not_found: true, hits: [] });++ expect((await call('storage_list', { store: 'supabase' })).cards.map((c: { id: string }) => c.id)).toEqual(['family-media']);+ expect((await call('storage_list', { status: 'archived' })).total).toBe(2);+ expect((await call('storage_find', { query: 'export', store: 'supabase' })).hits).toEqual([]);+ }, 30_000);++ test('validation refuses incomplete cards, command fields, stamped fields, secrets and credential shapes', async () => {+ const cases: Array<[Record<string, unknown>, string, string]> = [+ [card('a-1', { locations: [{ store: 'b2', path: '/x', tool: 'restic' }] }), 'storage_record_invalid', 'schema'],+ [card('a-2', { restore: { skill: 'restore-data', command: 'restore-data --id a-2' } }), 'storage_record_invalid', 'command_field'],+ [card('a-3', { details: { steps: [{ Script: 'rm -rf /' }] } }), 'storage_record_invalid', 'command_field'],+ [card('a-4', { origin: 'import' }), 'storage_record_invalid', 'stamped_field'],+ [card('a-5', { reason: 'key AKIAIOSFODNN7EXAMPLE was used' }), 'storage_record_secret', 'secret_scanner'],+ [card('a-6', { reason: 'run with B2_ACCOUNT_KEY=abcdef123' }), 'storage_record_secret', 'env_assignment'],+ [card('a-7', { restore: { skill: 'restore-data', args: { id: 'a-7', key: '$B2_APPLICATION_KEY' } } }), 'storage_record_secret', 'credential_variable'],+ [card('a-8', { locations: [{ store: 's3', path: 'https://user:@example.invalid/x', tool: 'object', size_bytes: 1 }] }), 'storage_record_secret', 'url_userinfo'],+ [card('a-9', { locations: [{ store: 's3', path: 'https://example.invalid/x?X-Amz-Signature=abc', tool: 'object', size_bytes: 1 }] }), 'storage_record_secret', 'presigned_url'],+ ];+ for (const [input, code, reason] of cases) {+ const r = await refusal(call('storage_register', { card: input }));+ expect({ id: input.id, code: r?.code, reason: r?.reason }).toEqual({ id: input.id, code, reason });+ expect(r!.message).not.toContain('abcdef123');+ expect(r!.message).not.toContain('AKIAIOSFODNN7EXAMPLE');+ }+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='storage'")).toEqual([]);+ }, 30_000);++ test('the write guard refuses put_page and remember into the shelf, forged parameters included', async () => {+ await call('storage_register', { card: card('guarded-item') });+ const put = await refusal(call('put_page', { slug: 'guarded-item', source_id: 'storage', content: '---\ntype: note\ntitle: x\n---\nOverwrite.\n', request_id: randomUUID() }));+ expect(put?.code).toBe('storage_source_managed');+ const forged = await refusal(call('put_page', { slug: 'other', source_id: 'storage', content: '---\ntype: note\ntitle: y\n---\nNew.\n', storage_door: true, request_id: randomUUID() }));+ expect(forged?.code).not.toBeNull();+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='storage' AND slug='other'")).toEqual([]);+ const remember = await refusal(call('remember', { fact: 'The item moved.', entity: 'guarded-item', source_id: 'storage', provenance: 'test', request_id: randomUUID() }));+ expect(remember?.message).toContain('is the storage manifest; only the storage verbs write it');+ expect(await engine.executeRaw("SELECT 1 FROM facts WHERE source_id='storage'")).toEqual([]);+ const got = await call('storage_get', { id: 'guarded-item' });+ expect(got.card.title).toBe('Dataset guarded-item');+ }, 30_000);++ test('register never overwrites; update binds to its revision and records restores newest first', async () => {+ await call('storage_register', { card: card('item-b') });+ expect((await refusal(call('storage_register', { card: card('item-b') })))?.code).toBe('storage_card_exists');+ const first = await call('storage_get', { id: 'item-b' });+ await call('storage_update', { id: 'item-b', expected_revision: first.revision, restored_to: '/scratch/item-b', restored_verified: true });+ const stale = await refusal(call('storage_update', { id: 'item-b', expected_revision: first.revision, patch: { status: 'retired' } }));+ expect(stale?.code).toBe('storage_revision_conflict');+ const second = await call('storage_get', { id: 'item-b' });+ expect(second.card.status).toBe('restored');+ expect(second.card.restores[0]).toMatchObject({ to: '/scratch/item-b', verified: true });+ await call('storage_update', { id: 'item-b', expected_revision: second.revision, restored_to: '/scratch/item-b-2' });+ const third = await call('storage_get', { id: 'item-b' });+ expect(third.card.restores.map((r: { to: string }) => r.to)).toEqual(['/scratch/item-b-2', '/scratch/item-b']);+ expect((await refusal(call('storage_update', { id: 'item-b', expected_revision: third.revision, patch: { reason: 'TOKEN=abc123' } })))?.code).toBe('storage_record_secret');+ expect((await refusal(call('storage_update', { id: 'item-b', expected_revision: third.revision, patch: { origin: 'import' } })))?.code).toBe('storage_record_invalid');+ }, 30_000);++ test('remote callers cannot write; a bound client without the storage grant reads nothing; only a grant naming the shelf reads it', async () => {+ await call('storage_register', { card: card('remote-item') });+ const remote = ctx({ remote: true, transport: 'http' } as Partial<OperationContext>);+ expect((await refusal(call('storage_register', { card: card('remote-new') }, remote)))?.code).toBe('trusted_local_only');+ const rev = (await call('storage_get', { id: 'remote-item' })).revision;+ expect((await refusal(call('storage_update', { id: 'remote-item', expected_revision: rev, patch: { status: 'retired' } }, remote)))?.code).toBe('trusted_local_only');++ const bound = ctx({ remote: true, transport: 'http', sourceId: 'default',+ auth: { token: 'fixture', clientId: 'client-a', principal: { kind: 'oauth_client', id: 'client-a' }, scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } as Partial<OperationContext>);+ const boundFind = await refusal(call('storage_find', { query: 'remote-item' }, bound));+ expect(boundFind?.code).toBe('permission_denied');+ expect((await refusal(call('storage_get', { id: 'remote-item' }, bound)))?.code).toBe('permission_denied');++ const unbound = ctx({ remote: true, transport: 'stdio' } as Partial<OperationContext>);+ expect((await refusal(call('storage_find', { query: 'remote-item' }, unbound)))?.code).toBe('permission_denied');++ const granted = ctx({ remote: true, transport: 'http', sourceId: 'default',+ auth: { token: 'fixture', clientId: 'client-b', principal: { kind: 'oauth_client', id: 'client-b' }, scopes: ['read'], sourceId: 'default', allowedSources: ['default', 'storage'] } } as Partial<OperationContext>);+ expect((await call('storage_find', { query: 'remote-item' }, granted)).hits[0].id).toBe('remote-item');+ expect((await call('storage_get', { id: 'remote-item' }, granted)).card.id).toBe('remote-item');+ }, 30_000);++ test('derived writers skip the shelf: dream scoped to it runs no phase, enrichment considers no card', async () => {+ await call('storage_register', { card: card('thin-card') });+ const before = await engine.executeRaw<{ revision: string }>("SELECT updated_at::text AS revision FROM pages WHERE source_id='storage'");+ const report = await runCycle(engine, { brainDir: null, sourceId: 'storage', phases: ['extract', 'extract_facts', 'backlinks', 'lint'] });+ expect(report).toMatchObject({ status: 'skipped', reason: 'storage_manifest_source', phases: [] });+ let modelCalls = 0;+ const enriched = await runEnrichCore(engine, { sourceId: 'storage', types: ['stored-object'], thinThreshold: 1_000_000, minContextChars: 0, dryRun: false,+ synthesizeFn: (async () => { modelCalls++; return 'enriched'; }) as never });+ expect(enriched).toMatchObject({ candidates_considered: 0, pages_enriched: 0, pages_failed: 0 });+ expect(modelCalls).toBe(0);+ expect(await engine.executeRaw("SELECT updated_at::text AS revision FROM pages WHERE source_id='storage'")).toEqual(before);+ }, 30_000);++ test('a brain with a Git checkout needs storage init first, and init needs managed persistence', async () => {+ await engine.setConfig('sync.repo_path', join(home, 'repo'));+ expect((await refusal(call('storage_register', { card: card('repo-item') })))?.code).toBe('storage_manifest_missing');+ const { initStorageSource } = await import('../src/core/storage-manifest/source.ts');+ expect((await refusal(initStorageSource(engine, { dryRun: true })))?.code).toBe('invalid_params');+ expect((await refusal(initStorageSource(engine, { dir: join(home, 'shelf'), dryRun: true })))?.code).toBe('strict_requires_managed');+ expect(await engine.executeRaw("SELECT 1 FROM sources WHERE id='storage'")).toEqual([]);+ }, 30_000);++ test('storage init on a repo-less brain previews, then creates the database-only shelf once', async () => {+ const { initStorageSource } = await import('../src/core/storage-manifest/source.ts');+ const preview = await initStorageSource(engine, { dryRun: true });+ expect(preview).toMatchObject({ action: 'create_database_source', dry_run: true, apply: ['gbrain', 'storage', 'init'] });+ expect(await engine.executeRaw("SELECT 1 FROM sources WHERE id='storage'")).toEqual([]);+ expect(await initStorageSource(engine, { dryRun: false })).toMatchObject({ action: 'create_database_source', dry_run: false });+ expect(await initStorageSource(engine, { dryRun: false })).toMatchObject({ action: 'none' });+ }, 30_000);+});