Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(ai): fit a touchpoint-declared Matryoshka model's native-width response to the brain's width (PR #5921)

garrytandc91e7c221c7
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 90fa4e45e1..b574509378 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -1,26 +1,26 @@
# Key files — per-file index (gbrain repo)
Read a file's entry before editing it. This page routes to bounded subsystem
-references; **do not load every file in the directory**. Entries retain the
-implementation evidence and test references from the former single-file index.
+references; **do not load every file in the directory**. Entries keep the
+implementation evidence and test references.
-Find a specific path locally, then read that entry and its surrounding contract:
+Find a path locally, then read its entry and surrounding contract:
```bash
rg -n -F 'src/core/ops/pages.ts' docs/architecture/key-files/
```
-The ranges below use the first path in each entry; grouped entries can document
-several related files. Search is the fallback when a path crosses subsystems.
-Edit the subsystem entry, not this routing page, when behavior changes.
-Keep entries current-state: release history belongs in `CHANGELOG.md` and Git.
+Ranges use each entry's first path; grouped entries can document several
+files. Search is the fallback when a path crosses subsystems.
+Edit the subsystem entry, not this page, when behavior changes.
+Keep entries current-state: history belongs in `CHANGELOG.md` and Git.
Where a new storage method, migration, doctor check, command, route or sync
phase goes: [CONTRIBUTING.md](../../CONTRIBUTING.md#where-does-my-change-go).
A branch written before refactor wave 1 follows the generated
[porting guide](wave-1-porting.md) ([JSON map](wave-1-moves.json)).
`scripts/check-key-files-current-state.sh` checks every subsystem for history,
-duplicate file entries, and size growth. Split a growing subsystem at a useful
-boundary and add its link here rather than raising the cap.
+duplicate file entries and size growth. Split a growing subsystem at a useful
+boundary and link it here rather than raising the cap.
| Subsystem | Entry range / scope |
|---|---|
@@ -36,14 +36,15 @@ boundary and add its link here rather than raising the cap.
| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `src/commands/protocol.ts` through `src/commands/reindex-search-vector.ts`, `init-mode-picker.ts`, `src/core/embedding-migration-cli.ts` |
| [Commands (5/6)](key-files/commands-5.md) | `src/commands/reindex.ts` through `src/commands/storage.ts` |
| [Commands (6/6)](key-files/commands-6.md) | `src/commands/sync.ts` through `src/commands/whoknows.ts` |
-| [Core Ai](key-files/core-ai.md) | `src/core/ai/build-gateway-config.ts` through `src/core/ai/types.ts` |
+| [Core Ai](key-files/core-ai.md) | `src/core/ai/` gateway, embedding, dims, errors, fallbacks |
+| [Core Ai (continued)](key-files/core-ai-continued.md) | `src/core/ai/providers/*`, `recipes/*`, `voyage-gateway.ts` |
| [Core Decide](key-files/core-decide.md) | `src/core/ai/decide/*`, `src/core/search/decide-stage.ts`, `gbrain decide`, `decide_health` (System One) |
| [Core Cycle](key-files/core-cycle.md) | `src/core/cycle/anomaly.ts` through `src/core/cycle/phase-table.ts`: atoms, facts, drains, probes, phase scope |
| [Core Cycle (continued)](key-files/core-cycle-continued.md) | `src/core/cycle/` synthesis, patterns, consolidation, concept publication and `connector-atoms.ts` |
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` |
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
-| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, database-write, attribution, purge-deleted, fact retirement, single-write path |
+| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, attribution, purge-deleted, fact retirement, single-write path |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding |
| [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.md
new file mode 100644
index 0000000000..fa0c265188
--- /dev/null
+++ b/docs/architecture/key-files/core-ai-continued.md
@@ -0,0 +1,26 @@
+# Key files: Core Ai (continued)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](core-ai.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+Provider adapters, recipes and the Voyage width plumbing.
+
+- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse a clipped answer (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`).
+
+- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.
+
+- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.
+
+- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp; the user supplies the matching `--model` and `--alias` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane `getRerankerModel()` reads nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
+
+- `src/core/ai/recipes/lmstudio.ts` — LM Studio local OpenAI-compatible recipe (embedding touchpoint only; default base URL `http://localhost:1234/v1`, env `LMSTUDIO_BASE_URL`). Ships `models: []` like llama-server — the model identity is whatever the user loaded in the app, so `--embedding-model lmstudio:<id>` + `--embedding-dimensions <N>` are required (the wizard refuses implicit defaults). Its own provider id keeps `openai:` pointed at OpenAI (complement of the keyless `OPENAI_BASE_URL` route). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with the `embed_timeout` stamp, reload the model to recover.
+
+- `src/core/ai/recipes/nan.ts` — nan.builders openai-compatible reranker recipe. `POST {base}/v1/rerank` → `results[{index, relevance_score}]`, leaf-only (`base_url_default` ends `/v1`; bare `/rerank` and `/compatible-api/v1/reranks` both 404). Model id is the literal `rerank` (a Qwen3-Reranker-8B deployment). `auth_env.required: ['NAN_API_KEY']`.
+
+- `src/core/ai/recipes/ollama.ts` — the Ollama local recipe. `thinking_by_default` is a per-family predicate over the model id (qwen3 with a boundary so `qwen2.5-*` is never swallowed and a `-coder` exclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the `-mini-reasoning` tags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default. The chat touchpoint declares `supports_structured_outputs: true` (Ollama enforces `response_format: json_schema` server-side via grammar-constrained decoding, model-independent — unlike tools, which stay `false`), so `chat()` sends a caller's `responseSchema` to Ollama (facts extraction) and `expand()` routes `ollama:*` expansion models through the strict generateObject lane with its existing rejected-recipe fallback.
+
+- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is enforced by `classifyCapabilities()` in `src/core/ai/capabilities.ts` (verdict `unusable:no_subagent_loop` — `enforceSubagentCapable()` in `src/core/model-config.ts` consumes the verdict: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. OpenRouter reports upstream rate limits and some outages as an `error` object inside an HTTP 200 body; `rewriteOpenRouterErrorEnvelopeStatus` (composed into `openrouterCompatFetch`) gives a 200 `application/json` body with an integer `error.code` of 429 or 5xx that status, keeping an existing `Retry-After` and promoting a finite non-negative `error.metadata.retry_after`/`retryAfter` when absent, so the AI SDK's status-keyed retry and gbrain's classification see it; success, 4xx, unparseable and SSE responses pass through untouched. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
+
+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (responses accept `{data: [{index, relevance_score}]}` or the compatible `results` array), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex-code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
+
+
+- `src/core/ai/voyage-gateway.ts` — Voyage width plumbing for `voyageCompatFetch` (#6061). `applyVoyageOutputDimension(body, input, dims)` always sets root `output_dimension` and adds `providerOptions.voyage.outputDimension` only when the request URL's hostname is exactly `ai-gateway.vercel.sh` (the Vercel AI Gateway reads only that; Voyage's own API answers 400 on `providerOptions`; look-alike hosts, suffixes and path mentions never match). `embeddingDimMismatchError(...)` builds the dim-mismatch `AIConfigError`: with a non-default `provider_base_urls.<provider>` it names that host as the likely cause (a proxy dropping the width), says nothing was written and points at fixing the proxy plus `gbrain doctor --only embedding_provider --probe --json` before a migration; the default route keeps the `gbrain migrate --embedding-model … --embedding-dimensions …` hint. Pinned in `test/ai/gateway.test.ts` (Voyage shim describe).
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index aa06d52497..b16431ee92 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.
- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.
-- `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/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. `fitMatryoshkaPrefix(recipe, modelId, vector, expected)` (PR #5921, wave 14): when the recipe's embedding touchpoint declares the model in `matryoshka` (`{ native, prefixes }`, folded ids; `recipes/nvidia.ts` declares Nemotron-3-Embed-8B at 4096 with 1024/2048) and the provider answered at the native width for a listed target, the vector is sliced from the start and L2-normalized before `gateway.embedSubBatch`'s dim-mismatch check; every other vector returns untouched, an overflowing norm is refused, a zero or non-finite prefix falls to the per-item screen. 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/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).
@@ -36,27 +36,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/key-warnings.ts` — #5137 print seam with one replaceable sink and two once-per-process latches: `warnShadowedProviderKeys` (called from `src/cli.ts` for every command except `gbrain hook`; `gbrain serve` starts through the same path) names the variable, the config key, that env is in effect, and both fixes (remove the variable from that process's environment and restart it, or `gbrain config unset <key>`, which also silences it); `reportEmbeddingAuthFailure` prints `embedding_auth_failed` (catalogue entry) on the first embedding 401/403, naming the key source in effect and the fix plus `gbrain embed --stale`. Never prints a key or fragment. Doctor `embedding_key_source` (`src/commands/doctor/checks/embedding-health.ts`, engine-free filesystem-lane entry `embeddingKeySourceEntry`) reports the same shadows and the embedding key's source, and says it sees only the environment doctor runs in.
- `src/core/ai/key-redact.ts` — `redactProviderKeys(text, env)`: scrubs every `*_API_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD` value in the gateway env, masked echoes (`sk-...****abcd`) and 8+ character key fragments from upstream error text. The gateway passes it to `normalizeAIError` (which also scrubs the wrapped error's cause chain in place, keeping status and headers for `.cause` walkers) on embed, multimodal, expand and chat errors, and applies it to multimodal response bodies.
-- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse a clipped answer (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`).
-
-- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.
-
-- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.
-
-- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp; the user supplies the matching `--model` and `--alias` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane `getRerankerModel()` reads nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
-
-- `src/core/ai/recipes/lmstudio.ts` — LM Studio local OpenAI-compatible recipe (embedding touchpoint only; default base URL `http://localhost:1234/v1`, env `LMSTUDIO_BASE_URL`). Ships `models: []` like llama-server — the model identity is whatever the user loaded in the app, so `--embedding-model lmstudio:<id>` + `--embedding-dimensions <N>` are required (the wizard refuses implicit defaults). Its own provider id keeps `openai:` pointed at OpenAI (complement of the keyless `OPENAI_BASE_URL` route). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with the `embed_timeout` stamp, reload the model to recover.
-
-- `src/core/ai/recipes/nan.ts` — nan.builders openai-compatible reranker recipe. `POST {base}/v1/rerank` → `results[{index, relevance_score}]`, leaf-only (`base_url_default` ends `/v1`; bare `/rerank` and `/compatible-api/v1/reranks` both 404). Model id is the literal `rerank` (a Qwen3-Reranker-8B deployment). `auth_env.required: ['NAN_API_KEY']`.
-
-- `src/core/ai/recipes/ollama.ts` — the Ollama local recipe. `thinking_by_default` is a per-family predicate over the model id (qwen3 with a boundary so `qwen2.5-*` is never swallowed and a `-coder` exclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the `-mini-reasoning` tags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default. The chat touchpoint declares `supports_structured_outputs: true` (Ollama enforces `response_format: json_schema` server-side via grammar-constrained decoding, model-independent — unlike tools, which stay `false`), so `chat()` sends a caller's `responseSchema` to Ollama (facts extraction) and `expand()` routes `ollama:*` expansion models through the strict generateObject lane with its existing rejected-recipe fallback.
-
-- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is enforced by `classifyCapabilities()` in `src/core/ai/capabilities.ts` (verdict `unusable:no_subagent_loop` — `enforceSubagentCapable()` in `src/core/model-config.ts` consumes the verdict: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. OpenRouter reports upstream rate limits and some outages as an `error` object inside an HTTP 200 body; `rewriteOpenRouterErrorEnvelopeStatus` (composed into `openrouterCompatFetch`) gives a 200 `application/json` body with an integer `error.code` of 429 or 5xx that status, keeping an existing `Retry-After` and promoting a finite non-negative `error.metadata.retry_after`/`retryAfter` when absent, so the AI SDK's status-keyed retry and gbrain's classification see it; success, 4xx, unparseable and SSE responses pass through untouched. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
-
-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (responses accept `{data: [{index, relevance_score}]}` or the compatible `results` array), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex-code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
-
-
- `src/core/ai/reranker-readiness.ts` — pure leaf answering "is the reranker actually going to run?" for `gbrain search modes` (`buildModesReport.reranker_readiness`), doctor's `reranker_health`, and init's reranker-default write. `rerankerReadiness(model, env, { baseUrlOverrides? })` → `{model, provider, modelId (alias-canonical), recipeKnown, hasTouchpoint, modelListed, requiredKey (the first MISSING key, else the first required key — this is how `Reranker: … VOYAGE_API_KEY present` renders; null only for keyless recipes), keyPresent, selfHosted, ready}`; the env snapshot comes from the CALLER — the leaf never reads `process.env` and never imports the gateway (init runs before `configureGateway` and passes `mergedProviderEnv(cfg, process.env)` where `cfg` is `loadConfigFileOnly()` merged with the brain's DB-plane provider keys via `loadConfigWithEngine` — file plane alone if that read fails — so a `--force` re-init sees a Voyage key that lives only in the config table). A recipe with a custom `resolveAuth` needs no env key (mirrors the gateway); a `provider_base_urls` override marks the provider self-hosted. `describeRerankerFix(r)` renders the paste-ready one-liner (unknown-model > missing key + disable command). `src/core/ai/reranker-readiness-engine.ts` is the engine-plane wrapper doctor and `gbrain search modes` share: `rerankerReadinessForEngine(engine, model)` reads the LIVE gateway snapshot (env + base_urls — exactly what `rerank()` consults, so the verdict cannot disagree with search and a mounted brain's DB plane cannot steer it) and falls back to env > file > DB-plane provider keys + `provider_base_urls` via `loadConfigWithEngine` only when no gateway is configured; `redactReadinessForRemote` (modes-report.ts) strips `required_key`/`key_present`/`fix` from the `search_modes` op for untrusted callers. `test/ai/reranker-readiness.test.ts` pins agreement with `isAvailable('reranker', m)` on an env × model matrix (`recipeKnown && hasTouchpoint && keyPresent`) so the two predicates cannot drift.
- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling: `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
-
-- `src/core/ai/voyage-gateway.ts` — Voyage width plumbing for `voyageCompatFetch` (#6061). `applyVoyageOutputDimension(body, input, dims)` always sets root `output_dimension` and adds `providerOptions.voyage.outputDimension` only when the request URL's hostname is exactly `ai-gateway.vercel.sh` (the Vercel AI Gateway reads only that; Voyage's own API answers 400 on `providerOptions`; look-alike hosts, suffixes and path mentions never match). `embeddingDimMismatchError(...)` builds the dim-mismatch `AIConfigError`: with a non-default `provider_base_urls.<provider>` it names that host as the likely cause (a proxy dropping the width), says nothing was written and points at fixing the proxy plus `gbrain doctor --only embedding_provider --probe --json` before a migration; the default route keeps the `gbrain migrate --embedding-model … --embedding-dimensions …` hint. Pinned in `test/ai/gateway.test.ts` (Voyage shim describe).
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index 70f371af7a..024422d1b1 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -21,7 +21,7 @@ import { AIConfigError } from './errors.ts';
* module's tables and comparisons is already lowercase, making the fold
* total. Error messages keep the ORIGINAL id so they stay paste-ready.
*/
-function modelMatchKey(id: string): string {
+export function modelMatchKey(id: string): string {
return id.trim().toLowerCase();
}
@@ -119,6 +119,8 @@ export function isValidPerplexityDim(modelId: string, dims: number): boolean {
const NVIDIA_EMBEDDING_DIMS: Record<string, number> = {
'nvidia/nv-embedqa-e5-v5': 1024,
'nvidia/llama-nemotron-embed-1b-v2': 2048,
+ // PR #5921: 4096 native; 2048/1024 are client-side prefixes (recipe `matryoshka`), never a `dimensions` override.
+ 'nvidia/nemotron-3-embed-8b': 4096,
'nvidia/nv-embed-v1': 4096,
'nvidia/nv-embedcode-7b-v1': 4096,
};
diff --git a/src/core/ai/embedding-guard.ts b/src/core/ai/embedding-guard.ts
index f1379fdedd..97dda67f6a 100644
--- a/src/core/ai/embedding-guard.ts
+++ b/src/core/ai/embedding-guard.ts
@@ -12,6 +12,8 @@
* and nothing degenerate is ever written.
*/
import { AIConfigError } from './errors.ts';
+import { modelMatchKey } from './dims.ts';
+import type { Recipe } from './types.ts';
export const EMBEDDING_ZERO_NORM = 'embedding_zero_norm';
export const EMBEDDING_ZERO_NORM_DOCS = 'docs/guides/write-refusals.md#embedding_zero_norm';
@@ -105,3 +107,25 @@ export function screenAlignedEmbeddings(out: (Float32Array | null)[], model: str
if (failures.length) throw new EmbeddingZeroNormError(failures, out, model);
return out as Float32Array[];
}
+
+/**
+ * PR #5921 / wave 14 P3.18: fit a Matryoshka model's native-width response to the brain's width by the rule its
+ * card documents (keep the first `expected` coordinates, L2-normalize), when the recipe's embedding touchpoint
+ * declares the model (`matryoshka`) with that native width and lists `expected` among its prefixes. Every other
+ * vector returns as it came, so the caller's dim-mismatch check still decides. A prefix whose norm overflows is
+ * refused here; a zero or non-finite prefix returns unnormalized and `screenAlignedEmbeddings` refuses it per item.
+ */
+export function fitMatryoshkaPrefix(recipe: Recipe, modelId: string, vector: number[], expected: number): number[] {
+ const declared = recipe.touchpoints?.embedding?.matryoshka?.[modelMatchKey(modelId)];
+ if (!declared || !Array.isArray(vector) || vector.length !== declared.native || expected === declared.native || !declared.prefixes.includes(expected)) return vector;
+ const prefix = vector.slice(0, expected);
+ if (degenerateEmbeddingReason(prefix)) return prefix;
+ let sum = 0;
+ for (const value of prefix) sum += value * value;
+ const norm = Math.sqrt(sum);
+ if (!Number.isFinite(norm)) {
+ throw new AIConfigError(`Embedding provider returned a ${expected}-dim prefix with a non-finite norm for ${modelId}.`,
+ 'Retry after checking provider output; a vector whose norm overflows is not safe to index.');
+ }
+ return prefix.map(value => value / norm);
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 11ac7ebca3..a531562502 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -62,7 +62,7 @@ import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';
import { AIConfigError, AITransientError, isStructuredOutputRejection, isUnbilledEmbeddingRejection, normalizeAIError } from './errors.ts';
-import { isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';
+import { fitMatryoshkaPrefix, isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';
import { getProviderCapabilities } from './capabilities.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
import { loadConfig } from '../config.ts';
@@ -1765,17 +1765,17 @@ async function embedSubBatch(
);
}
- for (const embedding of result.embeddings) {
+ const embeddings: number[][] = result.embeddings.map((e: number[]) => fitMatryoshkaPrefix(recipe, modelId, e, expectedDims)); // PR #5921
+ for (const embedding of embeddings) {
if (Array.isArray(embedding) && embedding.length !== expectedDims) {
- throw embeddingDimMismatchError(modelId, embedding.length, expectedDims, `gbrain migrate --embedding-model ${getEmbeddingModel()} --embedding-dimensions ${embedding.length}`,
- { provider: recipe.id, baseUrl: _config?.base_urls?.[recipe.id], defaultBaseUrl: recipe.base_url_default });
+ throw embeddingDimMismatchError(modelId, embedding.length, expectedDims, `gbrain migrate --embedding-model ${getEmbeddingModel()} --embedding-dimensions ${embedding.length}`, { provider: recipe.id, baseUrl: _config?.base_urls?.[recipe.id], defaultBaseUrl: recipe.base_url_default });
}
}
recordSubBatchSuccess(recipe);
const usageTokens = (result as { usage?: { tokens?: unknown } }).usage?.tokens;
return {
- embeddings: result.embeddings.map((e: number[]) => new Float32Array(e)),
+ embeddings: embeddings.map((e: number[]) => new Float32Array(e)),
reportedTokens: typeof usageTokens === 'number' && Number.isFinite(usageTokens) && usageTokens > 0
? usageTokens
: null,
diff --git a/src/core/ai/recipes/nvidia.ts b/src/core/ai/recipes/nvidia.ts
index b20ca6e1b2..36c88f6627 100644
--- a/src/core/ai/recipes/nvidia.ts
+++ b/src/core/ai/recipes/nvidia.ts
@@ -24,6 +24,7 @@ export const nvidia: Recipe = {
'nvidia/nemotron-3-super-120b-a12b',
'nvidia/nv-embedqa-e5-v5',
'nvidia/llama-nemotron-embed-1b-v2',
+ 'nvidia/nemotron-3-embed-8b',
'nvidia/nv-embed-v1',
'nvidia/nv-embedcode-7b-v1',
],
@@ -35,6 +36,7 @@ export const nvidia: Recipe = {
aliases: {
'nv-embedqa-e5-v5': 'nvidia/nv-embedqa-e5-v5',
'llama-nemotron-embed-1b-v2': 'nvidia/llama-nemotron-embed-1b-v2',
+ 'nemotron-3-embed-8b': 'nvidia/nemotron-3-embed-8b',
'nemotron-3-super': 'nvidia/nemotron-3-super-120b-a12b',
'nemotron-3-super-120b-a12b': 'nvidia/nemotron-3-super-120b-a12b',
'nv-embed-v1': 'nvidia/nv-embed-v1',
@@ -60,9 +62,17 @@ export const nvidia: Recipe = {
models: [
'nvidia/nv-embedqa-e5-v5',
'nvidia/llama-nemotron-embed-1b-v2',
+ 'nvidia/nemotron-3-embed-8b',
'nvidia/nv-embed-v1',
'nvidia/nv-embedcode-7b-v1',
],
+ // PR #5921 (@abudhi19): Nemotron-3-Embed-8B answers 4096 wide whatever `dimensions` asks; its card documents
+ // 2048/1024 as "keep the first coordinates, then L2-normalize", which the gateway applies (fitMatryoshkaPrefix).
+ // Keys are folded ids; the Hugging Face / vLLM served name carries a -bf16 suffix.
+ matryoshka: {
+ 'nvidia/nemotron-3-embed-8b': { native: 4096, prefixes: [1024, 2048] },
+ 'nvidia/nemotron-3-embed-8b-bf16': { native: 4096, prefixes: [1024, 2048] },
+ },
// Default to the lightest tested hosted model. Larger NVIDIA models are
// supported via explicit embedding_dimensions (2048 or 4096).
default_dims: 1024,
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 007f2d230d..4f2f9e73eb 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -53,6 +53,13 @@ export interface EmbeddingTouchpoint {
* `default_dims`, so a recipe can declare only the models it knows.
*/
model_dims?: Readonly<Record<string, number>>;
+ /**
+ * PR #5921 / wave 14: models whose endpoint returns the native width whatever `dimensions` asked, and whose model
+ * card documents dynamic sizes as "slice from the start, then L2-normalize". Keyed by folded model id
+ * (`modelMatchKey`). When such a model answers at `native` and the brain expects one of `prefixes`, the gateway fits
+ * the vector (`fitMatryoshkaPrefix`); any other width keeps the dim-mismatch refusal. Partial by design.
+ */
+ matryoshka?: Readonly<Record<string, { native: number; prefixes: readonly number[] }>>;
/**
* #4530: per-model maximum tokens PER SINGLE INPUT, keyed like model_dims
* (partial by design — declare only the models whose limit is known).
diff --git a/test/ai/matryoshka-prefix.test.ts b/test/ai/matryoshka-prefix.test.ts
new file mode 100644
index 0000000000..043d25b5e5
--- /dev/null
+++ b/test/ai/matryoshka-prefix.test.ts
@@ -0,0 +1,119 @@
+/**
+ * PR #5921 (@abudhi19), wave 14 P3.18: a Matryoshka model whose endpoint returns its native width whatever
+ * `dimensions` asked is fitted to the brain's width by the card-documented rule (slice from the start, L2
+ * re-normalize), declared on the recipe's embedding touchpoint (`matryoshka`), never by a model id in the gateway.
+ *
+ * Protects: a 4096-wide Nemotron-3-Embed-8B response lands in a 1024/2048 brain as a unit-length prefix; a
+ * response of any other width, a target width the card does not list, a model with no declaration, and a vector
+ * already at the expected width all keep today's behavior (mismatch error or bytes unchanged); a prefix with a
+ * non-finite coordinate or a zero or overflowing norm is refused, never indexed.
+ * Seams: `__setEmbedTransportForTests`, `__setTestRecipesForTests`, `fitMatryoshkaPrefix`.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { __setEmbedTransportForTests, configureGateway, embed, resetGateway } from '../../src/core/ai/gateway.ts';
+import { fitMatryoshkaPrefix } from '../../src/core/ai/embedding-guard.ts';
+import { nvidia } from '../../src/core/ai/recipes/nvidia.ts';
+import { __setTestRecipesForTests } from '../../src/core/ai/recipes/index.ts';
+import type { Recipe } from '../../src/core/ai/types.ts';
+
+const MODEL = 'nvidia/nemotron-3-embed-8b';
+
+function configureNemotron(dimensions: number, model = MODEL): void {
+ configureGateway({ embedding_model: `nvidia:${model}`, embedding_dimensions: dimensions, env: { NVIDIA_API_KEY: 'test-only' } });
+}
+function respond(vectors: number[][]): void {
+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: vectors, usage: { tokens: args.values.length } }) as any);
+}
+/** 4096 wide; the coordinate just past the prefix is large, so normalizing the whole vector would change the result. */
+function native(prefixWidth: number, first: number, second: number): number[] {
+ const v = new Array(4096).fill(0);
+ v[0] = first; v[1] = second; v[prefixWidth] = 12;
+ return v;
+}
+
+beforeEach(() => { resetGateway(); __setEmbedTransportForTests(null); });
+afterEach(() => { __setEmbedTransportForTests(null); __setTestRecipesForTests([]); });
+afterAll(() => resetGateway());
+
+describe('fitMatryoshkaPrefix (pure)', () => {
+ test('the declared model at its native width is sliced to a listed prefix and re-normalized', () => {
+ expect(nvidia.touchpoints.embedding?.matryoshka?.[MODEL]).toEqual({ native: 4096, prefixes: [1024, 2048] });
+ const out = fitMatryoshkaPrefix(nvidia, 'nvidia/Nemotron-3-Embed-8B', native(1024, 3, 4), 1024);
+ expect(out).toHaveLength(1024);
+ expect(out[0]).toBeCloseTo(0.6, 6);
+ expect(out[1]).toBeCloseTo(0.8, 6);
+ expect(out[2]).toBe(0);
+ });
+
+ test('anything else passes through untouched', () => {
+ const v = native(1024, 3, 4);
+ expect(fitMatryoshkaPrefix(nvidia, MODEL, v, 1536)).toBe(v);
+ expect(fitMatryoshkaPrefix(nvidia, 'nvidia/nv-embed-v1', v, 1024)).toBe(v);
+ const narrow = new Array(1024).fill(0.5);
+ expect(fitMatryoshkaPrefix(nvidia, MODEL, narrow, 1024)).toBe(narrow);
+ const odd = new Array(3072).fill(1);
+ expect(fitMatryoshkaPrefix(nvidia, MODEL, odd, 1024)).toBe(odd);
+ });
+});
+
+describe('embed() through the nvidia recipe', () => {
+ test('a 4096-wide response fits a 1024 and a 2048 brain, in batch order', async () => {
+ configureNemotron(1024);
+ respond([native(1024, 3, 4), native(1024, 4, 3)]);
+ const vectors = await embed(['first passage', 'second passage']);
+ expect(vectors.map((v) => v.length)).toEqual([1024, 1024]);
+ expect(vectors[0]![0]).toBeCloseTo(0.6, 6);
+ expect(vectors[0]![1]).toBeCloseTo(0.8, 6);
+ expect(vectors[1]![0]).toBeCloseTo(0.8, 6);
+ expect(vectors[1]![1]).toBeCloseTo(0.6, 6);
+
+ configureNemotron(2048);
+ respond([native(2048, 3, 4)]);
+ const [wide] = await embed(['one passage']);
+ expect(wide).toHaveLength(2048);
+ expect(wide![0]).toBeCloseTo(0.6, 6);
+ });
+
+ test('an already expected-width vector is unchanged', async () => {
+ configureNemotron(1024);
+ const v = new Array(1024).fill(0); v[0] = 3; v[1] = 4;
+ respond([v]);
+ const [out] = await embed(['already narrow']);
+ expect(out![0]).toBe(3);
+ expect(out![1]).toBe(4);
+ });
+
+ test('a non-finite coordinate, a zero norm and an overflowing norm are refused', async () => {
+ configureNemotron(1024);
+ for (const [label, a, b] of [['nan', Number.NaN, 1], ['inf', Number.POSITIVE_INFINITY, 1], ['overflow', Number.MAX_VALUE, Number.MAX_VALUE], ['zero', 0, 0]] as const) {
+ const v = new Array(4096).fill(0); v[0] = a; v[1] = b;
+ respond([v]);
+ await expect(embed([label])).rejects.toThrow(/finite|norm|zero/i);
+ }
+ });
+
+ test('a wrong raw width, an unlisted target width and an undeclared model keep the mismatch error', async () => {
+ configureNemotron(1024);
+ respond([new Array(3072).fill(1)]);
+ await expect(embed(['wrong raw width'])).rejects.toThrow(/3072/);
+ configureNemotron(1536);
+ respond([new Array(4096).fill(1)]);
+ await expect(embed(['unlisted target'])).rejects.toThrow(/4096/);
+ configureNemotron(1024, 'nvidia/nv-embed-v1');
+ respond([new Array(4096).fill(1)]);
+ await expect(embed(['undeclared model'])).rejects.toThrow(/4096/);
+ });
+
+ test('a recipe with no declaration is byte-for-byte unchanged', async () => {
+ const plain: Recipe = { id: 'synthetic-plain', name: 'plain', tier: 'openai-compat', implementation: 'openai-compatible', base_url_default: 'http://127.0.0.1:9/v1',
+ touchpoints: { embedding: { models: ['plain-embed'], default_dims: 1024, max_batch_tokens: 8192 } } };
+ __setTestRecipesForTests([plain]);
+ configureGateway({ embedding_model: 'synthetic-plain:plain-embed', embedding_dimensions: 1024, env: {} });
+ const v = new Array(1024).fill(0); v[0] = 3; v[1] = 4;
+ respond([v]);
+ const [out] = await embed(['plain']);
+ expect(Array.from(out!.slice(0, 3))).toEqual([3, 4, 0]);
+ respond([new Array(4096).fill(1)]);
+ await expect(embed(['plain wide'])).rejects.toThrow(/4096/);
+ });
+});