Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(engine-open): an embedded engine carries its own AI gateway (settings.ai)
garrytan0445fd3b9e7d
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex dbc762a6d1..f049a3327d 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1483,6 +1483,16 @@ More: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/moMore: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)+### engine_scope_missing++<a id="engine_scope_missing"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An engine opened from settings made an AI call (embed, chat, expansion or rerank) through a provider its settings.ai does not name, so nothing was sent. | An embedded engine's AI calls reach only the providers and keys its host passed as values. Falling back to a process.env key, ~/.gbrain/config.json or the process-wide gateway would spend another brain's key and send this brain's text where its host never pointed it. | Pass the provider in settings.ai.providers (apiKey, and baseUrl when it is not the default) to openEngine, or point settings.ai.models (or settings.embedding) at a provider the engine has. | agent | `repeat the read that failed` | 1 | no |++More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)+### engine_settings_invalid<a id="engine_settings_invalid"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 08eedaf929..e0ffdcdd0b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 1949 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug listsrc/commands/jobs.ts 687 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts)src/commands/serve-http.ts 941 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)-src/core/ai/gateway.ts 4538 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+src/core/ai/gateway.ts 4562 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)src/commands/sync.ts 559 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)src/core/cycle.ts 3345 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 relativesrc/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)diff --git a/src/core/ai/anthropic-key.ts b/src/core/ai/anthropic-key.tsindex c1969b3a1a..00a037ec14 100644--- a/src/core/ai/anthropic-key.ts+++ b/src/core/ai/anthropic-key.ts@@ -24,6 +24,15 @@*/import { loadConfig } from '../config.ts';+import { embeddedSettingsRecord } from '../embedded-engine.ts';+import { embeddedEngineInScope } from '../engine-scope.ts';++/** In an embedded engine's scope (engine-scope.ts): its own `settings.ai` Anthropic key, or null. Undefined outside one. */+function engineAnthropicKey(): string | null | undefined {+ const engine = embeddedEngineInScope();+ if (!engine) return undefined;+ return embeddedSettingsRecord(engine)?.ai?.providers.anthropic?.apiKey || null;+}/*** The Anthropic key the AI gateway was configured with, when it did NOT come@@ -64,6 +73,8 @@ export function setGatewayAnthropicKeySnapshot(key: string | undefined): void {* servable — without exposing a raw engine.getConfig read to the planner.*/export function getGatewayAnthropicKeySnapshot(): string | undefined {+ const scoped = engineAnthropicKey();+ if (scoped !== undefined) return scoped ?? undefined;return _gatewayEnvKeySnapshot;}@@ -73,12 +84,15 @@ export function hasAnthropicKey(): boolean {/*** Resolve the actual key value: env first, then the gateway env snapshot,- * then the gbrain config file. Callers constructing an Anthropic client+ * then the gbrain config file. In an embedded engine's scope, only that engine's+ * own `settings.ai.providers.anthropic.apiKey`. Callers constructing an Anthropic client* directly (e.g. the legacy subagent path) must pass this as `apiKey` — a* bare `new Anthropic()` only sees env, so launchd/MCP workers with* config-stored keys fail.*/export function resolveAnthropicKey(): string | undefined {+ const scoped = engineAnthropicKey();+ if (scoped !== undefined) return scoped ?? undefined;if (process.env.ANTHROPIC_API_KEY) return process.env.ANTHROPIC_API_KEY;if (_gatewayEnvKeySnapshot) return _gatewayEnvKeySnapshot;try {diff --git a/src/core/ai/engine-gateway.ts b/src/core/ai/engine-gateway.tsnew file mode 100644index 0000000000..21c49a645f--- /dev/null+++ b/src/core/ai/engine-gateway.ts@@ -0,0 +1,95 @@+/**+ * The AI gateway configuration of an engine `openEngine` opened, built from `settings.ai` and `settings.embedding`+ * alone: no `process.env` key, no `~/.gbrain/config.json` and no process-wide gateway reaches it. The gateway+ * (gateway.ts) reads it for every call that runs in that engine's scope (engine-scope.ts).+ */+import { opError } from '../ops/contract.ts';+import { embeddedSettingsRecord, type EngineSettings } from '../embedded-engine.ts';+import { embeddedEngineInScope } from '../engine-scope.ts';+import { DEFAULT_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_MODEL } from './defaults.ts';+import { getRecipe } from './recipes/index.ts';+import type { AIGatewayConfig, Recipe } from './types.ts';++const NATIVE_BASE_URL_ENV: Partial<Record<Recipe['implementation'], string>> = {+ 'native-openai': 'OPENAI_BASE_URL',+ 'native-anthropic': 'ANTHROPIC_BASE_URL',+ 'native-google': 'GOOGLE_GENERATIVE_AI_BASE_URL',+};++/** The env name the gateway reads a recipe's API key from; undefined for a recipe that takes none. */+export function recipeKeyEnv(recipe: Recipe): string | undefined {+ return recipe.auth_env?.required[0] ?? recipe.auth_env?.optional?.find(name => !/_(BASE_)?URL$/.test(name));+}++/**+ * Why `id` cannot be an engine provider, or null when it can. The local Claude CLI runs under this process's own+ * login, and Azure OpenAI reads its endpoint and deployment from the environment, so neither takes its settings+ * as values.+ */+export function engineProviderProblem(id: string): string | null {+ const recipe = getRecipe(id);+ if (!recipe) return `${id} is not a known provider.`;+ if (recipe.implementation === 'claude-cli') return `${id} runs the local Claude CLI under this process's login, so an engine cannot use it.`;+ if (recipe.resolveOpenAICompatConfig) return `${id} reads its endpoint from the environment, so an engine cannot use it yet.`;+ return null;+}++/** The gateway config and the providers an engine's calls may reach. Keys live only in `config.env`. */+export function engineGatewayInput(settings: EngineSettings): { config: AIGatewayConfig; providers: ReadonlySet<string> } {+ const env: Record<string, string> = {};+ const base_urls: Record<string, string> = {};+ const providers = settings.ai?.providers ?? {};+ for (const [id, provider] of Object.entries(providers)) {+ const recipe = getRecipe(id)!;+ const keyEnv = recipeKeyEnv(recipe);+ if (provider.apiKey && keyEnv) env[keyEnv] = provider.apiKey;+ if (!provider.baseUrl) continue;+ const nativeEnv = NATIVE_BASE_URL_ENV[recipe.implementation];+ if (nativeEnv) env[nativeEnv] = provider.baseUrl;+ else base_urls[id] = provider.baseUrl;+ }+ const models = settings.ai?.models ?? {};+ return {+ providers: new Set(Object.keys(providers)),+ config: {+ embedding_model: settings.embedding?.model ?? DEFAULT_EMBEDDING_MODEL,+ embedding_identity_unverified: false,+ embedding_dimensions: settings.embedding?.dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS,+ expansion_model: models.expansion,+ chat_model: models.chat,+ reranker_model: models.reranker,+ base_urls,+ env,+ },+ };+}++/** The config a gateway call uses and the clients built from it. `providers` is set only on an embedded engine's state. */+export interface GatewayState { config: AIGatewayConfig | null; modelCache: Map<string, any>; providers?: ReadonlySet<string>; cacheTag: string }++/** Keyed by the settings the engine holds, so a disconnect (which drops them) drops the state and its keys too. */+const states = new WeakMap<EngineSettings, GatewayState>();+const CLOSED = {} as EngineSettings;++/**+ * The state of the embedded engine the current call runs for (its page transactions, views and proxies share it), or+ * undefined outside one. `normalize` is the gateway's own config defaults. A disconnected engine has no providers.+ */+export function scopedGatewayState(normalize: (config: AIGatewayConfig) => AIGatewayConfig): GatewayState | undefined {+ const engine = embeddedEngineInScope();+ if (!engine) return undefined;+ const settings = embeddedSettingsRecord(engine) ?? CLOSED;+ let state = states.get(settings);+ if (!state) {+ const { config, providers } = engineGatewayInput(settings);+ state = { config: normalize(config), modelCache: new Map(), providers, cacheTag: `engine:${crypto.randomUUID()}:` };+ states.set(settings, state);+ }+ return state;+}++/** The refusal for a call whose provider the engine was not given. Names the provider and touchpoint, never a key. */+export function engineScopeMissing(provider: string, touchpoint: string): Error {+ return opError('engine_scope_missing', `This engine has no AI provider ${provider} for ${touchpoint}.`,+ `An engine opened from settings calls only the providers in settings.ai.providers, never a process.env key, ~/.gbrain/config.json or the process-wide gateway, so nothing was sent. Pass settings.ai.providers.${provider} (apiKey, and baseUrl when it is not the default) to openEngine, or point settings.ai.models (or settings.embedding) at a provider the engine has.`);+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 0d8e144388..24ef295009 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -64,6 +64,8 @@ import { parseLlmJson } from '../llm-json.ts';import type { BrainEngine } from '../engine.ts';import { dimsProviderOptions } from './dims.ts';import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';+import { withEngineScope } from '../engine-scope.ts';+import { engineScopeMissing, scopedGatewayState, type GatewayState } from './engine-gateway.ts';import { AIConfigError, AITransientError, isStructuredOutputRejection, isUnbilledEmbeddingRejection, normalizeAIError } from './errors.ts';import { embeddingModelNotFoundHint, gatewayModelNotFoundHint } from './model-not-found-hint.ts';import { fitMatryoshkaPrefix, isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';@@ -137,10 +139,17 @@ const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';// `DEFAULT_RERANKER_MODEL` imported from ./defaults.ts (ONE constant, shared with// the mode bundles) — `voyage:rerank-3-lite` (was `voyage:rerank-2.5` from v0.48.2).-let _config: AIGatewayConfig | null = null;+/** What `configureGateway` writes and every call reads, except a call in an embedded engine's scope (engine-gateway.ts). */+const processState: GatewayState = { config: null, modelCache: new Map(), cacheTag: '' };+const gw = (): GatewayState => scopedGatewayState(gatewayConfigOf) ?? processState;+/** The config a call to `recipe` uses; an embedded engine not given that provider refuses `engine_scope_missing`. */+function configFor(recipe: Recipe, touchpoint: string): AIGatewayConfig {+ const { providers } = gw();+ if (providers && !providers.has(recipe.id)) throw engineScopeMissing(recipe.id, touchpoint);+ return requireConfig();+}/** #5137: provider auth errors echo keys; scrub every key in effect before the text leaves the gateway. */-const redactKeys = (text: string): string => redactProviderKeys(text, _config?.env ?? {});-const _modelCache = new Map<string, any>();+const redactKeys = (text: string): string => redactProviderKeys(text, gw().config?.env ?? {});/*** Materialize `applyResolveAuth`'s SDK-shaped result ({apiKey}|{headers}) into@@ -163,7 +172,7 @@ export function authToHeaders(auth: { apiKey?: string; headers?: Record<string,* are deliberately left unchanged.*/export function configureGatewayIfUninitialized(): void {- if (_config) return;+ if (processState.config || gw() !== processState) return;const config = loadConfig();if (config) configureGateway(buildGatewayConfig(config));}@@ -457,7 +466,21 @@ export function recipeSupportsStructuredOutputs(recipe: Recipe): boolean {/** Configure the gateway. Called by cli.ts#connectEngine. Clears cached models. */export function configureGateway(config: AIGatewayConfig): void {- _config = {+ processState.config = gatewayConfigOf(config);+ stashGatewayAnthropicKeyFromEnv(config.env); // #2119: filter + rationale in anthropic-key.ts+ processState.modelCache.clear();+ clearQueryEmbedCache();+ _shrinkState.clear();+ // A (re)configure is a new env snapshot: a key that appeared or vanished+ // since the last no_key audit row deserves a fresh once-per-process row.+ _noKeyNoticed.clear();+ warnRecipesMissingBatchTokens();+ installAICallLogFromEnv();+}++/** The config the gateway keeps for `config`, with the chat and expansion defaults applied. */+function gatewayConfigOf(config: AIGatewayConfig): AIGatewayConfig {+ return {embedding_model: config.embedding_model,embedding_identity_unverified: config.embedding_identity_unverified,// #1292/D6: do NOT fabricate a default here. Every gateway-internal reader@@ -481,15 +504,6 @@ export function configureGateway(config: AIGatewayConfig): void {provider_chat_options: config.provider_chat_options,env: config.env,};- stashGatewayAnthropicKeyFromEnv(config.env); // #2119: filter + rationale in anthropic-key.ts- _modelCache.clear();- clearQueryEmbedCache();- _shrinkState.clear();- // A (re)configure is a new env snapshot: a key that appeared or vanished- // since the last no_key audit row deserves a fresh once-per-process row.- _noKeyNoticed.clear();- warnRecipesMissingBatchTokens();- installAICallLogFromEnv();}/**@@ -501,7 +515,7 @@ export function configureGateway(config: AIGatewayConfig): void {* here would reset those to file-plane-only values). No-op before configure.*/export function refreshGatewayEnvFromFilePlane(): void {- if (!_config) return;+ if (!processState.config) return;let cfg: GBrainConfig | null = null;try {cfg = loadConfig();@@ -513,8 +527,8 @@ export function refreshGatewayEnvFromFilePlane(): void {// boot fold installed from provider_base_urls.{anthropic,openai}. File-plane// only (cfg is loadConfig() here), preserving the mount-safety rule that// DB-plane base_urls never steer native keys.- _config = { ..._config, env: foldNativeBaseUrlsFromFilePlane(cfg, mergedProviderEnv(cfg, process.env)) };- _modelCache.clear();+ processState.config = { ...processState.config, env: foldNativeBaseUrlsFromFilePlane(cfg, mergedProviderEnv(cfg, process.env)) };+ processState.modelCache.clear();clearQueryEmbedCache();}@@ -538,9 +552,13 @@ export function refreshGatewayEnvFromFilePlane(): void {* config for callers who want to inspect what landed.*/export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promise<AIGatewayConfig> {- _discoveryEngine = engine;- _discovery = null;- return resolveGatewayModels(engine);+ return withEngineScope(engine, async () => {+ // An embedded engine's models are values in its settings: nothing to re-resolve, and its config stays its own.+ if (gw() !== processState) return requireConfig();+ _discoveryEngine = engine;+ _discovery = null;+ return resolveGatewayModels(engine);+ });}let _discoveryEngine: BrainEngine | null = null;@@ -555,7 +573,7 @@ let _discovery: Promise<void> | null = null;* key. Fail-open.*/async function discoverBeforeOpenAICall(modelStr: string | undefined): Promise<void> {- if (!modelStr) return;+ if (!modelStr || gw().providers) return;try { if (resolveRecipe(modelStr).recipe.id !== 'openai') return; } catch { return; }_discovery ??= (async () => {try {@@ -627,13 +645,13 @@ async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConficonst expansionFull = newExpansion.includes(':') ? newExpansion : prefixWithProviderFrom(cfg.expansion_model ?? DEFAULT_EXPANSION_MODEL, newExpansion);const chatFull = newChat.includes(':') ? newChat : prefixWithProviderFrom(cfg.chat_model ?? DEFAULT_CHAT_MODEL, newChat);- _config = { ...cfg, expansion_model: expansionFull, chat_model: chatFull };+ processState.config = { ...cfg, expansion_model: expansionFull, chat_model: chatFull };setGatewayModelSource('expansion', expansionFull, dbExpansion ? { source: 'config_key', origin: 'expansion_model' } : gatewayModelSource('expansion', expansionDetailed, expansionEffective));setGatewayModelSource('chat', chatFull, dbChat ? { source: 'config_key', origin: 'chat_model' } : gatewayModelSource('chat', chatDetailed, chatEffective));- _modelCache.clear();+ processState.modelCache.clear();clearQueryEmbedCache();_shrinkState.clear();- return _config;+ return processState.config;}/** Carry over the provider prefix from `original` when `bare` lacks one. */@@ -664,7 +682,7 @@ const _warnedRecipes = new Set<string>();*/function warnRecipesMissingBatchTokens(): void {const configuredProviderIds = new Set<string>();- for (const model of [_config?.embedding_model, _config?.embedding_multimodal_model]) {+ for (const model of [processState.config?.embedding_model, processState.config?.embedding_multimodal_model]) {if (!model) continue;const providerId = model.split(':')[0];if (providerId) configuredProviderIds.add(providerId);@@ -710,12 +728,12 @@ export function __setGatewayResetBaselineForTests(/** Clear every piece of module state. Shared by both reset flavors. */function clearGatewayState(): void {- _config = null;+ processState.config = null;_discoveryEngine = null;_discovery = null;clearGatewayModelSources();stashGatewayAnthropicKeyFromEnv(undefined); // gateway-owned snapshot dies with the config- _modelCache.clear();+ processState.modelCache.clear();clearQueryEmbedCache();_shrinkState.clear();_embedTransport = sdkEmbedMany;@@ -824,13 +842,14 @@ export function __setChatTransportForTests(* `models doctor` base-URL probe (which reads the same merged config the* gateway calls with, inside its own fail-open guard). */export function requireConfig(): AIGatewayConfig {- if (!_config) {+ const config = gw().config;+ if (!config) {throw new AIConfigError('AI gateway is not configured. Call configureGateway() during engine connect.','This is a gbrain bug — file an issue at https://github.com/garrytan/gbrain/issues',);}- return _config;+ return config;}/** Public config accessors (for schema setup, doctor, etc.). */@@ -932,7 +951,8 @@ export type EmbeddingDiagnosis =| { ok: false; reason: 'missing_env'; model: string; provider: string; recipeId: string; missingEnvVars: string[] };export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {- if (_config?.embedding_identity_unverified && !modelOverride) {+ const config = gw().config;+ if (config?.embedding_identity_unverified && !modelOverride) {return { ok: false, reason: 'unknown_provider', model: 'unconfigured', provider: 'unconfigured', message: unverifiedEmbeddingIdentityError().message };}// Test-transport fast path: matches the `if (touchpoint === 'chat' &&@@ -940,13 +960,13 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {// install an embed transport stub also pass the preflight without// having to configure real provider env vars.if (_embedTransportInstalled) {- const modelStr = modelOverride ?? _config?.embedding_model ?? DEFAULT_EMBEDDING_MODEL;+ const modelStr = modelOverride ?? config?.embedding_model ?? DEFAULT_EMBEDDING_MODEL;return { ok: true, model: modelStr, provider: '<test-transport>', recipeId: '<test-transport>' };}- if (!_config) return { ok: false, reason: 'no_gateway_config' };+ if (!config) return { ok: false, reason: 'no_gateway_config' };- const modelStr = modelOverride ?? _config.embedding_model ?? DEFAULT_EMBEDDING_MODEL;+ const modelStr = modelOverride ?? config.embedding_model ?? DEFAULT_EMBEDDING_MODEL;if (!modelStr) return { ok: false, reason: 'no_model_configured' };let parsed;@@ -999,7 +1019,7 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {// listed models via model_dims, so those must not fail preflight when// embedding_dimensions is unset — only genuinely unknown ids do.const recipeDeclaredDims = embeddingDimsForModel(recipe, parsed.modelId);- if ((isUserProvided || recipeDeclaredDims === 0) && !_config!.embedding_dimensions) {+ if ((isUserProvided || recipeDeclaredDims === 0) && !config!.embedding_dimensions) {return {ok: false,reason: 'user_provided_dims_unset',@@ -1014,9 +1034,9 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {// keyless local OpenAI-compatible server, so the override satisfies the// key requirement — mirrors instantiateEmbedding's placeholder path.const keylessBaseUrl =- recipe.implementation === 'native-openai' && !!resolveNativeBaseUrl('openai', _config);+ recipe.implementation === 'native-openai' && !!resolveNativeBaseUrl('openai', config);const missing = required.filter(- k => !_config!.env[k] && !(keylessBaseUrl && k === 'OPENAI_API_KEY'),+ k => !config!.env[k] && !(keylessBaseUrl && k === 'OPENAI_API_KEY'),);if (missing.length > 0) {return {@@ -1053,6 +1073,7 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {* their inline logic for now.*/export function isAvailable(touchpoint: TouchpointKind, modelOverride?: string): boolean {+ const config = gw().config;// Test seam: when a transport stub is installed for this touchpoint, the// gateway is "available" for tests that exercise the whole pipeline without// configuring real providers. See __setChatTransportForTests /@@ -1061,7 +1082,7 @@ export function isAvailable(touchpoint: TouchpointKind, modelOverride?: string):if (touchpoint === 'embedding') return diagnoseEmbedding(modelOverride).ok;- if (!_config) return false;+ if (!config) return false;try {const modelStr =modelOverride@@ -1085,7 +1106,7 @@ export function isAvailable(touchpoint: TouchpointKind, modelOverride?: string):// For openai-compatible without auth requirements (Ollama local), treat as always-available.const required = recipe.auth_env?.required ?? [];if (required.length === 0) return true;- return required.every(k => !!_config!.env[k]);+ return required.every(k => !!config!.env[k]);} catch {return false;}@@ -1429,14 +1450,14 @@ async function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any;await discoverBeforeOpenAICall(modelStr);const { parsed, recipe } = resolveRecipe(modelStr);assertTouchpoint(recipe, 'embedding', parsed.modelId);- const cfg = requireConfig();+ const cfg = configFor(recipe, 'embedding');const cacheKey = `emb:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;- const cached = _modelCache.get(cacheKey);+ const cached = gw().modelCache.get(cacheKey);if (cached) return { model: cached, recipe, modelId: parsed.modelId };const model = instantiateEmbedding(recipe, parsed.modelId, cfg);- _modelCache.set(cacheKey, model);+ gw().modelCache.set(cacheKey, model);return { model, recipe, modelId: parsed.modelId };}@@ -1799,7 +1820,7 @@ async function embedSubBatch(const embeddings: number[][] = result.embeddings.map((e: number[]) => fitMatryoshkaPrefix(recipe, modelId, e, expectedDims)); // PR #5921for (const embedding of embeddings) {if (Array.isArray(embedding) && embedding.length !== expectedDims) {- throw embeddingDimMismatchError(modelId, embedding.length, expectedDims, `gbrain migrate --embedding-model ${getEmbeddingModel()} --embedding-dimensions ${embedding.length}`, { provider: recipe.id, baseUrl: _config?.base_urls?.[recipe.id], defaultBaseUrl: recipe.base_url_default });+ throw embeddingDimMismatchError(modelId, embedding.length, expectedDims, `gbrain migrate --embedding-model ${getEmbeddingModel()} --embedding-dimensions ${embedding.length}`, { provider: recipe.id, baseUrl: gw().config?.base_urls?.[recipe.id], defaultBaseUrl: recipe.base_url_default });}}@@ -1850,7 +1871,7 @@ export async function embedQuery(const cfg = requireConfig();const { recipe, modelId } = await resolveEmbeddingProvider(opts?.embeddingModel ?? getEmbeddingModel());const dims = opts?.dimensions ?? cfg.embedding_dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;- const key = queryEmbedCacheKey(recipe.id, modelId, cfg.base_urls?.[recipe.id] ?? '', dims, input);+ const key = queryEmbedCacheKey(recipe.id, modelId, gw().cacheTag + (cfg.base_urls?.[recipe.id] ?? ''), dims, input);const cached = hasAIInvocationGuard() ? undefined : cachedQueryEmbedding(key);if (cached) return cached;const generation = queryEmbedGeneration();@@ -1901,6 +1922,7 @@ export async function embedMultimodal(if (!tracker) return embedMultimodalUnmetered(inputs, opts);const modelStr = requireConfig().embedding_multimodal_model ?? getEmbeddingModel();const { parsed, recipe } = resolveRecipe(modelStr);+ configFor(recipe, 'embedding');const mmModelId = `${recipe.id}:${parsed.modelId}`;const charsPerToken = Math.max(recipe.touchpoints.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN, 1);const estimatedInputTokens = inputs.reduce((n, input) => n + (input.kind === 'text' ? Math.ceil(input.text.length / charsPerToken) : MULTIMODAL_IMAGE_TOKEN_CEILING), 0);@@ -1931,6 +1953,7 @@ async function embedMultimodalUnmetered(// primary embedding_model. Falls back to embedding_model for single-model setups.const modelStr = cfg.embedding_multimodal_model ?? getEmbeddingModel();const { parsed, recipe } = resolveRecipe(modelStr);+ configFor(recipe, 'embedding');const touchpoint = recipe.touchpoints.embedding;if (!touchpoint?.supports_multimodal) {throw new AIConfigError(@@ -2368,14 +2391,14 @@ async function resolveExpansionProvider(modelStr: string): Promise<{ model: any;await discoverBeforeOpenAICall(modelStr);const { parsed, recipe } = resolveRecipe(modelStr);assertTouchpoint(recipe, 'expansion', parsed.modelId);- const cfg = requireConfig();+ const cfg = configFor(recipe, 'expansion');const cacheKey = `exp:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;- const cached = _modelCache.get(cacheKey);+ const cached = gw().modelCache.get(cacheKey);if (cached) return { model: cached, recipe, modelId: parsed.modelId };const model = instantiateExpansion(recipe, parsed.modelId, cfg);- _modelCache.set(cacheKey, model);+ gw().modelCache.set(cacheKey, model);return { model, recipe, modelId: parsed.modelId };}@@ -2517,7 +2540,7 @@ export async function expand(query: string): Promise<string[]> {});try {- await discoverBeforeOpenAICall(_config?.expansion_model);+ await discoverBeforeOpenAICall(gw().config?.expansion_model);const requestedModelId = getExpansionModel();const { model, recipe, modelId } = await resolveExpansionProvider(requestedModelId);const modelLabel = `${recipe.id}:${modelId}`;@@ -2663,7 +2686,7 @@ export async function expand(query: string): Promise<string[]> {} catch (err) {if (isAIInvocationPolicyError(err)) throw err;// Expansion is best-effort: on failure, fall back to the original query alone.- const normalized = normalizeAIError(err, `expand(${_config?.expansion_model ?? ''})`, redactKeys, gatewayModelNotFoundHint('expansion', _config?.expansion_model ?? ''));+ const normalized = normalizeAIError(err, `expand(${gw().config?.expansion_model ?? ''})`, redactKeys, gatewayModelNotFoundHint('expansion', gw().config?.expansion_model ?? ''));if (normalized instanceof AIConfigError) {console.warn(`[ai.gateway] expansion disabled: ${normalized.message}`);}@@ -2690,7 +2713,7 @@ export async function expand(query: string): Promise<string[]> {export async function generateOcrText(imageBytes: Buffer, mime: string): Promise<string> {// Unconfigured gateway stays a silent '' no-op (the pre-#4107 isAvailable// gate's behavior), never a requireConfig() throw.- if (!_config) return '';+ if (!gw().config) return '';const ocrModel = getImageOcrModel();// Fail-closed on a misconfigured OCR model (provider without an expansion// touchpoint, or unkeyed): '' rather than silently OCRing with the@@ -3297,14 +3320,14 @@ async function resolveChatProvider(modelStr: string): Promise<{ model: any; reciawait discoverBeforeOpenAICall(modelStr);const { parsed, recipe } = resolveRecipe(modelStr);assertTouchpoint(recipe, 'chat', parsed.modelId);- const cfg = requireConfig();+ const cfg = configFor(recipe, 'chat');const cacheKey = `chat:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;- const cached = _modelCache.get(cacheKey);+ const cached = gw().modelCache.get(cacheKey);if (cached) return { model: cached, recipe, modelId: parsed.modelId };const model = instantiateChat(recipe, parsed.modelId, cfg);- _modelCache.set(cacheKey, model);+ gw().modelCache.set(cacheKey, model);return { model, recipe, modelId: parsed.modelId };}@@ -3544,9 +3567,9 @@ export function toAISDKTools(tools: ChatToolDef[] | undefined): Record<string, a}export async function chat(opts: ChatOpts): Promise<ChatResult> {- await discoverBeforeOpenAICall(opts.model ?? _config?.chat_model);- const fallbackChain = opts.allowFallback === false ? undefined : _config?.chat_fallback_chain;- if (fallbackChain?.length) return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat, { onRefusal: _config?.chat_fallback_on_refusal !== false });+ await discoverBeforeOpenAICall(opts.model ?? gw().config?.chat_model);+ const fallbackChain = opts.allowFallback === false ? undefined : gw().config?.chat_fallback_chain;+ if (fallbackChain?.length) return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat, { onRefusal: gw().config?.chat_fallback_on_refusal !== false });const tracker = __budgetStore.getStore() ?? null;const modelStrEarly = opts.model ?? getChatModel();@@ -3592,6 +3615,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {// Test seam: when a test transport is installed, route through it without// touching provider resolution, AI SDK, or any network. See// __setChatTransportForTests. Production paths see _chatTransport === null.+ if (gw().providers) configFor(resolveRecipe(modelStrEarly).recipe, 'chat');if (_chatTransport) {let res: ChatResult | null = null;let threw: unknown = null;@@ -4341,7 +4365,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {'unknown',);}- const cfg = requireConfig();+ const cfg = configFor(recipe, 'reranker');if (tp.wire_format === 'typesafe-systemone') { // System One reranker: packed score questions via the decide core (#5178 contract)if (recipe.authPresent && !recipe.authPresent(cfg.env)) { noKeyOnce(modelStr, 'TYPESAFE_API_KEY', input.query, input.documents.length); throw new RerankError(`Reranker ${modelStr} needs TYPESAFE_API_KEY (not set) — rerank skipped, results pass through unreranked.`, 'no_key'); }return rerankViaDecide(input, { model: modelStr, modelId: parsed.modelId, maxPayloadBytes: tp.max_payload_bytes, defaultTimeoutMs: DEFAULT_RERANK_TIMEOUT_MS, tracker, transport: _rerankTransport ?? ((u, init) => fetch(u, init)),diff --git a/src/core/embedded-engine.ts b/src/core/embedded-engine.tsindex 66adbf3855..b1d5c0ce95 100644--- a/src/core/embedded-engine.ts+++ b/src/core/embedded-engine.ts@@ -24,10 +24,24 @@ export interface EngineSettings {/** `search.keyword_statement_timeout_ms` for this engine (Postgres). */keyword_statement_timeout_ms?: number;pglite?: { shared_buffers?: string };+ /**+ * This engine's AI gateway: the only providers its embed, chat and rerank calls reach, keyed by provider id+ * (`openai`, `voyage`, ...), and the `provider:model` it uses for chat, expansion and reranking. The embedding+ * model is `embedding` above. Without it every AI call refuses `engine_scope_missing`; no process key is used.+ */+ ai?: EngineAISettings;}-/** The settings `embeddedSettings` returns: everything the host passed except the writer credential. */-export type EmbeddedSettingsView = Readonly<Omit<EngineSettings, 'writer'> & { writer?: { id: string; lane: 'cli' | 'stdio' } }>;+export interface EngineAISettings {+ providers: Record<string, { apiKey?: string; baseUrl?: string }>;+ models?: { chat?: string; expansion?: string; reranker?: string };+}++/** The settings `embeddedSettings` returns: everything the host passed except the writer credential and the provider keys. */+export type EmbeddedSettingsView = Readonly<Omit<EngineSettings, 'writer' | 'ai'> & {+ writer?: { id: string; lane: 'cli' | 'stdio' };+ ai?: { providers: Record<string, { baseUrl?: string; hasApiKey: boolean }>; models?: EngineAISettings['models'] };+}>;interface EmbeddedRecord {hostId: string | undefined;@@ -70,12 +84,15 @@ export function embeddedSettingsRecord(engine: object): EngineSettings | undefinreturn recordOf(engine)?.settings ?? undefined;}-/** The settings an embedded engine was opened with, without the writer credential; undefined after disconnect. */+/** The settings an embedded engine was opened with, without the writer credential or provider keys; undefined after disconnect. */export function embeddedSettings(engine: object): EmbeddedSettingsView | undefined {const settings = embeddedSettingsRecord(engine);if (!settings) return undefined;- const { writer, ...rest } = settings;- return Object.freeze({ ...rest, ...(writer ? { writer: { id: writer.id, lane: writer.lane } } : {}) });+ const { writer, ai, ...rest } = settings;+ const providers = ai && Object.fromEntries(Object.entries(ai.providers)+ .map(([id, p]) => [id, { ...(p.baseUrl ? { baseUrl: p.baseUrl } : {}), hasApiKey: !!p.apiKey }]));+ return Object.freeze({ ...rest, ...(writer ? { writer: { id: writer.id, lane: writer.lane } } : {}),+ ...(ai ? { ai: { providers: providers!, ...(ai.models ? { models: { ...ai.models } } : {}) } } : {}) });}/** Drops the settings (the writer credential included) an embedded engine held; it stays marked embedded with its host id. */diff --git a/src/core/engine-open.ts b/src/core/engine-open.tsindex 1751803750..b503568d8e 100644--- a/src/core/engine-open.ts+++ b/src/core/engine-open.ts@@ -6,11 +6,14 @@ import type { BrainEngine } from './engine.ts';import type { EngineConfig } from './types.ts';import { opError } from './ops/contract.ts';import { createEngine } from './engine-factory.ts';-import { markEmbeddedEngine, releaseEmbeddedEngine, type EngineSettings } from './embedded-engine.ts';+import { markEmbeddedEngine, releaseEmbeddedEngine, type EngineAISettings, type EngineSettings } from './embedded-engine.ts';import { assertLocalWriterValue, setEngineHostId } from './persistence/identity.ts';+import { engineProviderProblem, recipeKeyEnv } from './ai/engine-gateway.ts';+import { getRecipe } from './ai/recipes/index.ts';-export type { EngineSettings, EmbeddedSettingsView } from './embedded-engine.ts';+export type { EngineAISettings, EngineSettings, EmbeddedSettingsView } from './embedded-engine.ts';export { embeddedSettings, isEmbeddedEngine, processHasEmbeddedEngines } from './embedded-engine.ts';+export { withEngineScope } from './engine-scope.ts';export { hostIdFor } from './persistence/identity.ts';/** Connections a Postgres engine opened from settings may open when `pool.max` is not given. */@@ -19,6 +22,30 @@ export const DEFAULT_EMBEDDED_POOL_MAX = 4;const invalid = (setting: string, why: string) => opError('engine_settings_invalid', `The ${setting} setting is invalid.`, `${why} Nothing was opened.`);const text = (value: unknown) => typeof value === 'string' && value.length > 0;const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const AI_MODELS = ['chat', 'expansion', 'reranker'];++/** Names the setting that is wrong, never a key: a key's value is never part of a refusal. */+function checkAI(ai: EngineAISettings): void {+ if (!ai || typeof ai !== 'object' || !ai.providers || typeof ai.providers !== 'object') {+ throw invalid('ai', 'ai is { providers: { <provider id>: { apiKey?, baseUrl? } }, models?: { chat?, expansion?, reranker? } }.');+ }+ for (const [id, provider] of Object.entries(ai.providers)) {+ const problem = engineProviderProblem(id);+ if (problem) throw invalid(`ai.providers.${id}`, problem);+ const fields = provider && typeof provider === 'object' ? Object.keys(provider) : null;+ const extra = fields?.find(field => field !== 'apiKey' && field !== 'baseUrl');+ if (!fields || extra) throw invalid(`ai.providers.${id}${extra ? `.${extra}` : ''}`, 'Each provider is { apiKey?, baseUrl? }.');+ if (provider.apiKey !== undefined && !text(provider.apiKey)) throw invalid(`ai.providers.${id}.apiKey`, 'apiKey is a non-empty string when given.');+ if (provider.apiKey !== undefined && !recipeKeyEnv(getRecipe(id)!)) throw invalid(`ai.providers.${id}.apiKey`, `${id} takes no API key.`);+ if (provider.baseUrl !== undefined && !(text(provider.baseUrl) && /^https?:\/\/[^\s/]+/i.test(provider.baseUrl))) {+ throw invalid(`ai.providers.${id}.baseUrl`, 'baseUrl is an http or https URL when given.');+ }+ }+ for (const [name, model] of Object.entries(ai.models ?? {})) {+ if (!AI_MODELS.includes(name)) throw invalid(`ai.models.${name}`, 'ai.models takes chat, expansion and reranker; the embedding model is settings.embedding.');+ if (!text(model) || !model.includes(':')) throw invalid(`ai.models.${name}`, 'Each model is a provider:model string.');+ }+}function checkSettings(settings: EngineSettings): void {if (settings.engine !== 'postgres' && settings.engine !== 'pglite') throw invalid('engine', "engine is 'postgres' or 'pglite'.");@@ -44,11 +71,13 @@ function checkSettings(settings: EngineSettings): void {if (embedding !== undefined && !(text(embedding.model) && Number.isInteger(embedding.dimensions) && embedding.dimensions > 0)) {throw invalid('embedding', 'embedding is { model, dimensions } with a model name and a positive whole width.');}+ if (settings.ai !== undefined) checkAI(settings.ai);}/*** Creates and connects an engine from `settings` alone. It reads no config file, no environment variable, no home- * directory and no working directory for its database, pool, direct URL, host identity, writer or embedding identity.+ * directory and no working directory for its database, pool, direct URL, host identity, writer, embedding identity or+ * AI gateway: its embed, chat and rerank calls reach only `settings.ai` (ai/engine-gateway.ts).* A Postgres engine always gets its own pool (never the module singleton in db.ts), and its direct pool is only* `database.directUrl` (or the one a known pooler URL derives); `GBRAIN_DIRECT_DATABASE_URL` is never consulted.*@@ -70,6 +99,10 @@ export async function openEngine(settings: EngineSettings): Promise<BrainEngine>...(settings.writer ? { writer: { ...settings.writer } } : {}),...(settings.embedding ? { embedding: { ...settings.embedding } } : {}),...(settings.pglite ? { pglite: { ...settings.pglite } } : {}),+ ...(settings.ai ? { ai: {+ providers: Object.fromEntries(Object.entries(settings.ai.providers).map(([id, provider]) => [id, { ...provider }])),+ ...(settings.ai.models ? { models: { ...settings.ai.models } } : {}),+ } } : {}),};const config: EngineConfig = {engine: held.engine,diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 83ce18621a..643a7ba7ab 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -303,6 +303,7 @@ export const CODES = {embedded_core_required: { class: 'caller', summary: "openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened.", why: 'Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing.' },engine_embedding_mismatch: { class: 'host_only', actor: 'user', summary: "An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing.", why: 'The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there.", fix: { argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: "Read-only: reports the brain's recorded embedding model and width and what a migration would change." } },engine_host_missing: { class: 'caller', summary: "An engine opened from settings has no host identity, so nothing that needs one ran and no host.json was created.", why: 'An embedded engine publishes and claims work under the host id its host gave at open; minting a host.json under the home directory instead would tie its writes to whatever process happens to share that directory.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass host: { id: <uuid> } to openEngine; keep the same id for the same host across restarts.' },+ engine_scope_missing: { class: 'caller', summary: "An engine opened from settings made an AI call (embed, chat, expansion or rerank) through a provider its settings.ai does not name, so nothing was sent.", why: "An embedded engine's AI calls reach only the providers and keys its host passed as values. Falling back to a process.env key, ~/.gbrain/config.json or the process-wide gateway would spend another brain's key and send this brain's text where its host never pointed it.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass the provider in settings.ai.providers (apiKey, and baseUrl when it is not the default) to openEngine, or point settings.ai.models (or settings.embedding) at a provider the engine has.' },engine_settings_invalid: { class: 'caller', summary: "A setting passed to openEngine is missing or malformed (engine kind, database url or path, pool size, host or writer id, writer credential or lane, embedding identity), so nothing was opened or registered.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Correct the setting the message names and call again.' },engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },// wave 18b (GBRA-106) #4772: onboarding coverage checks read entity types from the active pack(s).diff --git a/test/engine-gateway.test.ts b/test/engine-gateway.test.tsnew file mode 100644index 0000000000..4e1a074b82--- /dev/null+++ b/test/engine-gateway.test.ts@@ -0,0 +1,255 @@+/**+ * GBRA-283 Wave B2: an engine opened from settings carries its own AI gateway (settings.ai). Its embed, chat and+ * rerank calls reach only its own providers and keys, a missing provider refuses engine_scope_missing with nothing+ * sent, the gateway follows engineKey (page transactions, proxies, a recovered degraded engine), two engines never+ * cross, and a key never shows up in an error, a log line, doctor output or the settings read back. Every provider+ * is a transport stub: nothing here opens a socket.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { randomBytes, randomUUID } from 'node:crypto';+import {+ __clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __setGenerateTextTransportForTests, __setRerankTransportForTests,+ chat, configureGateway, embedQuery, requireConfig, rerank, resetGateway,+} from '../src/core/ai/gateway.ts';+import { resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';+import { embeddedSettings, openEngine, withEngineScope, type EngineSettings } from '../src/core/engine-open.ts';+import { createEngine } from '../src/core/engine-factory.ts';+import { createDegradedEngine } from '../src/core/degraded-engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++const EMBEDDING = { model: 'openai:text-embedding-3-small', dimensions: 1536 };+const key = (label: string) => `sk-${label}-${randomBytes(12).toString('hex')}`;+const settingsFor = (over: Partial<EngineSettings> = {}): EngineSettings =>+ ({ embedded_core: true, engine: 'pglite', database: {}, host: { id: randomUUID() }, embedding: EMBEDDING, ...over });+const hostCtx = (engine: BrainEngine): OperationContext => ({+ engine, config: {}, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: true,+} as unknown as OperationContext);+const failure = async (work: () => Promise<unknown>) => {+ try { await work(); return null; } catch (error) { return error as Error & { code?: string; suggestion?: string }; }+};++/** What each provider call carried: the URL it would post to and its bearer. */+type Sent = { kind: string; url: string; auth: string | null; model: string };+const sent: Sent[] = [];+async function sentBy(kind: string, model: any): Promise<void> {+ const headers = await model.config.headers();+ sent.push({ kind, model: model.modelId, url: model.config.url({ path: '/x', modelId: model.modelId }), auth: headers.authorization ?? headers.Authorization ?? null });+}+function installStubs(): void {+ __setEmbedTransportForTests((async ({ model, values }: any) => {+ await sentBy('embed', model);+ return { embeddings: values.map(() => Array.from({ length: EMBEDDING.dimensions }, (_, i) => (i % 7) + 1)), usage: { tokens: 1 } };+ }) as any);+ __setGenerateTextTransportForTests((async ({ model }: any) => {+ await sentBy('chat', model);+ return { content: [{ type: 'text', text: 'ok' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } };+ }) as any);+ __setRerankTransportForTests(async (url, init) => {+ sent.push({ kind: 'rerank', url, auth: new Headers(init.headers).get('authorization'), model: JSON.parse(String(init.body)).model });+ return new Response(JSON.stringify({ data: [{ index: 0, relevance_score: 0.9 }] }), { status: 200 });+ });+}++afterEach(() => {+ sent.length = 0;+ __setEmbedTransportForTests(null);+ __setGenerateTextTransportForTests(null);+ __setRerankTransportForTests(null);+ resetGateway();+});++/** Process-wide keys and gateway that an embedded engine must never fall back to. */+const PROCESS_KEY = key('process');+const ambient = { OPENAI_API_KEY: PROCESS_KEY, ANTHROPIC_API_KEY: PROCESS_KEY, VOYAGE_API_KEY: PROCESS_KEY };+function configureProcessGateway(): void {+ configureGateway({ embedding_model: EMBEDDING.model, embedding_dimensions: EMBEDDING.dimensions, chat_model: 'openai:gpt-5.6', reranker_model: 'voyage:rerank-3-lite', env: { ...ambient } });+}++describe('engine_scope_missing', () => {+ test('an engine without settings.ai refuses embed, chat and rerank; no process key or process gateway is used and nothing is sent', async () => {+ installStubs();+ configureProcessGateway();+ await withEnv(ambient, async () => {+ const engine = await openEngine(settingsFor());+ try {+ for (const [touchpoint, call] of [+ ['embedding', () => embedQuery('a question')],+ ['chat', () => chat({ messages: [{ role: 'user', content: 'hello' }] })],+ ['reranker', () => rerank({ query: 'q', documents: ['d'] })],+ ] as const) {+ const error = await withEngineScope(engine, () => failure(call));+ expect(error?.code).toBe('engine_scope_missing');+ expect(error!.message).toContain(touchpoint);+ expect(error!.suggestion).toContain('nothing was sent');+ expect(`${error!.message} ${error!.suggestion}`).not.toContain(PROCESS_KEY);+ }+ expect(withEngineScope(engine, () => resolveAnthropicKey())).toBeUndefined();+ expect(sent).toEqual([]);+ } finally {+ await engine.disconnect();+ }+ });+ });++ test('a provider the settings do not name refuses while the named one answers', async () => {+ installStubs();+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } }, models: { chat: 'anthropic:claude-sonnet-4-6' } } }));+ try {+ await withEngineScope(engine, () => embedQuery('reaches openai'));+ const error = await withEngineScope(engine, () => failure(() => chat({ messages: [{ role: 'user', content: 'hello' }] })));+ expect(error?.code).toBe('engine_scope_missing');+ expect(error!.message).toBe('This engine has no AI provider anthropic for chat.');+ expect(sent.map(s => s.kind)).toEqual(['embed']);+ } finally {+ await engine.disconnect();+ }+ });++ test('a disconnected engine drops its gateway: its next call refuses', async () => {+ installStubs();+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } } } }));+ await engine.disconnect();+ const error = await withEngineScope(engine, () => failure(() => embedQuery('after close')));+ expect(error?.code).toBe('engine_scope_missing');+ expect(sent).toEqual([]);+ });+});++describe('two engines in one process', () => {+ test('each call reaches its own engine\'s provider, key, base URL and model; the same query is never served across engines', async () => {+ installStubs();+ configureProcessGateway();+ const keyA = key('a'), keyB = key('b');+ const a = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA, baseUrl: 'https://a.example/v1' }, voyage: { apiKey: keyA, baseUrl: 'https://rerank-a.example/v1' } }, models: { chat: 'openai:gpt-5.6-terra', reranker: 'voyage:rerank-3-lite' } } }));+ const b = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyB, baseUrl: 'https://b.example/v1' }, voyage: { apiKey: keyB, baseUrl: 'https://rerank-b.example/v1' } }, models: { chat: 'openai:gpt-5.6-luna', reranker: 'voyage:rerank-3' } } }));+ try {+ for (const engine of [a, b, a]) {+ await withEngineScope(engine, async () => {+ await embedQuery('the same question');+ await chat({ messages: [{ role: 'user', content: 'hello' }] });+ await rerank({ query: 'q', documents: ['d'] });+ });+ }+ const of = (auth: string) => sent.filter(s => s.auth === `Bearer ${auth}`);+ // Engine a's second embedQuery is its own cached vector; engine b's identical query still reaches b's provider.+ expect(sent).toHaveLength(8);+ expect(of(PROCESS_KEY)).toEqual([]);+ expect(of(keyA).map(s => [s.kind, s.url, s.model])).toEqual([+ ['embed', 'https://a.example/v1/x', 'text-embedding-3-small'], ['chat', 'https://a.example/v1/x', 'gpt-5.6-terra'], ['rerank', 'https://rerank-a.example/v1/rerank', 'rerank-3-lite'],+ ['chat', 'https://a.example/v1/x', 'gpt-5.6-terra'], ['rerank', 'https://rerank-a.example/v1/rerank', 'rerank-3-lite'],+ ]);+ expect(of(keyB).map(s => [s.kind, s.url, s.model])).toEqual([+ ['embed', 'https://b.example/v1/x', 'text-embedding-3-small'], ['chat', 'https://b.example/v1/x', 'gpt-5.6-luna'], ['rerank', 'https://rerank-b.example/v1/rerank', 'rerank-3'],+ ]);+ } finally {+ await a.disconnect();+ await b.disconnect();+ }+ });++ test('an operation handler runs in its engine\'s scope: query embeds with that engine\'s key, no scope entered by the host', async () => {+ installStubs();+ configureProcessGateway();+ const keyA = key('a'), keyB = key('b');+ const a = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } } } }));+ const b = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyB } } } }));+ try {+ await a.initSchema();+ await b.initSchema();+ await operationsByName.query.handler(hostCtx(a), { query: 'what does brain a know' });+ await operationsByName.query.handler(hostCtx(b), { query: 'what does brain b know' });+ const embeds = sent.filter(s => s.kind === 'embed').map(s => s.auth);+ expect(embeds).toEqual([`Bearer ${keyA}`, `Bearer ${keyB}`]);+ } finally {+ await a.disconnect();+ await b.disconnect();+ }+ }, 120_000);+});++describe('the gateway follows engineKey', () => {+ test('a page transaction, a forwarding proxy and a recovered degraded engine share their engine\'s gateway', async () => {+ installStubs();+ const keyA = key('a');+ const a = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } } } }));+ try {+ await a.initSchema();+ const degraded = createDegradedEngine({ initialError: new Error('down'), reconnect: async () => a, minIntervalMs: 0 });+ await failure(() => (degraded as unknown as { getStats: () => Promise<unknown> }).getStats());+ await a.transaction(async tx => { await withEngineScope(tx, () => embedQuery('from a transaction')); });+ await withEngineScope(new Proxy(a, {}), () => embedQuery('from a proxy'));+ await withEngineScope(degraded, () => embedQuery('from a recovered degraded engine'));+ expect(sent.map(s => s.auth)).toEqual(Array(3).fill(`Bearer ${keyA}`));+ } finally {+ await a.disconnect();+ }+ }, 60_000);+});++describe('an engine that openEngine did not open', () => {+ test('keeps the process gateway byte for byte, in its own scope and with embedded engines open', async () => {+ installStubs();+ configureProcessGateway();+ const snapshot = async () => {+ sent.length = 0;+ __clearQueryEmbedCacheForTests();+ await embedQuery('the same question');+ await chat({ messages: [{ role: 'user', content: 'hello' }] });+ return JSON.stringify({ config: requireConfig(), sent, anthropic: resolveAnthropicKey() === PROCESS_KEY });+ };+ await withEnv(ambient, async () => {+ const outside = await snapshot();+ expect(outside).toContain(`Bearer ${PROCESS_KEY}`);+ const embedded = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } }, models: { chat: 'openai:gpt-5.6' } } }));+ const cli = await createEngine({ engine: 'pglite' });+ try {+ expect(await withEngineScope(cli, snapshot)).toBe(outside);+ expect(await snapshot()).toBe(outside);+ expect(await withEngineScope(embedded, snapshot)).not.toBe(outside);+ } finally {+ await embedded.disconnect();+ }+ });+ });+});++describe('keys stay out of errors, logs, doctor output and read-back', () => {+ test('a canary key never appears anywhere the engine reports', async () => {+ const canary = key('canary');+ const printed: string[] = [];+ const spies = [spyOn(console, 'log'), spyOn(console, 'warn'), spyOn(console, 'error'), spyOn(console, 'info')];+ const stderr = spyOn(process.stderr, 'write');+ for (const spy of [...spies, stderr]) spy.mockImplementation(((...args: unknown[]) => { printed.push(args.map(String).join(' ')); return true; }) as never);+ try {+ const seen: string[] = [];+ const report = (error: unknown) => seen.push(JSON.stringify(error), String((error as Error)?.message), String((error as Error)?.stack), Bun.inspect(error));+ report(await failure(() => openEngine(settingsFor({ ai: { providers: { openai: { apiKey: canary, baseUrl: 'not a url' } } } }))));+ report(await failure(() => openEngine(settingsFor({ ai: { providers: { openai: { apiKey: canary, api_key: canary } as never } } }))));+ report(await failure(() => openEngine(settingsFor({ ai: { providers: { 'claude-cli': { apiKey: canary } } } }))));+ expect(seen.join('\n')).toContain('engine_settings_invalid');++ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: canary } } } }));+ try {+ await engine.initSchema();+ __setEmbedTransportForTests((async () => { throw Object.assign(new Error(`401 Incorrect API key provided: ${canary}`), { statusCode: 401 }); }) as any);+ report(await withEngineScope(engine, () => failure(() => embedQuery('a question'))));+ report(await withEngineScope(engine, () => failure(() => chat({ messages: [{ role: 'user', content: 'hello' }], model: 'anthropic:claude-sonnet-4-6' }))));+ const { buildChecks } = await import('../src/commands/doctor.ts');+ const checks = await withEngineScope(engine, () => buildChecks(engine, ['--fast', '--json', '--scope=brain']));+ seen.push(JSON.stringify(checks));+ const held = embeddedSettings(engine)!;+ expect(held.ai?.providers.openai).toEqual({ hasApiKey: true });+ seen.push(JSON.stringify(held), Bun.inspect(engine));+ } finally {+ await engine.disconnect();+ }+ expect(seen.join('\n')).not.toContain(canary);+ expect(printed.join('\n')).not.toContain(canary);+ expect(seen.join('\n')).not.toContain(canary.slice(3, 20));+ } finally {+ for (const spy of [...spies, stderr]) spy.mockRestore();+ }+ }, 120_000);+});diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex c7db0a4404..1b816644ce 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -646,7 +646,8 @@"hostIdFor","isEmbeddedEngine","openEngine",- "processHasEmbeddedEngines"+ "processHasEmbeddedEngines",+ "withEngineScope"],"./eval/longmemeval/reader": ["READER_MAX_SESSION_CHARS",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 111ce70901..9593ec0720 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4433,12 +4433,21 @@"kind": "type","name": "EmbeddedSettingsView","signature": [- "{ readonly pglite?: { shared_buffers?: string; } | undefined; readonly host: { id: string; }; readonly database: { url?: string; directUrl?: string; path?: string; }; readonly embedding?: { model: string; dimensions: number; } | undefined; readonly embedded_core: boolean; readonly engine: \"postgres\" | \"pglite\"; readonly pool?: { max?: number; } | undefined; readonly keyword_statement_timeout_ms?: number | undefined; readonly writer?: { id: string; lane: \"cli\" | \"stdio\"; } | undefined; }"+ "{ readonly pglite?: { shared_buffers?: string; } | undefined; readonly host: { id: string; }; readonly database: { url?: string; directUrl?: string; path?: string; }; readonly embedding?: { model: string; dimensions: number; } | undefined; readonly embedded_core: boolean; readonly engine: \"postgres\" | \"pglite\"; readonly pool?: { max?: number; } | undefined; readonly keyword_statement_timeout_ms?: number | undefined; readonly writer?: { id: string; lane: \"cli\" | \"stdio\"; } | undefined; readonly ai?: { providers: Record<string, { baseUrl?: string; hasApiKey: boolean; }>; models?: EngineAISettings[\"models\"]; } | undefined; }"]},{"kind": "interface","members": [+ "models?: { chat?: string; expansion?: string; reranker?: string; } | undefined",+ "providers: Record<string, { apiKey?: string; baseUrl?: string; }>"+ ],+ "name": "EngineAISettings"+ },+ {+ "kind": "interface",+ "members": [+ "ai?: EngineAISettings | undefined","database: { url?: string; directUrl?: string; path?: string; }","embedded_core: boolean","embedding?: { model: string; dimensions: number; } | undefined",@@ -4485,6 +4494,13 @@"signature": ["() => boolean"]+ },+ {+ "kind": "function",+ "name": "withEngineScope",+ "signature": [+ "<T>(engine: object, fn: () => T) => T"+ ]}],"./eval/longmemeval/reader": [@@ -6778,7 +6794,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"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\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"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\" | \"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\" | \"engine_host_missing\" | \"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_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"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\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"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\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"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\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"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\" | \"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\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"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_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"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\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"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\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",