Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(contextual): route synopsis through configured models (#3678)
Garry Tan61ef7277102b
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 482cb624c9..55d27956e8 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -136,9 +136,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Pinned by 13 unit cases.- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. 8-step resolution chain: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves non-Anthropic, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` (the Anthropic Messages API tool-loop can't run on OpenAI/Gemini). `_resetDeprecationWarningsForTest()` also clears `_subagentTierWarningsEmitted`. Pinned by `test/model-config.serial.test.ts`.- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId, extendedModels?)` takes an optional 4th `extendedModels: ReadonlySet<string>`: when the modelId is in that set the native-recipe allowlist throw is bypassed (user explicitly opted in via config, so provider rejection surfaces as `model_not_found` at HTTP call time and `gbrain models doctor` catches it earlier). Default code paths with hardcoded model strings MUST NOT pass `extendedModels` — source typos still fail fast (the fail-fast contract for chat + expand + embed stays intact).-- `src/core/ai/gateway.ts` extension — module-scoped `_extendedModels: Map<providerId, Set<modelId>>` registry feeds `assertTouchpoint`'s 4th-arg path. `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`. `__setChatTransportForTests` seam mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport.+- `src/core/ai/gateway.ts` extension — module-scoped `_extendedModels: Map<providerId, Map<touchpoint, Set<modelId>>>` registry feeds `assertTouchpoint`'s extended-model path without broadening unrelated surfaces. `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. `registerConfigSelectedChatModel(model)` is the narrow runtime seam for a dedicated contextual-synopsis model: the ID joins the chat allowlist but remains rejected for embedding, expansion, and reranking. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport.- `src/core/minions/queue.ts` extension — `MinionQueue.add()` rejects `subagent` jobs whose `data.model` resolves via `isAnthropicProvider()` to a non-Anthropic provider. Lazy-imports `model-config.ts` to avoid pulling engine types into queue's eager-load surface. Layer 1 of the three-layer subagent provider enforcement (layers 2+3: `model-config.ts:enforceSubagentAnthropic` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`.-- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (11 `PER_TASK_KEYS`: `models.dream.synthesize`, `models.dream.patterns`, `models.drift`, `models.auto_think`, `models.think`, `models.subagent`, `facts.extraction_model`, `models.eval.longmemeval`, `models.expansion`, `models.chat`, `models.dream.synthesize_verdict`), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.+- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (13 `PER_TASK_KEYS`, now including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + file-plane `openai/anthropic/zeroentropy_api_key` from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Single owner of folding file-plane API keys (openai/anthropic/zeroentropy) into the gateway env and threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.- `src/commands/doctor.ts` extension — `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`.@@ -262,6 +262,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms).+- `src/core/minions/handlers/contextual-reindex-per-chunk.ts` — per-page contextual re-embed handler. Resolves `models.contextual_synopsis` once, registers native chat models at the chat touchpoint, and isolates cross-worker leases by the full resolved model id. `GBRAIN_CONTEXTUAL_SYNOPSIS_RPM` controls the cap; `GBRAIN_CONTEXTUAL_HAIKU_RPM` is the compatibility alias.- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `tool_use_id`. UTF-8-safe truncation; unknown block types fall through to fenced JSON.- `src/core/minions/plugin-loader.ts` — `GBRAIN_PLUGIN_PATH` discovery. Absolute paths only, left-wins collision, `gbrain.plugin.json` with `plugin_version: "gbrain-plugin-v1"`, plugins ship DEFS only (no new tools), `allowed_tools:` validated at load time against the derived registry.diff --git a/src/commands/models.ts b/src/commands/models.tsindex 5d00c736cf..03a4b5634d 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -38,7 +38,15 @@ import { resolveRecipe } from '../core/ai/model-resolver.ts';const TIERS: ModelTier[] = ['utility', 'reasoning', 'deep', 'subagent'];-const PER_TASK_KEYS: Array<{ key: string; tier: ModelTier; description: string }> = [+interface PerTaskModelRoute {+ key: string;+ tier: ModelTier;+ description: string;+ deprecatedConfigKey?: string;+ envVar?: string;+}++const PER_TASK_KEYS: PerTaskModelRoute[] = [{ key: 'models.dream.synthesize', tier: 'reasoning', description: 'Dream synthesis (conversation → brain pages)' },{ key: 'models.dream.synthesize_verdict', tier: 'utility', description: 'Dream synthesis verdict (Haiku judge)' },{ key: 'models.dream.patterns', tier: 'reasoning', description: 'Pattern discovery (cross-take themes)' },@@ -50,6 +58,13 @@ const PER_TASK_KEYS: Array<{ key: string; tier: ModelTier; description: string }{ key: 'models.eval.longmemeval', tier: 'reasoning', description: 'LongMemEval benchmark answer-gen' },{ key: 'models.eval.contradictions_judge', tier: 'utility', description: 'Contradiction probe judge (v0.34 temporal-aware)' },{ key: 'models.expansion', tier: 'utility', description: 'Query expansion for hybrid search' },+ {+ key: 'models.contextual_synopsis',+ tier: 'utility',+ description: 'Per-chunk contextual synopsis generation',+ deprecatedConfigKey: 'contextual_retrieval.haiku_model',+ envVar: 'GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL',+ },{ key: 'models.chat', tier: 'reasoning', description: 'Default `gateway.chat()` model' },];@@ -67,12 +82,26 @@ interface ModelsReport {aliases: { defaults: Record<string, string>; user: Record<string, string> };}-async function probeSource(engine: BrainEngine, configKey: string, envVar: string): Promise<string | null> {+async function probeSource(+ engine: BrainEngine,+ route: Pick<PerTaskModelRoute, 'key' | 'tier' | 'deprecatedConfigKey' | 'envVar'>,+): Promise<string | null> {// For per-task probes, return the source the resolver USED (config / env /- // tier default / hardcoded). The resolver itself is the source of truth;- // we re-walk a subset of its precedence here to attribute the value.- const configVal = await engine.getConfig(configKey);- if (configVal && configVal.trim()) return `config: ${configKey}`;+ // tier default / hardcoded). Keep this walk in the same order as+ // resolveModel so dedicated task env vars and compatibility keys are+ // attributed truthfully in `gbrain models` output.+ const configVal = await engine.getConfig(route.key);+ if (configVal && configVal.trim()) return `config: ${route.key}`;+ if (route.deprecatedConfigKey) {+ const deprecated = await engine.getConfig(route.deprecatedConfigKey);+ if (deprecated && deprecated.trim()) return `config: ${route.deprecatedConfigKey}`;+ }+ const globalDefault = await engine.getConfig('models.default');+ if (globalDefault && globalDefault.trim()) return 'config: models.default';+ const tierKey = `models.tier.${route.tier}`;+ const tierValue = await engine.getConfig(tierKey);+ if (tierValue && tierValue.trim()) return `config: ${tierKey}`;+ const envVar = route.envVar ?? 'GBRAIN_MODEL';if (process.env[envVar] && process.env[envVar]!.trim()) return `env: ${envVar}`;return null;}@@ -97,9 +126,16 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {}const per_task: ModelsReport['per_task'] = [];- for (const { key, tier, description } of PER_TASK_KEYS) {- const resolved = await resolveModel(engine, { configKey: key, tier, fallback: TIER_DEFAULTS[tier] });- const explicit = await probeSource(engine, key, 'GBRAIN_MODEL');+ for (const route of PER_TASK_KEYS) {+ const { key, tier, description, deprecatedConfigKey, envVar } = route;+ const resolved = await resolveModel(engine, {+ configKey: key,+ deprecatedConfigKey,+ envVar,+ tier,+ fallback: TIER_DEFAULTS[tier],+ });+ const explicit = await probeSource(engine, route);const source = explicit ?? `tier.${tier}`;per_task.push({ key, tier, resolved, source, description });}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex bd7df3fba9..16e196d4a3 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -139,34 +139,40 @@ export function configureGatewayIfUninitialized(): void {/*** v0.31.12 recipe-models merge: per-gateway-instance set of model ids the* user opted into via config. Keyed by provider id (`anthropic`, `openai`,- * etc.). Passed into `assertTouchpoint` so native-recipe allowlist checks- * skip these models — provider 404s surface at HTTP call time instead of- * config-build time.+ * etc.) AND touchpoint so a chat-only selection cannot silently authorize+ * expansion/embedding/reranker. Passed into `assertTouchpoint` so native-recipe+ * allowlist checks skip these models — provider 404s surface at HTTP call time+ * instead of config-build time.** Replaces the earlier plan to soften `assertTouchpoint` from throw to* warn (Codex F4/F5 — too broad, removed fail-fast for chat/expand/embed* across all callers). This narrower approach preserves fail-fast for* source-code typos while allowing config-time model selection of any id.*/-const _extendedModels: Map<string, Set<string>> = new Map();+const _extendedModels: Map<string, Map<TouchpointKind, Set<string>>> = new Map();/**- * v0.31.12 — register a model id under its provider so `assertTouchpoint`- * (called via the gateway's chat/embed/expand entry points) permits it- * even when it isn't in the recipe's declared `models:` array.+ * v0.31.12 — register a model id under its provider+touchpoint so+ * `assertTouchpoint` (called via the gateway's chat/embed/expand entry points)+ * permits it there even when it isn't in the recipe's declared `models:` array.** Idempotent + safe to call before/after configureGateway. Exported only* for the `gbrain models doctor` probe path (where the operator may want* to probe any user-supplied id without re-running configure).*/-function registerExtendedModel(modelStr: string): void {+function registerExtendedModel(touchpoint: TouchpointKind, modelStr: string): void {if (!modelStr) return;try {const { providerId, modelId } = parseModelId(modelStr);- let set = _extendedModels.get(providerId);+ let byTouchpoint = _extendedModels.get(providerId);+ if (!byTouchpoint) {+ byTouchpoint = new Map();+ _extendedModels.set(providerId, byTouchpoint);+ }+ let set = byTouchpoint.get(touchpoint);if (!set) {set = new Set();- _extendedModels.set(providerId, set);+ byTouchpoint.set(touchpoint, set);}set.add(modelId);} catch {@@ -175,8 +181,24 @@ function registerExtendedModel(modelStr: string): void {}}-function getExtendedModelsForProvider(providerId: string): ReadonlySet<string> | undefined {- return _extendedModels.get(providerId);+/**+ * Register a model that was selected through a DB/env config resolver for a+ * chat-backed call site outside the gateway's built-in chat/expansion defaults.+ *+ * This preserves `assertTouchpoint`'s native-provider fail-fast behavior for+ * hardcoded source models while allowing an explicit operator-selected chat+ * model (for example `models.contextual_synopsis`) to reach the provider even+ * when the recipe's curated model list has not yet learned the new id.+ */+export function registerConfigSelectedChatModel(modelStr: string): void {+ registerExtendedModel('chat', modelStr);+}++function getExtendedModelsForProvider(+ providerId: string,+ touchpoint: TouchpointKind,+): ReadonlySet<string> | undefined {+ return _extendedModels.get(providerId)?.get(touchpoint);}/**@@ -497,15 +519,13 @@ export function configureGateway(config: AIGatewayConfig): void {_extendedModels.clear();// Register configured models so assertTouchpoint allows them even when// they aren't in the recipe's declared models: array (v0.31.12).- for (const m of [- _config.embedding_model,- _config.embedding_multimodal_model,- _config.expansion_model,- _config.chat_model,- _config.reranker_model,- ...(_config.chat_fallback_chain ?? []),- ]) {- if (m) registerExtendedModel(m);+ if (_config.embedding_model) registerExtendedModel('embedding', _config.embedding_model);+ if (_config.embedding_multimodal_model) registerExtendedModel('embedding', _config.embedding_multimodal_model);+ if (_config.expansion_model) registerExtendedModel('expansion', _config.expansion_model);+ if (_config.chat_model) registerExtendedModel('chat', _config.chat_model);+ if (_config.reranker_model) registerExtendedModel('reranker', _config.reranker_model);+ for (const m of _config.chat_fallback_chain ?? []) {+ if (m) registerExtendedModel('chat', m);}warnRecipesMissingBatchTokens();}@@ -570,16 +590,16 @@ export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promise_modelCache.clear();_shrinkState.clear();_extendedModels.clear();- for (const m of [- _config.embedding_model,- _config.embedding_multimodal_model,- _config.expansion_model,- _config.chat_model,- _config.reranker_model,- ...(_config.chat_fallback_chain ?? []),- ...tierModels,- ]) {- if (m) registerExtendedModel(m);+ if (_config.embedding_model) registerExtendedModel('embedding', _config.embedding_model);+ if (_config.embedding_multimodal_model) registerExtendedModel('embedding', _config.embedding_multimodal_model);+ if (_config.expansion_model) registerExtendedModel('expansion', _config.expansion_model);+ if (_config.chat_model) registerExtendedModel('chat', _config.chat_model);+ if (_config.reranker_model) registerExtendedModel('reranker', _config.reranker_model);+ for (const m of _config.chat_fallback_chain ?? []) {+ if (m) registerExtendedModel('chat', m);+ }+ for (const m of tierModels) {+ if (m) registerExtendedModel('chat', m);}return _config;}@@ -1485,7 +1505,7 @@ export const perplexityCompatFetch = (async (input: RequestInfo | URL, init?: Reasync function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {const { parsed, recipe } = resolveRecipe(modelStr);- assertTouchpoint(recipe, 'embedding', parsed.modelId, getExtendedModelsForProvider(parsed.providerId));+ assertTouchpoint(recipe, 'embedding', parsed.modelId, getExtendedModelsForProvider(parsed.providerId, 'embedding'));const cfg = requireConfig();const cacheKey = `emb:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;@@ -2444,7 +2464,7 @@ export async function embedMultimodalSafe(async function resolveExpansionProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {const { parsed, recipe } = resolveRecipe(modelStr);- assertTouchpoint(recipe, 'expansion', parsed.modelId, getExtendedModelsForProvider(parsed.providerId));+ assertTouchpoint(recipe, 'expansion', parsed.modelId, getExtendedModelsForProvider(parsed.providerId, 'expansion'));const cfg = requireConfig();const cacheKey = `exp:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;@@ -2942,7 +2962,10 @@ export type ModelIdValidity =| { ok: true; parsed: ParsedModelId; recipe: Recipe }| { ok: false; reason: 'unknown_provider' | 'unknown_model'; detail: string; fix?: string };-export function validateModelId(modelStr: string): ModelIdValidity {+export function validateModelId(+ modelStr: string,+ touchpoint: TouchpointKind = 'chat',+): ModelIdValidity {let parsed: ParsedModelId;let recipe: Recipe;try {@@ -2952,7 +2975,7 @@ export function validateModelId(modelStr: string): ModelIdValidity {throw e;}try {- assertTouchpoint(recipe, 'chat', parsed.modelId, getExtendedModelsForProvider(parsed.providerId));+ assertTouchpoint(recipe, touchpoint, parsed.modelId, getExtendedModelsForProvider(parsed.providerId, touchpoint));} catch (e) {if (e instanceof AIConfigError) return { ok: false, reason: 'unknown_model', detail: e.message, fix: e.fix };throw e;@@ -3006,7 +3029,7 @@ function chatSupportsPromptCache(recipe: Recipe, modelId: string): boolean {async function resolveChatProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {const { parsed, recipe } = resolveRecipe(modelStr);- assertTouchpoint(recipe, 'chat', parsed.modelId, getExtendedModelsForProvider(parsed.providerId));+ assertTouchpoint(recipe, 'chat', parsed.modelId, getExtendedModelsForProvider(parsed.providerId, 'chat'));const cfg = requireConfig();const cacheKey = `chat:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;diff --git a/src/core/config.ts b/src/core/config.tsindex f5e51b1de0..4ab5a212ec 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1003,6 +1003,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.think','models.subagent','models.expansion',+ 'models.contextual_synopsis','models.chat','models.brainstorm.judge','models.eval.longmemeval',diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex ab1f34ec18..a9c8fb79a1 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -29,12 +29,12 @@* propagate the throw up).** Per D27 P2-2 the embedBatch call runs ONCE per page after the per-chunk- * Haiku loop completes, not per-chunk. Saves per-call overhead + reduces+ * synopsis loop completes, not per-chunk. Saves per-call overhead + reduces* failure surface.** Rate-leasing is the caller's responsibility (D26 P0-3 — the Minion- * handler acquires a shared `anthropic:utility:contextual-synopsis` lease- * per chunk before invoking the service's optional `acquireSynopsisLease`+ * handler acquires a shared, resolved-model-specific synopsis lease per chunk+ * before invoking the service's optional `acquireSynopsisLease`* / `releaseSynopsisLease` hooks). Inline callers (import-file, reindex* command) pass no hooks and rely on the gateway's own rate-limit retry.*/@@ -45,12 +45,13 @@ import { embedBatch } from './embedding.ts';import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';import {buildContextualPrefix,- modeRequiresHaiku,+ modeRequiresSynopsis,modeRequiresWrapper,sanitizeTitle,wrapChunkForEmbedding,} from './embedding-context.ts';import {+ DEFAULT_SYNOPSIS_MODEL,generatePerChunkSynopsis,SYNOPSIS_PROMPT_VERSION,SYNOPSIS_DOC_MAX_CHARS,@@ -70,7 +71,6 @@ import type { SourceRow } from './sources-ops.ts';* corpus_generation hash.*/export const TITLE_WRAPPER_VERSION = 1;-const DEFAULT_HAIKU_MODEL = 'anthropic:claude-haiku-4-5-20251001';export const DEFAULT_CONTEXTUAL_CHUNK_CONCURRENCY = 4;export const MAX_CONTEXTUAL_CHUNK_CONCURRENCY = 16;@@ -108,17 +108,18 @@ function getEmbeddingModelTag(): string {}/**- * Compose the corpus_generation hash per D27 P1-5. Folds the prompt- * version + Haiku model + wrapper version + embedding model so a tweak- * to ANY of those invalidates prior cache rows via the+ * Compose the corpus_generation hash per D27 P1-5. Per-chunk synopsis+ * generations fold in the prompt version + synopsis model; title-only+ * generations retain the historical default-model identity because they do+ * not call a synopsis model. Both include the wrapper version + embedding+ * model so a relevant tweak invalidates prior cache rows via the* `query_cache.page_generations` LEFT JOIN.** Pure function — `embedding_dimensions` and `embedding_column` stay in* the existing KNOBS_HASH_VERSION space per A6 in the eng-review pass.*/-export function computeCorpusGeneration(args: {+export type ComputeCorpusGenerationArgs = {crMode: CRMode;- haikuModel: string;/*** Resolved `SYNOPSIS_DOC_MAX_CHARS` for per_chunk_synopsis runs. When* present, folded into the hash so changes to@@ -128,13 +129,31 @@ export function computeCorpusGeneration(args: {* back-compat with pre-cap embeddings.*/synopsisDocMaxChars?: number;-}): string {+} & (+ | {+ /** Canonical provider-neutral synopsis model identifier. */+ synopsisModel: string;+ /** @deprecated Use `synopsisModel`. Ignored when both are present. */+ haikuModel?: string;+ }+ | {+ synopsisModel?: undefined;+ /** @deprecated Use `synopsisModel`. */+ haikuModel: string;+ }+);++export function computeCorpusGeneration(args: ComputeCorpusGenerationArgs): string {+ const synopsisModel =+ args.crMode === 'per_chunk_synopsis'+ ? args.synopsisModel ?? args.haikuModel+ : DEFAULT_SYNOPSIS_MODEL;const h = createHash('sha256').update(args.crMode).update('|').update(String(SYNOPSIS_PROMPT_VERSION)).update('|')- .update(args.haikuModel)+ .update(synopsisModel).update('|').update(String(TITLE_WRAPPER_VERSION)).update('|')@@ -155,7 +174,7 @@ export function computeCorpusGeneration(args: {* Matches what the inline import path writes for its title-tier pages.*/export function titleTierCorpusGeneration(): string {- return computeCorpusGeneration({ crMode: 'title', haikuModel: DEFAULT_HAIKU_MODEL });+ return computeCorpusGeneration({ crMode: 'title', synopsisModel: DEFAULT_SYNOPSIS_MODEL });}/**@@ -223,10 +242,11 @@ export interface ReembedPageArgs {* already in `content_chunks` continue serving queries.*/killSwitchDisabled?: boolean;+ /** Resolved provider-neutral model used for per-chunk synopsis generation. */+ synopsisModel?: string;/**- * Optional Haiku model override. When unset, page-summary.ts falls back- * to its default (Haiku 4.5). Threaded so eval / future per-source- * model overrides can choose a different model.+ * @deprecated Use `synopsisModel`. Retained for callers compiled against+ * the pre-provider-neutral service shape.*/haikuModel?: string;/** Optional abort signal threaded into gateway.chat + embedBatch. */@@ -240,7 +260,7 @@ export interface ReembedPageArgs {releaseSynopsisLease?: (lease?: unknown) => Promise<void>;/*** Intra-page per-chunk synopsis concurrency. 1 preserves the legacy- * sequential loop exactly; higher values only parallelize Haiku synopsis+ * sequential loop exactly; higher values only parallelize synopsis* calls. Embedding remains one batch after all synopses succeed.*/chunkConcurrency?: number;@@ -299,7 +319,7 @@ export async function reembedPageWithContextualRetrieval(resolution.mode,computeCorpusGeneration({crMode: resolution.mode,- haikuModel: args.haikuModel ?? DEFAULT_HAIKU_MODEL,+ synopsisModel: args.synopsisModel ?? args.haikuModel ?? DEFAULT_SYNOPSIS_MODEL,synopsisDocMaxChars: resolution.mode === 'per_chunk_synopsis' ? SYNOPSIS_DOC_MAX_CHARS : undefined,}),);@@ -312,7 +332,7 @@ export async function reembedPageWithContextualRetrieval(// fall-back path is the D14 page-level consistency guarantee: a// single bad chunk demotes the whole page to title-only so all// chunks on the page share the same wrapper shape.- const haikuModel = args.haikuModel ?? DEFAULT_HAIKU_MODEL;+ const synopsisModel = args.synopsisModel ?? args.haikuModel ?? DEFAULT_SYNOPSIS_MODEL;let attemptMode: CRMode = resolution.mode;let fallbackReason: SynopsisFailureKind | null = null;@@ -323,13 +343,13 @@ export async function reembedPageWithContextualRetrieval(page,chunks: chunks as ChunkInput[],args,- haikuModel,+ synopsisModel,});if (phase1.kind === 'success') {const corpus_generation = computeCorpusGeneration({crMode: attemptMode,- haikuModel,+ synopsisModel,synopsisDocMaxChars: attemptMode === 'per_chunk_synopsis' ? SYNOPSIS_DOC_MAX_CHARS : undefined,});@@ -424,17 +444,17 @@ async function tryBuildPhase1(opts: {page: Page;chunks: ChunkInput[];args: ReembedPageArgs;- haikuModel: string;+ synopsisModel: string;}): Promise<Phase1Result> {- const { attemptMode, page, chunks, args, haikuModel } = opts;+ const { attemptMode, page, chunks, args, synopsisModel } = opts;// Build the wrapper prefix for THIS page. Title-only tier: one prefix// reused across all chunks. per_chunk_synopsis tier: prefix is built- // per-chunk with the chunk-specific Haiku synopsis.+ // per-chunk with the chunk-specific generated synopsis.const safeTitle = sanitizeTitle(page.title);- if (attemptMode === 'title' || !modeRequiresHaiku(attemptMode)) {- // Title-only path. No Haiku calls; pure string concat.+ if (attemptMode === 'title' || !modeRequiresSynopsis(attemptMode)) {+ // Title-only path. No synopsis-model calls; pure string concat.// Use compiled_truth first sentences as a free pseudo-summary when// the title tier wants slightly more context — but per D2 the// balanced default is title-only without summary. Keep it pure for@@ -485,7 +505,7 @@ async function tryBuildPhase1(opts: {safeTitle,page,args,- haikuModel,+ synopsisModel,});},});@@ -532,9 +552,9 @@ async function buildWrappedChunkText(opts: {safeTitle: string;page: Page;args: ReembedPageArgs;- haikuModel: string;+ synopsisModel: string;}): Promise<string> {- const { chunk: c, sourceText, safeTitle, page, args, haikuModel } = opts;+ const { chunk: c, sourceText, safeTitle, page, args, synopsisModel } = opts;// Code chunks always bypass the wrapper (D20-T4) — pass through.if (c.chunk_source === 'fenced_code') {@@ -569,7 +589,7 @@ async function buildWrappedChunkText(opts: {pageSlug: args.pageSlug,sourceId: args.sourceId,chunkIndex: c.chunk_index,- model: haikuModel,+ model: synopsisModel,abortSignal: args.abortSignal,});} finally {diff --git a/src/core/embedding-context.ts b/src/core/embedding-context.tsindex 97c1d08a79..cd5d13fa2b 100644--- a/src/core/embedding-context.ts+++ b/src/core/embedding-context.ts@@ -172,13 +172,18 @@ function escapeRegex(s: string): string {/*** Exported guard for D26 P0-4 verification — given a CRMode, does it- * NEED Haiku synopsis generation? Used by the service to decide whether+ * NEED model-generated synopsis generation? Used by the service to decide whether* to invoke `page-summary.ts:generatePerChunkSynopsis` per chunk.*/-export function modeRequiresHaiku(mode: CRMode): boolean {+export function modeRequiresSynopsis(mode: CRMode): boolean {return mode === 'per_chunk_synopsis';}+/** @deprecated Use `modeRequiresSynopsis`. */+export function modeRequiresHaiku(mode: CRMode): boolean {+ return modeRequiresSynopsis(mode);+}+/*** Exported guard: given a CRMode, does it NEED any wrapper at all?* `none` skips wrapping; `title` and `per_chunk_synopsis` both wrap.diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 8752863c3c..010bd8a748 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -29,7 +29,7 @@ import {import { loadConfig, loadConfigWithEngine } from './config.ts';import {buildContextualPrefix,- modeRequiresHaiku,+ modeRequiresSynopsis,modeRequiresWrapper,sanitizeTitle,wrapChunkForEmbedding,@@ -38,6 +38,7 @@ import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';import { normalizeAliasList } from './search/alias-normalize.ts';import { isUndefinedTableError, warnOncePerProcess, validateSlug } from './utils.ts';import { computeCorpusGeneration } from './contextual-retrieval-service.ts';+import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';import { runGuardrails } from './guardrails.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from './facts-fence.ts';@@ -737,7 +738,7 @@ export async function importFromContent(// v0.40.3.0 contextual retrieval wrapper (D20-T1 chunk_text separation):// - Resolve effective CR mode via the page/source/global override chain.// - For title tier (free): build the title-only prefix and wrap chunks- // inline at embed time. Per-chunk Haiku synopsis tier is NOT supported+ // inline at embed time. Per-chunk generated synopsis tier is NOT supported// on the import path — that's an async backfill via the Minion handler// (the cost prompt + 10s grace UX from D3 gates spending; inline import// path takes the cheaper title-only treatment for tokenmax pages here@@ -770,7 +771,7 @@ export async function importFromContent(if (!opts.noEmbed && chunks.length > 0) {const safeTitle = sanitizeTitle(parsed.title);const prefix =- modeRequiresWrapper(effectiveCRMode) && !modeRequiresHaiku(effectiveCRMode)+ modeRequiresWrapper(effectiveCRMode) && !modeRequiresSynopsis(effectiveCRMode)? buildContextualPrefix(safeTitle, null): null;const wrappedTexts = prefix@@ -793,7 +794,7 @@ export async function importFromContent(? null: computeCorpusGeneration({crMode: effectiveCRMode,- haikuModel: 'anthropic:claude-haiku-4-5-20251001',+ synopsisModel: DEFAULT_SYNOPSIS_MODEL,// Inline import-file path never uses per_chunk_synopsis (refuses// upstream); pass undefined so the doc-cap field stays out of// the hash here. Per_chunk_synopsis runs through the Miniondiff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.tsindex 9d03b80f61..9a6d958930 100644--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts@@ -5,7 +5,7 @@* worker-driven). The primitive's audit + cost-cap value lives at the* SUBMITTER side (`gbrain reindex --markdown`, which IS retrofitted in* T11), not at the handler. The handler already routes its cost through- * the global Haiku rate-leaser (D26 P0-3). No further retrofit needed.+ * the global synopsis rate-leaser (D26 P0-3). No further retrofit needed.** v0.40.3.0 — Minion handler for per-page contextual retrieval re-embed.*@@ -15,14 +15,14 @@* - `doctor --remediate` when contextual_retrieval_coverage flags drift.* - The reindex command for backfill orchestration.*- * This handler is DELIBERATELY thin (D23) — it wires the global Haiku+ * This handler is DELIBERATELY thin (D23) — it wires the global synopsis* rate-leaser (D26 P0-3), validates the job payload, and delegates the* actual re-embed work to `src/core/contextual-retrieval-service.ts:* reembedPageWithContextualRetrieval`. The service owns the two-phase* build pattern + page-level fall-back per D14. This handler owns:- * - Rate-lease acquire/release per Haiku call (shared key across the- * whole worker pool so concurrent page jobs don't blow the 50 RPM- * default per D26 P0-3).+ * - Rate-lease acquire/release per synopsis call (shared, resolved-model+ * key across the whole worker pool so concurrent page jobs stay under+ * the configured provider-neutral cap per D26 P0-3).* - Source-id derivation from page-id (D27 P2-1 defense-in-depth* against stale/malicious payloads that try to apply source-level* trust decisions from the wrong source).@@ -48,23 +48,39 @@ import {releaseLease,} from '../rate-leases.ts';import { resolveSearchMode, loadSearchModeConfig } from '../../search/mode.ts';--const RATE_LEASE_KEY = 'anthropic:utility:contextual-synopsis';+import { resolveModel } from '../../model-config.ts';+import { DEFAULT_SYNOPSIS_MODEL } from '../../page-summary.ts';+import { registerConfigSelectedChatModel } from '../../ai/gateway.ts';/**- * Default global Haiku RPM for contextual synopsis calls. Anthropic's- * published default is 50 RPM for Haiku 4.5; operators can raise via- * the env override on a tier with higher quota.+ * Default global concurrency cap for contextual synopsis calls. The public+ * setting keeps the historical RPM name; the lease primitive enforces active+ * calls, while provider SDKs own request-rate retries.*/-const DEFAULT_HAIKU_RPM = 50;+const DEFAULT_SYNOPSIS_RPM = 50;-function resolveMaxConcurrent(): number {- const env = process.env.GBRAIN_CONTEXTUAL_HAIKU_RPM;- if (env) {- const n = parseInt(env, 10);- if (Number.isFinite(n) && n > 0) return n;+export function resolveContextualSynopsisLeaseSettings(+ synopsisModel: string,+ env: Record<string, string | undefined> = process.env,+): { key: string; maxConcurrent: number } {+ const configuredLimits = [+ env.GBRAIN_CONTEXTUAL_SYNOPSIS_RPM,+ env.GBRAIN_CONTEXTUAL_HAIKU_RPM,+ ];+ for (const configuredLimit of configuredLimits) {+ if (!configuredLimit) continue;+ const parsed = parseInt(configuredLimit, 10);+ if (Number.isFinite(parsed) && parsed > 0) {+ return {+ key: `contextual-synopsis:${synopsisModel}`,+ maxConcurrent: parsed,+ };+ }}- return DEFAULT_HAIKU_RPM;+ return {+ key: `contextual-synopsis:${synopsisModel}`,+ maxConcurrent: DEFAULT_SYNOPSIS_RPM,+ };}/**@@ -84,6 +100,22 @@ export interface ContextualReindexJobData {export interface MakeContextualReindexHandlerOpts {engine: BrainEngine;+ /** @internal Hermetic handler seam; production callers omit this. */+ reembedPage?: typeof reembedPageWithContextualRetrieval;+}++export async function resolveContextualSynopsisModel(+ engine: BrainEngine,+ explicitModel?: string,+): Promise<string> {+ return resolveModel(engine, {+ cliFlag: explicitModel,+ configKey: 'models.contextual_synopsis',+ deprecatedConfigKey: 'contextual_retrieval.haiku_model',+ envVar: 'GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL',+ tier: 'utility',+ fallback: DEFAULT_SYNOPSIS_MODEL,+ });}/**@@ -92,6 +124,7 @@ export interface MakeContextualReindexHandlerOpts {*/export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOpts) {const { engine } = opts;+ const reembedPage = opts.reembedPage ?? reembedPageWithContextualRetrieval;return async function contextualReindexHandler(ctx: MinionJobContext,@@ -129,18 +162,21 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOconst globalMode = knobs.contextual_retrieval;const killSwitchDisabled = knobs.contextual_retrieval_disabled;- // Run the service with rate-leasing hooks (D26 P0-3). Each Haiku+ // Run the service with rate-leasing hooks (D26 P0-3). Each synopsis// call inside the service acquires/releases a lease against the// shared key across all worker processes.- const maxConcurrent = resolveMaxConcurrent();const chunkConcurrency = resolveContextualChunkConcurrency();+ const synopsisModel = await resolveContextualSynopsisModel(engine);+ const leaseSettings = resolveContextualSynopsisLeaseSettings(synopsisModel);+ registerConfigSelectedChatModel(synopsisModel);- const result: ReembedPageResult = await reembedPageWithContextualRetrieval({+ const result: ReembedPageResult = await reembedPage({engine,pageSlug: data.page_slug,sourceId: foundPage.source_id,globalMode,killSwitchDisabled,+ synopsisModel,abortSignal: ctx.signal,chunkConcurrency,acquireSynopsisLease: async () => {@@ -151,9 +187,15 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOconst maxAttempts = 60; // ~1 min max wait per chunk before giving upwhile (attempts < maxAttempts) {if (ctx.signal.aborted) throw abortError();- const res = await acquireLease(engine, RATE_LEASE_KEY, ctx.id, maxConcurrent, {- ttlMs: 60_000,- });+ const res = await acquireLease(+ engine,+ leaseSettings.key,+ ctx.id,+ leaseSettings.maxConcurrent,+ {+ ttlMs: 60_000,+ },+ );if (res.acquired && res.leaseId != null) {return res.leaseId;}@@ -161,8 +203,8 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerOawait sleepWithAbort(1000, ctx.signal);}throw new Error(- `Failed to acquire ${RATE_LEASE_KEY} lease after ${maxAttempts} attempts; ` +- `Haiku rate limit pile-up too deep.`,+ `Failed to acquire ${leaseSettings.key} lease after ${maxAttempts} attempts; ` ++ `Synopsis rate limit pile-up too deep.`,);},releaseSynopsisLease: async (lease) => {diff --git a/src/core/page-summary.ts b/src/core/page-summary.tsindex 78e04d41c9..d0fb325ca5 100644--- a/src/core/page-summary.ts+++ b/src/core/page-summary.ts@@ -1,10 +1,10 @@/**- * v0.40.3.0 — per-chunk Haiku synopsis generator.+ * v0.40.3.0 — per-chunk synopsis generator.** For the tokenmax tier (D1 — Anthropic's published per-chunk synopsis* method), this module owns:*- * - Routing the Haiku call through `gateway.chat(tier='utility')` —+ * - Routing the synopsis call through `gateway.chat()` —* the cheapest tier per CLAUDE.md gateway docs.* - The richer failure envelope from D27 P1-2: distinguishing* refusal / empty / malformed (→ page-level fall-back to title-only@@ -35,14 +35,14 @@ import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.timport { sanitizeSynopsis } from './embedding-context.ts';/**- * Hard cap on Haiku output tokens. ~200 tokens gives 50-100 token+ * Hard cap on synopsis output tokens. ~200 tokens gives 50-100 token* synopsis with some headroom; the wrapper layer caps the final* synopsis at SUMMARY_HARD_CAP_CHARS (300) regardless.*/-const HAIKU_MAX_TOKENS = 200;+const SYNOPSIS_MAX_TOKENS = 200;/** Default model when caller doesn't override. Resolves through the gateway. */-const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';+export const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';/*** Hard cap on `documentText` length (chars) before send.@@ -100,7 +100,7 @@ export interface GeneratePerChunkSynopsisArgs {documentText: string;/** The chunk for which we're generating the synopsis. */chunkText: string;- /** The page's title — gives Haiku document-level anchor. */+ /** The page's title — gives the synopsis model a document-level anchor. */pageTitle: string;/** Page slug for audit logging on failure. */pageSlug: string;@@ -131,8 +131,7 @@ export type GeneratePerChunkSynopsisResult =** Caller is responsible for:* - Rate-leasing via `src/core/minions/rate-leases.ts` (the SERVICE- * layer does this with the global `anthropic:utility:contextual-synopsis`- * key per D26 P0-3).+ * layer does this with a resolved-model-specific synopsis key per D26 P0-3).* - LRU caching by `(content_hash, chunk_index, corpus_generation,* source_text_hash)`. This module is a pure transformer — no cache* lookup here; the service decides when to call us.@@ -150,7 +149,7 @@ export async function generatePerChunkSynopsis(model: args.model ?? DEFAULT_SYNOPSIS_MODEL,system: SYSTEM_PROMPT,messages: [{ role: 'user', content: userPrompt }],- maxTokens: HAIKU_MAX_TOKENS,+ maxTokens: SYNOPSIS_MAX_TOKENS,abortSignal: args.abortSignal,cacheSystem: true,};diff --git a/test/config-set.test.ts b/test/config-set.test.tsindex af2787b458..05526b8582 100644--- a/test/config-set.test.ts+++ b/test/config-set.test.ts@@ -38,6 +38,10 @@ describe('KNOWN_CONFIG_KEYS', () => {expect(KNOWN_CONFIG_KEYS).toContain('models.tier.subagent');});+ test('allows the contextual synopsis model key', () => {+ expect(KNOWN_CONFIG_KEYS).toContain('models.contextual_synopsis');+ });+test('contains the dream synthesize timeout keys (#1594)', () => {expect(KNOWN_CONFIG_KEYS).toContain('dream.synthesize.subagent_timeout_ms');expect(KNOWN_CONFIG_KEYS).toContain('dream.synthesize.subagent_wait_timeout_ms');diff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.tsindex 3ba8d56d1e..3ebce54d9a 100644--- a/test/contextual-retrieval-service-pure.test.ts+++ b/test/contextual-retrieval-service-pure.test.ts@@ -7,6 +7,7 @@*/import { afterEach, describe, test, expect } from 'bun:test';+import { readFileSync } from 'node:fs';import {computeCorpusGeneration,computeSourceTextHash,@@ -35,6 +36,25 @@ afterEach(() => {});describe('computeCorpusGeneration', () => {+ test('uses synopsisModel canonically while retaining the deprecated alias', () => {+ const canonical = computeCorpusGeneration({+ crMode: 'title',+ synopsisModel: 'codex-proxy:gpt-5.6-luna',+ });+ const deprecatedAlias = computeCorpusGeneration({+ crMode: 'title',+ haikuModel: 'codex-proxy:gpt-5.6-luna',+ });+ const canonicalWins = computeCorpusGeneration({+ crMode: 'title',+ synopsisModel: 'codex-proxy:gpt-5.6-luna',+ haikuModel: 'anthropic:legacy-ignored',+ });++ expect(canonical).toBe(deprecatedAlias);+ expect(canonicalWins).toBe(canonical);+ });+test('returns 16-char hex hash', () => {const h = computeCorpusGeneration({crMode: 'title',@@ -65,18 +85,31 @@ describe('computeCorpusGeneration', () => {expect(b).not.toBe(c);});- test('different model → different hash', () => {+ test('different synopsis model changes per-chunk generation', () => {const a = computeCorpusGeneration({- crMode: 'title',+ crMode: 'per_chunk_synopsis',haikuModel: 'anthropic:claude-haiku-4-5-20251001',});const b = computeCorpusGeneration({- crMode: 'title',+ crMode: 'per_chunk_synopsis',haikuModel: 'anthropic:claude-haiku-future-model',});expect(a).not.toBe(b);});+ test('title generation ignores the unused synopsis model', () => {+ const configured = computeCorpusGeneration({+ crMode: 'title',+ synopsisModel: 'codex-proxy:gpt-5.6-luna',+ });+ const fallback = computeCorpusGeneration({+ crMode: 'title',+ synopsisModel: 'anthropic:claude-haiku-4-5-20251001',+ });++ expect(configured).toBe(fallback);+ });+test('TITLE_WRAPPER_VERSION is stable across reads', () => {// Bump this constant only when changing the wrapper text shape.// The hash composition includes it so a future change invalidates@@ -85,6 +118,24 @@ describe('computeCorpusGeneration', () => {});});+describe('inline import contextual synopsis containment', () => {+ test('uses the shared default without starting paid synopsis generation', () => {+ const importSource = readFileSync(+ new URL('../src/core/import-file.ts', import.meta.url),+ 'utf8',+ );++ expect(importSource).toContain(+ "import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';",+ );+ expect(importSource).toContain('synopsisModel: DEFAULT_SYNOPSIS_MODEL');+ expect(importSource).toContain(+ "effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;",+ );+ expect(importSource).not.toContain('generatePerChunkSynopsis');+ });+});+describe('computeSourceTextHash', () => {test('returns 16-char hex', () => {expect(computeSourceTextHash('any text')).toMatch(/^[0-9a-f]{16}$/);@@ -187,6 +238,22 @@ describe('resolveContextualChunkConcurrency', () => {});describe('per-chunk synopsis concurrency', () => {+ test('threads a provider-neutral synopsis model to gateway chat byte-for-byte', async () => {+ const chatModels: string[] = [];+ const out = await runWithChatStub({+ chunks: makeChunks(['alpha']),+ concurrency: 1,+ synopsisModel: 'codex-proxy:gpt-5.6-luna',+ chat: async (opts) => {+ chatModels.push(opts.model ?? '');+ return chatSuccess('Synopsis for alpha');+ },+ });++ expect(out.result.kind).toBe('success');+ expect(chatModels).toEqual(['codex-proxy:gpt-5.6-luna']);+ });+test('concurrency > 1 preserves chunk-order embed input', async () => {const chunks = makeChunks(['alpha', 'beta', 'gamma', 'delta']);const delays: Record<string, number> = { alpha: 30, beta: 5, gamma: 20, delta: 1 };@@ -335,6 +402,7 @@ function makeChunks(texts: string[]): ChunkInput[] {async function runWithChatStub(opts: {chunks: ChunkInput[];concurrency: number;+ synopsisModel?: string;abortSignal?: AbortSignal;delayForChunk?: (chunk: string) => number;chat?: (opts: ChatOpts) => Promise<ChatResult>;@@ -371,6 +439,7 @@ async function runWithChatStub(opts: {sourceId: 'default',globalMode: 'per_chunk_synopsis',chunkConcurrency: opts.concurrency,+ synopsisModel: opts.synopsisModel,abortSignal: opts.abortSignal,...(opts.acquireSynopsisLease && { acquireSynopsisLease: opts.acquireSynopsisLease }),...(opts.releaseSynopsisLease && { releaseSynopsisLease: opts.releaseSynopsisLease }),diff --git a/test/contextual-synopsis-model.serial.test.ts b/test/contextual-synopsis-model.serial.test.tsnew file mode 100644index 0000000000..3e6d708b9e--- /dev/null+++ b/test/contextual-synopsis-model.serial.test.ts@@ -0,0 +1,340 @@+/**+ * Task 5: provider-neutral contextual synopsis model routing.+ * Hermetic resolver coverage; no DB or provider credentials required.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { TIER_DEFAULTS, resolveModel } from '../src/core/model-config.ts';+import { runModels } from '../src/commands/models.ts';+import {+ makeContextualReindexHandler,+ resolveContextualSynopsisLeaseSettings,+ resolveContextualSynopsisModel,+} from '../src/core/minions/handlers/contextual-reindex-per-chunk.ts';+import type { ReembedPageArgs } from '../src/core/contextual-retrieval-service.ts';+import {+ __setGenerateTextTransportForTests,+ chat,+ configureGateway,+ resetGateway,+ validateModelId,+} from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';++class StubConfigEngine {+ private readonly config = new Map<string, string>();+ readonly reads: string[] = [];++ set(key: string, value: string): void {+ this.config.set(key, value);+ }++ unset(key: string): void {+ this.config.delete(key);+ }++ async getConfig(key: string): Promise<string | null> {+ this.reads.push(key);+ return this.config.get(key) ?? null;+ }++ async getPage(): Promise<{ source_id: string }> {+ return { source_id: 'default' };+ }+}++afterEach(() => {+ __setGenerateTextTransportForTests(null);+ resetGateway();+});++describe('contextual synopsis model resolution', () => {+ test('isolates rate leases by resolved model', () => {+ expect(resolveContextualSynopsisLeaseSettings('openai:gpt-5.2', {})).toMatchObject({+ key: 'contextual-synopsis:openai:gpt-5.2',+ });+ expect(resolveContextualSynopsisLeaseSettings('anthropic:claude-haiku-4-5', {})).toMatchObject({+ key: 'contextual-synopsis:anthropic:claude-haiku-4-5',+ });+ });++ test('prefers the canonical synopsis RPM setting over the Haiku alias', () => {+ expect(resolveContextualSynopsisLeaseSettings('openai:gpt-5.2', {+ GBRAIN_CONTEXTUAL_SYNOPSIS_RPM: '17',+ GBRAIN_CONTEXTUAL_HAIKU_RPM: '9',+ })).toEqual({+ key: 'contextual-synopsis:openai:gpt-5.2',+ maxConcurrent: 17,+ });+ });++ test('retains the Haiku RPM alias and the existing default', () => {+ expect(resolveContextualSynopsisLeaseSettings('anthropic:claude-haiku-4-5', {+ GBRAIN_CONTEXTUAL_HAIKU_RPM: '9',+ })).toEqual({+ key: 'contextual-synopsis:anthropic:claude-haiku-4-5',+ maxConcurrent: 9,+ });++ expect(resolveContextualSynopsisLeaseSettings('openai:gpt-5.2', {})).toEqual({+ key: 'contextual-synopsis:openai:gpt-5.2',+ maxConcurrent: 50,+ });+ });++ test('uses the canonical precedence and utility tier keeps caller fallback unreachable', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.contextual_synopsis', 'codex-proxy:new-key');+ engine.set('contextual_retrieval.haiku_model', 'codex-proxy:deprecated-key');+ engine.set('models.default', 'codex-proxy:global-default');+ engine.set('models.tier.utility', 'codex-proxy:utility-tier');++ await withEnv({ GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL: 'codex-proxy:env-model' }, async () => {+ expect(await resolveContextualSynopsisModel(engine as never, 'codex-proxy:explicit')).toBe(+ 'codex-proxy:explicit',+ );++ expect(await resolveContextualSynopsisModel(engine as never)).toBe('codex-proxy:new-key');++ engine.unset('models.contextual_synopsis');+ expect(await resolveContextualSynopsisModel(engine as never)).toBe(+ 'codex-proxy:deprecated-key',+ );++ engine.unset('contextual_retrieval.haiku_model');+ expect(await resolveContextualSynopsisModel(engine as never)).toBe(+ 'codex-proxy:global-default',+ );++ engine.unset('models.default');+ expect(await resolveContextualSynopsisModel(engine as never)).toBe(+ 'codex-proxy:utility-tier',+ );++ engine.unset('models.tier.utility');+ expect(await resolveContextualSynopsisModel(engine as never)).toBe(+ 'codex-proxy:env-model',+ );+ });++ expect(await resolveContextualSynopsisModel(engine as never)).toBe(TIER_DEFAULTS.utility);++ expect(+ await resolveModel(engine as never, {+ configKey: 'models.contextual_synopsis',+ deprecatedConfigKey: 'contextual_retrieval.haiku_model',+ envVar: 'GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL',+ tier: 'utility',+ fallback: 'codex-proxy:caller-fallback-must-not-win',+ }),+ ).toBe(TIER_DEFAULTS.utility);+ });++ test('reports the contextual synopsis route in gbrain models JSON', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.contextual_synopsis', 'codex-proxy:gpt-5.6-luna');++ let stdout = '';+ const originalWrite = process.stdout.write;+ process.stdout.write = ((chunk: string | Uint8Array) => {+ stdout += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+ try {+ await runModels(engine as never, ['--json']);+ } finally {+ process.stdout.write = originalWrite;+ }++ const report = JSON.parse(stdout) as {+ per_task: Array<{+ key: string;+ tier: string;+ resolved: string;+ source: string;+ description: string;+ }>;+ };+ expect(report.per_task).toContainEqual({+ key: 'models.contextual_synopsis',+ tier: 'utility',+ resolved: 'codex-proxy:gpt-5.6-luna',+ source: 'config: models.contextual_synopsis',+ description: 'Per-chunk contextual synopsis generation',+ });+ });++ test('models report honors the synopsis deprecated key and dedicated env', async () => {+ const engine = new StubConfigEngine();+ engine.set('contextual_retrieval.haiku_model', 'codex-proxy:deprecated-report');++ await withEnv({+ GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL: 'codex-proxy:dedicated-env',+ GBRAIN_MODEL: 'codex-proxy:wrong-generic-env',+ }, async () => {+ const deprecatedReport = await captureModelsReport(engine);+ expect(deprecatedReport.per_task.find((entry) =>+ entry.key === 'models.contextual_synopsis'+ )).toMatchObject({+ resolved: 'codex-proxy:deprecated-report',+ source: 'config: contextual_retrieval.haiku_model',+ });++ engine.unset('contextual_retrieval.haiku_model');+ const envReport = await captureModelsReport(engine);+ expect(envReport.per_task.find((entry) =>+ entry.key === 'models.contextual_synopsis'+ )).toMatchObject({+ resolved: 'codex-proxy:dedicated-env',+ source: 'env: GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL',+ });+ });+ });++ test('handler resolves once and passes synopsisModel to the service seam', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.contextual_synopsis', 'codex-proxy:gpt-5.6-luna');+ const serviceCalls: ReembedPageArgs[] = [];+ const handler = makeContextualReindexHandler({+ engine: engine as never,+ reembedPage: async (args) => {+ serviceCalls.push(args);+ return {+ kind: 'success',+ mode_applied: 'per_chunk_synopsis',+ chunks_embedded: 1,+ corpus_generation: 'test-generation',+ };+ },+ });+ const controller = new AbortController();++ const result = await handler({+ id: 42,+ name: 'contextual_reindex_per_chunk',+ data: { page_slug: 'wiki/provider-neutral' },+ signal: controller.signal,+ } as never);++ expect(result).toEqual({+ ok: true,+ mode_applied: 'per_chunk_synopsis',+ chunks_embedded: 1,+ });+ expect(engine.reads.filter((key) => key === 'models.contextual_synopsis')).toHaveLength(1);+ expect(serviceCalls).toHaveLength(1);+ expect(serviceCalls[0]?.synopsisModel).toBe('codex-proxy:gpt-5.6-luna');+ });++ test('handler registers canonical native synopsis model before service gateway chat', async () => {+ await expectHandlerRegistersNativeSynopsisRoute({+ configKey: 'models.contextual_synopsis',+ model: 'openai:gpt-5.6-luna-contextual-canonical',+ });+ });++ test('handler registers deprecated native synopsis model before service gateway chat', async () => {+ await expectHandlerRegistersNativeSynopsisRoute({+ configKey: 'contextual_retrieval.haiku_model',+ model: 'openai:gpt-5.6-luna-contextual-deprecated',+ });+ });++ test('handler registers env native synopsis model before service gateway chat', async () => {+ await expectHandlerRegistersNativeSynopsisRoute({+ envModel: 'openai:gpt-5.6-luna-contextual-env',+ });+ });+});++async function expectHandlerRegistersNativeSynopsisRoute(opts: {+ configKey?: string;+ model?: string;+ envModel?: string;+}): Promise<void> {+ const engine = new StubConfigEngine();+ const expectedModel = opts.envModel ?? opts.model;+ if (!expectedModel) throw new Error('expectedModel required');+ if (opts.configKey && opts.model) engine.set(opts.configKey, opts.model);++ const generatedModels: string[] = [];+ __setGenerateTextTransportForTests((async (callOpts: { model?: { modelId?: string } }) => {+ generatedModels.push(`openai:${callOpts.model?.modelId ?? '<missing>'}`);+ return {+ text: 'ok',+ content: [{ type: 'text', text: 'ok' }],+ finishReason: 'stop',+ usage: { inputTokens: 1, outputTokens: 1 },+ providerMetadata: {},+ };+ }) as never);++ await withEnv(+ {+ OPENAI_API_KEY: 'test-openai-key',+ GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL: opts.envModel,+ GBRAIN_MODEL: 'openai:gpt-5.2',+ },+ async () => {+ configureGateway({+ chat_model: 'openai:gpt-5.2',+ expansion_model: 'openai:gpt-5.2',+ embedding_model: 'openai:text-embedding-3-small',+ embedding_dimensions: 1536,+ env: process.env as Record<string, string | undefined>,+ });++ const handler = makeContextualReindexHandler({+ engine: engine as never,+ reembedPage: async (args) => {+ expect(args.synopsisModel).toBe(expectedModel);+ const chatResult = await chat({+ model: args.synopsisModel,+ system: 'test',+ messages: [{ role: 'user', content: 'test' }],+ });+ expect(chatResult.model).toBe(expectedModel);+ return {+ kind: 'success',+ mode_applied: 'per_chunk_synopsis',+ chunks_embedded: 1,+ corpus_generation: 'test-generation',+ };+ },+ });++ await expect(handler({+ id: 42,+ name: 'contextual_reindex_per_chunk',+ data: { page_slug: 'wiki/provider-neutral' },+ signal: new AbortController().signal,+ } as never)).resolves.toEqual({+ ok: true,+ mode_applied: 'per_chunk_synopsis',+ chunks_embedded: 1,+ });+ },+ );++ expect(generatedModels).toEqual([expectedModel]);+ expect(validateModelId(expectedModel, 'chat').ok).toBe(true);+ expect(validateModelId(expectedModel, 'expansion').ok).toBe(false);+}++async function captureModelsReport(engine: StubConfigEngine): Promise<{+ per_task: Array<{ key: string; resolved: string; source: string }>;+}> {+ let stdout = '';+ const originalWrite = process.stdout.write;+ process.stdout.write = ((chunk: string | Uint8Array) => {+ stdout += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+ try {+ await runModels(engine as never, ['--json']);+ } finally {+ process.stdout.write = originalWrite;+ }+ return JSON.parse(stdout) as {+ per_task: Array<{ key: string; resolved: string; source: string }>;+ };+}diff --git a/test/embedding-context.test.ts b/test/embedding-context.test.tsindex 85c0b862c5..1b46d7cd31 100644--- a/test/embedding-context.test.ts+++ b/test/embedding-context.test.ts@@ -5,6 +5,7 @@ import {sanitizeTitle,sanitizeSynopsis,extractFirstTwoSentences,+ modeRequiresSynopsis,modeRequiresHaiku,modeRequiresWrapper,} from '../src/core/embedding-context.ts';@@ -130,11 +131,12 @@ describe('extractFirstTwoSentences', () => {});});-describe('modeRequiresHaiku / modeRequiresWrapper', () => {- test('per_chunk_synopsis requires Haiku', () => {- expect(modeRequiresHaiku('per_chunk_synopsis')).toBe(true);- expect(modeRequiresHaiku('title')).toBe(false);- expect(modeRequiresHaiku('none')).toBe(false);+describe('modeRequiresSynopsis / modeRequiresWrapper', () => {+ test('provider-neutral guard retains the deprecated Haiku alias', () => {+ for (const mode of ['per_chunk_synopsis', 'title', 'none'] as const) {+ expect(modeRequiresSynopsis(mode)).toBe(mode === 'per_chunk_synopsis');+ expect(modeRequiresHaiku(mode)).toBe(modeRequiresSynopsis(mode));+ }});test('title and per_chunk_synopsis require wrapper; none does not', () => {