Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(think): report, price and save the fallback model that answered (#6997)

time-attack5490537928a6
diff --git a/docs/guides/chat-fallback.md b/docs/guides/chat-fallback.md
index 5b7ad9064f..ca84869ced 100644
--- a/docs/guides/chat-fallback.md
+++ b/docs/guides/chat-fallback.md
@@ -95,6 +95,11 @@ chain on its own.
the chain.
- A fallback call is billed by the entry's provider; budget caps price each
attempt by the model that actually ran.
+- `gbrain think` without `--model` (and the `think` tool) report the model that
+ answered: `modelUsed`, `cost_usd` and the `--save` page's `model:` name it,
+ `requested_model` names the configured model, and `fallback_reason` says why it
+ did not answer (not returned to HTTP MCP callers). The human output reads
+ `Model: <answered> (fallback from <requested>: failed (...))`.
An upgrade that finds a chain already set says so once in the
`behavior_changes` safety notice; `gbrain doctor --only behavior_changes`
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ace5e85f7d..e5f2d8c2bf 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2044 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2643 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
src/commands/jobs.ts 666 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
src/commands/serve-http.ts 937 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)
-src/core/ai/gateway.ts 4523 ratchet +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
+src/core/ai/gateway.ts 4525 ratchet +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
src/commands/sync.ts 548 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)
src/core/cycle.ts 3330 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)
src/core/cycle/synthesize.ts 3230 ratchet +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)
diff --git a/src/commands/think.ts b/src/commands/think.ts
index e8d89c1efa..d26a3a9710 100644
--- a/src/commands/think.ts
+++ b/src/commands/think.ts
@@ -287,7 +287,8 @@ prints what would have been the input (exit 0).
}
console.log('---');
const costSuffix = costUsd !== undefined ? ` | Cost: $${costUsd.toFixed(4)}` : '';
- console.log(`Model: ${result.modelUsed} | Pages: ${result.pagesGathered} | Takes: ${result.takesGathered} | Graph: ${result.graphHits} | Citations: ${result.citations.length}${costSuffix}`);
+ const fallbackNote = result.requested_model ? ` (fallback from ${result.requested_model}${result.fallback_reason ? `: ${result.fallback_reason}` : ''})` : '';
+ console.log(`Model: ${result.modelUsed}${fallbackNote} | Pages: ${result.pagesGathered} | Takes: ${result.takesGathered} | Graph: ${result.graphHits} | Citations: ${result.citations.length}${costSuffix}`);
if (savedSlug) {
console.log(`Saved: ${savedSlug} (${evidenceInserted} evidence rows)`);
}
diff --git a/src/core/ai/chat-fallback.ts b/src/core/ai/chat-fallback.ts
index bcd7bb9b48..572bb698a0 100644
--- a/src/core/ai/chat-fallback.ts
+++ b/src/core/ai/chat-fallback.ts
@@ -15,7 +15,9 @@
* - completes with a structural refusal (`stopReason` 'refusal' or
* 'content_filter'), the signal `mapStopReason` derives for this purpose.
* A result a chain entry produced carries `fallbackFrom` (the call's own model),
- * so callers that cache or key on model identity can tell it apart.
+ * so callers that cache or key on model identity can tell it apart, and
+ * `fallbackReason` (why that model did not answer: "failed (<first error line>)"
+ * or "refused (...)", at most 200 characters of the error).
* With `chat_fallback_on_refusal: false` (`onRefusal: false` here) a refusal
* ends the walk instead: a structural refusal is returned and a provider
* content block (`providerContentBlockReason`) is thrown, so content one
@@ -108,8 +110,9 @@ export async function chatWithFallback(
): Promise<ChatResult> {
const onRefusal = options.onRefusal !== false;
const models = chatFallbackAttempts(primary, chain);
+ let primaryCause: string | undefined;
const answered = (result: ChatResult, model: string): ChatResult =>
- model === models[0] ? result : { ...result, fallbackFrom: models[0] };
+ model === models[0] ? result : { ...result, fallbackFrom: models[0], ...(primaryCause ? { fallbackReason: primaryCause } : {}) };
let refused: ChatResult | null = null;
let primaryError: unknown;
for (let i = 0; ; i++) {
@@ -119,6 +122,7 @@ export async function chatWithFallback(
const result = await attempt({ ...opts, model, allowFallback: false });
if (next === undefined || !isStructuralRefusal(result) || !onRefusal || opts.abortSignal?.aborted) return answered(result, model);
refused ??= answered(result, model);
+ if (i === 0) primaryCause = `refused (stopReason ${result.stopReason})`;
console.warn(`[ai.gateway] chat ${result.model} stopped with ${result.stopReason}; trying ${next} from chat_fallback_chain`);
queueFirstHop(result.model, next, `stopReason ${result.stopReason}`, true);
} catch (err) {
@@ -139,8 +143,10 @@ export async function chatWithFallback(
}
throw primaryError ?? err;
}
+ const cause = blocked !== undefined ? `content block ${blocked}` : hopReason(err);
+ if (i === 0) primaryCause = blocked !== undefined ? `refused (${cause})` : `failed (${cause})`;
console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); trying ${next} from chat_fallback_chain`);
- queueFirstHop(model, next, blocked !== undefined ? `content block ${blocked}` : hopReason(err), blocked !== undefined);
+ queueFirstHop(model, next, cause, blocked !== undefined);
}
}
}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index fecd2bda5d..0986306bfa 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -3100,6 +3100,8 @@ export interface ChatResult {
providerMetadata?: Record<string, any>;
/** Set when a `chat_fallback_chain` entry answered: the call's own model, which failed or refused (`model` names the one that ran). */
fallbackFrom?: string;
+ /** With `fallbackFrom`: why that model did not answer ("failed (<first error line>)" / "refused (...)"). */
+ fallbackReason?: string;
}
export interface ChatOpts {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d65d780848..386af037c4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -904,12 +904,13 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
- // Wave 20 lane 1 (#6944 #6945 #6940 #6953 #6958).
+ // Wave 20 lane 1 (#6944 #6945 #6940 #6953 #6958 #6997).
{ since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },
{ since: '0.60.307.0', text: '`gbrain recall --since-last-run` (and `--watch`) on a local brain no longer skips facts when more than `--limit` of them arrived since the last run. A run that fills the window now shows the OLDEST `--limit` new facts (newest first within the page) and the next run continues right after the last one shown, until it catches up; before, it showed the newest `--limit` and the rest were never shown. The cursor file keeps `schema_version: 1` and gains two optional fields, so cursor files from earlier versions keep working. A thin client cannot page yet: when its window is full it prints a warning to raise `--limit`.' },
{ since: '0.60.307.0', text: '`get_health` / `gbrain health` `most_connected` no longer counts links to or from soft-deleted pages, so a hub whose neighbours were deleted drops in the ranking instead of keeping their edges (#6940). The islanded scan already applied this liveness rule.' },
{ since: '0.60.307.0', text: 'The dream cycle\'s `edge_contradictions` phase now judges a `works_at` group only when its subject is a person (the pack\'s `person` type or a type that declares `aliases: [person]`) and its targets can employ someone: links from companies, and links to people, meetings, conversations, emails, sources, notes or inbox pages, no longer become "Ended works_at" proposals, and such malformed groups no longer use up the phase\'s subject limit (#6953). Link extraction no longer types a link to a conversation, email, source, note or inbox page as `works_at` (it stays `mentions`). Open proposals made earlier are not re-checked: reject unwanted ones with `gbrain edge-proposals reject <id>`. The judge prompt is unchanged.' },
{ since: '0.60.307.0', text: 'Automatic mention linking now skips a page of any type whose whole title is one generic word (such as "Info", "Team" or "Update"); before, only person pages were skipped, so a company or concept page with such a title collected a mention link from every page that used the word (#6958). The page itself is unchanged, multi-word titles still link, and `gbrain extract mentions --explain <slug>` reports the reason as `generic_token`.' },
+ { since: '0.60.307.0', text: 'When `chat_fallback_chain` answers a `gbrain think` (or `think` tool) call, the result now names the model that answered instead of the configured one that failed: `modelUsed`, `cost_usd`, the synthesize verb\'s `cost.model` and a `--save` page\'s `model:` frontmatter use it. New fields `requested_model` (the configured model) and `fallback_reason` (why it did not answer; omitted for HTTP MCP callers) appear only after a fallback, and the human output says `(fallback from ...)`. Calls the first model answers are unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index cd8f579658..639a6c8ae4 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 26bb36e380..0928e51ea6 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -332,6 +332,8 @@ const think: Operation = {
remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
}).catch((e: unknown) => { throw thinkModelError(ctx, e); });
result.answer = result.answer.replace(' or pass `client`', ' on the brain host');
+ // A6: the fallback cause is a provider error line, host posture an HTTP caller is never told.
+ if (ctx.transport === 'http') delete result.fallback_reason;
if (ctx.transport === 'http' && (result.synthesis_status === 'no_llm' || result.synthesis_status === 'model_unusable')) {
// A6 HTTP view: a remote caller is never told the host's key names or provider posture. The stub
// answer and gaps are prose for the operator; synthesis_status and the warning codes stay as data.
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index ed90f1abd4..98fb87f548 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -256,6 +256,10 @@ export interface ThinkResult {
abstained?: ThinkAbstention;
/** The date frame the synthesis read in (reference date + brain timezone). */
temporal?: { reference_date: string; time_zone: string };
+ /** #6997: set only when a `chat_fallback_chain` model answered: the model asked first (`modelUsed` names the one that answered, which is priced and saved). */
+ requested_model?: string;
+ /** #6997: with `requested_model`, why it did not answer ("failed (...)" / "refused (...)"). Not returned to HTTP MCP callers. */
+ fallback_reason?: string;
/** PR #5086: who bounded the evidence, when a window applied: the caller's `since`/`until`, or the one explicit date the question named (`WINDOW_FROM_QUESTION` warning). */
window_source?: 'caller' | 'question';
}
@@ -828,6 +832,7 @@ export async function runThink(
// [E2] best-effort usage aggregation across synthesis calls (single-pass in
// v0.28+, but summed so the round loop inherits it when gap-fill lands).
let usage: { input_tokens: number; output_tokens: number } | null = null;
+ let fallback: { answered_by: string; reason?: string } | undefined;
// Initialized to the llm_error shape; every non-throwing branch overwrites it.
let response: ThinkResponse = { answer: '', citations: [], gaps: [] };
if (opts.stubResponse) {
@@ -924,17 +929,8 @@ export async function runThink(
// response keeps its empty llm_error initialization.
}
if (created) {
- // [E2] capture usage when the message carries it (test-injected clients
- // and providers without accounting leave it null).
- const u = (created as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;
- if (u && typeof u.input_tokens === 'number' && typeof u.output_tokens === 'number') {
- // Single synthesis call in v0.28+; when gap-driven rounds land, sum here.
- const prev = usage as { input_tokens: number; output_tokens: number } | null;
- usage = {
- input_tokens: (prev?.input_tokens ?? 0) + u.input_tokens,
- output_tokens: (prev?.output_tokens ?? 0) + u.output_tokens,
- };
- }
+ fallback = (created as { fallback?: { answered_by: string; reason?: string } }).fallback;
+ usage = addMessageUsage(usage, created);
const block = created.content.find(b => b.type === 'text');
const text = block && 'text' in block ? block.text : '';
const parsed = tryParseJSON(text);
@@ -1021,7 +1017,8 @@ export async function runThink(
pagesGathered: gather.pages.length,
takesGathered: gather.takes.length,
graphHits: gather.graphSlugs.length,
- modelUsed,
+ modelUsed: fallback?.answered_by ?? modelUsed,
+ ...(fallback ? { requested_model: modelUsed, ...(fallback.reason ? { fallback_reason: fallback.reason } : {}) } : {}),
rounds: 1,
warnings,
// #1698: persistable only when a real synthesis produced a non-empty answer.
@@ -1045,6 +1042,20 @@ export async function runThink(
};
}
+/**
+ * [E2] `prev` plus the message's token usage; `prev` unchanged when the message carries none
+ * (test-injected clients and providers without accounting). Single synthesis call in v0.28+;
+ * when gap-driven rounds land, runThink sums each round through here.
+ */
+function addMessageUsage(
+ prev: { input_tokens: number; output_tokens: number } | null,
+ message: unknown,
+): { input_tokens: number; output_tokens: number } | null {
+ const u = (message as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;
+ if (!u || typeof u.input_tokens !== 'number' || typeof u.output_tokens !== 'number') return prev;
+ return { input_tokens: (prev?.input_tokens ?? 0) + u.input_tokens, output_tokens: (prev?.output_tokens ?? 0) + u.output_tokens };
+}
+
/** Normalizes the model's parsed JSON envelope. */
function toThinkResponse(r: Partial<ThinkResponse>): ThinkResponse {
return {
@@ -1310,6 +1321,7 @@ function chatResultToMessage(result: ChatResult, modelStr: string): {
type: 'message';
role: 'assistant';
model: string;
+ fallback?: { answered_by: string; reason?: string };
content: Array<{ type: 'text'; text: string }>;
usage: { input_tokens: number; output_tokens: number };
stop_reason: 'end_turn' | 'max_tokens' | 'tool_use' | 'stop_sequence';
@@ -1319,6 +1331,7 @@ function chatResultToMessage(result: ChatResult, modelStr: string): {
type: 'message',
role: 'assistant',
model: modelStr,
+ ...(result.fallbackFrom ? { fallback: { answered_by: result.model, ...(result.fallbackReason ? { reason: result.fallbackReason } : {}) } } : {}),
content: [{ type: 'text', text: result.text }],
usage: {
input_tokens: result.usage.input_tokens,
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 91792a56ac..73171e78e0 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1737,6 +1737,7 @@
"members": [
"blocks: ChatBlock[]",
"fallbackFrom?: string | undefined",
+ "fallbackReason?: string | undefined",
"model: string",
"providerId: string",
"providerMetadata?: Record<string, any> | undefined",
@@ -8286,6 +8287,7 @@
"evidence_delivery?: DeliveryMeta | undefined",
"evidence_truncated?: boolean | undefined",
"extractive?: ExtractiveFallback | undefined",
+ "fallback_reason?: string | undefined",
"feedback_evidence?: { source_id: string; slug: string; content_hash: string | null; }[] | undefined",
"gaps: string[]",
"graphHits: number",
@@ -8294,6 +8296,7 @@
"persist?: { answer: string; unverified_claims: Array<{ text: string; reason: string; detail: string; }>; } | undefined",
"question: string",
"quote_check?: { grounded: number; repaired: number; unverified: number; } | undefined",
+ "requested_model?: string | undefined",
"rounds: number",
"savedSlug?: string | undefined",
"synthesisOk?: boolean | undefined",
@@ -8319,7 +8322,7 @@
"kind": "variable",
"name": "__thinkAdapter",
"signature": [
- "{ tryBuildGatewayClient: (modelUsed: string, opts?: { explicitModel?: boolean; allowFallback?: boolean; }) => Promise<ThinkLLMClient | null>; chatResultToMessage: (result: ChatResult, modelStr: string) => { id: string; type: \"message\"; role: \"assistant\"; model: string; content: Array<{ type: \"text\"; text: string; }>; usage: { input_tokens: number; output_tokens: number; }; stop_reason: \"end_turn\" | \"max_tokens\" | \"tool_use\" | \"stop_sequence\"; }; mapStopReason: (s: ChatResult[\"stopReason\"]) => \"end_turn\" | \"max_tokens\" | \"tool_use\" | \"stop_sequence\"; buildGracefulMessage: (modelStr: string, err?: AIConfigError) => { id: string; type: \"message\"; role: \"assistant\"; model: string; content: Array<{ type: \"text\"; text: string; }>; usage: { input_tokens: number; output_tokens: number; }; stop_reason: \"end_turn\"; }; hasAnthropicKey: () => boolean; }"
+ "{ tryBuildGatewayClient: (modelUsed: string, opts?: { explicitModel?: boolean; allowFallback?: boolean; }) => Promise<ThinkLLMClient | null>; chatResultToMessage: (result: ChatResult, modelStr: string) => { id: string; type: \"message\"; role: \"assistant\"; model: string; fallback?: { answered_by: string; reason?: string; }; content: Array<{ type: \"text\"; text: string; }>; usage: { input_tokens: number; output_tokens: number; }; stop_reason: \"end_turn\" | \"max_tokens\" | \"tool_use\" | \"stop_sequence\"; }; mapStopReason: (s: ChatResult[\"stopReason\"]) => \"end_turn\" | \"max_tokens\" | \"tool_use\" | \"stop_sequence\"; buildGracefulMessage: (modelStr: string, err?: AIConfigError) => { id: string; type: \"message\"; role: \"assistant\"; model: string; content: Array<{ type: \"text\"; text: string; }>; usage: { input_tokens: number; output_tokens: number; }; stop_reason: \"end_turn\"; }; hasAnthropicKey: () => boolean; }"
]
},
{
diff --git a/test/think-pipeline.test.ts b/test/think-pipeline.test.ts
index 677b923287..a6bb438ee2 100644
--- a/test/think-pipeline.test.ts
+++ b/test/think-pipeline.test.ts
@@ -1,4 +1,4 @@
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { operationsByName } from '../src/core/operations.ts';
@@ -7,6 +7,8 @@ import { sanitizeTakeForPrompt, renderTakesBlock } from '../src/core/think/sanit
import { resolveCitations, parseInlineCitations, normalizeStructuredCitations } from '../src/core/think/cite-render.ts';
import { runGather, renderPagesBlock } from '../src/core/think/gather.ts';
import { withoutAnthropicKey } from './helpers/no-anthropic-key.ts';
+import { configureGateway, resetGateway, __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';
+import { __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';
let engine: PGLiteEngine;
let alicePageId: number;
@@ -540,6 +542,56 @@ describe('runThink — #1698 explicit-model hard error', () => {
});
});
+describe('runThink — chat_fallback_chain answer', () => {
+ afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ __resetChatFallbackHopNoticeForTests();
+ resetGateway();
+ });
+
+ test('modelUsed names the chain model that answered, not the one that failed', async () => {
+ configureGateway({
+ chat_model: 'openai:gpt-5.2',
+ chat_fallback_chain: ['deepseek:deepseek-chat'],
+ env: { OPENAI_API_KEY: 'fake-openai', DEEPSEEK_API_KEY: 'fake-deepseek' },
+ });
+ __setGenerateTextTransportForTests((async (args: any) => {
+ if (args.model.modelId === 'gpt-5.2') throw Object.assign(new Error('upstream 503'), { status: 503 });
+ return {
+ content: [{ type: 'text', text: JSON.stringify({ answer: 'Alice founded Acme.', citations: [], gaps: [] }) }],
+ finishReason: 'stop',
+ usage: { inputTokens: 3, outputTokens: 2 },
+ };
+ }) as any);
+
+ const result = await runThink(engine, { question: 'who founded Acme', model: 'openai:gpt-5.2' });
+
+ expect(result.answer).toBe('Alice founded Acme.');
+ expect(result.modelUsed).toBe('deepseek:deepseek-chat');
+ expect(result.requested_model).toBe('openai:gpt-5.2');
+ expect(result.fallback_reason).toContain('upstream 503');
+ });
+
+ test('an answer from the requested model carries no fallback fields', async () => {
+ configureGateway({
+ chat_model: 'openai:gpt-5.2',
+ chat_fallback_chain: ['deepseek:deepseek-chat'],
+ env: { OPENAI_API_KEY: 'fake-openai', DEEPSEEK_API_KEY: 'fake-deepseek' },
+ });
+ __setGenerateTextTransportForTests((async () => ({
+ content: [{ type: 'text', text: JSON.stringify({ answer: 'Alice founded Acme.', citations: [], gaps: [] }) }],
+ finishReason: 'stop',
+ usage: { inputTokens: 3, outputTokens: 2 },
+ })) as any);
+
+ const result = await runThink(engine, { question: 'who founded Acme', model: 'openai:gpt-5.2' });
+
+ expect(result.modelUsed).toBe('openai:gpt-5.2');
+ expect(result.requested_model).toBeUndefined();
+ expect(result.fallback_reason).toBeUndefined();
+ });
+});
+
describe('runThink + persistSynthesis — #1698 never persist empty', () => {
test('#3734: question embedder is called for vector takes retrieval', async () => {
let embeddedQuestion: string | undefined;