Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
B2 r5: per-engine chat usage sink; unscoped AI calls fail closed while embedded engines are open
garrytanc8c6dc67ef07
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 25c4e6a85c..7cdd4b869c 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 4563 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given+src/core/ai/gateway.ts 4564 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts)src/commands/sync.ts 561 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts); +2 #7866: SyncOpts.fullRound interface field and its doc comment (internal: the conversion strict passes in persistence/git-conversion.ts set it; read in persistence/sync-pass-run.ts); +1 #8007: SyncResult.storage_invalid_kept interface field (the keep lives in persistence/sync-discovery.ts); +2 GBRA-287: SyncResult.reexport_failures interface field (the re-export lives in commands/sync/full.ts)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 49f7c67ebe..a097c60a99 100644--- a/src/core/ai/anthropic-key.ts+++ b/src/core/ai/anthropic-key.ts@@ -25,8 +25,8 @@import { loadConfig } from '../config.ts';import { embeddedSettingsRecord } from '../embedded-engine.ts';-import { embeddedEngineInScope } from '../engine-scope.ts';-import { engineScopeMissing } from './engine-gateway.ts';+import { embeddedEngineInScope, unscopedInEmbeddedProcess } from '../engine-scope.ts';+import { engineScopeMissing, engineScopeUnentered } from './engine-gateway.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 {@@ -43,6 +43,8 @@ function engineAnthropicKey(): string | null | undefined {* `ANTHROPIC_API_KEY`). Cleared by the gateway reset paths via the stash.*/let _gatewayEnvKeySnapshot: string | undefined;+/** Whether `configureGateway()` set a process gateway: in a process holding embedded engines, only then may an unscoped call use process keys. */+let _processGatewayConfigured = false;/*** Push seam for `configureGateway()`: stash the gateway env's Anthropic key@@ -57,6 +59,7 @@ export function stashGatewayAnthropicKeyFromEnv(): void {const key = env?.ANTHROPIC_API_KEY;_gatewayEnvKeySnapshot = key !== process.env.ANTHROPIC_API_KEY ? key : undefined;+ _processGatewayConfigured = env !== undefined;}/**@@ -86,6 +89,7 @@ export function getGatewayAnthropicKeySnapshot(): string | undefined {*/export function anthropicClientOptions(): { apiKey?: string; baseURL?: string } {const engine = embeddedEngineInScope();+ if (!engine && unscopedInEmbeddedProcess() && !_processGatewayConfigured) throw engineScopeUnentered();if (!engine) return { apiKey: resolveAnthropicKey() };const provider = embeddedSettingsRecord(engine)?.ai?.providers.anthropic;if (!provider?.apiKey) throw engineScopeMissing('anthropic', 'chat');@@ -107,6 +111,7 @@ export function hasAnthropicKey(): boolean {export function resolveAnthropicKey(): string | undefined {const scoped = engineAnthropicKey();if (scoped !== undefined) return scoped ?? undefined;+ if (unscopedInEmbeddedProcess() && !_processGatewayConfigured) return undefined;if (process.env.ANTHROPIC_API_KEY) return process.env.ANTHROPIC_API_KEY;if (_gatewayEnvKeySnapshot) return _gatewayEnvKeySnapshot;try {diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.tsindex a73096fcfe..8bfaeed648 100644--- a/src/core/ai/chat-usage.ts+++ b/src/core/ai/chat-usage.ts@@ -35,6 +35,9 @@import { AsyncLocalStorage } from 'node:async_hooks';import { canonicalLookup, priceAtPromptSize } from '../model-pricing.ts';import { priceFor, type PricingOverrides } from '../budget/reservation-cost.ts';+import { embeddedEngineInScope } from '../engine-scope.ts';+import { isEmbeddedEngine } from '../embedded-engine.ts';+import { engineKey } from '../engine-key.ts';export interface ChatUsageRecord {/** "provider:modelId" of the model that actually answered. */@@ -101,12 +104,23 @@ export function withChatCallMeter<T>(meter: ChatCallMeter, fn: () => T): T {* sink. Records route to the TOP live entry (still single-writer —* simultaneous multi-brain attribution stays documented best-effort).*/-interface SinkEntry { sink: ChatUsageSink }+interface SinkEntry { sink: ChatUsageSink; engine?: object }let _sinks: SinkEntry[] = [];-/** Register a usage sink. Returns an idempotent deregister handle. */-export function registerChatUsageSink(sink: ChatUsageSink): () => void {- const entry: SinkEntry = { sink };+/**+ * The sink a record goes to: in an embedded engine's scope, that engine's own (engine-scope.ts); otherwise the top+ * entry that is not an embedded engine's, so one brain's usage never lands in another's database.+ */+function sinkInScope(): ChatUsageSink | null {+ const scoped = embeddedEngineInScope();+ const entry = scoped ? _sinks.findLast(e => e.engine !== undefined && engineKey(e.engine) === engineKey(scoped))+ : _sinks.findLast(e => e.engine === undefined || !isEmbeddedEngine(e.engine));+ return entry?.sink ?? null;+}++/** Register a usage sink, for `engine` when given. Returns an idempotent deregister handle. */+export function registerChatUsageSink(sink: ChatUsageSink, engine?: object): () => void {+ const entry: SinkEntry = { sink, engine };_sinks.push(entry);return () => {_sinks = _sinks.filter((e) => e !== entry);@@ -173,7 +187,7 @@ export function recordChatUsage(input: {}): void {const meter = __chatMeterStore.getStore();if (meter) meter.calls++;- const sink = _sinks.length > 0 ? _sinks[_sinks.length - 1]!.sink : null;+ const sink = sinkInScope();const pricedMeter = meter && meter.cost_usd !== undefined ? meter : null;if (!sink && !pricedMeter) return;try {diff --git a/src/core/ai/engine-gateway.ts b/src/core/ai/engine-gateway.tsindex 2dcfc626b7..64ce38374a 100644--- a/src/core/ai/engine-gateway.ts+++ b/src/core/ai/engine-gateway.ts@@ -113,6 +113,12 @@ export function releasedKeyEnv(): Record<string, string> {return Object.fromEntries((engine ? releasedEngineKeys(engine) : []).map((value, i) => [`RELEASED_${i}_API_KEY`, value]));}+/** The refusal for an AI call made outside any engine scope in a process holding embedded engines whose host configured no process gateway. */+export function engineScopeUnentered(): Error {+ return opError('engine_scope_missing', 'An AI call ran outside any engine scope in a process that holds engines opened from settings.',+ 'Its brain is unknown, so no process.env key, ~/.gbrain/config.json or default gateway is used and nothing was sent. Run it inside withEngineScope(engine, fn), or configure a process gateway (configureGateway) for calls that belong to no engine.');+}+/** In an embedded engine's scope, its settings.ai.models.reranker; search uses it in place of the mode bundle's default. */export function engineRerankerModel(): string | undefined {const engine = embeddedEngineInScope();diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex aa03b17550..bf4f7e6814 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -64,8 +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, releasedKeyEnv, scopedGatewayState, type GatewayState } from './engine-gateway.ts';+import { unscopedInEmbeddedProcess, withEngineScope } from '../engine-scope.ts';+import { engineScopeMissing, engineScopeUnentered, releasedKeyEnv, 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';@@ -172,7 +172,7 @@ export function authToHeaders(auth: { apiKey?: string; headers?: Record<string,* are deliberately left unchanged.*/export function configureGatewayIfUninitialized(): void {- if (processState.config || gw() !== processState) return;+ if (processState.config || gw() !== processState || unscopedInEmbeddedProcess()) return;const config = loadConfig();if (config) configureGateway(buildGatewayConfig(config));}@@ -467,7 +467,7 @@ export function recipeSupportsStructuredOutputs(recipe: Recipe): boolean {/** Configure the gateway. Called by cli.ts#connectEngine. Clears cached models. */export function configureGateway(config: AIGatewayConfig): void {processState.config = gatewayConfigOf(config);- stashGatewayAnthropicKeyFromEnv(config.env); // #2119: filter + rationale in anthropic-key.ts+ stashGatewayAnthropicKeyFromEnv(config.env ?? {}); // #2119: filter + rationale in anthropic-key.tsprocessState.modelCache.clear();clearQueryEmbedCache();_shrinkState.clear();@@ -844,6 +844,7 @@ export function __setChatTransportForTests(export function requireConfig(): AIGatewayConfig {const config = gw().config;if (!config) {+ if (unscopedInEmbeddedProcess()) throw engineScopeUnentered();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',diff --git a/src/core/embedded-engine.ts b/src/core/embedded-engine.tsindex b47e0dbb59..14acef6aa1 100644--- a/src/core/embedded-engine.ts+++ b/src/core/embedded-engine.ts@@ -81,6 +81,7 @@ export function settingsConnectionOptions(url: string): { host: string; port: nu/** Keyed by `engineKey`, so a page-transaction clone, a view and every forwarding proxy over the engine share its record. */const records = new WeakMap<object, EmbeddedRecord>();let embeddedProcess = false;+let openEmbeddedEngines = 0;function recordOf(engine: object): EmbeddedRecord | undefined {return records.get(engineKey(engine));@@ -92,6 +93,7 @@ export function markEmbeddedEngine(engine: object, settings: EngineSettings): voconst record: EmbeddedRecord = { hostId: typeof id === 'string' && id ? id.toLowerCase() : undefined, settings };records.set(engineKey(engine), record);embeddedProcess = true;+ openEmbeddedEngines++;}/** True for an engine `openEngine` opened, and for its page transactions and read-through views. */@@ -104,6 +106,11 @@ export function processHasEmbeddedEngines(): boolean {return embeddedProcess;}+/** True while an embedded engine is open in this process: then an AI call outside any engine scope refuses (engine-gateway.ts). */+export function processHoldsEmbeddedEngines(): boolean {+ return openEmbeddedEngines > 0;+}+/** The host id an embedded engine was opened with; undefined for every other engine. */export function embeddedHostId(engine: object): string | undefined {return recordOf(engine)?.hostId;@@ -136,6 +143,7 @@ export function embeddedSettings(engine: object): EmbeddedSettingsView | undefinexport function releaseEmbeddedEngine(engine: object): void {const record = recordOf(engine);if (!record?.settings) return;+ openEmbeddedEngines--;record.releasedKeys = Object.values(record.settings.ai?.providers ?? {}).flatMap(provider => provider.apiKey ? [provider.apiKey] : []);record.settings = null;}diff --git a/src/core/engine-factory.ts b/src/core/engine-factory.tsindex ba5878722c..3d3e4a5c3f 100644--- a/src/core/engine-factory.ts+++ b/src/core/engine-factory.ts@@ -36,7 +36,7 @@ export async function createEngine(config: EngineConfig): Promise<BrainEngine> {// route to a closed engine. Concurrent multi-engine attribution remains// top-of-stack best-effort; the sink is fail-open, so a not-yet-migrated// engine never breaks a chat call.- const deregisterUsageSink = registerChatUsageSink(makeEngineChatUsageSink(engine));+ const deregisterUsageSink = registerChatUsageSink(makeEngineChatUsageSink(engine), engine);const origDisconnect = engine.disconnect.bind(engine);engine.disconnect = async (): Promise<void> => {deregisterUsageSink();diff --git a/src/core/engine-scope.ts b/src/core/engine-scope.tsindex c10789004b..165ee4c846 100644--- a/src/core/engine-scope.ts+++ b/src/core/engine-scope.ts@@ -8,7 +8,7 @@* one, the gateway keeps its process-wide state exactly as before, and no scope is even entered.*/import { AsyncLocalStorage } from 'node:async_hooks';-import { isEmbeddedEngine, processHasEmbeddedEngines } from './embedded-engine.ts';+import { isEmbeddedEngine, processHasEmbeddedEngines, processHoldsEmbeddedEngines } from './embedded-engine.ts';const scope = new AsyncLocalStorage<object>();@@ -17,6 +17,11 @@ export function withEngineScope<T>(engine: object, fn: () => T): T {return processHasEmbeddedEngines() ? scope.run(engine, fn) : fn();}+/** True for a call that entered no engine scope while the process holds an open embedded engine. */+export function unscopedInEmbeddedProcess(): boolean {+ return processHoldsEmbeddedEngines() && scope.getStore() === undefined;+}+/** The embedded engine the current call runs for (a page transaction, view or proxy over one counts), else undefined. */export function embeddedEngineInScope(): object | undefined {if (!processHasEmbeddedEngines()) return undefined;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ff2dc2457a..77cc827e4d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -304,7 +304,7 @@ export const CODES = {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_closed: { class: 'caller', summary: 'An engine opened from settings was disconnected, which closes it for good, so connect() and reconnect() refuse and nothing was reopened.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call openEngine again with the settings to open a new engine.' },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_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, or a call ran outside any engine scope in a process holding such engines, 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.tsindex 76cc76270b..6aa0599290 100644--- a/test/engine-gateway.test.ts+++ b/test/engine-gateway.test.ts@@ -8,7 +8,7 @@import { afterEach, describe, expect, spyOn, test } from 'bun:test';import { randomBytes, randomUUID } from 'node:crypto';import {- __clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __setGenerateTextTransportForTests, __setRerankTransportForTests,+ __clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __unconfigureGatewayForTests, __setGenerateTextTransportForTests, __setRerankTransportForTests,chat, configureGateway, diagnoseEmbedding, embedQuery, isAvailable, requireConfig, rerank, resetGateway,} from '../src/core/ai/gateway.ts';import Anthropic from '@anthropic-ai/sdk';@@ -280,6 +280,54 @@ describe('availability follows the engine\'s providers', () => {});});+describe('chat usage and unscoped calls', () => {+ const usageRows = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM chat_usage_log'))[0]!.n);+ const settled = () => Bun.sleep(200);++ test('chat usage lands in the in-scope engine\'s database, and an unscoped call never books to an embedded engine', async () => {+ installStubs();+ configureProcessGateway();+ const cli = await createEngine({ engine: 'pglite' });+ await cli.connect({ engine: 'pglite' } as never);+ await cli.initSchema();+ const a = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } }, models: { chat: 'openai:gpt-5.6' } } }));+ const b = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('b') } }, models: { chat: 'openai:gpt-5.6' } } }));+ try {+ await a.initSchema();+ await b.initSchema();+ await withEngineScope(a, () => chat({ messages: [{ role: 'user', content: 'hello from a' }] }));+ await settled();+ expect([await usageRows(a), await usageRows(b), await usageRows(cli)]).toEqual([1, 0, 0]);+ await chat({ messages: [{ role: 'user', content: 'hello from the host' }] });+ await settled();+ expect([await usageRows(a), await usageRows(b), await usageRows(cli)]).toEqual([1, 0, 1]);+ } finally {+ await Promise.all([a.disconnect(), b.disconnect(), cli.disconnect()]);+ }+ }, 120_000);++ test('a process holding an embedded engine refuses an unscoped AI call unless the host configured a process gateway', async () => {+ __unconfigureGatewayForTests();+ installStubs();+ await withEnv(ambient, async () => {+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } } } }));+ try {+ const error = await failure(() => chat({ messages: [{ role: 'user', content: 'hello' }] }));+ expect(error?.code).toBe('engine_scope_missing');+ expect(`${error!.message} ${error!.suggestion}`).toContain('withEngineScope');+ expect(resolveAnthropicKey()).toBeUndefined();+ expect((await failure(async () => anthropicClientOptions()))?.code).toBe('engine_scope_missing');+ configureProcessGateway();+ expect(await failure(() => chat({ messages: [{ role: 'user', content: 'hello' }] }))).toBeNull();+ expect(resolveAnthropicKey()).toBe(PROCESS_KEY);+ } finally {+ await engine.disconnect();+ }+ expect(resolveAnthropicKey()).toBe(PROCESS_KEY);+ });+ });+});+describe('search reranking on an engine', () => {test('search uses the engine\'s settings.ai.models.reranker unless the brain or the call names one', async () => {const engine = await openEngine(settingsFor({ ai: { providers: { voyage: { apiKey: key('v') } }, models: { reranker: 'voyage:rerank-2.5' } } }));