Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(ai): chat() walks chat_fallback_chain, pinned where model identity matters (#5490)

Andrei Neacsubc96ba8a0c38
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 90ef8068e5..347f55c1b6 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -35,4 +35,4 @@
- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.
- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.
- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.
-- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies plus the synthesis model); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`.
+- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies plus the synthesis model; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`.
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 63f17a6ab4..a1e4928a08 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -15,6 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).
- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.
+- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`) or the caller's own abort stops the chain; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts`.
- `src/core/ai/sdk-warnings.ts` — AI SDK provider warnings to stderr (#5892). The gateway calls `installAiSdkWarningWriter()` when it loads, which sets `globalThis.AI_SDK_LOG_WARNINGS` to a writer with the `ai` logger signature (`{ warnings, provider, model }`) that prints each warning in the SDK's own wording to stderr and never the SDK's `console.info` banner, which landed on stdout and broke `--json` output (the claude-cli model's v2-compat notice fires on every process's first call). A user-set value (`false` or a function) is kept. Tests: `ai-sdk-warnings.test.ts`, `json-stdout-ai-warnings.serial.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index bc86fe13e6..fd856c81e1 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -12,7 +12,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source; a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections` as a `preserving` writer bound to the page's current snapshot) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim while database-only timeline history is kept. `verifyBody` skips units inside a validly marked bullet (`materializedHistoryRanges`) only when that bullet is absent from the pre-run revision, i.e. it was materialized from the database during the run; a new page gets no exemption, and a claim added under a marked bullet that already existed is verified. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`). System One S8: `verifyBody` also returns `groundingUnits` (new units that pass only because they carry no quote, number or attribution; ≥5 words, not headings) without changing any other field; `verifyDreamPage` returns them per body, `verifyAndRepairDreamPages` takes an optional `grounding: GroundingPass` applied before write-back, and `quarantineUnits` removes S8-rejected units into `unverified_claims` with reason `unsupported_paraphrase`.
-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`).
+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached, nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`).
- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line. Its conversation-page section is the DB discovery (#4419): `discoverConversationPages(engine, opts)` returns the cycle source's live `type: conversation` pages (date filter on the `date` frontmatter, min_chars, exclude_patterns, `dream_generated`/`mode: lsd` and gbrain-self-session guards) as transcripts keyed `gbrain-page://<source>/<slug>` with a sha256 of the body; `withConversationPages(engine, opts, config, corpus)` appends them to the corpus list when the setting is on and drops a page whose body hash a corpus file already carries; `conversationPagesNotConsumed` returns the `conversation_pages_not_consumed` warn when synthesis is unconfigured but such pages exist. Gated by `dream.synthesize.conversation_pages` (on by default with a corpus dir, `true` opts in without one, `false` off). Pinned by `test/dream-conversation-pages.test.ts`. Each discovered corpus file carries `seat` when its session's `<sessionId>.seat.json` sidecar (`context/seat.ts`, keyed through `corpusFileSessionId`, so segments and writeback files share the session's seat) holds a valid label; the sidecar itself is never a transcript. `withTranscriptSeats` credits synthesis output refs to the seat of the transcript in their `raw_source`. Pinned by `test/transcript-discovery-seat.test.ts`.
diff --git a/evals/functional-area-resolver/harness-runner.ts b/evals/functional-area-resolver/harness-runner.ts
index 6fadff510d..57bc0a7810 100644
--- a/evals/functional-area-resolver/harness-runner.ts
+++ b/evals/functional-area-resolver/harness-runner.ts
@@ -333,6 +333,7 @@ async function callModel(prompt: string, modelFull: string): Promise<{ text: str
model: modelFull,
messages: [{ role: 'user', content: prompt }],
maxTokens: 64,
+ allowFallback: false,
});
return {
text: result.text,
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index e1d00035bd..550276888c 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -24,7 +24,7 @@ src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (de
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/serve.ts installStdioLifecycle 315 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first sync
-src/core/ai/gateway.ts chat 311 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/ai/gateway.ts chat 313 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5490: a configured chat_fallback_chain hands the call to chatWithFallback (loop lives in ai/chat-fallback.ts)
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTS
src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
@@ -38,7 +38,7 @@ src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 447 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 451 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/import-file.ts importFromContent 807 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..42088aa42c 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,10 +11,10 @@ src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2528 ratchet 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)
src/commands/jobs.ts 660 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)
src/commands/serve-http.ts 919 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)
-src/core/ai/gateway.ts 4393 ratchet +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)
+src/core/ai/gateway.ts 4407 ratchet +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)
src/commands/sync.ts 510 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)
src/core/cycle.ts 3224 ratchet +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)
-src/core/cycle/synthesize.ts 3297 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)
+src/core/cycle/synthesize.ts 3311 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)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
diff --git a/src/commands/models.ts b/src/commands/models.ts
index dc58b4dea6..9aa8ef2a56 100644
--- a/src/commands/models.ts
+++ b/src/commands/models.ts
@@ -644,6 +644,8 @@ export async function probeModel(modelStr: string, touchpoint: 'chat' | 'expansi
try {
await chat({
model: modelStr,
+ // A probe reports on this model; a chain hop would answer for another.
+ allowFallback: false,
messages: [{ role: 'user', content: '.' }],
// OpenAI rejects max_output_tokens below 16 ("Invalid
// 'max_output_tokens': integer below minimum value. Expected a value
diff --git a/src/commands/notability-eval.ts b/src/commands/notability-eval.ts
index c2b0bf271b..0b87895238 100644
--- a/src/commands/notability-eval.ts
+++ b/src/commands/notability-eval.ts
@@ -265,6 +265,7 @@ async function classifyBatch(paragraphs: string[]): Promise<Array<'high' | 'medi
system,
messages: [{ role: 'user', content: userMsg }],
maxTokens: 200,
+ allowFallback: false,
});
const text = result.text.trim().replace(/^```(?:json)?\s*/, '').replace(/\s*```$/, '');
const parsed = JSON.parse(text) as { tiers?: string[] };
diff --git a/src/commands/providers.ts b/src/commands/providers.ts
index 8900e8878f..7b2646aec4 100644
--- a/src/commands/providers.ts
+++ b/src/commands/providers.ts
@@ -273,6 +273,7 @@ async function runTest(args: string[]): Promise<void> {
const result = await gwChat({
messages: [{ role: 'user', content: 'Reply with just the word: pong' }],
maxTokens: 16,
+ allowFallback: false,
});
const ms = Date.now() - start;
const preview = (result.text || '<empty>').replace(/\s+/g, ' ').slice(0, 80);
diff --git a/src/core/ai/chat-fallback.ts b/src/core/ai/chat-fallback.ts
new file mode 100644
index 0000000000..a1c51a4dac
--- /dev/null
+++ b/src/core/ai/chat-fallback.ts
@@ -0,0 +1,100 @@
+/**
+ * `chat_fallback_chain` consumer (#5490). `gateway.chat()` delegates here when
+ * a chain is configured and the caller did not pin its model with
+ * `allowFallback: false`.
+ *
+ * Attempt order is the call's own model, then each chain entry not already
+ * tried. Every attempt is a complete single-model `chat()` call, so budget
+ * reservation, the usage ledger, guardrails and error normalization all see
+ * the model that actually ran, and `ChatResult.model` names it.
+ *
+ * The next model runs when an attempt
+ * - throws a provider error: a Claude subscription limit on a claude-cli
+ * model (apiErrorStatus 429), a rate limit, an outage, a timeout, a
+ * rejected key; or
+ * - 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.
+ * The chain stops on a gbrain policy refusal (an invocation-guard denial or a
+ * BudgetTracker `BudgetExhausted`: budget, caps and pricing describe gbrain's
+ * own accounting, and the next model is billed by the same ledger)
+ * and once the caller's own abort signal has fired. When every model fails,
+ * a refusal from an earlier attempt is returned in preference to a later
+ * attempt's error; otherwise the call's own model's error is thrown, so retry
+ * and halt classification (a 429 stays a rate limit) follow the configured
+ * model rather than whichever fallback failed last.
+ */
+
+import type { ChatOpts, ChatResult } from './gateway.ts';
+import { isAIInvocationPolicyError } from './invocation-guard.ts';
+import { BudgetExhausted } from '../budget/budget-tracker.ts';
+
+const HOP_REASON_MAX_CHARS = 200;
+
+/**
+ * The configured chain as trimmed model strings. A string value (the env and
+ * DB form, also accepted from a hand-edited config.json) is split on commas,
+ * so it is never walked one character at a time.
+ */
+export function normalizeChatFallbackChain(value: unknown): string[] | undefined {
+ const entries: unknown[] = typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : [];
+ const chain = entries.map(entry => String(entry).trim()).filter(Boolean);
+ return chain.length > 0 ? chain : undefined;
+}
+
+/** The primary model followed by each chain entry not already in the list. */
+export function chatFallbackAttempts(primary: string, chain: readonly string[]): string[] {
+ const attempts = [primary];
+ for (const model of chain) {
+ if (!attempts.includes(model)) attempts.push(model);
+ }
+ return attempts;
+}
+
+function isStructuralRefusal(result: ChatResult): boolean {
+ return result.stopReason === 'refusal' || result.stopReason === 'content_filter';
+}
+
+/** First line of an error message, bounded: claude-cli errors carry a raw output blob after it. */
+function hopReason(err: unknown): string {
+ const message = err instanceof Error ? err.message : String(err);
+ return message.split('\n', 1)[0]!.slice(0, HOP_REASON_MAX_CHARS);
+}
+
+export async function chatWithFallback(
+ opts: ChatOpts,
+ primary: string,
+ chain: readonly string[],
+ attempt: (opts: ChatOpts) => Promise<ChatResult>,
+): Promise<ChatResult> {
+ const models = chatFallbackAttempts(primary, chain);
+ const answered = (result: ChatResult, model: string): ChatResult =>
+ model === models[0] ? result : { ...result, fallbackFrom: models[0] };
+ let refused: ChatResult | null = null;
+ let primaryError: unknown;
+ for (let i = 0; ; i++) {
+ const model = models[i]!;
+ const next = models[i + 1];
+ try {
+ const result = await attempt({ ...opts, model, allowFallback: false });
+ if (next === undefined || !isStructuralRefusal(result)) return answered(result, model);
+ refused ??= answered(result, model);
+ console.warn(`[ai.gateway] chat ${result.model} stopped with ${result.stopReason}; trying ${next} from chat_fallback_chain`);
+ } catch (err) {
+ if (isAIInvocationPolicyError(err) || err instanceof BudgetExhausted || opts.abortSignal?.aborted) throw err;
+ if (model === models[0]) primaryError = err;
+ if (next === undefined) {
+ if (refused) {
+ console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); returning the earlier refusal from ${refused.model}`);
+ return refused;
+ }
+ if (model !== models[0]) {
+ console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); chat_fallback_chain exhausted, surfacing the ${models[0]} error`);
+ }
+ throw primaryError ?? err;
+ }
+ console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); trying ${next} from chat_fallback_chain`);
+ }
+ }
+}
diff --git a/src/core/ai/decide/index.ts b/src/core/ai/decide/index.ts
index 4c5ff6919f..9231a45af3 100644
--- a/src/core/ai/decide/index.ts
+++ b/src/core/ai/decide/index.ts
@@ -246,6 +246,8 @@ async function runLlm(req: DecideRequest, cfg: DecideConfig, a: RunArgs): Promis
model, system: LLM_SYSTEM_PROMPT, messages: [{ role: 'user', content: buildLlmPrompt(a.state, questions) }],
...(capability === 'structured' ? { responseSchema: LLM_ANSWER_SCHEMA } : {}),
temperature: 0, abortSignal: signal, purpose: `decide:${req.slot}`, maxTokens: 64 + questions.length * 96,
+ // The egress gate cleared this provider only; a chain hop would send the pack elsewhere.
+ allowFallback: false,
});
inputTokens += reply.usage.input_tokens;
outputTokens += reply.usage.output_tokens;
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 8c11167cdb..247e3948d1 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -36,6 +36,7 @@ import { DEFAULT_CHARS_PER_TOKEN, DEFAULT_SAFETY_FACTOR, embedRequestMaxInputTok
export { splitByTokenBudget, capBatchItems, NO_BATCH_CAP_SUB_BATCH_ITEMS } from './embed-batch-plan.ts';
import { BudgetTracker, type BudgetKind } from '../budget/budget-tracker.ts';
import { failedCallUsage, recordOnTracker } from './budget-record.ts';
+import { chatWithFallback, normalizeChatFallbackChain } from './chat-fallback.ts';
import type {
AIGatewayConfig,
EmbedMultimodalOpts,
@@ -445,7 +446,7 @@ export function configureGateway(config: AIGatewayConfig): void {
embedding_image_ocr_model: config.embedding_image_ocr_model,
expansion_model: config.expansion_model ?? DEFAULT_EXPANSION_MODEL,
chat_model: config.chat_model ?? DEFAULT_CHAT_MODEL,
- chat_fallback_chain: config.chat_fallback_chain,
+ chat_fallback_chain: normalizeChatFallbackChain(config.chat_fallback_chain),
// v0.35.0.0+: reranker_model stays undefined when unset — reranker is
// opt-in and pulling DEFAULT_RERANKER_MODEL into every gateway start
// would silently register a third-party model id on brains that never
@@ -3008,6 +3009,8 @@ export interface ChatResult {
providerId: string;
/** Raw provider metadata (Anthropic-specific cache fields, OpenAI finish_reason, etc.) for downstream callers that need it. */
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;
}
export interface ChatOpts {
@@ -3054,6 +3057,12 @@ export interface ChatOpts {
responseSchema?: { name: string; description?: string; schema: Record<string, unknown> };
/** Caller purpose (`skillopt.judge`, …) stamped on the BudgetTracker ledger row. */
purpose?: string;
+ /**
+ * `false` pins the call to its own model: `chat_fallback_chain` is not
+ * consulted (see `chat-fallback.ts`). Judge, critic and eval call sites set
+ * it so a verdict or score always comes from the model they named.
+ */
+ allowFallback?: boolean;
}
/**
@@ -3232,7 +3241,7 @@ function instantiateChat(recipe: Recipe, modelId: string, cfg: AIGatewayConfig):
/**
* Map AI SDK's `finish_reason` (and provider-specific signals) to a provider-
* neutral `stopReason`. This is the structural-signal layer that
- * `chatWithFallback` (commit 3) consults BEFORE any regex heuristic (per D8).
+ * `chatWithFallback` (chat-fallback.ts) consults BEFORE any regex heuristic (per D8).
*/
function mapStopReason(
finishReason: string | undefined,
@@ -3418,6 +3427,8 @@ export function toAISDKTools(tools: ChatToolDef[] | undefined): Record<string, a
}
export async function chat(opts: ChatOpts): Promise<ChatResult> {
+ const fallbackChain = opts.allowFallback === false ? undefined : _config?.chat_fallback_chain;
+ if (fallbackChain?.length) return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat);
const tracker = __budgetStore.getStore() ?? null;
const modelStrEarly = opts.model ?? getChatModel();
@@ -3784,6 +3795,8 @@ export interface ToolLoopOpts {
cacheSystem?: boolean;
/** Forwarded to every `chat()` turn; see `ChatOpts.purpose`. */
purpose?: string;
+ /** Forwarded to every `chat()` turn; see `ChatOpts.allowFallback`. */
+ allowFallback?: boolean;
/** Crash-replay state. When set, the loop resumes from the recorded position. */
replayState?: ToolLoopReplayState;
@@ -3933,6 +3946,7 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {
: opts.abortSignal,
cacheSystem: opts.cacheSystem,
purpose: opts.purpose,
+ allowFallback: opts.allowFallback,
});
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 55812ff626..96d8f1f695 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -493,9 +493,9 @@ export interface AIGatewayConfig {
reranker_model?: string;
/**
- * Optional silent-refusal fallback chain ("provider:modelId" entries).
- * Plumbed for `chatWithFallback()` (commit 3). Blocked from critic/judge/
- * synthesize flows in their respective handlers.
+ * Optional chat fallback chain ("provider:modelId" entries), walked by
+ * `chatWithFallback()` (chat-fallback.ts) when a chat call fails or refuses.
+ * Judge, critic and eval call sites opt out with `allowFallback: false`.
*/
chat_fallback_chain?: string[];
/** Optional per-provider base URL override (openai-compatible variants). */
diff --git a/src/core/brainstorm/judges.ts b/src/core/brainstorm/judges.ts
index b5f0c1da18..fd65528422 100644
--- a/src/core/brainstorm/judges.ts
+++ b/src/core/brainstorm/judges.ts
@@ -542,6 +542,7 @@ async function runJudgeChunk(
// (judge truncation at default 36-96 idea batches).
maxTokens: computeJudgeMaxTokens(ideas.length, options.modelOverride),
abortSignal: options.abortSignal,
+ allowFallback: false,
});
const parsed = parseJudgeJSON(result.text);
diff --git a/src/core/calibration/voice-gate.ts b/src/core/calibration/voice-gate.ts
index c1d588da57..8640a33739 100644
--- a/src/core/calibration/voice-gate.ts
+++ b/src/core/calibration/voice-gate.ts
@@ -164,6 +164,7 @@ export async function defaultJudge(input: {
// install without Anthropic credit judges with a provider it has.
model: resolveTierDefault('utility'),
maxTokens: 100,
+ allowFallback: false,
});
return parseJudgeOutput(result.text);
}
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..e41834bb88 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -150,9 +150,9 @@ export interface GBrainConfig {
*/
chat_model?: string;
/**
- * Optional silent-refusal fallback chain for `chatWithFallback()` (v0.27+).
- * Each entry is a "provider:modelId" string. Blocked from critic/judge/
- * synthesize flows in their respective handlers (per D13 review decision).
+ * Optional chat fallback chain for `chatWithFallback()` (v0.27+): tried in
+ * order when a chat call fails or refuses. Each entry is a "provider:modelId"
+ * string. Judge, critic and eval call sites pin their model (allowFallback).
*/
chat_fallback_chain?: string[];
/** Optional base URL overrides for openai-compatible providers (keyed by recipe id). */
diff --git a/src/core/cross-modal-eval/runner.ts b/src/core/cross-modal-eval/runner.ts
index c740df90be..805862a751 100644
--- a/src/core/cross-modal-eval/runner.ts
+++ b/src/core/cross-modal-eval/runner.ts
@@ -236,6 +236,7 @@ async function callSlot(
messages,
maxTokens: opts.maxTokens,
abortSignal: opts.abortSignal,
+ allowFallback: false,
});
const parsed = parseModelJSON(result.text ?? '');
diff --git a/src/core/cycle/auto-think.ts b/src/core/cycle/auto-think.ts
index 567f67ab0b..3e66e71735 100644
--- a/src/core/cycle/auto-think.ts
+++ b/src/core/cycle/auto-think.ts
@@ -172,6 +172,8 @@ export async function runPhaseAutoThink(
save: config.autoCommit,
client: opts.client,
model: modelId,
+ // The BudgetMeter above priced modelId; a chain hop would spend on a model it never checked.
+ allowFallback: false,
// Fail-closed trust: the local dream cycle must say so explicitly, or
// trajectory injection degrades to visibility='world' rows.
remote: false,
diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.ts
index c9f729ecbf..1b89d7431d 100644
--- a/src/core/cycle/drift.ts
+++ b/src/core/cycle/drift.ts
@@ -174,6 +174,7 @@ export async function defaultDriftJudge(input: {
messages: [{ role: 'user', content: buildDriftPrompt(input.candidate, input.evidence) }],
...(input.modelHint ? { model: input.modelHint } : {}),
maxTokens: input.maxOutputTokens ?? resolveSynthMaxOutputTokens(input.modelHint ?? ''),
+ allowFallback: false,
});
const parsed = parseDriftOutput(result.text);
if (!parsed) {
diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts
index a8dad3b615..51c993d793 100644
--- a/src/core/cycle/grade-takes.ts
+++ b/src/core/cycle/grade-takes.ts
@@ -436,6 +436,7 @@ export async function defaultJudge(input: {
messages: [{ role: 'user', content: prompt }],
...(input.modelHint ? { model: input.modelHint } : {}),
maxTokens: 600,
+ allowFallback: false,
});
const parsed = parseJudgeOutput(result.text);
if (!parsed) {
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index 8a9b80f09d..b3497dcf76 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -313,11 +313,13 @@ export async function runPhaseSynthesizeConcepts(
}
// The narrative is a function of the member atoms, their strictest
// visibility and the model. When none changed and the page holds a real
- // narrative, there is nothing to spend or rewrite; a fallback page is retried.
- const memberHash = createHash('sha256')
- .update(JSON.stringify([synthModel, group.visibility, group.atomSlugs.map((s, i) => [s, group.atomTitles[i], group.atomBodies[i]])
+ // narrative, there is nothing to spend or rewrite; a fallback page is retried,
+ // and so is one a chat_fallback_chain model wrote (hashed under that model).
+ const hashFor = (model: string): string => createHash('sha256')
+ .update(JSON.stringify([model, group.visibility, group.atomSlugs.map((s, i) => [s, group.atomTitles[i], group.atomBodies[i]])
.sort((a, b) => a[0].localeCompare(b[0]))]))
.digest('hex').slice(0, 16);
+ const memberHash = hashFor(synthModel);
const priorMode = existing?.frontmatter?.synthesis_mode;
if (existing?.frontmatter?.member_hash === memberHash && (priorMode === 'llm' || priorMode === 'deterministic_tier')) {
skippedUnchanged.push(conceptSlug);
@@ -326,6 +328,7 @@ export async function runPhaseSynthesizeConcepts(
tierCounts[group.tier]++;
let narrative: string;
let synthesisMode: ConceptSynthesisMode;
+ let fallbackWriter: string | undefined;
if (group.tier === 'T1' || group.tier === 'T2') {
if (estimatedSpendUsd >= budgetCap) {
narrative = deterministicNarrative(group);
@@ -367,6 +370,7 @@ export async function runPhaseSynthesizeConcepts(
if (text) {
narrative = text;
synthesisMode = 'llm';
+ if (result.fallbackFrom) fallbackWriter = result.model;
} else {
failures.push({ concept: group.conceptSlug, error: 'empty model response' });
narrative = deterministicNarrative(group);
@@ -420,7 +424,7 @@ export async function runPhaseSynthesizeConcepts(
mention_count: group.atomTitles.length,
composite_score: group.atomTitles.length,
synthesis_mode: synthesisMode,
- member_hash: memberHash,
+ member_hash: fallbackWriter ? hashFor(fallbackWriter) : memberHash,
synthesized_at: synthesizedAt,
synthesized_by: 'synthesize_concepts-v0.41',
visibility: pageVisibility,
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 2d01adf66c..7d57d86478 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -1940,6 +1940,8 @@ export function makeJudgeClient(verdictModel: string): JudgeClient | null {
type: 'message',
role: 'assistant',
model: modelStr,
+ // A chat_fallback_chain entry answered: judgeSignificance marks the verdict uncacheable.
+ ...(result.fallbackFrom ? { answered_by: result.model } : {}),
content: [{ type: 'text', text: result.text }],
stop_reason: result.stopReason === 'length' ? 'max_tokens'
: result.stopReason === 'tool_calls' ? 'tool_use'
@@ -1992,6 +1994,12 @@ export interface TriageResult {
* the call was paid whether or not the verdict parsed.
*/
tokens?: { in: number; out: number };
+ /**
+ * The model that answered when it is not the verdict model (a
+ * chat_fallback_chain hop). Its score is not comparable within the cache
+ * tuple, so runTriagePass uses the verdict for this run without caching it.
+ */
+ answeredBy?: string;
}
/** Degenerate TriageResult factory — score 0, never cached (unreliable is always set). */
@@ -2116,7 +2124,9 @@ Quote verbatim; never paraphrase inside "quote".`;
&& typeof rawUsage.output_tokens === 'number' && Number.isFinite(rawUsage.output_tokens)
? { in: rawUsage.input_tokens, out: rawUsage.output_tokens }
: undefined;
- const withTokens = (r: TriageResult): TriageResult => (callTokens ? { ...r, tokens: callTokens } : r);
+ const answeredBy = (msg as { answered_by?: string }).answered_by;
+ const withTokens = (r: TriageResult): TriageResult =>
+ ({ ...r, ...(callTokens ? { tokens: callTokens } : {}), ...(answeredBy ? { answeredBy } : {}) });
const refused = stopReasonRaw === 'refusal';
const abnormalStop: TriageResult['unreliable'] | undefined =
truncated ? 'truncated' : refused ? 'refusal' : undefined;
@@ -2540,16 +2550,20 @@ export async function runTriagePass(
// #4077: a cancelled cycle must not bank new dream_verdicts rows for
// work it is abandoning — the next run re-judges from a clean slate.
throwIfAborted(cfg.signal, '[dream] significance judge');
- await engine.putDreamVerdict(t.filePath, t.contentHash, {
- worth_processing: triage.worth_processing,
- reasons: triage.reasons,
- score: triage.score,
- content_type: triage.content_type,
- segments: triage.segments,
- entities: triage.entities,
- model: cfg.model,
- triage_version: TRIAGE_VERSION,
- });
+ if (triage.answeredBy) {
+ process.stderr.write(`[dream] triage for ${t.basename} came from fallback model ${triage.answeredBy}; not caching in dream_verdicts\n`);
+ } else {
+ await engine.putDreamVerdict(t.filePath, t.contentHash, {
+ worth_processing: triage.worth_processing,
+ reasons: triage.reasons,
+ score: triage.score,
+ content_type: triage.content_type,
+ segments: triage.segments,
+ entities: triage.entities,
+ model: cfg.model,
+ triage_version: TRIAGE_VERSION,
+ });
+ }
byPath.set(t.filePath, {
worth_processing: triage.worth_processing,
reasons: triage.reasons,
diff --git a/src/core/eval-contradictions/judge.ts b/src/core/eval-contradictions/judge.ts
index fd4edd7196..b1d8e00c77 100644
--- a/src/core/eval-contradictions/judge.ts
+++ b/src/core/eval-contradictions/judge.ts
@@ -437,6 +437,7 @@ export async function judgeContradiction(input: JudgeInput): Promise<JudgeOutput
messages: [{ role: 'user', content: prompt }],
maxTokens: 1024,
abortSignal: input.abortSignal,
+ allowFallback: false,
});
if (isRefusalResponse(result)) {
throw new Error('judge refused to answer');
diff --git a/src/core/skillopt/bootstrap-benchmark.ts b/src/core/skillopt/bootstrap-benchmark.ts
index f10a17a44b..38256234a1 100644
--- a/src/core/skillopt/bootstrap-benchmark.ts
+++ b/src/core/skillopt/bootstrap-benchmark.ts
@@ -132,6 +132,7 @@ export async function runBootstrap(opts: BootstrapOpts): Promise<BootstrapResult
maxTokens: skilloptOutputCap(optimizerModel, 500),
cacheSystem: true,
purpose: SKILLOPT_PURPOSE.optimizer,
+ allowFallback: false,
});
if (result.stopReason === 'length') {
skipped += 1;
@@ -252,6 +253,7 @@ export async function runBootstrapFromSkill(opts: BootstrapFromSkillOpts): Promi
maxTokens: skilloptOutputCap(optimizerModel, Math.min(8000, Math.max(4000, taskCount * 220))),
cacheSystem: true,
purpose: SKILLOPT_PURPOSE.optimizer,
+ allowFallback: false,
});
const { generated, skipped } = parseSkillBenchmarkJsonl(result.text, skillName, result.stopReason === 'length');
diff --git a/src/core/skillopt/reflect.ts b/src/core/skillopt/reflect.ts
index cc6cf6460c..08b095564e 100644
--- a/src/core/skillopt/reflect.ts
+++ b/src/core/skillopt/reflect.ts
@@ -242,6 +242,7 @@ export async function runOneShotRewrite(opts: ReflectOpts): Promise<OneShotRewri
cacheSystem: true,
abortSignal: opts.abortSignal,
purpose: SKILLOPT_PURPOSE.optimizer,
+ allowFallback: false,
});
} catch (err) {
if (isSkilloptMustAbort(err)) throw err;
@@ -287,6 +288,7 @@ async function callReflect(
cacheSystem: true, // D11
abortSignal: opts.abortSignal,
purpose: SKILLOPT_PURPOSE.optimizer,
+ allowFallback: false,
});
} catch (err) {
if (isSkilloptMustAbort(err)) throw err;
diff --git a/src/core/skillopt/rollout.ts b/src/core/skillopt/rollout.ts
index cf7e0d1069..1668d45ec0 100644
--- a/src/core/skillopt/rollout.ts
+++ b/src/core/skillopt/rollout.ts
@@ -111,6 +111,7 @@ export async function runRollout(opts: RolloutOpts): Promise<Trajectory> {
cacheSystem: true, // D11: candidate skill is stable for a step's batch.
abortSignal: opts.abortSignal,
purpose: SKILLOPT_PURPOSE.target,
+ allowFallback: false,
onToolCallStart: async (_turnIdx, _messageIdx, _ordinal, toolName, input, providerToolCallId) => {
const gbrainToolUseId = `skillopt-${nextOrdinal++}-${providerToolCallId}`;
const idx = toolCalls.length;
diff --git a/src/core/skillopt/score.ts b/src/core/skillopt/score.ts
index a5d8143719..40396d86ff 100644
--- a/src/core/skillopt/score.ts
+++ b/src/core/skillopt/score.ts
@@ -177,6 +177,7 @@ async function scoreLlm(
maxTokens: skilloptOutputCap(judgeModel, JUDGE_SITE_MAX_TOKENS),
cacheSystem: true, // D11: judge system prompt is stable across calls.
purpose: SKILLOPT_PURPOSE.judge,
+ allowFallback: false,
});
const parsed = parseJudgeJson(result.text);
if (!parsed) {
diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.ts
index c1ce3960ee..7a75dbe47e 100644
--- a/src/core/takes-quality-eval/runner.ts
+++ b/src/core/takes-quality-eval/runner.ts
@@ -126,6 +126,7 @@ async function callOneModel(
messages: [{ role: 'user', content: systemPrompt }],
maxTokens: 2000,
abortSignal,
+ allowFallback: false,
});
try {
const parsed = parseModelJSON(result.text);
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 44541d92c9..a740f9417e 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -79,6 +79,8 @@ export interface RunThinkOpts {
* default model path keeps its graceful-degrade behavior.
*/
modelExplicit?: boolean;
+ /** `false` keeps the gateway client on `model` (no `chat_fallback_chain` hop); an explicit model always does. */
+ allowFallback?: boolean;
/** Optional time window for temporal questions. */
since?: string;
until?: string;
@@ -773,7 +775,7 @@ export async function runThink(
// That bypassed gateway config (gbrain config set anthropic_api_key)
// because the Anthropic SDK only reads process.env.ANTHROPIC_API_KEY.
// Closes #952 (think over MCP returns "no LLM available").
- const client = opts.client ?? await tryBuildGatewayClient(modelUsed, { explicitModel: opts.modelExplicit });
+ const client = opts.client ?? await tryBuildGatewayClient(modelUsed, { explicitModel: opts.modelExplicit, allowFallback: opts.allowFallback });
if (!client) {
// Label the failure honestly: a missing key and an unusable model id are
// different incidents with different fixes. Pre-fix EVERY null client was
@@ -1112,7 +1114,7 @@ async function readThinkTrajectoryEnabled(engine: BrainEngine): Promise<boolean>
*/
async function tryBuildGatewayClient(
modelUsed: string,
- opts: { explicitModel?: boolean } = {},
+ opts: { explicitModel?: boolean; allowFallback?: boolean } = {},
): Promise<ThinkLLMClient | null> {
// Normalize: ensure provider:model shape (and slash→colon — #1698). resolveModel
// returns bare anthropic ids (`claude-opus-4-7`); gateway.chat needs `anthropic:...`.
@@ -1158,6 +1160,8 @@ async function tryBuildGatewayClient(
system,
messages,
maxTokens: params.max_tokens,
+ // An explicit --model is a hard requirement (#1698), never a hop.
+ ...(opts.explicitModel || opts.allowFallback === false ? { allowFallback: false } : {}),
});
} catch (e) {
// AIConfigError at chat time = e.g. key revoked mid-run. For an EXPLICIT
diff --git a/src/eval/longmemeval/gateway-client.ts b/src/eval/longmemeval/gateway-client.ts
index 7bb223004a..69884ab1f9 100644
--- a/src/eval/longmemeval/gateway-client.ts
+++ b/src/eval/longmemeval/gateway-client.ts
@@ -36,6 +36,7 @@ export function makeGatewayThinkClient(): ThinkLLMClient {
system,
messages,
maxTokens: params.max_tokens,
+ allowFallback: false,
});
return {
id: '',
diff --git a/src/eval/shared/judge-runner.ts b/src/eval/shared/judge-runner.ts
index 674a54f0cb..aaba7fe44d 100644
--- a/src/eval/shared/judge-runner.ts
+++ b/src/eval/shared/judge-runner.ts
@@ -151,6 +151,7 @@ export async function runJudge(opts: RunJudgeOpts): Promise<JudgeOutcome> {
maxTokens: opts.maxTokens,
temperature: opts.temperature,
...(opts.signal ? { abortSignal: opts.signal } : {}),
+ allowFallback: false,
});
} catch (err) {
const cls = classifyJudgeTransportError(err);
diff --git a/test/ai/gateway-chat-fallback.test.ts b/test/ai/gateway-chat-fallback.test.ts
new file mode 100644
index 0000000000..9f03b80662
--- /dev/null
+++ b/test/ai/gateway-chat-fallback.test.ts
@@ -0,0 +1,362 @@
+/**
+ * #5490: gateway.chat() consults `chat_fallback_chain`.
+ *
+ * Drives the real chat() path (provider resolution, error normalization,
+ * invocation policy) through the generateText transport seam, so every
+ * attempt is observed by the model the gateway actually instantiated. The
+ * primary is a claude-cli model failing the way a Claude subscription limit
+ * does: a ClaudeCliProcessError carrying apiErrorStatus 429.
+ */
+
+import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';
+import {
+ configureGateway,
+ resetGateway,
+ chat,
+ toolLoop,
+ withBudgetTracker,
+ __setGenerateTextTransportForTests,
+} from '../../src/core/ai/gateway.ts';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { buildGatewayConfig } from '../../src/core/ai/build-gateway-config.ts';
+import { loadConfig } from '../../src/core/config.ts';
+import { BudgetExhausted, BudgetTracker } from '../../src/core/budget/budget-tracker.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { AITransientError } from '../../src/core/ai/errors.ts';
+import { ClaudeCliProcessError } from '../../src/core/ai/providers/claude-cli-language-model.ts';
+import { isAIInvocationPolicyError, withAIInvocationPreflight } from '../../src/core/ai/invocation-guard.ts';
+import { defaultJudge } from '../../src/core/cycle/grade-takes.ts';
+import { judgeContradiction } from '../../src/core/eval-contradictions/judge.ts';
+import type { Take } from '../../src/core/engine.ts';
+import { probeModel } from '../../src/commands/models.ts';
+import { defaultDriftJudge } from '../../src/core/cycle/drift.ts';
+import { makeJudgeClient } from '../../src/core/cycle/synthesize.ts';
+import { runJudge } from '../../src/eval/shared/judge-runner.ts';
+
+const PRIMARY = 'claude-cli:claude-sonnet-4-6';
+const FALLBACK = 'openai:gpt-5.6-luna';
+const SECOND_FALLBACK = 'deepseek:deepseek-v4-flash';
+const ENV = { OPENAI_API_KEY: 'fake-openai', DEEPSEEK_API_KEY: 'fake-deepseek' };
+
+type Outcome = 'ok' | 'limit' | 'refusal' | 'filtered' | 'outage';
+
+/** Synthetic subscription-limit failure in the claude-cli envelope shape, raw CLI output after the first line. */
+function subscriptionLimit(): ClaudeCliProcessError {
+ return new ClaudeCliProcessError(
+ "claude-cli API error 429: You've hit your session limit · resets 3:00am (UTC)\n--- raw ---\n{\"is_error\":true,\"result\":\"synthetic raw blob\"}",
+ { apiErrorStatus: 429, exitCode: 1 },
+ );
+}
+
+let attempts: string[] = [];
+
+/** Install a transport that answers per model id and records the attempt order. */
+function installTransport(outcomes: Record<string, Outcome>): void {
+ __setGenerateTextTransportForTests((async (args: any) => {
+ const modelId: string = args.model.modelId;
+ attempts.push(modelId);
+ const outcome = outcomes[modelId] ?? 'ok';
+ if (outcome === 'limit') throw subscriptionLimit();
+ if (outcome === 'outage') throw Object.assign(new Error(`${modelId} upstream 503`), { status: 503 });
+ return {
+ content: [{ type: 'text', text: `answer from ${modelId}` }],
+ finishReason: outcome === 'filtered' ? 'content-filter' : 'stop',
+ usage: { inputTokens: 3, outputTokens: 2 },
+ ...(outcome === 'refusal' ? { providerMetadata: { anthropic: { stopReason: 'refusal' } } } : {}),
+ };
+ }) as any);
+}
+
+const ask = (extra: Record<string, unknown> = {}) =>
+ chat({ model: PRIMARY, messages: [{ role: 'user', content: 'hello' }], ...extra });
+
+let warn: ReturnType<typeof spyOn>;
+
+beforeEach(() => {
+ resetGateway();
+ attempts = [];
+ warn = spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ warn.mockRestore();
+ resetGateway();
+});
+
+interface HopCase {
+ name: string;
+ chain: string[];
+ outcomes: Record<string, Outcome>;
+ expectAttempts: string[];
+ expectModel: string;
+}
+
+describe('chat() with chat_fallback_chain (#5490)', () => {
+ test.each<HopCase>([
+ {
+ name: 'claude-cli subscription limit falls through to the API model',
+ chain: [FALLBACK],
+ outcomes: { 'claude-sonnet-4-6': 'limit' },
+ expectAttempts: ['claude-sonnet-4-6', 'gpt-5.6-luna'],
+ expectModel: FALLBACK,
+ },
+ {
+ name: 'a healthy primary never touches the chain',
+ chain: [FALLBACK],
+ outcomes: {},
+ expectAttempts: ['claude-sonnet-4-6'],
+ expectModel: PRIMARY,
+ },
+ {
+ name: 'the chain is walked in order past a failing entry',
+ chain: [FALLBACK, SECOND_FALLBACK],
+ outcomes: { 'claude-sonnet-4-6': 'limit', 'gpt-5.6-luna': 'outage' },
+ expectAttempts: ['claude-sonnet-4-6', 'gpt-5.6-luna', 'deepseek-v4-flash'],
+ expectModel: SECOND_FALLBACK,
+ },
+ {
+ name: 'chain entries repeating the primary or each other run once',
+ chain: [PRIMARY, FALLBACK, FALLBACK],
+ outcomes: { 'claude-sonnet-4-6': 'limit' },
+ expectAttempts: ['claude-sonnet-4-6', 'gpt-5.6-luna'],
+ expectModel: FALLBACK,
+ },
+ {
+ name: 'a structural refusal falls through to the next model',
+ chain: [FALLBACK],
+ outcomes: { 'claude-sonnet-4-6': 'refusal' },
+ expectAttempts: ['claude-sonnet-4-6', 'gpt-5.6-luna'],
+ expectModel: FALLBACK,
+ },
+ {
+ name: 'a content filter falls through to the next model',
+ chain: [FALLBACK],
+ outcomes: { 'claude-sonnet-4-6': 'filtered' },
+ expectAttempts: ['claude-sonnet-4-6', 'gpt-5.6-luna'],
+ expectModel: FALLBACK,
+ },
+ ])('$name', async ({ chain, outcomes, expectAttempts, expectModel }) => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: chain, env: ENV });
+ installTransport(outcomes);
+
+ const result = await ask();
+
+ expect(attempts).toEqual(expectAttempts);
+ expect(result.model).toBe(expectModel);
+ expect(result.text).toBe(`answer from ${expectAttempts.at(-1)}`);
+ expect(result.fallbackFrom).toBe(expectModel === PRIMARY ? undefined : PRIMARY);
+ });
+
+ test('each hop is reported on stderr with the failed model and the next one', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ await ask();
+
+ const lines = warn.mock.calls.map((c: unknown[]) => String(c[0]));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain(PRIMARY);
+ expect(lines[0]).toContain('session limit');
+ expect(lines[0]).toContain(FALLBACK);
+ expect(lines[0]).not.toContain('--- raw ---');
+ });
+
+ test("when every model fails, the call's own model's error surfaces and the last failure is logged", async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit', 'gpt-5.6-luna': 'outage' });
+
+ const err = await ask().catch(e => e);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna']);
+ expect(err).toBeInstanceOf(AITransientError);
+ expect(err.apiErrorStatus).toBe(429);
+ expect(String(warn.mock.calls.at(-1)?.[0])).toContain('gpt-5.6-luna upstream 503');
+ });
+
+ test('a refusal earlier in the chain is returned instead of a later failure', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'refusal', 'gpt-5.6-luna': 'outage' });
+
+ const result = await ask();
+
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna']);
+ expect(result.model).toBe(PRIMARY);
+ expect(result.stopReason).toBe('refusal');
+ });
+
+ test('allowFallback: false pins the call to its own model', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ const err = await ask({ allowFallback: false }).catch(e => e);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ expect(err).toBeInstanceOf(AITransientError);
+ expect(err.apiErrorStatus).toBe(429);
+ });
+
+ test('a gbrain policy refusal is never retried on another model', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({});
+ const denied: string[] = [];
+
+ const err = await withAIInvocationPreflight(async call => {
+ denied.push(call.model);
+ throw new Error('budget cap reached');
+ }, () => ask()).catch(e => e);
+
+ expect(isAIInvocationPolicyError(err)).toBe(true);
+ expect(denied).toHaveLength(1);
+ expect(attempts).toEqual([]);
+ });
+
+ test("the caller's own abort stops the chain", async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ const controller = new AbortController();
+ __setGenerateTextTransportForTests((async (args: any) => {
+ attempts.push(args.model.modelId);
+ controller.abort();
+ throw subscriptionLimit();
+ }) as any);
+
+ const err = await ask({ abortSignal: controller.signal }).catch(e => e);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ expect(err).toBeInstanceOf(AITransientError);
+ });
+
+ test.each([
+ { name: 'unset', chain: undefined },
+ { name: 'empty', chain: [] as string[] },
+ ])('with the chain $name the primary error surfaces unchanged', async ({ chain }) => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: chain, env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ const err = await ask().catch(e => e);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ expect(err.apiErrorStatus).toBe(429);
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
+
+describe('toolLoop() and judge flows with chat_fallback_chain (#5490)', () => {
+ const loop = (extra: Record<string, unknown> = {}) => toolLoop({
+ model: PRIMARY,
+ initialMessages: [{ role: 'user', content: 'hello' }],
+ tools: [],
+ toolHandlers: new Map(),
+ ...extra,
+ });
+
+ test('toolLoop turns fall back like any other chat call', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ const result = await loop();
+
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna']);
+ expect(result.finalText).toBe('answer from gpt-5.6-luna');
+ });
+
+ const take = { claim: 'a synthetic claim', kind: 'fact', holder: 'alice-example', since_date: null, weight: 0.5 } as unknown as Take;
+
+ const driftCandidate = { takeId: 1, pageId: 1, pageSlug: 'notes/a-example', rowNum: 1, claim: 'a synthetic claim', weight: 0.5, recentEvidenceCount: 1 };
+
+ test.each([
+ { name: 'toolLoop({ allowFallback: false }) (skillopt rollouts)', run: () => loop({ allowFallback: false }) },
+ { name: 'grade_takes judge', run: () => defaultJudge({ take, evidence: 'synthetic evidence', modelHint: PRIMARY }) },
+ { name: 'drift judge', run: () => defaultDriftJudge({ candidate: driftCandidate, evidence: 'synthetic evidence', modelHint: PRIMARY }) },
+ { name: 'models doctor probe', run: () => probeModel(PRIMARY, 'chat') },
+ {
+ name: 'LongMemEval judge',
+ run: () => runJudge({ client: chat, model: PRIMARY, prompt: 'synthetic', maxTokens: 16, temperature: 0, parse: () => 'yes' as never, retries: 0 }),
+ },
+ {
+ name: 'contradiction eval judge',
+ run: () => judgeContradiction({
+ query: 'synthetic query',
+ a: { slug: 'notes/a-example', text: 'statement one' },
+ b: { slug: 'notes/b-example', text: 'statement two' },
+ model: PRIMARY,
+ }),
+ },
+ ])('$name keeps its own model at the subscription limit', async ({ run }) => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ await run().catch(() => undefined);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ });
+
+ test('the synthesize triage client marks a verdict a chain model gave', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ const msg = await makeJudgeClient(PRIMARY)!.create({ model: PRIMARY, max_tokens: 16, messages: [{ role: 'user', content: 'hello' }] });
+
+ expect((msg as unknown as { answered_by?: string }).answered_by).toBe(FALLBACK);
+ });
+});
+
+describe('chain sources and budget refusals (#5490)', () => {
+ /** A throwaway GBRAIN_HOME whose config.json names the claude-cli primary and, optionally, a chain. */
+ function homeWith(fileChain?: unknown): string {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-chat-fallback-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ database_path: join(home, 'brain.pglite'),
+ chat_model: PRIMARY,
+ ...(fileChain !== undefined ? { chat_fallback_chain: fileChain } : {}),
+ }));
+ return home;
+ }
+
+ test.each([
+ { name: 'GBRAIN_CHAT_FALLBACK_CHAIN', fileChain: undefined, envChain: FALLBACK },
+ { name: 'a config.json array', fileChain: [FALLBACK], envChain: undefined },
+ { name: 'a hand-written config.json string', fileChain: ` ${FALLBACK} `, envChain: undefined },
+ ])('a chain from $name reaches chat() through loadConfig and buildGatewayConfig', async ({ fileChain, envChain }) => {
+ await withEnv({
+ GBRAIN_HOME: homeWith(fileChain),
+ GBRAIN_CHAT_FALLBACK_CHAIN: envChain,
+ GBRAIN_CHAT_MODEL: undefined,
+ DATABASE_URL: undefined,
+ GBRAIN_DATABASE_URL: undefined,
+ OPENAI_API_KEY: 'fake-openai',
+ }, async () => {
+ configureGateway(buildGatewayConfig(loadConfig()!));
+ installTransport({ 'claude-sonnet-4-6': 'limit' });
+
+ const result = await ask();
+
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna']);
+ expect(result.model).toBe(FALLBACK);
+ });
+ });
+
+ test('a BudgetTracker refusal stops the chain instead of trying a cheaper model', async () => {
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ chat_fallback_chain: ['openai:gpt-4o-mini'],
+ env: { ...ENV, ANTHROPIC_API_KEY: 'fake-anthropic' },
+ });
+ installTransport({});
+ const tracker = new BudgetTracker({ label: 'chat-fallback-budget', maxCostUsd: 0.005, auditPath: '/dev/null' });
+
+ const err = await withBudgetTracker(tracker, () => chat({
+ model: 'anthropic:claude-sonnet-4-6',
+ messages: [{ role: 'user', content: 'hello' }],
+ maxTokens: 4096,
+ })).catch(e => e);
+
+ expect(err).toBeInstanceOf(BudgetExhausted);
+ expect(attempts).toEqual([]);
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts
index 9b0b1a4ac9..b7a54ccadb 100644
--- a/test/ai/gateway-chat.test.ts
+++ b/test/ai/gateway-chat.test.ts
@@ -5,7 +5,7 @@
* - chat() resolves provider:model strings + aliases
* - assertTouchpoint surfaces chat-only providers correctly
* - getChatModel() default + override
- * - chat_fallback_chain plumbing (config plumbing only — chatWithFallback ships in commit 3)
+ * - chat_fallback_chain plumbing (the fallback loop itself: test/ai/gateway-chat-fallback.test.ts)
* - new openai-compat recipes (deepseek, groq, together) parse + resolve
* - new ChatTouchpoint shape: supports_subagent_loop, supports_prompt_cache
* - mapStopReason via the chat() boundary (mocked client) — refusal / content_filter / tool_calls / end / length
diff --git a/test/cycle-synthesize-triage.test.ts b/test/cycle-synthesize-triage.test.ts
index 4e83862cd1..7be2c85578 100644
--- a/test/cycle-synthesize-triage.test.ts
+++ b/test/cycle-synthesize-triage.test.ts
@@ -121,6 +121,23 @@ describe('runTriagePass — cache validity (C8)', () => {
expect(rows.get(`${t.filePath}|${t.contentHash}`)?.triage_version).toBe(TRIAGE_VERSION);
});
+ test('a verdict a chat_fallback_chain model gave decides this run but is never cached', async () => {
+ const fake = makeFakeEngine();
+ const t = makeTranscript('fallback');
+ const judge: JudgeClient = {
+ create: async () => ({
+ content: [{ type: 'text', text: JSON.stringify({ score: 0.7, reasons: ['mock'] }) }],
+ stop_reason: 'end_turn',
+ answered_by: 'openai:gpt-example',
+ } as never),
+ };
+ const r = await runTriagePass(fake.engine, [t], baseCfg(judge));
+ expect(r.judged).toBe(1);
+ expect(fake.putCalls).toBe(0);
+ expect(r.reports[0]?.score).toBe(0.7);
+ expect(r.reports[0]?.worth).toBe(true);
+ });
+
test('model mismatch is a MISS — switching models re-judges (C8)', async () => {
const { engine, rows } = makeFakeEngine();
const t = makeTranscript('model-switch');
diff --git a/test/cycle/synthesize-concepts-identity.test.ts b/test/cycle/synthesize-concepts-identity.test.ts
index 236df0ec94..55591d9258 100644
--- a/test/cycle/synthesize-concepts-identity.test.ts
+++ b/test/cycle/synthesize-concepts-identity.test.ts
@@ -118,6 +118,20 @@ describe('synthesize_concepts narrative stability (C-5)', () => {
expect(page?.frontmatter.synthesis_mode).toBe('llm');
}, 120000);
+ test('a narrative a chat_fallback_chain model wrote is re-synthesized on the next cycle', async () => {
+ const calls = { n: 0 };
+ const viaChain = chatReturning('Chain narrative.', calls);
+ await runPhaseSynthesizeConcepts(engine, {
+ _atoms: t2Atoms(), sourceId: 'default',
+ _chat: async (o: ChatOpts) => ({ ...(await viaChain(o)), model: 'openai:gpt-example', fallbackFrom: o.model }),
+ });
+ expect((await engine.getPage('concepts/flywheel', { sourceId: 'default' }))?.compiled_truth.trim()).toBe('Chain narrative.');
+
+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: chatReturning('Configured narrative.', calls) });
+ expect(calls.n).toBe(2);
+ expect((await engine.getPage('concepts/flywheel', { sourceId: 'default' }))?.compiled_truth.trim()).toBe('Configured narrative.');
+ }, 120000);
+
test('a fallback page is retried with the LLM on the next cycle', async () => {
const failing = (async () => { throw new Error('boom: unexpected provider fault'); }) as unknown as (o: ChatOpts) => Promise<ChatResult>;
await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: failing });
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index fb4aa5732c..fc488e7a6a 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1524,6 +1524,7 @@
"kind": "interface",
"members": [
"abortSignal?: AbortSignal | undefined",
+ "allowFallback?: boolean | undefined",
"cacheSystem?: boolean | undefined",
"maxTokens?: number | undefined",
"messages: ChatMessage[]",
@@ -1541,6 +1542,7 @@
"kind": "interface",
"members": [
"blocks: ChatBlock[]",
+ "fallbackFrom?: string | undefined",
"model: string",
"providerId: string",
"providerMetadata?: Record<string, any> | undefined",
@@ -1713,6 +1715,7 @@
"members": [
"abortSignal?: AbortSignal | undefined",
"acquireTurnPermit?: (() => Promise<TurnPermit>) | undefined",
+ "allowFallback?: boolean | undefined",
"cacheSystem?: boolean | undefined",
"initialMessages: ChatMessage[]",
"maxTokens?: number | undefined",
@@ -7095,6 +7098,7 @@
{
"kind": "interface",
"members": [
+ "allowFallback?: boolean | undefined",
"allowedSources?: string[] | undefined",
"anchor?: string | undefined",
"calibrationHolder?: string | undefined",
@@ -7170,7 +7174,7 @@
"kind": "variable",
"name": "__thinkAdapter",
"signature": [
- "{ tryBuildGatewayClient: (modelUsed: string, opts?: { explicitModel?: 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; 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; }"
]
},
{