Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: adversarial review fixes
garrytan065c68574293
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 020c59f723..25c4e6a85c 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 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/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 givensrc/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/engine-gateway.ts b/src/core/ai/engine-gateway.tsindex 9e6f304cdf..ba9ae7476b 100644--- a/src/core/ai/engine-gateway.ts+++ b/src/core/ai/engine-gateway.ts@@ -4,7 +4,9 @@* (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 { embeddedSettingsRecord, releasedEngineKeys, type EngineAISettings, type EngineSettings } from '../embedded-engine.ts';++type EngineAIProvider = EngineAISettings['providers'][string];import { embeddedEngineInScope } from '../engine-scope.ts';import { DEFAULT_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_MODEL } from './defaults.ts';import { getRecipe } from './recipes/index.ts';@@ -35,18 +37,35 @@ export function engineProviderProblem(id: string): string | null {return null;}+/** The gateway env entries a provider fills: its key and, for a native SDK, its endpoint. */+function providerEnv(id: string, provider: EngineAIProvider): [string, string][] {+ const recipe = getRecipe(id)!;+ const keyEnv = recipeKeyEnv(recipe);+ const native = NATIVE_BASE_URL[recipe.implementation];+ return [...(provider.apiKey && keyEnv ? [[keyEnv, provider.apiKey] as [string, string]] : []), ...(native ? [[native.env, provider.baseUrl ?? native.url] as [string, string]] : [])];+}++/** Why two providers cannot share this engine (they read one env entry with different values), or null. Names no value. */+export function sharedProviderEnvConflict(providers: Record<string, EngineAIProvider>): string | null {+ const owners = new Map<string, [string, string]>();+ for (const [id, provider] of Object.entries(providers)) {+ for (const [name, value] of providerEnv(id, provider)) {+ const prior = owners.get(name);+ if (prior && prior[1] !== value) return `${prior[0]} and ${id} both read ${name}, so they take the same ${name.endsWith('_URL') ? 'baseUrl' : 'apiKey'}.`;+ owners.set(name, [id, value]);+ }+ }+ 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;- const native = NATIVE_BASE_URL[recipe.implementation];- if (native) env[native.env] = provider.baseUrl ?? native.url;- else if (provider.baseUrl) base_urls[id] = provider.baseUrl;+ for (const [name, value] of providerEnv(id, provider)) env[name] = value;+ if (provider.baseUrl && !NATIVE_BASE_URL[getRecipe(id)!.implementation]) base_urls[id] = provider.baseUrl;}const models = settings.ai?.models ?? {};return {@@ -88,6 +107,12 @@ export function scopedGatewayState(normalize: (config: AIGatewayConfig) => AIGatreturn state;}+/** Provider keys of a disconnected engine in scope, as env entries, so a call still in flight scrubs them from its error. */+export function releasedKeyEnv(): Record<string, string> {+ const engine = embeddedEngineInScope();+ return Object.fromEntries((engine ? releasedEngineKeys(engine) : []).map((value, i) => [`RELEASED_${i}_API_KEY`, value]));+}+/** 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 24ef295009..aa03b17550 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -65,7 +65,7 @@ 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 { engineScopeMissing, 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';@@ -149,7 +149,7 @@ function configFor(recipe: Recipe, touchpoint: string): AIGatewayConfig {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, gw().config?.env ?? {});+const redactKeys = (text: string): string => redactProviderKeys(text, { ...gw().config?.env, ...releasedKeyEnv() });/*** Materialize `applyResolveAuth`'s SDK-shaped result ({apiKey}|{headers}) into@@ -990,6 +990,7 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {};}+ if (gw().providers && !gw().providers!.has(recipe.id)) return { ok: false, reason: 'unknown_provider', model: modelStr, provider: parsed.providerId, message: engineScopeMissing(recipe.id, 'embedding').message };const tp = recipe.touchpoints.embedding;if (!tp) {return {@@ -1101,7 +1102,7 @@ export function isAvailable(touchpoint: TouchpointKind, modelOverride?: string):// Anthropic declares only expansion + chat (no embedding model); requesting// embedding from an anthropic-configured brain is unavailable regardless of auth.const touchpointConfig = recipe.touchpoints[touchpoint as 'expansion' | 'chat' | 'reranker'];- if (!touchpointConfig) return false;+ if (!touchpointConfig || (gw().providers && !gw().providers!.has(recipe.id))) return false;// For openai-compatible without auth requirements (Ollama local), treat as always-available.const required = recipe.auth_env?.required ?? [];diff --git a/src/core/embedded-engine.ts b/src/core/embedded-engine.tsindex bb828880cf..de68d0b3a2 100644--- a/src/core/embedded-engine.ts+++ b/src/core/embedded-engine.ts@@ -47,6 +47,8 @@ export type EmbeddedSettingsView = DeepReadonly<Omit<EngineSettings, 'writer' |interface EmbeddedRecord {hostId: string | undefined;settings: EngineSettings | null;+ /** The provider keys it held, kept past disconnect only so a call still in flight can scrub them from its error. */+ releasedKeys?: string[];}const parseConnectionUrl = (url: string) => new URL(url.replace(/^postgres(ql)?:\/\//, 'settings://'));@@ -133,7 +135,14 @@ export function embeddedSettings(engine: object): EmbeddedSettingsView | undefin/** Drops the settings (the writer credential included) an embedded engine held; it stays marked embedded with its host id. */export function releaseEmbeddedEngine(engine: object): void {const record = recordOf(engine);- if (record) record.settings = null;+ if (!record) return;+ record.releasedKeys = Object.values(record.settings?.ai?.providers ?? {}).flatMap(provider => provider.apiKey ? [provider.apiKey] : []);+ record.settings = null;+}++/** The provider keys an embedded engine held before it disconnected; empty while it is open. */+export function releasedEngineKeys(engine: object): readonly string[] {+ return recordOf(engine)?.releasedKeys ?? [];}/**diff --git a/src/core/engine-open.ts b/src/core/engine-open.tsindex d4a43121fa..0bbc357fa6 100644--- a/src/core/engine-open.ts+++ b/src/core/engine-open.ts@@ -9,7 +9,7 @@ import { opError } from './ops/contract.ts';import { createEngine } from './engine-factory.ts';import { connectionUrlProblem, 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 { engineProviderProblem, recipeKeyEnv, sharedProviderEnvConflict } from './ai/engine-gateway.ts';import { getRecipe } from './ai/recipes/index.ts';export type { EngineAISettings, EngineSettings, EmbeddedSettingsView } from './embedded-engine.ts';@@ -40,10 +40,15 @@ function checkAI(ai: EngineAISettings): void {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.apiKey === undefined && provider.baseUrl === undefined && getRecipe(id)!.auth_env?.required.length) {+ throw invalid(`ai.providers.${id}.apiKey`, `${id} needs an apiKey, or a baseUrl for a server that takes none.`);+ }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.');}}+ const conflict = sharedProviderEnvConflict(ai.providers);+ if (conflict) throw invalid('ai.providers', conflict);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.');diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex fab91778d1..11f9c9ad8f 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -53,6 +53,7 @@ import { resolveModel, isAnthropicProvider, isOpenRouterSubagentFamily, TIER_DEFimport { splitProviderModelId, normalizeModelId } from '../../model-id.ts';import { anthropicClientOptions } from '../../ai/anthropic-key.ts';import { withEngineScope } from '../../engine-scope.ts';+import { redactProviderKeys } from '../../ai/key-redact.ts';import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';import { toolLoop as gatewayToolLoop, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../ai/gateway.ts';import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';@@ -249,6 +250,19 @@ async function runLoopConvertingLeaseLoss<T>(}}+/** The legacy path's client: #2048 key (env, then config; an embedded engine's own key and endpoint, in its scope) on first use; #5137 scrubbed errors. */+function legacyMessagesClient(engine: BrainEngine, make?: () => Anthropic): MessagesClient {+ let messages: MessagesClient | undefined, env: Record<string, string | undefined> = {};+ return { async create(params, opts) {+ if (!messages) { const options = make ? undefined : withEngineScope(engine, anthropicClientOptions); env = { ANTHROPIC_API_KEY: options?.apiKey }; messages = (make ? make() : new Anthropic(options)).messages; }+ try { return await messages.create(params, opts); } catch (err) {+ if (err instanceof Error) for (const field of ['message', 'stack'] as const) err[field] = redactProviderKeys(err[field] ?? '', env);+ if (err && typeof err === 'object' && 'error' in err) (err as { error: unknown }).error = JSON.parse(redactProviderKeys(JSON.stringify((err as { error: unknown }).error) ?? 'null', env));+ throw err;+ }+ } };+}+export function makeSubagentHandler(deps: SubagentDeps) {const engine = deps.engine;// sdk.messages IS the MessagesClient-shaped object. The v0.16.0 bug was@@ -256,11 +270,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {// lives at sdk.messages.create. Assigning sdk.messages directly gets the// right object; JS method-call semantics preserve `this` at the call// site (subagent.ts invokes client.create(...) with client === sdk.messages).- // #2048: the key resolves env, then config (anthropic_api_key); for an embedded engine, its own key and endpoint,- // in this handler's engine's scope (engine-scope.ts), when a job first calls the client.- const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic(withEngineScope(engine, anthropicClientOptions)));- let messages = deps.client;- const client: MessagesClient = { create: (params, opts) => (messages ??= makeAnthropic().messages).create(params, opts) };+ const client: MessagesClient = deps.client ?? legacyMessagesClient(engine, deps.makeAnthropic);const config = deps.config ?? loadConfig() ?? ({ engine: 'postgres' } as GBrainConfig);const rateLeaseKey = deps.rateLeaseKey ?? DEFAULT_RATE_KEY;const maxConcurrent = deps.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;diff --git a/test/engine-gateway.test.ts b/test/engine-gateway.test.tsindex ed82e1a3e4..36ddca980f 100644--- a/test/engine-gateway.test.ts+++ b/test/engine-gateway.test.ts@@ -9,7 +9,7 @@ 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,+ chat, configureGateway, diagnoseEmbedding, embedQuery, isAvailable, requireConfig, rerank, resetGateway,} from '../src/core/ai/gateway.ts';import Anthropic from '@anthropic-ai/sdk';import { anthropicClientOptions, resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';@@ -190,9 +190,11 @@ describe('settings.ai validation', () => {[{ providers: { openai: canary } }, 'ai.providers.openai'],[{ providers: { openai: { apiKey: canary, key: canary } } }, 'ai.providers.openai.key'],[{ providers: { openai: { apiKey: '' } } }, 'ai.providers.openai.apiKey'],+ [{ providers: { openai: {} } }, 'ai.providers.openai.apiKey'],[{ providers: { openai: { apiKey: canary, baseUrl: 'ftp://proxy.example' } } }, 'ai.providers.openai.baseUrl'],[{ providers: { openai: { apiKey: canary } }, models: { embedding: 'openai:text-embedding-3-small' } }, 'ai.models.embedding'],[{ providers: { openai: { apiKey: canary } }, models: { chat: 'gpt-5.6' } }, 'ai.models.chat'],+ [{ providers: { dashscope: { apiKey: canary }, 'dashscope-rerank': { apiKey: key('other') } } }, 'ai.providers'],] as const) {const error = await failure(() => openEngine(settingsFor({ ai: ai as never })));expect([error?.code, error?.message]).toEqual(['engine_settings_invalid', `The ${setting} setting is invalid.`]);@@ -241,6 +243,43 @@ describe('process base URLs never reach an engine', () => {});});+describe('keys stay scrubbed past disconnect and in shared slots', () => {+ test('two providers that read one key slot open when given the same key', async () => {+ const shared = key('shared');+ const engine = await openEngine(settingsFor({ ai: { providers: { dashscope: { apiKey: shared }, 'dashscope-rerank': { apiKey: shared } } } }));+ await engine.disconnect();+ });++ test('a call still in flight when its engine disconnects scrubs that engine\'s key from its error', async () => {+ const keyA = key('a');+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } } } }));+ await engine.initSchema();+ let reject!: (error: unknown) => void;+ let started!: () => void;+ const begun = new Promise<void>(resolve => { started = resolve; });+ __setEmbedTransportForTests((() => { started(); return new Promise((_, fail) => { reject = fail; }); }) as any);+ const pending = withEngineScope(engine, () => failure(() => embedQuery('a question')));+ await begun;+ await engine.disconnect();+ reject(Object.assign(new Error(`401 Incorrect API key provided: ${keyA}`), { statusCode: 401 }));+ const error = await pending;+ expect(error).not.toBeNull();+ expect(`${error!.message} ${JSON.stringify(error)} ${error!.stack}`).not.toContain(keyA);+ });+});++describe('availability follows the engine\'s providers', () => {+ test('a keyless provider the engine does not name reads as unavailable', async () => {+ const engine = await openEngine(settingsFor({ embedding: { model: 'ollama:nomic-embed-text', dimensions: 768 }, ai: { providers: { openai: { apiKey: key('a') } } } }));+ try {+ expect(withEngineScope(engine, () => [diagnoseEmbedding().ok, isAvailable('embedding'), isAvailable('chat', 'ollama:llama3')])).toEqual([false, false, false]);+ expect(withEngineScope(engine, () => isAvailable('chat', 'openai:gpt-5.6'))).toBe(true);+ } finally {+ await engine.disconnect();+ }+ });+});+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' } } }));@@ -285,6 +324,22 @@ describe('the subagent handler\'s Anthropic client', () => {return handler(ctx);}+ test('a provider error that echoes the engine\'s key leaves the handler scrubbed', async () => {+ const keyA = key('a');+ const fetchSpy = spyOn(Anthropic.prototype as unknown as { fetchWithTimeout: () => Promise<Response> }, 'fetchWithTimeout').mockImplementation((async () =>+ new Response(JSON.stringify({ type: 'error', error: { type: 'authentication_error', message: `invalid x-api-key ${keyA}` } }), { status: 401, headers: { 'content-type': 'application/json' } })) as never);+ const engine = await openEngine(settingsFor({ ai: { providers: { anthropic: { apiKey: keyA } } } }));+ try {+ await engine.initSchema();+ const error = await failure(() => runJob(engine));+ expect(error).not.toBeNull();+ expect(`${error!.message} ${error!.stack} ${JSON.stringify(error)}`).not.toContain(keyA);+ } finally {+ fetchSpy.mockRestore();+ await engine.disconnect();+ }+ }, 120_000);+test('is built for the handler\'s engine, whatever scope built the handler, and only when a job calls it', async () => {const calls: { url: string; key: string | null }[] = [];const fetchSpy = spyOn(Anthropic.prototype as unknown as { fetchWithTimeout: (url: string, init: RequestInit) => Promise<Response> }, 'fetchWithTimeout').mockImplementation((async (url: string, init: RequestInit) => {