Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.2.0 fix(skillopt): fail loud on unusable optimizer output + model provenance (#5584, #5585) (#5608)
Garry Tan334ffadafb8e
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 51dea73f6a..efa54ade3a 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 1fdb76efab..b7c3908ca5 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 9c229083f2..2f2fe42b87 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.0.0 -->+<!-- gbrain-runbook-stamp: 0.59.2.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eeea819360..352a75e8ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,97 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.59.2.0] - 2026-09-28++**When skill optimization gets nothing usable back from the optimizer model, it now says so instead of quietly reporting "no improvement", and every run tells you exactly which models it used and what they cost.**++`gbrain skillopt` asks a large model to suggest edits to a skill, then tests them. With newer "thinking" models, those replies were often cut off at a small output limit, so no edits came back. The run still finished with a calm "no improvement", as if the skill were already as good as it gets, and it kept spending the rest of its budget. Now a cut-off, empty or unreadable reply is counted as an error. A run where no reply was ever usable ends `errored`, stops early instead of spending the rest of its budget, and prints the fix plus a paste-ready resume command. Before any money is spent, a short banner lists every model the run will call and where each choice came from. Afterwards the receipt lists every model that was actually called, with calls and cost.++### How to use it++```bash+gbrain skillopt my-skill --dry-run # models banner + cost preview, zero model calls+gbrain skillopt my-skill --reflect-max-tokens 16000+gbrain config set skillopt.reflect_max_tokens 16000+gbrain skillopt my-skill --models-strict # refuse to run on models you did not choose explicitly+gbrain models # now flags when a newer Claude model is available+```++### What changes for you++| Situation | Before | Now |+|---|---|---|+| Optimizer replies all cut off or unreadable | `no_improvement`, exit 1, budget spent | `errored`, exit 2, stops after 2 such steps, fix + resume command printed |+| Which models ran | Not recorded | Banner before spend; `models_plan` and `models_used` on the receipt |+| Budget abort or error mid-run | Resume re-ran or skipped steps | Resume continues at the exact step and retries unusable steps |+| Nightly cycle skill that can never fit its cap | Tried and failed every night | `skipped_budget`, retried only after the config changes |++### Things to watch++- **Exit code 2 for unusable output.** Scripts that treated `no_improvement` (exit 1) as "nothing to do" will now see `errored` (exit 2) when the optimizer never produced a usable reply.+- **Model flags resolve aliases.** `--optimizer-model`, `--target-model` and `--judge-model` values go through the same alias resolution as config keys, so a short alias resolves to its full model id.+- **Thinking optimizers get a larger output cap** (32,000 tokens; other models keep 4,096). Each call reserves its full cap against `--max-cost-usd`. In the nightly cycle, a Claude 5 thinking optimizer can exceed the default $0.50 per-skill cap; that skill is recorded `skipped_budget` with the fix instead of running.+- **Old checkpoints and queued jobs still work.** Checkpoints from earlier versions resume and report `models_used_scope: since_resume`. Background jobs queued before the upgrade resolve their model sources as `unknown`, which strict mode rejects.+- **The cost cap applies per run segment.** A resumed run gets a fresh `--max-cost-usd` on top of what earlier segments spent.+- **The `gbrain models` newer-model hint is advisory.** Built-in defaults do not change.++### To take advantage of v0.59.2.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes+ ```+2. **Your agent reads `skills/migrations/v0.59.2.0.md` the next time you interact with it.** No database migration runs; the note covers exit-code and nightly-cycle checks for anyone running skillopt from scripts or the dream cycle.+3. **Verify the outcome:**+ ```bash+ gbrain skillopt --help # lists --reflect-max-tokens and --models-strict+ gbrain models # sources are attributed; newer-model hints appear where relevant+ gbrain skillopt <skill> --dry-run+ ```+4. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with:+ - output of `gbrain doctor`+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists+ - which step broke++ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.++### Itemized changes++### Added++- Optimizer output cap by model: 32,000 tokens for thinking optimizers, 4,096 otherwise. Set it with `--reflect-max-tokens`, `skillopt.reflect_max_tokens` or the MCP/job `reflect_max_tokens` param. Remote values are clamped to 256-32,000.+- Error codes for every unusable optimizer reply (`reflect_truncated`, `reflect_empty_reply`, `reflect_no_parseable_edits`, `reflect_invalid_edits`, `reflect_context_too_small`, `reflect_context_overflow`, one-shot variants, `reservation_exceeds_cap`, and more). Each maps to a receipt `remediation[]` entry that links to the new error-code table in `docs/guides/skillopt.md`.+- `resume_command` on errored, aborted and early-stopped receipts. It is rebuilt from the stored run spec plus the run's mode, cost cap, runtime cap and `--models-strict`. Output-cap failures double the reflect cap; an edits-contract failure puts a quoted `'<other-model>'` placeholder in place of the optimizer model.+- Models banner and `models_plan`: optimizer, target, judge (including per-task judge overrides), expansion, chat, embedding and the reranker when enabled, each with where the choice came from. Printed before any spend, and recorded on the receipt and the `run_start` audit row.+- Per-model spend ledger and `models_used` on receipts: requested and served model, purpose, attempts, calls, failures and cost per model. Merged across resume segments.+- Strict mode (`--models-strict` / `skillopt.models_strict`) aborts before any spend when an active model came from `models.default`, a built-in default, a substitution or unknown provenance. It lists a copy-paste fix per touchpoint and applies to the CLI, MCP op, cycle, jobs, `--all`, fleets and both bootstrap modes. An unreadable setting counts as on.+- `--dry-run` shows the models banner, strict verdict and cost preview with zero model calls.+- `gbrain models` prints `[newer <family> available: <id>]` with the config command when a configured Claude model is older than the newest priced model of its family.++### Changed++- A run with no usable optimizer reply ends `errored` (`abort_detail: optimizer_output_unusable: <first error>`, exit 2). Two consecutive fully unusable steps stop the loop (`stop_reason: early_stop_unusable_output`). A run that accepted a candidate still reports `accepted`.+- `--optimizer-model`, `--target-model` and `--judge-model` are resolved through one role resolver shared by the CLI, the `run_skillopt` MCP op, the cycle phase and background jobs. Background jobs re-resolve their models and re-run the strict check when they execute.+- Preflight aborts before spend when a single call's reservation alone exceeds the cost cap, naming the role. The expected cost and the reservation are shown separately.+- Nightly cycle: an errored run records `cycle.skillopt.last_error.<skill>` and is retried after 24 hours instead of banking `last_run`. A run that can never fit the per-skill cap is recorded `skipped_budget` and retried only when the models, caps, price overrides, benchmark or gbrain version change. Result rows carry `abort_reason`, `abort_detail`, `run_id` and `remediation`. Kept checkpoints older than 7 days are cleaned up.+- Bootstrap modes run under the `--max-cost-usd` tracker. An optimizer with no pricing entry needs `pricing.overrides` or `--no-max-cost`.+- `gbrain models` source labels come from the same resolver the runtime uses.++### Fixed++- Budget exhaustion, spend-policy refusals, the runtime deadline and SIGINT now abort the run with their real reason instead of being turned into a reflect error, a judge score of 0 or a skipped bootstrap row.+- The judge and bootstrap calls get output headroom on thinking models (a floor of 8,192 tokens) and record `llm_truncated` / `truncated` instead of parsing a cut-off reply.+- Resume correctness: checkpoints store a next-step cursor and a run spec. `--resume` refuses a changed benchmark, held-out set or split, and refuses widening from no-mutate to mutate. A resume retries the trailing unusable steps and never counts an interrupted step twice. It accepts a SKILL.md with uncommitted changes only when the file is exactly the run's own accepted text.+- The skill body is sent whole when it fits the optimizer's context window. Otherwise it is truncated with an in-prompt disclosure and recorded as `skill_body_truncated` on the receipt.++### For contributors++- New modules: `src/core/skillopt/{output-cap,run-outcome,remediation,models-plan,must-abort,job,bootstrap-run}.ts`, `src/core/budget/{models-used,reservation-cost}.ts`, `src/core/ai/{budget-record,gateway-model-sources,anthropic-model-ids}.ts`. `reservationCostUsd` is shared by `BudgetTracker.reserve()` and preflight.+- Error-code docs anchors are pinned by `test/skillopt/error-code-docs.test.ts`; the four model-resolution paths are pinned by a golden test.+## [0.59.0.0] - 2026-09-25**The LongMemEval reader now checks the evidence before giving its short answer.**diff --git a/TODOS.md b/TODOS.mdindex 89ea88cdad..c9d66b49b1 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,32 @@# TODOS+## Skillopt honesty + model provenance wave follow-ups (filed 2026-09-28, #5584 / #5585 fix wave)++- [ ] **P1 — TODO-D: validated Anthropic default-model migration.**+ **What:** `TIER_DEFAULTS`, `DEFAULT_ALIASES` and the gateway's `DEFAULT_EXPANSION_MODEL` / `DEFAULT_CHAT_MODEL` still pin older Claude ids (`claude-sonnet-4-6`, `claude-opus-4-7`). `gbrain models` now prints an advisory `[newer <family> available]` hint, but no default moves. **Fix:** recipe-metadata recommended defaults (not "newest wins": `fable` and any preview id are never auto-selected), measured cost/latency/quality on a representative cycle + dream run before flipping, and an explicit output-cap policy for thinking models across small-cap callers (judges, classifiers, the cycle budget meter), since Claude 5 thinking needs headroom that explicit caller `maxTokens` does not grant today. Reuse `src/core/ai/anthropic-model-ids.ts` for version parsing. Ship with a CHANGELOG disclosure of the cost change. **Effort:** L. **Priority:** P1.+- [ ] **P2 — TODO-A: adopt `buildModelsUsed` in eval / dream / cycle receipts.**+ **What:** only skillopt receipts carry `models_used`; the BudgetTracker ledger (`snapshot().models`) already records every gateway operation for any tracked run. **Fix:** call `buildModelsUsed` from `src/core/budget/models-used.ts` in the eval, dream and cycle receipt writers so every paid run names the models it called (engine-internal expansion/embedding included), additive fields only. **Effort:** M. **Priority:** P2.+- [ ] **P3 — TODO-B: sweep literal Anthropic fallback pins + guard.**+ **What:** call sites still hand-roll model literals instead of `TIER_DEFAULTS.<tier>` (e.g. `src/core/facts/extract.ts`, `src/core/brainstorm/orchestrator.ts`, `src/core/page-summary.ts`, `src/core/cross-modal-eval/runner.ts`). **Fix:** route them through the tier table and add a `scripts/check-*` guard with an allowlist (model-config, pricing, recipes, tests) so new literal pins fail CI. **Effort:** S. **Priority:** P3.+- [ ] **P3 — TODO-C: `claude-opus-5-5` recipe + verified pricing (#5563).**+ **What:** the anthropic recipe and `src/core/model-pricing.ts` do not list `claude-opus-5-5`. **Fix:** add the recipe entry and canonical price only once the price is verified from the provider's published pricing; coordinate with #5563. **Effort:** S. **Priority:** P3.+- [ ] **P3 — TODO-E: guard chat consumers that ignore `stopReason === 'length'`.**+ **What:** skillopt reflect/one-shot/judge/bootstrap now check the length stop; other `gateway.chat()` consumers that parse structured output can still silently parse a truncated reply. **Fix:** a guard script or test that flags chat call sites parsing output without checking `stopReason`, with an opt-out marker for free-text consumers. **Effort:** M. **Priority:** P3.+- [ ] **P3 — TODO-F: configurable optimizer context size for unregistered long-context models.**+ **What:** skillopt sizes the skill-body budget from `resolveChatContextTokens(optimizer)`; an unregistered model falls back to 120,000 chars and may truncate a body its real window could hold. **Fix:** a validated override (config key or recipe metadata) for the optimizer's context window, shown on the banner and honored by the context-too-small check. **Effort:** S. **Priority:** P3.+- [ ] **P1 — TODO-H: enforce the strict model plan at call time for rollout tool arguments.**+ **What:** strict mode checks the models plan before spend. A rollout's search tool call can name an explicit `embedding_column`, which routes the query embedding through that column's provider without a plan check. **Fix:** carry the validated plan into the rollout tool context and refuse (or re-check) a column whose provider is not in the plan, or enforce provenance per gateway invocation under a strict run. **Effort:** M. **Priority:** P1.+- [ ] **P2 — TODO-I: whole-run cost cap across resume segments.**+ **What:** `--max-cost-usd` caps each run segment; a resumed run starts a fresh tracker, so N resumes can spend N x the cap (documented in the guide). **Fix:** seed the resumed tracker and preflight with `max(0, cap - prior_segments_cost_usd)`, and make the budget_exhausted remediation and resume command say "total run cap". Contract change: needs a CHANGELOG callout. **Effort:** S. **Priority:** P2.+- [ ] **P2 — TODO-J: `--resume` refuses a missing checkpoint and carries the brain.**+ **What:** `--resume <id>` with a missing, GC'd or corrupt checkpoint silently starts a fresh full run under that id, and the printed resume command omits `--brain`, so pasting it from another directory can resume against a different brain. **Fix:** refuse with a structured `resume_checkpoint_missing` error; persist the resolved brain id in the run spec, validate it on resume and emit it in the command. **Effort:** S. **Priority:** P2.+- [ ] **P3 — TODO-K: record the provider-reported served model in the spend ledger.**+ **What:** chat ledger rows record the routed `provider:model` as the served model; the provider's `response.modelId` (already surfaced as `responseModel`) is not kept, so alias/proxy substitutions are invisible in `models_used`. **Fix:** add a separate `servedModelId` field from the response while keeping the routed id for pricing. **Effort:** S. **Priority:** P3.+- [ ] **P3 — TODO-L: background skillopt jobs coalesce onto an earlier errored run.**+ **What:** `--background` submits with the fixed idempotency key `cli:skillopt:<skill>`; an `errored` run completes normally and keeps the key, so a retry with a raised cap returns the old job id. **Fix:** include the run parameters in the key (or free it on non-accepted outcomes) and report `coalesced` to the user. **Effort:** S. **Priority:** P3.+- [ ] **P3 — TODO-G: under-5-minute first skillopt run.**+ **What:** the first-ever run still takes ~20 minutes (bootstrap, review, strengthen judges). **Fix:** ship a pre-reviewed sample benchmark for one bundled skill and add a validated `split` param to the `run_skillopt` MCP op so agents can run the 15-task starter (`1:1:1`) without the CLI. **Effort:** M. **Priority:** P3.+## Remote MCP over Tailscale follow-ups (filed 2026-09-17, follow-up from v0.51.3.0, `gbrain mcp expose` wave)diff --git a/VERSION b/VERSIONindex 6df244a216..891f45f84d 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.0.0+0.59.2.0diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex a20980e84d..d2579ee860 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/migrations/v0_46_3.ts` — idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.-- `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 (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), 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}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `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 (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `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}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `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/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter.diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 70b9998560..3f4bd3bceb 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -11,7 +11,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/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts`+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex a098ee20a8..abf85e948a 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.-- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps (warn-once preserved when cap is unset); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases.+- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps (warn-once preserved when cap is unset); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math (`reservationCostUsd`, overrides, free local providers, unknown-price `null`) lives in the pure `src/core/budget/reservation-cost.ts`, shared with skillopt preflight's impossible-reservation check so the two cannot disagree. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases.- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex e67fb407ad..c471d88819 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/llm-json.ts` — tolerant JSON extraction from LLM output. `parseLlmJson<T>(raw, {array?})` walks a strategy ladder (strip ```json fences → direct parse → first `{...}`/`[...]` substring), then — only after the raw parse has failed — retries the same ladder with reasoning blocks stripped, so a payload that parses raw is untouched and a payload legitimately containing `<think>` is unaffected; returns null on any failure (adversarial throws swallowed). Exports `stripReasoningBlocks(raw)`: removes closed `<think>…</think>` pairs AND a truncated never-closed `<think>` tail (output-budget exhaustion) — reasoning models draft their JSON inside the think block, which defeats the greedy first-to-last-brace substring scan. `src/core/facts/extract.ts`'s hand-rolled `parseExtractorJsonDetailed` applies the same raw-first fallback ladder with the shared `stripReasoningBlocks`.-- `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`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.tier.<tier>` → `models.default` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback (the tier key sits ABOVE `models.default` — tier-specific beats generic, so setting a cheap utility tier is honored even when `models.default` is also set); `resolveModel()` is the thin wrapper for callers that only want the string. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→`expansion_model`, other tiers→`chat_model`, checked via `providerKeyReady`, `PIN_KEY_BY_TIER` is the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `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). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.+- `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`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.tier.<tier>` → `models.default` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback (the tier key sits ABOVE `models.default` — tier-specific beats generic, so setting a cheap utility tier is honored even when `models.default` is also set); `resolveModel()` is the thin wrapper for callers that only want the string. When the subagent capability gate replaces a configured model, the detailed result carries `substituted_from` + `substitution_reason` (`no_tools` / `no_subagent_loop` / `unknown_provider`); `describeResolveOrigin(source, opts)` renders the key-name origin (`models.tier.deep`, `models.default`, `GBRAIN_MODEL`, `built-in default`) used by the skillopt banner and `gbrain models`. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→`expansion_model`, other tiers→`chat_model`, checked via `providerKeyReady`, `PIN_KEY_BY_TIER` is the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `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). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex db7b11db5f..97489aff62 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -21,6 +21,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.+- `src/core/skillopt/{reflect,output-cap,run-outcome,remediation,checkpoint,models-plan,job,bootstrap-run,must-abort,preflight}.ts` — skillopt run honesty and model provenance (user docs: `docs/guides/skillopt.md` "Optimizer output" + "Model provenance"). **Output caps** (`output-cap.ts`): one optimizer cap for every reflect call (patch + rewrite modes) and the eval-internal one-shot ablation, precedence `--reflect-max-tokens` / MCP+job `reflect_max_tokens` (remote callers clamped to 256-32000) > `skillopt.reflect_max_tokens` (invalid warns once, valid honored exactly) > `defaultMaxOutputTokens(optimizer)` (32000 thinking, 4096 otherwise); `skilloptOutputCap(model, siteCap)` gives the judge (200) and bootstrap sites `max(siteCap, 8192)` on thinking models only — gateway `chat()` semantics are untouched. **Reply classification** (`reflect.ts`): at most one error per call, in precedence `reflect_<mode>_truncated` (length stop; partial edits dropped) > `_empty_reply` > `_no_parseable_edits` > `_invalid_edits`; a fenced or bare `{"edits": []}` is a deliberate, usable empty; partial invalid drops sum into `reflect_invalid_edits_dropped`; the skill body is sent whole when it fits `resolveChatContextTokens(optimizer)` minus output cap and bounded prompt overhead at 3 chars/token (unknown window → 120,000 chars), else truncated with an in-prompt disclosure + `skill_body_truncated`; prompt + cap over the window refuses the call (`_context_too_small`), provider length errors map to `_context_overflow`; the one-shot rewrite refuses on `one_shot_rewrite_output_cap_too_small` / `_body_truncated` and never promotes a `_truncated` reply. The judge records `judge_error: llm_truncated` and bootstrap rows skip as `truncated` on a length stop. **Must-abort** (`must-abort.ts`): budget exhaustion, AI spend-policy refusals, runtime deadline and SIGINT rethrow (the validation gate uses the same predicate) at every optimizer/judge/held-out/bootstrap site, so the run ends `aborted` with its real reason. **Outcome** (`run-outcome.ts`): `accepted` if any candidate was accepted (even after an early stop), `errored` with `abort_detail: optimizer_output_unusable: <first error>` when no optimizer reply in the whole run was usable, else `no_improvement`; 2 consecutive fully-unusable steps (any class) stop the loop (`stop_reason: early_stop_unusable_output`); `buildResumeCommand` rebuilds the exact resume command from the stored run spec plus the run's mode, cost cap, runtime cap, `--models-strict` and `--force` (only when the run used it; the dirty-tree gate admits a resume whose SKILL.md equals the checkpoint's best text); output-cap failures (from `abort_detail`, or the trailing reflect error of an early stop) double the reflect cap, contract failures put a quoted `'<other-model>'` in place of the optimizer model. An early-stopped run keeps its checkpoint and resume command even when it resolves `no_improvement`; a resume re-runs the trailing fully-unusable steps (`rewindCursor`) and restarts the early-stop streak, a kept checkpoint banks the final evaluation's spend and the rewound cursor is persisted before any save, the cycle's skillopt phase GCs kept checkpoints older than 7 days, and a legacy checkpoint whose best text moved past its baseline counts as already accepted. CLI exit map: accepted 0, no_improvement 1, aborted/errored 2. **Remediation** (`remediation.ts`): `SKILLOPT_REMEDIATION_CODES` → `{code, fix, docs}` receipt entries whose `docs` anchors into the guide's error-code table (pinned by `test/skillopt/error-code-docs.test.ts`); errors deduped, max 20 x 300 chars. **Checkpoint/resume** (`checkpoint.ts`): stores a `next_epoch`/`next_step` cursor (legacy checkpoints converted), the early-stop counter, the reflect tally, ledger rows and cost on completed steps and handled aborts (an abort saves the step-start tally, since resume re-runs that step), and a run spec; `--resume` refuses a changed benchmark/held-out/split or a no-mutate → mutate widening, and allows optimizer model, reflect cap and cost cap overrides; the receipt merges prior segments into `models_used` (`models_used_scope: full_run`, or `since_resume` for legacy checkpoints) plus `prior_segments_cost_usd`. **Models plan** (`models-plan.ts`): `resolveSkillOptModels` is the ONE role resolution (optimizer→tier deep, target→subagent, judge→reasoning; flag > config chain) used by the CLI, the `run_skillopt` op, the cycle phase and the job handler (four-path golden test); `buildModelsPlan` adds per-task judge overrides (benchmark + held-out; the default judge is inactive when no reachable LLM-judged task lacks its own `judge.model`), gateway expansion/chat with retained sources, the embedding model of the column search actually reads (file plane / `GBRAIN_EMBEDDING_MODEL`, never DB rows) and the reranker when enabled; the stderr banner prints before any spend and `models_plan` lands on the receipt + `run_start` audit. Strict mode (`--models-strict` / `skillopt.models_strict`; unrecognized values warn and count as on) aborts before spend when any active touchpoint came from `models_default`, `tier_default`, `fallback`, `unknown` or a capability substitution, listing a copy-paste fix per touchpoint (an unreadable `skillopt.models_strict` counts as on; an explicit `embedding_columns.embedding` override counts as configuration); it applies to batch, fleet, both bootstrap modes and background jobs. Echoed strings pass `sanitizeEcho` (control chars stripped, 200-char cap). **Jobs** (`job.ts`): job data records the model flags and strict setting; the handler re-resolves sources and re-runs the strict check at execution time, legacy jobs resolve as `unknown`. **Bootstrap** (`bootstrap-run.ts`): both bootstrap modes resolve the optimizer via the plan, print its banner row, honor strict and `--dry-run`, and run under a `--max-cost-usd` tracker. **Preflight** (`preflight.ts`): prices each role's per-call reservation with the tracker's `reservationCostUsd` at effective caps and aborts pre-spend with `reservation_exceeds_cap` naming the role; the heuristic expected-cost estimate is reported separately. The cycle phase forwards `abort_reason`/`abort_detail`/`run_id`/`remediation`, records `skipped_budget` (no calls; retried only after the admission fingerprint — optimizer/target/judge models, reflect cap, per-skill cap, `pricing.overrides`, gbrain version, benchmark content (unreadable benchmark re-admits) — changes) and gates `errored` retries 24h via `cycle.skillopt.last_error.<skill>` without banking `last_run`.+- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; non-TTY requires `--trust`), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.diff --git a/docs/guides/skillopt.md b/docs/guides/skillopt.mdindex e91e7bdc1e..554f80f9f1 100644--- a/docs/guides/skillopt.md+++ b/docs/guides/skillopt.md@@ -85,8 +85,10 @@ the audit event only; the full meta-edit proposal is a tracked follow-up.| `--optimizer-model MODEL` | tier.deep | Reflects + proposes || `--target-model MODEL` | tier.subagent | Executes the skill || `--judge-model MODEL` | tier.reasoning | Scores rollouts |-| `--patch \| --rewrite` | patch | Edit ops only vs. full rewrites |-| `--dry-run` | off | Cost preview, no LLM calls |+| `--reflect-max-tokens N` | `skillopt.reflect_max_tokens`, else 32000 (thinking optimizer) / 4096 | Output cap for every optimizer call. See [Optimizer output cap](#optimizer-output-cap) |+| `--models-strict` | `skillopt.models_strict`, else off | Abort before any spend unless every active model was explicitly configured. See [Strict mode](#strict-mode) |+| `--patch \| --rewrite` | patch | Edit ops only vs. full rewrites (both go through the validation gate) |+| `--dry-run` | off | Models banner, strict verdict and cost preview; zero model calls || `--no-mutate` | off | Write proposed.md, don't replace SKILL.md (no held-out needed) || `--allow-mutate-bundled` | off | Required to mutate gbrain-bundled skills in place — ALSO requires `--held-out` (>=5 rows) or the run hard-refuses || `--held-out <path>` | — | Independent test set (same JSONL shape as the benchmark, task IDs disjoint from it). A candidate that beats the benchmark but regresses on the held-out set is refused. Required for in-place bundled mutation. |@@ -98,11 +100,303 @@ the audit event only; the full meta-edit proposal is a tracked follow-up.## Exit codes-| Code | Meaning |-|---|---|-| 0 | Improved + accepted (or `--no-mutate` proposed.md written) |-| 1 | No improvement; best skill unchanged |-| 2 | Aborted by gate (dirty tree, over budget, bench validation, etc.) |+| Code | Outcome | Meaning |+|---|---|---|+| 0 | `accepted` | Improved + accepted (or `--no-mutate` proposed.md written) |+| 1 | `no_improvement` | The optimizer replied usably at least once; best skill unchanged |+| 2 | `aborted` / `errored` | Aborted by a gate (dirty tree, over budget, bench validation, etc.) or errored, including a run whose optimizer never produced a usable reply (`optimizer_output_unusable`) |++`--dry-run` exits 0, or 1 when strict mode is on and fails.++An `errored` or `aborted` run keeps its checkpoint, and so does a run that+stopped early. The summary prints the run id, the checkpoint path and the+exact resume command. An output-cap failure (a truncated reply, or a one-shot+cap too small for the body) doubles the reflect cap in that command. A+body-too-large or context-window refusal keeps the cap, because the cap+shares the context window. The command also carries the run's mode, cost+cap, runtime cap, `--models-strict`, and `--force` only when the run used+it. A resume accepts a SKILL.md with uncommitted changes when the file is+exactly the text the run itself accepted, so it never needs `--force` for its+own edit; any other change to the file still stops the resume. An early stop+takes its cap remedy from the trailing errors, so a run that stopped on+truncated replies doubles the cap even when it still reports+`no_improvement` or `accepted`. An edits-contract failure puts a quoted+`'<other-model>'` placeholder in place of the optimizer model. The JSON+receipt carries the same `run_id` and `resume_command`. `--resume` refuses+when the benchmark, held-out set or split changed, or when the run would+widen from no-mutate to mutate. You can override the optimizer model, the+reflect cap and the cost cap on resume. The cost cap applies to each run+segment: a resumed run gets a fresh `--max-cost-usd` on top of what earlier+segments spent (the receipt reports that as `prior_segments_cost_usd`), so+after a `budget_exhausted` abort, pass the extra budget you want to allow.+A resume re-runs the trailing steps whose optimizer output was all unusable,+so raising the cap and resuming retries them. Run the resume command in the+same brain context (`--brain`, `GBRAIN_BRAIN_ID` or the mount directory) as+the original run; the command does not carry the brain.++A run that accepted a candidate still reports `accepted` when it later stops+early. `stop_reason` records why the loop ended: `completed`,+`early_stop_unusable_output` or `aborted`.++## Optimizer output++**Say to your agent:** *"Why did skillopt propose no edits?"*++### Optimizer output cap++Every optimizer call has one output cap: both reflect calls in patch mode and+in `--rewrite` mode, plus the eval-internal one-shot rewrite ablation.+`--rewrite` itself works the same as before. Its edits still go through the+validation gate. The CLI does not expose the ungated one-shot path.++Where the cap comes from, highest precedence first:++1. `--reflect-max-tokens N` (MCP op / job param `reflect_max_tokens`, clamped+ to 256-32000 for remote callers).+2. `gbrain config set skillopt.reflect_max_tokens N`. It must be a positive+ integer. An invalid value warns once and falls back to the default. A valid+ value is used exactly, even when it is below the default.+3. The default: 32000 for thinking optimizers (Claude 5 family and other+ thinking-capable models), 4096 otherwise.++The banner shows the effective cap and its source. The receipt records it as+`reflect_max_tokens` and `reflect_max_tokens_source` (`flag`, `config` or+`default`). Every call reserves its full cap against `--max-cost-usd`. If one+call alone would reserve more than the cap, preflight aborts before any spend+and names the role (`reservation_exceeds_cap`).++The LLM judge and the bootstrap generators are **not** governed by this cap.+They keep their own small caps (judge 200 tokens, bootstrap rows 500-8000).+For thinking models those caps are raised to at least 8192, so reasoning+tokens don't use up the whole reply. A judge reply that still hits its cap+records `judge_error: llm_truncated`. A bootstrap row that hits its cap is+skipped, with `truncated` printed on stderr.++### What the optimizer sees++The optimizer gets the whole skill body when it fits the optimizer's context+window. Output cap and prompt overhead are reserved, and the budget assumes+3 chars/token. If the context size is unknown, the limit is 120,000 chars. A+body that does not fit is truncated. The prompt then says `(skill body+truncated: sent X of Y chars)` and the receipt records+`skill_body_truncated: {sent_chars, total_chars}`. The one-shot rewrite+refuses to run on a truncated body.++### Unusable replies fail loud++Each optimizer call records at most one error. When the reply hit the cap, its+partial edits are dropped. When a whole run never gets a usable optimizer+reply, the outcome is `errored` (exit 2), with+`abort_detail: optimizer_output_unusable: <first error>`. After 2 consecutive+steps where every optimizer call failed (any error class), the loop stops and+does not spend the rest of the budget. A deliberate `{"edits": []}` (fenced or+bare) is a usable "nothing to change" reply and is not an error.++Some replies are only partly usable: a few edits are malformed and the rest+are valid. The malformed edits are dropped and counted in+`reflect_invalid_edits_dropped`. That is not an error.++### Error codes++Each code in `reflect_errors` / `abort_detail` produces one receipt+`remediation` entry `{code, fix, docs}`, and `docs` links to the anchor below.+The reflect codes are emitted with a mode, as `reflect_failure_<class>` or+`reflect_success_<class>`. They are listed here once, without the mode.++| Code | Meaning | Cause | Fix |+|---|---|---|---|+| <a id="reflect_truncated"></a>`reflect_truncated` | Reflect reply hit the output cap | Cap too small for the optimizer's reasoning + edits JSON | Raise `--reflect-max-tokens` / `skillopt.reflect_max_tokens` |+| <a id="reflect_empty_reply"></a>`reflect_empty_reply` | Reflect reply was empty or whitespace | Optimizer is not following the edits JSON contract | Try a different `--optimizer-model` |+| <a id="reflect_no_parseable_edits"></a>`reflect_no_parseable_edits` | Reply had no parseable edits array | Optimizer is not following the edits JSON contract | Try a different `--optimizer-model` |+| <a id="reflect_invalid_edits"></a>`reflect_invalid_edits` | Every proposed edit failed validation | Optimizer is not following the edits JSON contract | Try a different `--optimizer-model` |+| <a id="reflect_context_too_small"></a>`reflect_context_too_small` | Call not made: prompt + output cap exceed the context window | Cap or prompt too large for the optimizer's window | Lower the cap, or use an `--optimizer-model` with a larger window |+| <a id="reflect_context_overflow"></a>`reflect_context_overflow` | Provider rejected the prompt as too long | Same as above, detected by the provider | Lower the cap, or use a larger-window `--optimizer-model` |+| <a id="reflect_failed"></a>`reflect_failed` | Reflect provider call failed | Provider/network/auth error | Check `gbrain models doctor`, then resume |+| <a id="one_shot_rewrite_truncated"></a>`one_shot_rewrite_truncated` | One-shot rewrite hit the output cap; nothing promoted | Cap too small for a full rewrite | Raise `--reflect-max-tokens` / `skillopt.reflect_max_tokens` |+| <a id="one_shot_rewrite_output_cap_too_small"></a>`one_shot_rewrite_output_cap_too_small` | One-shot refused before calling: the body cannot fit the cap | `ceil(body chars / 3) + 1024` exceeds the cap | Raise the cap, or use the default reflect mode |+| <a id="one_shot_rewrite_body_truncated"></a>`one_shot_rewrite_body_truncated` | One-shot refused: the body had to be truncated | Skill body larger than the optimizer's context | Lower the reflect cap (it shares the window), use a larger-window `--optimizer-model`, or use reflect mode |+| <a id="one_shot_rewrite_empty_reply"></a>`one_shot_rewrite_empty_reply` | One-shot reply was empty | Optimizer is not following the rewrite contract | Try a different `--optimizer-model` |+| <a id="one_shot_rewrite_failed"></a>`one_shot_rewrite_failed` | One-shot provider call failed | Provider/network/auth error | Check `gbrain models doctor`, then resume |+| <a id="budget_exhausted"></a>`budget_exhausted` | Run aborted at the cost cap | Spend (including each call's full-cap reservation) reached `--max-cost-usd` | Raise `--max-cost-usd` (cycle: `cycle.skillopt.per_skill_cap_usd`), or lower the reflect cap |+| <a id="runtime_exceeded"></a>`runtime_exceeded` | Run aborted at the wall-clock cap | `--max-runtime-min` reached | Raise `--max-runtime-min`, then resume |+| <a id="reservation_exceeds_cap"></a>`reservation_exceeds_cap` | No model call made: one call alone reserves more than the cost cap | Reflect cap x optimizer price exceeds `--max-cost-usd` / `cycle.skillopt.per_skill_cap_usd` | Lower the reflect cap, pick a cheaper model, or raise the cost cap |++In the dream cycle, a skill that hits `reservation_exceeds_cap` is recorded as+`skipped_budget` and makes no calls. It is retried only after+`skillopt.reflect_max_tokens`, `cycle.skillopt.per_skill_cap_usd`,+`pricing.overrides`, the skill's benchmark, the gbrain version or one of the+resolved optimizer, target or judge models changes. An `errored` cycle run does not update+`cycle.skillopt.last_run.<skill>`. It records+`cycle.skillopt.last_error.<skill>` instead, and the skill is retried no+sooner than 24h later.++Example `errored` summary (stderr):++```+[skillopt] Outcome: errored+[skillopt] Failure reason: error+[skillopt] Detail: optimizer_output_unusable: reflect_failure_truncated: 4096 output tokens, max_tokens=4096+[skillopt] Stopped early: optimizer output was unusable for consecutive steps; remaining budget not spent.+[skillopt] Warning: 2 optimizer reply error(s) (optimizer output cap 4096); first: reflect_failure_truncated: 4096 output tokens, max_tokens=4096+[skillopt] Fix (reflect_truncated): The optimizer ran out of output tokens. Raise the cap: --reflect-max-tokens <n> or gbrain config set skillopt.reflect_max_tokens <n>. See docs/guides/skillopt.md#reflect_truncated+[skillopt] Run id: so-20260928-1a2b3c+[skillopt] Checkpoint: skills/meeting-prep/skillopt/checkpoint-so-20260928-1a2b3c.json+[skillopt] Resume: gbrain skillopt meeting-prep --resume so-20260928-1a2b3c --skills-dir skills --benchmark skills/meeting-prep/skillopt-benchmark.jsonl --split 4:1:5 --epochs 4 --batch-size 8 --lr 4 --lr-schedule cosine --optimizer-model openai:gpt-5.2 --target-model anthropic:claude-sonnet-5 --judge-model anthropic:claude-sonnet-5 --reflect-max-tokens 8192 --max-cost-usd 5 --max-runtime-min 30+```++## Model provenance++**Say to your agent:** *"Show me which models my skillopt run actually called"*++### Models banner++Before any spend (and on `--dry-run`), skillopt prints every touchpoint the+run can call. Each row shows the model and the flag, key or env var that chose+it:++```+[skillopt] Models:+[skillopt] optimizer anthropic:claude-fable-5-1 (--optimizer-model)+[skillopt] target anthropic:claude-sonnet-5 (models.tier.subagent)+[skillopt] judge anthropic:claude-sonnet-5 (models.tier.reasoning)+[skillopt] expansion anthropic:claude-opus-5 (models.default) *+[skillopt] chat anthropic:claude-sonnet-5 (built-in default) *+[skillopt] embedding openai:text-embedding-3-large (~/.gbrain/config.json embedding_model)+[skillopt] optimizer output cap 32000 tokens (default)+[skillopt] * not chosen by touchpoint-specific configuration (models.default, a built-in default, a substitution or unknown provenance); --models-strict aborts on these+```++`expansion` is the query-expansion model that the target agent's search tool+calls use. The reranker row appears only when search enables it. Per-task+`judge.model` overrides (benchmark and held-out) are listed with origin+`benchmark`. When no reachable task uses an LLM judge, the judge row reads+`(inactive: rule/qrels benchmark)`. When a configured subagent model can't do+tool calls and is replaced, the row shows `-> substituted: <reason>`. Under+`--all` the banner prints once. After that, a per-skill block appears only+when a skill's plan differs, for example because of task judge overrides.+The receipt stores the plan as `models_plan`, and the `run_start` audit event+carries it too.++### Models called++After the run, the summary prints every model the run actually called. That+includes engine-internal calls, such as query expansion inside rollouts and+embeddings:++```+[skillopt] Models called (full run; a call is one gateway operation, internal retries count once; ~ = estimated cost):+[skillopt] touchpoint purpose model calls tokens in/out cost+[skillopt] chat skillopt.optimizer anthropic:claude-fable-5-1 8 182340/41210 $1.9421+[skillopt] chat skillopt.target anthropic:claude-sonnet-5 40 311200/52800 $1.7256+[skillopt] expansion engine anthropic:claude-opus-5 71 (72 attempts) 21300/7100 $0.2840+[skillopt] embedding engine openai:text-embedding-3-large 71 2130/0 ~$0.0003+```++Each row counts gateway operations for one (requested model, served model,+touchpoint, purpose) pair. SDK-internal retries count once. `attempts`+counts every recorded attempt, for example a structured-output fallback+inside one expansion. The purpose is `skillopt.optimizer`, `skillopt.target`+or `skillopt.judge` for the three roles, and `engine` for engine-internal+calls. Failed calls are counted. `~` means the cost was estimated (for+example from char-estimated embedding tokens). `unpriced` means the model has+no price entry. The receipt stores these rows as `models_used`, and the+`run_end` audit event carries them too.++On resume, earlier segments' rows are merged in (`models_used_scope:+'full_run'`) and `prior_segments_cost_usd` records their spend.+`final_cost_usd` covers this segment only. A checkpoint written before this+ledger existed gives `models_used_scope: 'since_resume'`.++### JSON receipt++`--json` prints the receipt on stdout (abridged):++```json+{+ "schema_version": 1,+ "outcome": "errored",+ "receipt": {+ "run_id": "so-20260928-1a2b3c",+ "skill": "meeting-prep",+ "outcome": "errored",+ "abort_reason": "error",+ "abort_detail": "optimizer_output_unusable: reflect_failure_truncated: 4096 output tokens, max_tokens=4096",+ "stop_reason": "early_stop_unusable_output",+ "reflect_errors": ["reflect_failure_truncated: 4096 output tokens, max_tokens=4096"],+ "reflect_invalid_edits_dropped": 0,+ "reflect_max_tokens": 4096,+ "reflect_max_tokens_source": "default",+ "remediation": [+ { "code": "reflect_truncated", "fix": "The optimizer ran out of output tokens. Raise the cap: ...", "docs": "docs/guides/skillopt.md#reflect_truncated" }+ ],+ "resume_command": "gbrain skillopt meeting-prep --resume so-20260928-1a2b3c ... --reflect-max-tokens 8192",+ "models_plan": [+ { "touchpoint": "expansion", "model": "anthropic:claude-opus-5", "source": "models_default", "origin": "models.default", "active": true }+ ],+ "models_strict": { "enabled": false, "ok": false, "violations": [ { "touchpoint": "expansion", "model": "anthropic:claude-opus-5", "source": "models_default", "origin": "models.default", "fix": "gbrain config set models.tier.utility anthropic:claude-opus-5" } ] },+ "models_used": [+ { "requested_model": "anthropic:claude-opus-5", "model": "anthropic:claude-opus-5", "touchpoint": "expansion", "purpose": null, "calls": 29, "attempts": 30, "failed_calls": 0, "input_tokens": 8700, "output_tokens": 2900, "cost_usd": 0.116, "cost_basis": "measured" }+ ],+ "models_used_scope": "full_run"+ }+}+```++The `run_skillopt` MCP op, background job results and the cycle phase carry+the same `remediation`, `abort_reason`, `abort_detail` and `run_id`.++### Strict mode++**Say to your agent:** *"Run skillopt only with models I've explicitly configured"*++```bash+gbrain skillopt my-skill --models-strict --dry-run # preview the verdict, zero calls+gbrain config set skillopt.models_strict true # enforce for every run+```++Strict mode guarantees that **every active model was chosen by explicit,+touchpoint-specific configuration**. It does not pin a model identity, and+aliases are allowed. Explicit means: a CLI flag, a role or tier key+(`models.tier.*`, `models.chat`, ...), an env var, the servable `config.json`+pin, a benchmark task's `judge.model`, or an embedding/reranker key.+`models.default` does **not** count. It is a catch-all that silently decides+touchpoints you never looked at, such as query expansion. Built-in defaults,+capability substitutions and unknown provenance (for example a legacy+background job) don't count either.++The check covers every touchpoint the run *could* call: optimizer, target,+the judge (when some reachable task uses an LLM judge without its own+`judge.model`), expansion, chat, embedding, and the reranker when it is+enabled. It checks these before any spend, even ones a given run may never+end up calling. It applies to the CLI, the MCP op, the cycle phase, background+jobs (re-checked when the job runs), `--all`, `--target-models` fleets and+both bootstrap modes. A violation aborts with each offending touchpoint and a+copy-paste fix:++```+models strict check: 1 active model touchpoint(s) were not chosen by touchpoint-specific configuration:+ expansion anthropic:claude-opus-5 (models.default)+ gbrain config set models.tier.utility anthropic:claude-opus-5+```++For an embedding violation, the fix points to `embedding_model` in+`~/.gbrain/config.json` or `GBRAIN_EMBEDDING_MODEL`, since changing it needs+an embedding migration. `skillopt.models_strict` accepts+`true|1|yes|on` and `false|0|no|off|empty`. Any other value warns once and+counts as **on**, and so does a setting that cannot be read.++What strict mode does not cover: the check runs on the plan before spend. A+rollout that asks a search tool for a specific, non-default embedding column+is not re-checked at call time.++### Newer models (`gbrain models`)++`gbrain models` adds an advisory `[newer <family> available: <id>]` hint, with+the `gbrain config set` command, when a configured Anthropic haiku/sonnet/opus+model is older than the newest priced model of the same family in the recipe.+Dated and undated ids of the same version compare equal. The hint is+informational only. Built-in defaults are unchanged, and a validated+default-model migration is tracked separately.## Cost modeldiff --git a/docs/tutorials/improving-skills-with-skillopt.md b/docs/tutorials/improving-skills-with-skillopt.mdindex b1f32a07b4..1161fb7d75 100644--- a/docs/tutorials/improving-skills-with-skillopt.md+++ b/docs/tutorials/improving-skills-with-skillopt.md@@ -159,13 +159,19 @@ Before spending anything, see what the run will cost:gbrain skillopt meeting-prep --split 1:1:1 --dry-run```-This makes **zero LLM calls** — it just prints the plan and the cost estimate.-A ~15-task benchmark with defaults runs around $0.70–$1.00. The preflight refuses-to start a real run whose estimate exceeds `--max-cost-usd` (default $5.00), so-you can't get surprise-billed mid-run.--> `--dry-run` exits with code **2** ("aborted"). That's the convention for "did-> not run the optimization," not a failure. The cost line is what you came for.+This makes **zero LLM calls**. It prints the models banner, the strict-mode+verdict and the cost estimate. The banner lists every model the run can call+(optimizer, target, judge, plus engine-internal query expansion, chat and+embedding), each with the flag or config key that chose it. A row marked `*`+came from `models.default` or a built-in default rather than configuration+you set for that touchpoint. A ~15-task benchmark with defaults runs around+$0.70–$1.00. The preflight refuses to start a real run whose estimate exceeds+`--max-cost-usd` (default $5.00), so you can't get surprise-billed mid-run.++> `--dry-run` exits **0**. It exits 1 only when strict mode is on+> (`--models-strict` / `skillopt.models_strict`) and some model was not+> explicitly configured. The abort lists a `gbrain config set` line for each+> offending touchpoint.## Step 3: Run it for real@@ -193,7 +199,11 @@ When it finishes, the last lines tell you everything:|---|---|---|---|| `accepted` | 0 | A candidate beat the baseline. SKILL.md was rewritten (or a proposed file written — see Step 5). | Review the diff, keep it. || `no_improvement` | 1 | Nothing cleared the gate. Your skill is already good, or the benchmark can't tell good from bad. | Strengthen the benchmark (Step 6) or stop. |-| `aborted` | 2 | A gate stopped it: dirty working tree, over budget, `D_sel < 5`, or `--dry-run`. | Read the message — it names the gate. |+| `aborted` | 2 | A gate stopped it: dirty working tree, over budget, `D_sel < 5`. | Read the message — it names the gate. |+| `errored` | 2 | Something broke, for example the optimizer never produced a usable reply (`optimizer_output_unusable`). It usually ran out of output tokens or ignored the edits JSON format. | Follow the printed `Fix (<code>)` line, then run the printed `Resume:` command. |++The summary also prints a "Models called" table showing every model the run+actually used, engine-internal calls included, with calls, tokens and cost.`no_improvement` is not a failure. It's the gate doing its job: it would ratherkeep your known-good skill than accept a change it can't prove is better.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 4a38385a09..14b58cc37a 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex e5d860b072..b8b8d1c8b5 100644--- a/package.json+++ b/package.json@@ -182,7 +182,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.0.0",+ "version": "0.59.2.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 243fb2d62d..427ffbc0dd 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex e79d0cdf48..7a00007c36 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 8d0719fdd6..01608df8f8 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.2.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 3ad0328726..9bad349503 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex ca516bbe30..ce2eac4cbe 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.0.0",+ "version": "0.59.2.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex c41874f1ec..ed07e6f415 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.2.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 551010cada..6038b4a13d 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.2.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 02c0f7a2eb..61c2887e58 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -15,6 +15,22 @@// No brace expansion, no ?, no [ ].export const E2E_TEST_MAP: Record<string, string[]> = {+ // SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger.+ "src/core/skillopt/**": [+ "test/e2e/skillopt-loop.serial.test.ts",+ "test/e2e/skillopt-pglite.serial.test.ts",+ "test/e2e/skillopt-outcome.serial.test.ts",+ "test/e2e/skillopt-models-strict.serial.test.ts",+ "test/e2e/skillopt-models-used.serial.test.ts",+ "test/e2e/dream-cycle-phase-order-pglite.test.ts",+ ],+ "src/commands/skillopt.ts": [+ "test/e2e/skillopt-loop.serial.test.ts",+ "test/e2e/skillopt-pglite.serial.test.ts",+ "test/e2e/skillopt-outcome.serial.test.ts",+ "test/e2e/skillopt-models-strict.serial.test.ts",+ "test/e2e/skillopt-models-used.serial.test.ts",+ ],"src/core/company-brain/receipts.ts": ["test/e2e/company-brain-receipts.test.ts"],"src/core/company-brain/receipt-schema.ts": ["test/e2e/company-brain-receipts.test.ts"],"src/core/minions/errors.ts": ["test/e2e/subagent-gateway-path.test.ts", "test/e2e/delegated-http-worker.test.ts", "test/e2e/subagent-crash-replay-multi-provider.test.ts"],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 76390f260a..1ed4f67102 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -9,9 +9,9 @@ src/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checsrc/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiringsrc/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)src/commands/extract.ts 2571 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain-src/commands/jobs.ts 3210 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration+src/commands/jobs.ts 3173 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check)src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks-src/core/ai/gateway.ts 4500 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed+src/core/ai/gateway.ts 4439 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removedsrc/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatchsrc/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:falsesrc/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegatesdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex df8e027c7c..fbc28a4536 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -290,6 +290,7 @@ test/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modtest/skillify-scaffold.test.ts applyScaffold 3 readFileSynctest/skillify-scaffold.test.ts planScaffold 13 readFileSynctest/skillopt/deadline-and-hermetic.test.ts #4741 — hermetic-config docs make no platform-survives-logout claim 2 readFileSync+test/skillopt/error-code-docs.test.ts skillopt error-code table 3 readFileSynctest/skillpack-check-report-only.test.ts (file-level) 2 readFileSynctest/skillpack-harness-bridge.test.ts review-driven hardening (ship pre-landing findings) 5 readFileSynctest/skillpack-harvest.test.ts addToBundleManifest 1 readFileSyncdiff --git a/skills/migrations/v0.59.2.0.md b/skills/migrations/v0.59.2.0.mdnew file mode 100644index 0000000000..f8b8e4d7c6--- /dev/null+++ b/skills/migrations/v0.59.2.0.md@@ -0,0 +1,46 @@+# Upgrade to v0.59.2.0: skillopt reports unusable optimizer output and model provenance++This release changes how `gbrain skillopt` reports a run whose optimizer model+never returned usable edits, and records which models every run used. No+database migration, new provider key or paid call is required.++1. **Scripts and schedulers that run `gbrain skillopt`:** a run where no+ optimizer reply was usable now ends `errored` with exit code 2 (it used to+ end `no_improvement` with exit 1). If a wrapper treats exit 1 as "nothing to+ do" and anything else as a failure, it will now correctly flag these runs.+ Do not remap exit 2 back to success. Read the printed `Fix (...)` line and+ `Resume:` command, or the receipt's `remediation` and `resume_command`.++2. **Nightly dream cycle (`cycle.skillopt.enabled true`):** check the most+ recent cycle report for skillopt rows with outcome `skipped_budget`:++ ```bash+ gbrain skillopt <skill> --dry-run+ ```++ A `skipped_budget` row means one optimizer call alone reserves more than+ `cycle.skillopt.per_skill_cap_usd`. This is expected for a Claude 5 thinking+ optimizer at the default $0.50 cap, because thinking optimizers now get a+ 32,000-token output cap. Tell the user and offer one of the fixes the row+ lists. Do not change their cost cap without asking:+ - `gbrain config set cycle.skillopt.per_skill_cap_usd <usd>`+ - `gbrain config set skillopt.reflect_max_tokens <n>`+ - a cheaper `models.tier.deep` optimizer++ The skill is retried automatically once one of those settings changes.++3. **Optional, only when the user wants it:** strict model provenance.+ `gbrain skillopt <skill> --models-strict --dry-run` previews whether every+ model the run would call was chosen explicitly. Enable it for every run+ with `gbrain config set skillopt.models_strict true` only if the user asks.++4. **Verify:**++ ```bash+ gbrain --version+ gbrain skillopt --help # lists --reflect-max-tokens and --models-strict+ gbrain models # sources attributed; advisory newer-model hints+ ```++ The `gbrain models` newer-model hint is advisory. Do not change model+ defaults or tier keys because of it unless the user asks.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex b835ea59de..0fd1f316dd 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -149,6 +149,7 @@"migrations/v0.56.2.0.md": "e88f04a5deaef82ebb8bd194aec931f26e69e87687098eb64b94666931b5e319","migrations/v0.58.0.0.md": "a6ee3d3125ff1be612df776c7b8d6dfcaeb57ca073255793a67dff78a23c51cc","migrations/v0.59.0.0.md": "7903e547e79ad3429a393d9102a610e2674388bfaa71607431b1cd857b4af939",+ "migrations/v0.59.2.0.md": "b6d61af8ef48c154a26e8d427dd6f6570e99efb82b891728426046eea493247b","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a","migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex f5f79ac791..f6770bab04 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -3144,47 +3144,10 @@ export async function registerBuiltinHandlers(// v0.42.0.0 SkillOpt Minion handler — for --background CLI invocations.// PROTECTED by name so MCP submission rejects (only trusted CLI can- // submit). Threaded SkillOptOpts JSON in job.data.- worker.register('skillopt', async (job) => {- const { runSkillOpt } = await import('../core/skillopt/orchestrator.ts');- const data = (job.data ?? {}) as Record<string, unknown>;- const skillsDir = String(data.skills_dir ?? '');- const skillName = String(data.skill_name ?? '');- const benchmarkPath = String(data.benchmark_path ?? '');- if (!skillsDir || !skillName || !benchmarkPath) {- throw new Error(`skillopt handler: missing required job.data fields (skills_dir, skill_name, benchmark_path)`);- }- const result = await runSkillOpt({- engine,- skillName,- skillsDir,- benchmarkPath,- epochs: Number(data.epochs ?? 4),- batchSize: Number(data.batch_size ?? 8),- lr: Number(data.lr ?? 4),- lrSchedule: (data.lr_schedule as 'cosine' | 'linear' | 'constant') ?? 'cosine',- split: (data.split as [number, number, number]) ?? [4, 1, 5],- optimizerModel: String(data.optimizer_model ?? 'anthropic:claude-opus-4-7'),- targetModel: String(data.target_model ?? 'anthropic:claude-sonnet-4-6'),- judgeModel: String(data.judge_model ?? 'anthropic:claude-sonnet-4-6'),- mode: (data.mode as 'patch' | 'rewrite') ?? 'patch',- dryRun: Boolean(data.dry_run),- noMutate: Boolean(data.no_mutate),- allowMutateBundled: Boolean(data.allow_mutate_bundled),- bootstrapReviewed: Boolean(data.bootstrap_reviewed),- ...(data.held_out_path ? { heldOutPath: String(data.held_out_path) } : {}),- json: true,- maxCostUsd: Number(data.max_cost_usd ?? 5.0),- maxRuntimeMin: Number(data.max_runtime_min ?? 30),- force: Boolean(data.force),- });- return {- outcome: result.outcome,- receipt: result.receipt,- mutated_skill_file: result.mutatedSkillFile,- proposed_path: result.proposedPath,- };- });+ // submit). Body in skillopt/job.ts: re-resolves the role models and re-runs+ // the strict check at execution time.+ worker.register('skillopt', async (job) =>+ (await import('../core/skillopt/job.ts')).runSkillOptJob(engine, job.data));process.stderr.write('[minion worker] brain-health-100 handlers registered (12 ops, 4 protected) + embed-backfill (v0.40) + embed-catch-up (v0.42) + unify-types (v0.42) + skillopt (v0.42.0.0, protected)\n');diff --git a/src/commands/models.ts b/src/commands/models.tsindex 00bbe00ce0..dc58b4dea6 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -7,9 +7,12 @@* tier defaults, the resolved value for each* (after consulting models.default + models.tier.*),* per-task overrides, alias map, and source-of-truth- * column (default / config / env).+ * column (default / config / env). An older+ * Anthropic haiku/sonnet/opus id gets an+ * advisory `[newer <family> available: <id>]`+ * hint plus the config command.*- * `gbrain models doctor` — opt-in probe. Fires a 1-token `gateway.chat()`+ * `gbrain models doctor` — opt-in probe. Fires a 1-token `gateway.chat()`* call against each configured chat / expansion* model and reports reachability with the* provider's error string. Catches the bug class@@ -31,12 +34,16 @@ import type { BrainEngine } from '../core/engine.ts';import {DEFAULT_ALIASES,TIER_DEFAULTS,- resolveModel,+ describeResolveOrigin,+ resolveModelDetailed,resolveAlias,type ModelTier,+ type ResolveModelOpts,+ type ResolveSource,} from '../core/model-config.ts';import { resolveExtractAtomsModelWithSource } from '../core/cycle/extract-atoms.ts';import { maybeAttachVersionSuffixHint } from '../core/ai/base-url-probe.ts';+import { newerAnthropicModel } from '../core/ai/anthropic-model-ids.ts';import type { AIGatewayConfig } from '../core/ai/types.ts';const TIERS: ModelTier[] = ['utility', 'reasoning', 'deep', 'subagent'];@@ -102,42 +109,63 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [{ key: 'models.chat', tier: 'reasoning', description: 'Default `gateway.chat()` model' },];+interface NewerAvailable {+ family: string;+ model: string;+ command: string;+}+interface ModelEntry {tier: ModelTier;resolved: string;source: string; // "default" | "config: <key>" | "env: <VAR>"+ newer_available?: NewerAvailable;+}++interface PerTaskEntry {+ key: string;+ tier: ModelTier;+ resolved: string;+ source: string;+ description: string;+ newer_available?: NewerAvailable;}interface ModelsReport {schema_version: 1;global_default: { value: string | null };tiers: Record<ModelTier, ModelEntry>;- per_task: Array<{ key: string; tier: ModelTier; resolved: string; source: string; description: string }>;+ per_task: PerTaskEntry[];aliases: { defaults: Record<string, string>; user: Record<string, string> };}-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). 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;+/**+ * Report label for the chain step `resolveModelDetailed` says won, so the+ * attribution can never disagree with the resolved value. Built-in defaults+ * render as `inheritedLabel` (`default` for tier rows, `tier.<tier>` for+ * per-task rows).+ */+function sourceLabel(+ source: ResolveSource,+ opts: Pick<ResolveModelOpts, 'configKey' | 'deprecatedConfigKey' | 'envVar' | 'tier'>,+ inheritedLabel: string,+): string {+ if (source === 'tier_default' || source === 'fallback') return inheritedLabel;+ const origin = describeResolveOrigin(source, opts);+ return source === 'env' ? `env: ${origin}` : `config: ${origin}`;+}++/**+ * Advisory `[newer <family> available]` hint: set when `resolved` is an+ * Anthropic haiku/sonnet/opus id older than the anthropic recipe's newest+ * priced id in the same family. `configKey` is the key the paste-ready fix+ * sets. Defaults are never changed by this.+ */+function newerAvailable(resolved: string, configKey: string): NewerAvailable | undefined {+ const newer = newerAnthropicModel(resolved);+ if (!newer) return undefined;+ const model = `anthropic:${newer.id}`;+ return { family: newer.family, model: newer.id, command: `gbrain config set ${configKey} ${model}` };}async function buildReport(engine: BrainEngine): Promise<ModelsReport> {@@ -145,23 +173,21 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {const tiers = {} as Record<ModelTier, ModelEntry>;for (const t of TIERS) {- const tierOverride = await engine.getConfig(`models.tier.${t}`);- // What models.default beats tier — re-walk the chain to attribute properly.- let source: string;- if (globalDefault && globalDefault.trim()) {- source = 'config: models.default';- } else if (tierOverride && tierOverride.trim()) {- source = `config: models.tier.${t}`;- } else {- source = 'default';- }- const resolved = await resolveModel(engine, { tier: t, fallback: TIER_DEFAULTS[t] });- tiers[t] = { tier: t, resolved, source };+ const detail = await resolveModelDetailed(engine, { tier: t, fallback: TIER_DEFAULTS[t] });+ const newer = newerAvailable(detail.model, `models.tier.${t}`);+ tiers[t] = {+ tier: t,+ resolved: detail.model,+ source: sourceLabel(detail.source, { tier: t }, 'default'),+ ...(newer ? { newer_available: newer } : {}),+ };}const per_task: ModelsReport['per_task'] = [];for (const route of PER_TASK_KEYS) {const { key, tier, description, deprecatedConfigKey, envVar, overrideKey, narrowResolver } = route;+ // Per-task rows carry the hint only when the row's OWN key supplied the+ // model; inherited rows follow their tier row, which already reports it.// A caller with its own narrower resolution (doesn't honor models.tier.*// / models.default / env var) reports via that exact resolver, not the// generic resolveModel() chain — see PerTaskModelRoute.narrowResolver.@@ -171,7 +197,8 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {// reflects (previously a separate getConfig truthiness re-check).const { model: resolved, source: narrowSource } = await narrowResolver(engine);const source = narrowSource === 'config' ? `config: ${key}` : `tier.${tier} (caller-specific)`;- per_task.push({ key, tier, resolved, source, description });+ const newer = narrowSource === 'config' ? newerAvailable(resolved, key) : undefined;+ per_task.push({ key, tier, resolved, source, description, ...(newer ? { newer_available: newer } : {}) });continue;}// Explicit pre-read override (loadSynthConfig 2A parity): when set, it IS@@ -179,19 +206,22 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {const overrideValue = overrideKey ? await engine.getConfig(overrideKey) : null;if (overrideKey && overrideValue?.trim()) {const resolved = await resolveAlias(engine, overrideValue.trim());- per_task.push({ key, tier, resolved, source: `config: ${overrideKey}`, description });+ const newer = newerAvailable(resolved, overrideKey);+ per_task.push({ key, tier, resolved, source: `config: ${overrideKey}`, description, ...(newer ? { newer_available: newer } : {}) });continue;}- const resolved = await resolveModel(engine, {- configKey: key,- deprecatedConfigKey,- envVar,+ const opts = { configKey: key, deprecatedConfigKey, envVar, tier };+ const detail = await resolveModelDetailed(engine, { ...opts, fallback: TIER_DEFAULTS[tier] });+ const ownKey = detail.source === 'config_key' || detail.source === 'deprecated_key';+ const newer = ownKey ? newerAvailable(detail.model, key) : undefined;+ per_task.push({+ key,tier,- fallback: TIER_DEFAULTS[tier],+ resolved: detail.model,+ source: sourceLabel(detail.source, opts, `tier.${tier}`),+ description,+ ...(newer ? { newer_available: newer } : {}),});- const explicit = await probeSource(engine, route);- const source = explicit ?? `tier.${tier}`;- per_task.push({ key, tier, resolved, source, description });}// User-defined aliases (engine.getConfig is the source; we don't enumerate@@ -211,12 +241,16 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {};}+function formatNewer(newer: NewerAvailable | undefined): string {+ return newer ? ` [newer ${newer.family} available: ${newer.model}] (${newer.command})` : '';+}+function formatText(report: ModelsReport): string {const lines: string[] = [];lines.push('Tier routing:');for (const t of TIERS) {const e = report.tiers[t];- lines.push(` tier.${t.padEnd(10)} ${e.resolved.padEnd(45)} [${e.source}]`);+ lines.push(` tier.${t.padEnd(10)} ${e.resolved.padEnd(45)} [${e.source}]${formatNewer(e.newer_available)}`);}lines.push('');lines.push('Global default:');@@ -224,7 +258,7 @@ function formatText(report: ModelsReport): string {lines.push('');lines.push('Per-task overrides:');for (const t of report.per_task) {- lines.push(` ${t.key.padEnd(34)} → ${t.resolved.padEnd(45)} [${t.source}]`);+ lines.push(` ${t.key.padEnd(34)} → ${t.resolved.padEnd(45)} [${t.source}]${formatNewer(t.newer_available)}`);}lines.push('');lines.push('Aliases:');diff --git a/src/commands/skillopt.ts b/src/commands/skillopt.tsindex 5445df1cdf..2af043d50c 100644--- a/src/commands/skillopt.ts+++ b/src/commands/skillopt.ts@@ -6,14 +6,26 @@*/import * as path from 'node:path';-import { resolveModel } from '../core/model-config.ts';import { autoDetectSkillsDirReadOnly } from '../core/repo-root.ts';-import { runBootstrap, runBootstrapFromSkill } from '../core/skillopt/bootstrap-benchmark.ts';+import { runGuardedBootstrap } from '../core/skillopt/bootstrap-run.ts';+import { buildSkillOptJobData } from '../core/skillopt/job.ts';+import {+ buildModelsPlan,+ describeStrictVerdict,+ formatModelsBanner,+ resolveSkillOptModels,+ skillOptModelOpts,+ type ModelsPlanEntry,+ type StrictVerdict,+} from '../core/skillopt/models-plan.ts';import { SKILLOPT_HELP_TEXT } from '../core/skillopt/help.ts';import { runSkillOpt, parseSplit } from '../core/skillopt/orchestrator.ts';+import { checkpointPath } from '../core/skillopt/checkpoint.ts';+import { formatModelsUsedTable } from '../core/budget/models-used.ts';+import { parsePositiveInt } from '../core/skillopt/output-cap.ts';import { serializeError, StructuredAgentError } from '../core/errors.ts';import type { BrainEngine } from '../core/engine.ts';-import type { SkillOptOpts } from '../core/skillopt/types.ts';+import type { RunReceipt, SkillOptOpts } from '../core/skillopt/types.ts';interface ParsedFlags {skillName: string;@@ -31,6 +43,10 @@ interface ParsedFlags {optimizerModel?: string;targetModel?: string;judgeModel?: string;+ /** Optimizer output cap; beats skillopt.reflect_max_tokens config. */+ reflectMaxTokens?: number;+ /** Abort before spend unless every active model was chosen by explicit configuration. */+ modelsStrict: boolean;mode: 'patch' | 'rewrite';dryRun: boolean;noMutate: boolean;@@ -85,47 +101,34 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strinprocess.exit(2);}- // Resolve models via the tier system.- const optimizerModel = parsed.optimizerModel- ?? await resolveModel(engine, { tier: 'deep', fallback: 'anthropic:claude-opus-4-7' });- const targetModel = parsed.targetModel- ?? await resolveModel(engine, { tier: 'subagent', fallback: 'anthropic:claude-sonnet-4-6' });- const judgeModel = parsed.judgeModel- ?? await resolveModel(engine, { tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' });+ // Resolve the three roles once (flag > role config chain), with provenance.+ const modelFlags = { optimizerModel: parsed.optimizerModel, targetModel: parsed.targetModel, judgeModel: parsed.judgeModel };+ const models = await resolveSkillOptModels(engine, modelFlags);+ const { optimizerModel, targetModel, judgeModel } = skillOptModelOpts(models);- // ── Bootstrap mode (short-circuits before the optimization loop) ────────- if (parsed.bootstrapFromRouting) {+ // ── Bootstrap modes (short-circuit before the optimization loop) ────────+ // --bootstrap-from-skill reads SKILL.md directly (no routing-eval needed)+ // and emits a full starter benchmark; --bootstrap-from-routing makes one+ // call per routing intent. Both write the D15 sentinel, run under the+ // --max-cost-usd tracker and honor --models-strict / --dry-run. Provider+ // errors propagate so the user sees the real failure instead of "0 tasks".+ if (parsed.bootstrapFromRouting || parsed.bootstrapFromSkill) {try {- const result = await runBootstrap({- skillsDir,- skillName: parsed.skillName,- optimizerModel,- force: parsed.force,- });- if (parsed.json) {- process.stdout.write(JSON.stringify({ ok: true, ...result }) + '\n');- }- process.exit(0);- } catch (err) {- handleErrorAndExit(err, parsed.json, 2);- }- }-- // ── Bootstrap-from-skill mode (short-circuits before the optimization loop) ─- // Reads SKILL.md directly (no routing-eval needed), emits a full starter- // benchmark, writes the D15 sentinel. Provider errors propagate so the user- // sees the real failure instead of "0 tasks".- if (parsed.bootstrapFromSkill) {- try {- const result = await runBootstrapFromSkill({+ const run = await runGuardedBootstrap({+ engine,+ mode: parsed.bootstrapFromRouting ? 'routing' : 'skill',skillsDir,skillName: parsed.skillName,- optimizerModel,+ optimizer: models.optimizer,taskCount: parsed.bootstrapTasks ?? 15,force: parsed.force,+ dryRun: parsed.dryRun,+ modelsStrict: parsed.modelsStrict,+ maxCostUsd: parsed.maxCostUsd,});+ if (run.dry_run) exitDryRun(run.models_plan, run.strict, parsed.json, {});if (parsed.json) {- process.stdout.write(JSON.stringify({ ok: true, ...result }) + '\n');+ process.stdout.write(JSON.stringify({ ok: true, ...run.result, cost_usd: run.cost_usd, models_plan: run.models_plan }) + '\n');}process.exit(0);} catch (err) {@@ -137,6 +140,8 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strinif (parsed.all) {try {const { runBatchAll } = await import('../core/skillopt/batch.ts');+ const basePlan = await buildModelsPlan(engine, models);+ process.stderr.write(formatModelsBanner(basePlan));const result = await runBatchAll({engine,skillsDir,@@ -145,6 +150,10 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strinoptimizerModel,targetModel,judgeModel,+ models,+ modelsStrict: parsed.modelsStrict,+ modelsBannerBaseline: basePlan,+ ...(parsed.reflectMaxTokens !== undefined ? { reflectMaxTokens: parsed.reflectMaxTokens } : {}),epochs: parsed.epochs,batchSize: parsed.batchSize,lr: parsed.lr,@@ -186,6 +195,9 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strintargetModels: parsed.targetModelsFleet,optimizerModel,judgeModel,+ models: { optimizer: models.optimizer, judge: models.judge },+ modelsStrict: parsed.modelsStrict,+ ...(parsed.reflectMaxTokens !== undefined ? { reflectMaxTokens: parsed.reflectMaxTokens } : {}),epochs: parsed.epochs,batchSize: parsed.batchSize,lr: parsed.lr,@@ -233,28 +245,29 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strintry {const { MinionQueue } = await import('../core/minions/queue.ts');const queue = new MinionQueue(engine);- const jobData = {- skills_dir: skillsDir,- skill_name: parsed.skillName,- benchmark_path: benchmarkPath,+ const jobData = buildSkillOptJobData({+ skillsDir,+ skillName: parsed.skillName,+ benchmarkPath,epochs: parsed.epochs,- batch_size: parsed.batchSize,+ batchSize: parsed.batchSize,lr: parsed.lr,- lr_schedule: parsed.lrSchedule,+ lrSchedule: parsed.lrSchedule,split: parsed.split,- optimizer_model: optimizerModel,- target_model: targetModel,- judge_model: judgeModel,+ models,+ modelFlags,+ modelsStrict: parsed.modelsStrict,+ ...(parsed.reflectMaxTokens !== undefined ? { reflectMaxTokens: parsed.reflectMaxTokens } : {}),mode: parsed.mode,- dry_run: parsed.dryRun,- no_mutate: parsed.noMutate,- allow_mutate_bundled: parsed.allowMutateBundled,- ...(parsed.heldOutPath ? { held_out_path: parsed.heldOutPath } : {}),- bootstrap_reviewed: parsed.bootstrapReviewed,- max_cost_usd: parsed.maxCostUsd,- max_runtime_min: parsed.maxRuntimeMin,+ dryRun: parsed.dryRun,+ noMutate: parsed.noMutate,+ allowMutateBundled: parsed.allowMutateBundled,+ ...(parsed.heldOutPath ? { heldOutPath: parsed.heldOutPath } : {}),+ bootstrapReviewed: parsed.bootstrapReviewed,+ maxCostUsd: parsed.maxCostUsd,+ maxRuntimeMin: parsed.maxRuntimeMin,force: parsed.force,- };+ });const job = await queue.add('skillopt', jobData, {queue: 'default',idempotency_key: `cli:skillopt:${parsed.skillName}`,@@ -286,9 +299,9 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strinlr: parsed.lr,lrSchedule: parsed.lrSchedule,split: parsed.split,- optimizerModel,- targetModel,- judgeModel,+ ...skillOptModelOpts(models),+ modelsStrict: parsed.modelsStrict,+ ...(parsed.reflectMaxTokens !== undefined ? { reflectMaxTokens: parsed.reflectMaxTokens } : {}),mode: parsed.mode,dryRun: parsed.dryRun,noMutate: parsed.noMutate,@@ -304,6 +317,9 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strintry {const result = await runSkillOpt(opts);+ if (parsed.dryRun) {+ exitDryRun(result.receipt.models_plan ?? [], result.receipt.models_strict!, parsed.json, { receipt: result.receipt });+ }if (parsed.json) {process.stdout.write(JSON.stringify({schema_version: 1,@@ -313,17 +329,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin...(result.proposedPath ? { proposed_path: result.proposedPath } : {}),}) + '\n');} else {- process.stderr.write(`[skillopt] Outcome: ${result.outcome}\n`);- // #3516: never a silent failure — say WHY the run aborted/errored.- if (result.outcome === 'aborted' || result.outcome === 'errored') {- const reason = result.receipt.abort_reason ?? 'unknown';- const detail = result.receipt.abort_detail ?? '(no detail captured)';- process.stderr.write(`[skillopt] Failure reason: ${reason}\n`);- process.stderr.write(`[skillopt] Detail: ${detail}\n`);- if (detail.includes('no_pricing')) {- process.stderr.write(`[skillopt] Hint: model has no pricing entry; pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.\n`);- }- }+ process.stderr.write(formatRunSummary(result.outcome, result.receipt, skillsDir));process.stderr.write(`[skillopt] Best sel-score: ${(result.receipt.best_sel_score ?? 0).toFixed(3)}\n`);process.stderr.write(`[skillopt] Final cost: $${(result.receipt.final_cost_usd ?? 0).toFixed(2)}\n`);if (result.mutatedSkillFile) {@@ -332,7 +338,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strinprocess.stderr.write(`[skillopt] Proposed improvements written to ${result.proposedPath}. Review + copy manually.\n`);}}- // Exit codes: 0 accepted, 1 no improvement, 2 aborted, 3 errored.+ // Exit codes: 0 accepted, 1 no improvement, 2 aborted or errored.const exitMap = { accepted: 0, no_improvement: 1, aborted: 2, errored: 2 };process.exit(exitMap[result.outcome]);} catch (err) {@@ -340,6 +346,67 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin}}+type RunSkillOptOutcome = NonNullable<RunReceipt['outcome']>;++/**+ * `--dry-run` exit: the models plan (banner already printed) and the strict+ * verdict, zero model calls. Exit 1 only when strict mode is on and fails.+ */+function exitDryRun(plan: ModelsPlanEntry[], strict: StrictVerdict, json: boolean, extra: Record<string, unknown>): never {+ if (json) {+ process.stdout.write(JSON.stringify({ schema_version: 1, dry_run: true, models_plan: plan, strict, ...extra }) + '\n');+ } else {+ process.stderr.write(`[skillopt] Dry run: no model calls made.\n${describeStrictVerdict(strict)}\n`);+ if (!strict.ok && !strict.enabled) {+ process.stderr.write('(strict mode is off; --models-strict or skillopt.models_strict would abort this run)\n');+ }+ }+ process.exit(strict.enabled && !strict.ok ? 1 : 0);+}++/**+ * Outcome + diagnostics block for the stderr summary. #3516: never a silent+ * failure — say WHY the run aborted/errored. #5584: optimizer-reply errors+ * warn even on a successful run; a retained checkpoint prints the run id,+ * its location and the exact resume command. Exported for unit tests.+ */+export function formatRunSummary(outcome: RunSkillOptOutcome, receipt: RunReceipt, skillsDir: string): string {+ const lines = [`[skillopt] Outcome: ${outcome}`];+ if (outcome === 'aborted' || outcome === 'errored') {+ const detail = receipt.abort_detail ?? '(no detail captured)';+ lines.push(`[skillopt] Failure reason: ${receipt.abort_reason ?? 'unknown'}`);+ lines.push(`[skillopt] Detail: ${detail}`);+ if (detail.includes('no_pricing')) {+ lines.push(`[skillopt] Hint: model has no pricing entry; pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.`);+ }+ }+ if (receipt.stop_reason === 'early_stop_unusable_output') {+ lines.push(`[skillopt] Stopped early: optimizer output was unusable for consecutive steps; remaining budget not spent.`);+ }+ const errors = receipt.reflect_errors ?? [];+ if (errors.length > 0) {+ lines.push(`[skillopt] Warning: ${errors.length} optimizer reply error(s) (optimizer output cap ${receipt.reflect_max_tokens ?? 'default'}); first: ${errors[0]}`);+ }+ if (receipt.skill_body_truncated) {+ lines.push(`[skillopt] Warning: skill body truncated for the optimizer (sent ${receipt.skill_body_truncated.sent_chars} of ${receipt.skill_body_truncated.total_chars} chars).`);+ }+ const modelsUsed = receipt.models_used ?? [];+ if (modelsUsed.length > 0) {+ const scope = receipt.models_used_scope === 'since_resume' ? 'since resume; earlier segments predate the ledger' : 'full run';+ lines.push(`[skillopt] Models called (${scope}; a call is one gateway operation, internal retries count once; ~ = estimated cost):`);+ for (const row of formatModelsUsedTable(modelsUsed)) lines.push(`[skillopt] ${row}`);+ }+ for (const r of receipt.remediation ?? []) {+ lines.push(`[skillopt] Fix (${r.code}): ${r.fix} See ${r.docs}`);+ }+ if (receipt.resume_command) {+ lines.push(`[skillopt] Run id: ${receipt.run_id}`);+ lines.push(`[skillopt] Checkpoint: ${checkpointPath(skillsDir, receipt.skill, receipt.run_id)}`);+ lines.push(`[skillopt] Resume: ${receipt.resume_command}`);+ }+ return lines.join('\n') + '\n';+}+/** Exported for unit tests (CLI flag parsing, --bootstrap-tasks cap, mutual exclusion). */export function parseFlags(args: string[]): ParsedFlags {let skillName = '';@@ -354,8 +421,10 @@ export function parseFlags(args: string[]): ParsedFlags {let lrSchedule: 'cosine' | 'linear' | 'constant' = 'cosine';let splitStr = '4:1:5';let optimizerModel: string | undefined;+ let modelsStrict = false;let targetModel: string | undefined;let judgeModel: string | undefined;+ let reflectMaxTokens: number | undefined;let mode: 'patch' | 'rewrite' = 'patch';let dryRun = false;let noMutate = false;@@ -399,8 +468,15 @@ export function parseFlags(args: string[]): ParsedFlags {}if (a === '--split') { splitStr = args[++i]!; i += 1; continue; }if (a === '--optimizer-model') { optimizerModel = args[++i]; i += 1; continue; }+ if (a === '--models-strict') { modelsStrict = true; i += 1; continue; }if (a === '--target-model') { targetModel = args[++i]; i += 1; continue; }if (a === '--judge-model') { judgeModel = args[++i]; i += 1; continue; }+ if (a === '--reflect-max-tokens') {+ const v = args[++i];+ reflectMaxTokens = parsePositiveInt(v);+ if (reflectMaxTokens === undefined) throw new Error(`--reflect-max-tokens requires a positive integer (got '${v}')`);+ i += 1; continue;+ }if (a === '--patch') { mode = 'patch'; i += 1; continue; }if (a === '--rewrite') { mode = 'rewrite'; i += 1; continue; }if (a === '--dry-run') { dryRun = true; i += 1; continue; }@@ -483,6 +559,8 @@ export function parseFlags(args: string[]): ParsedFlags {...(optimizerModel !== undefined ? { optimizerModel } : {}),...(targetModel !== undefined ? { targetModel } : {}),...(judgeModel !== undefined ? { judgeModel } : {}),+ ...(reflectMaxTokens !== undefined ? { reflectMaxTokens } : {}),+ modelsStrict,mode,dryRun,noMutate,diff --git a/src/core/ai/anthropic-model-ids.ts b/src/core/ai/anthropic-model-ids.tsnew file mode 100644index 0000000000..52219d94f4--- /dev/null+++ b/src/core/ai/anthropic-model-ids.ts@@ -0,0 +1,72 @@+/**+ * anthropic-model-ids — version grammar for Anthropic tier-family model ids.+ *+ * Parses `claude-<family>-<major>[-<minor>][-<YYYYMMDD>]` for the three tier+ * families (`haiku`, `sonnet`, `opus`), with an optional `anthropic:` (or+ * `anthropic/`) prefix. The 8-digit segment is a snapshot date, never a+ * version: `claude-haiku-4-5` and `claude-haiku-4-5-20251001` compare equal.+ * `fable` is not a tier family, and other providers (including OpenRouter's+ * `openrouter:anthropic/...` transport form) and unknown shapes parse to null,+ * so callers degrade to "no opinion" rather than a wrong comparison.+ *+ * `newerAnthropicModel` answers "does the anthropic recipe ship a newer priced+ * model in this id's family?" — advisory only (the `gbrain models` hint); it+ * never changes a default.+ */++import { splitProviderModelId } from '../model-id.ts';+import { canonicalLookup } from '../model-pricing.ts';+import { anthropic } from './recipes/anthropic.ts';++export type AnthropicFamily = 'haiku' | 'sonnet' | 'opus';++export interface ParsedAnthropicModelId {+ /** Bare model id (provider prefix stripped). */+ id: string;+ family: AnthropicFamily;+ major: number;+ minor: number;+ date?: string;+}++const ANTHROPIC_ID_RE = /^claude-(haiku|sonnet|opus)-(\d{1,2})(?:-(\d{1,2}))?(?:-(\d{8}))?$/;++export function parseAnthropicModelId(model: string): ParsedAnthropicModelId | null {+ const { provider, model: id } = splitProviderModelId(model);+ if (provider !== null && provider !== 'anthropic') return null;+ const m = ANTHROPIC_ID_RE.exec(id);+ if (!m) return null;+ return {+ id,+ family: m[1] as AnthropicFamily,+ major: Number(m[2]),+ minor: m[3] === undefined ? 0 : Number(m[3]),+ ...(m[4] ? { date: m[4] } : {}),+ };+}++/** Version order within a family: major, then minor. Snapshot dates are ignored. */+export function compareAnthropicVersions(a: ParsedAnthropicModelId, b: ParsedAnthropicModelId): number {+ return a.major - b.major || a.minor - b.minor;+}++/**+ * The anthropic recipe's newest priced chat model in `model`'s family when it+ * is strictly newer than `model`; null when `model` is current, newer than the+ * recipe, unpriced-family-only, fable, non-Anthropic or unparseable.+ */+export function newerAnthropicModel(+ model: string,+ ids: readonly string[] = anthropic.touchpoints.chat?.models ?? [],+ priced: (id: string) => boolean = (id) => canonicalLookup(`anthropic:${id}`) !== undefined,+): ParsedAnthropicModelId | null {+ const current = parseAnthropicModelId(model);+ if (!current) return null;+ let newest: ParsedAnthropicModelId | null = null;+ for (const id of ids) {+ const p = parseAnthropicModelId(id);+ if (!p || p.family !== current.family || !priced(id)) continue;+ if (!newest || compareAnthropicVersions(p, newest) > 0) newest = p;+ }+ return newest && compareAnthropicVersions(newest, current) > 0 ? newest : null;+}diff --git a/src/core/ai/budget-record.ts b/src/core/ai/budget-record.tsnew file mode 100644index 0000000000..4b71212ef1--- /dev/null+++ b/src/core/ai/budget-record.ts@@ -0,0 +1,38 @@+/**+ * Fail-open BudgetTracker recording for gateway spend sites. No tracker is a+ * no-op; a BudgetExhausted from `record()` (TX1) is swallowed — the breach+ * surfaces on the NEXT `reserve()`, and the call's own result or error wins.+ */++import {+ usageFromError,+ type BudgetActualUsage,+ type BudgetKind,+ type BudgetTracker,+} from '../budget/budget-tracker.ts';++export function recordOnTracker(tracker: BudgetTracker | null, actual: BudgetActualUsage & { kind?: BudgetKind }): void {+ if (!tracker) return;+ try {+ tracker.record(actual);+ } catch {+ // BudgetExhausted (TX1) — surfaced via the next reserve().+ }+}++/**+ * Usage fields for a failed call: what the SDK error reports, else the+ * pessimistic fallback (A3 amended) flagged `estimated`.+ */+export function failedCallUsage(+ err: unknown,+ fallback: { inputTokens: number; outputTokens: number },+): { inputTokens: number; outputTokens: number; failed: true; estimated: boolean } {+ const found = usageFromError(err);+ return {+ inputTokens: found?.inputTokens ?? fallback.inputTokens,+ outputTokens: found?.outputTokens ?? fallback.outputTokens,+ failed: true,+ estimated: found?.inputTokens == null || found?.outputTokens == null,+ };+}diff --git a/src/core/ai/gateway-model-sources.ts b/src/core/ai/gateway-model-sources.tsnew file mode 100644index 0000000000..0c2631e138--- /dev/null+++ b/src/core/ai/gateway-model-sources.ts@@ -0,0 +1,67 @@+/**+ * Provenance of the gateway's engine-resolved expansion and chat models.+ *+ * `reconfigureGatewayWithEngine` walks the resolution chain for both models+ * and records here which step won (`ResolveSource`, or `file_config` when+ * the servable config.json pin supplied it) plus a key-name origin. Each+ * record carries the model it describes; a getter answers only while the+ * gateway still routes to that model, so a later `configureGateway` with a+ * different model reads as unknown instead of inheriting stale provenance.+ */++import { describeResolveOrigin, type EffectiveModelSource, type ResolvedModel, type ResolveSource } from '../model-config.ts';++export type GatewayModelSourceKind = ResolveSource | 'file_config';++export interface GatewayModelSource {+ source: GatewayModelSourceKind;+ origin: string;+}++type GatewayTouchpoint = 'expansion' | 'chat';++const records = new Map<GatewayTouchpoint, GatewayModelSource & { model: string }>();++const RESOLUTION: Record<GatewayTouchpoint, { configKey: string; tier: 'utility' | 'reasoning'; pinKey: string; pinEnv: string }> = {+ expansion: { configKey: 'models.expansion', tier: 'utility', pinKey: 'expansion_model', pinEnv: 'GBRAIN_EXPANSION_MODEL' },+ chat: { configKey: 'models.chat', tier: 'reasoning', pinKey: 'chat_model', pinEnv: 'GBRAIN_CHAT_MODEL' },+};++/**+ * Provenance for one reconfigure resolution. `effective` is the file-plane+ * fallback result, present only when the engine chain fell through to a+ * default and the effective resolver picked the model instead. A file pin+ * that `loadConfig` folded in from `GBRAIN_EXPANSION_MODEL` /+ * `GBRAIN_CHAT_MODEL` is attributed to the env var.+ */+export function gatewayModelSource(+ touchpoint: GatewayTouchpoint,+ detailed: ResolvedModel,+ effective: { source: EffectiveModelSource } | null,+): GatewayModelSource {+ const r = RESOLUTION[touchpoint];+ if (!effective) {+ return { source: detailed.source, origin: describeResolveOrigin(detailed.source, { configKey: r.configKey, tier: r.tier }) };+ }+ if (effective.source === 'env_model') return { source: 'env', origin: 'GBRAIN_MODEL' };+ if (effective.source === 'file_pin') {+ return process.env[r.pinEnv]?.trim()+ ? { source: 'env', origin: r.pinEnv }+ : { source: 'file_config', origin: `${r.pinKey} (config.json)` };+ }+ return { source: 'tier_default', origin: 'built-in default' };+}++export function setGatewayModelSource(touchpoint: GatewayTouchpoint, model: string, source: GatewayModelSource): void {+ records.set(touchpoint, { model, ...source });+}++/** Provenance of `model` on `touchpoint`, or undefined when unrecorded or stale. */+export function getGatewayModelSource(touchpoint: GatewayTouchpoint, model: string): GatewayModelSource | undefined {+ const r = records.get(touchpoint);+ return r && r.model === model ? { source: r.source, origin: r.origin } : undefined;+}++export function clearGatewayModelSources(): void {+ records.clear();+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex f4ca33efbd..ac4a258c0b 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -32,11 +32,8 @@ import { createOpenAICompatible } from '@ai-sdk/openai-compatible';import { z } from 'zod';import { truncateUtf8 } from '../text-safe.ts';-import {- BudgetTracker,- extractUsageFromError as _extractUsageFromError,- type BudgetKind,-} from '../budget/budget-tracker.ts';+import { BudgetTracker, type BudgetKind } from '../budget/budget-tracker.ts';+import { failedCallUsage, recordOnTracker } from './budget-record.ts';import type {AIGatewayConfig,EmbedMultimodalOpts,@@ -54,6 +51,7 @@ import {} from './recipes/openrouter.ts';import { resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';import { snapshotConfigReader } from '../config-snapshot.ts';+import { clearGatewayModelSources, gatewayModelSource, setGatewayModelSource } from './gateway-model-sources.ts';import { parseLlmJson } from '../llm-json.ts';import type { BrainEngine } from '../engine.ts';import { dimsProviderOptions } from './dims.ts';@@ -567,12 +565,11 @@ export async function reconfigureGatewayWithEngine(engine: BrainEngine): PromisefileCfg = null;}}- const newChat = needsFileCfg(chatDetailed.source)- ? resolveEffectiveChatModel(fileCfg, cfg.env ?? process.env).model- : chatDetailed.model;- const newExpansion = needsFileCfg(expansionDetailed.source)- ? resolveEffectiveExpansionModel(fileCfg, cfg.env ?? process.env).model- : expansionDetailed.model;+ const env = cfg.env ?? process.env;+ const chatEffective = needsFileCfg(chatDetailed.source) ? resolveEffectiveChatModel(fileCfg, env) : null;+ const expansionEffective = needsFileCfg(expansionDetailed.source) ? resolveEffectiveExpansionModel(fileCfg, env) : null;+ const newChat = chatEffective?.model ?? chatDetailed.model;+ const newExpansion = expansionEffective?.model ?? expansionDetailed.model;// Resolved values are bare model ids (e.g. `claude-sonnet-4-6`) — prepend// the existing provider prefix from cfg so the gateway keeps routing to@@ -582,6 +579,8 @@ export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promiseconst chatFull = newChat.includes(':') ? newChat : prefixWithProviderFrom(cfg.chat_model ?? DEFAULT_CHAT_MODEL, newChat);_config = { ...cfg, expansion_model: expansionFull, chat_model: chatFull };+ setGatewayModelSource('expansion', expansionFull, gatewayModelSource('expansion', expansionDetailed, expansionEffective));+ setGatewayModelSource('chat', chatFull, gatewayModelSource('chat', chatDetailed, chatEffective));_modelCache.clear();_shrinkState.clear();return _config;@@ -662,6 +661,7 @@ export function __setGatewayResetBaselineForTests(/** Clear every piece of module state. Shared by both reset flavors. */function clearGatewayState(): void {_config = null;+ clearGatewayModelSources();stashGatewayAnthropicKeyFromEnv(undefined); // gateway-owned snapshot dies with the config_modelCache.clear();_shrinkState.clear();@@ -1655,19 +1655,16 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A// the worst case.const charsPerToken = recipe.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;const totalChars = truncated.reduce((s, t) => s + t.length, 0);- const inputTokens = Math.ceil(totalChars / Math.max(charsPerToken, 1));- try {- tracker.record({- modelId: `${recipe.id}:${modelId}`,- inputTokens,- outputTokens: 0,- embeddingDims: expected,- kind: 'embed',- label: _embedThrew ? 'gateway.embed.failed' : 'gateway.embed',- });- } catch {- // BudgetExhausted (TX1) — original throw (if any) wins.- }+ recordOnTracker(tracker, {+ modelId: `${recipe.id}:${modelId}`,+ requestedModelId: resolveTarget,+ inputTokens: Math.ceil(totalChars / Math.max(charsPerToken, 1)),+ outputTokens: 0,+ embeddingDims: expected,+ kind: 'embed',+ label: _embedThrew ? 'gateway.embed.failed' : 'gateway.embed',+ estimated: true,+ });}}}@@ -2451,26 +2448,6 @@ function normalizeSdkUsage(usage: unknown): { inputTokens: number; outputTokens:};}-/**- * #4121 — one fail-open record wrapper for every uninstrumented-path spend- * site (expand + OCR): no-tracker is a no-op; BudgetExhausted from record()- * (TX1) is swallowed exactly like chat()'s _recordBudget — the breach- * surfaces on the NEXT reserve(), never here.- */-function recordSpendOnTracker(- tracker: ReturnType<typeof getCurrentBudgetTracker>,- modelId: string,- label: string,- tokens: { inputTokens: number; outputTokens: number },-): void {- if (!tracker) return;- try {- tracker.record({ modelId, inputTokens: tokens.inputTokens, outputTokens: tokens.outputTokens, label });- } catch {- // BudgetExhausted (TX1) — surfaced via the next reserve().- }-}-/*** Expand a search query into up to 4 related queries.* Returns the original query PLUS expansions. On failure, returns just the original.@@ -2505,31 +2482,27 @@ export async function expand(query: string): Promise<string[]> {// provider tokens; the viaText fallback then bills its own call, so one// expand() can legitimately produce TWO records). Fail-open (no tracker →// no-op) and swallow BudgetExhausted the same way chat()'s _recordBudget- // does — TX1 surfaces on the NEXT reserve(), not here.+ // does — TX1 surfaces on the NEXT reserve(), not here. The fallback's+ // record is an extra attempt of the same operation (countsAsCall: false).const tracker = getCurrentBudgetTracker();- const recordExpansion = (- modelLabel: string,- label: 'gateway.expand' | 'gateway.expand.failed',- tokens: { inputTokens: number; outputTokens: number },- ): void => recordSpendOnTracker(tracker, modelLabel, label, tokens);- const recordExpansionUsage = (modelLabel: string, usage: unknown): void =>- recordExpansion(modelLabel, 'gateway.expand', normalizeSdkUsage(usage));const estimatedPromptTokens = estimateChatInputTokens({messages: [{ content: expansionPrompt }],});- const recordExpansionFailure = (modelLabel: string, err: unknown): void =>- recordExpansion(- modelLabel,- 'gateway.expand.failed',- _extractUsageFromError(err, {- inputTokens: estimatedPromptTokens,- outputTokens: EXPANSION_FAILED_PESSIMISTIC_OUTPUT_TOKENS,- }),- );try {- const { model, recipe, modelId } = await resolveExpansionProvider(getExpansionModel());+ const requestedModelId = getExpansionModel();+ const { model, recipe, modelId } = await resolveExpansionProvider(requestedModelId);const modelLabel = `${recipe.id}:${modelId}`;+ const recordExpansionUsage = (usage: unknown, countsAsCall: boolean): void =>+ recordOnTracker(tracker, { modelId: modelLabel, requestedModelId, label: 'gateway.expand', countsAsCall, ...normalizeSdkUsage(usage) });+ const recordExpansionFailure = (err: unknown, countsAsCall: boolean): void =>+ recordOnTracker(tracker, {+ modelId: modelLabel,+ requestedModelId,+ label: 'gateway.expand.failed',+ countsAsCall,+ ...failedCallUsage(err, { inputTokens: estimatedPromptTokens, outputTokens: EXPANSION_FAILED_PESSIMISTIC_OUTPUT_TOKENS }),+ });let expansions: string[];@@ -2537,7 +2510,7 @@ export async function expand(query: string): Promise<string[]> {// support is unknown: the AI SDK can't send a json_schema response_format// there, so generateObject would warn and silently degrade. generateText + a// tolerant parse recovers the queries instead. Fresh abortSignal per call.- const viaText = async (): Promise<string[]> => {+ const viaText = async (countsAsCall = true): Promise<string[]> => {let textResult: Awaited<ReturnType<GenerateTextFn>>;try {textResult = await guardedGeneration(modelLabel, _generateTextTransport, {@@ -2547,10 +2520,10 @@ export async function expand(query: string): Promise<string[]> {});} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- recordExpansionFailure(modelLabel, err); // failed call still billed upstream+ recordExpansionFailure(err, countsAsCall); // failed call still billed upstreamthrow err; // outer catch degrades to [query]}- recordExpansionUsage(modelLabel, textResult.usage);+ recordExpansionUsage(textResult.usage, countsAsCall);return parseExpansionResponse(textResult.text) ?? [];};@@ -2604,10 +2577,10 @@ export async function expand(query: string): Promise<string[]> {});} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- recordExpansionFailure(modelLabel, err);+ recordExpansionFailure(err, true);throw err; // outer catch degrades to [query]}- recordExpansionUsage(modelLabel, result.usage);+ recordExpansionUsage(result.usage, true);const parsed = ExpansionSchema.safeParse(result.object);expansions = parsed.success ? parsed.data.queries : [];} else if (recipeSupportsStructuredOutputs(recipe) && !_structuredOutputRejectedRecipes.has(recipe.id)) {@@ -2627,18 +2600,18 @@ export async function expand(query: string): Promise<string[]> {abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),prompt: expansionPrompt,});- recordExpansionUsage(modelLabel, result.usage);+ recordExpansionUsage(result.usage, true);const parsed = ExpansionSchema.safeParse(result.object);expansions = parsed.success ? parsed.data.queries : [];} catch (err) {if (isAIInvocationPolicyError(err)) throw err;// The rejected structured attempt billed real tokens — record it// before the fallback bills its own call (two records, both true).- recordExpansionFailure(modelLabel, err);+ recordExpansionFailure(err, true);// Adversarial F5: don't re-pay this attempt on every call — the// capability mis-declaration is stable for the process lifetime._structuredOutputRejectedRecipes.add(recipe.id);- expansions = await viaText();+ expansions = await viaText(false);}} else {// openai-compatible backend, structured-output support unknown: skip the@@ -2709,8 +2682,8 @@ export async function generateOcrText(imageBytes: Buffer, mime: string): Promiseconst estimatedOcrInputTokens =estimateChatInputTokens({ system: systemPrompt, messages: [{ content: 'Extract visible text only.' }] }) +OCR_IMAGE_INPUT_TOKEN_ESTIMATE;- const recordOcr = (label: 'gateway.ocr' | 'gateway.ocr.failed', tokens: { inputTokens: number; outputTokens: number }): void =>- recordSpendOnTracker(tracker, ocrModelId, label, tokens);+ const recordOcr = (label: 'gateway.ocr' | 'gateway.ocr.failed', usage: { inputTokens: number; outputTokens: number }): void =>+ recordOnTracker(tracker, { modelId: ocrModelId, requestedModelId: ocrModel, label, ...usage });let result: Awaited<ReturnType<GenerateTextFn>>;try {result = await guardedGeneration(ocrModelId, _generateTextTransport, {@@ -2736,7 +2709,7 @@ export async function generateOcrText(imageBytes: Buffer, mime: string): Promise});} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- recordOcr('gateway.ocr.failed', _extractUsageFromError(err, {+ recordOcr('gateway.ocr.failed', failedCallUsage(err, {inputTokens: estimatedOcrInputTokens,outputTokens: DEFAULT_MAX_OUTPUT_TOKENS,}));@@ -3144,6 +3117,8 @@ export interface ChatOpts {* validating it themselves (see `jsonSchemaOutput`).*/responseSchema?: { name: string; description?: string; schema: Record<string, unknown> };+ /** Caller purpose (`skillopt.judge`, …) stamped on the BudgetTracker ledger row. */+ purpose?: string;}/**@@ -3529,6 +3504,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {}const estimatedInputTokens = estimateChatInputTokens(opts);const maxOutputTokens = opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly);+ const chatRecord = { requestedModelId: modelStrEarly, purpose: opts.purpose, label: 'gateway.chat' };// TX5: reserve BEFORE the provider call. Throws BudgetExhausted on cost,// runtime, or no_pricing (when cap is set). Pre-resolution model id is@@ -3570,34 +3546,9 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {threw = err;throw err;} finally {- if (tracker) {- try {- if (res) {- tracker.record({- modelId: res.model ?? modelStrEarly,- inputTokens: res.usage.input_tokens,- outputTokens: res.usage.output_tokens,- label: 'gateway.chat',- });- } else {- const usage = _extractUsageFromError(threw, {- inputTokens: estimatedInputTokens,- outputTokens: maxOutputTokens,- });- tracker.record({- modelId: modelStrEarly,- inputTokens: usage.inputTokens,- outputTokens: usage.outputTokens,- label: 'gateway.chat',- });- }- } catch {- // record() can throw BudgetExhausted (TX1) — suppress here so the- // original error (if any) wins; the BudgetExhausted is surfaced- // on the NEXT call via reserve(). For test transport this branch- // is rare in practice.- }- }+ recordOnTracker(tracker, res+ ? { ...chatRecord, modelId: res.model ?? modelStrEarly, inputTokens: res.usage.input_tokens, outputTokens: res.usage.output_tokens }+ : { ...chatRecord, modelId: modelStrEarly, ...failedCallUsage(threw, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }) });}}@@ -3687,19 +3638,10 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {}let _budgetRecorded = false;- const _recordBudget = (modelLabel: string, inputTokens: number, outputTokens: number): void => {- if (!tracker || _budgetRecorded) return;+ const _recordBudget = (usage: { inputTokens: number; outputTokens: number; failed?: boolean; estimated?: boolean }): void => {+ if (_budgetRecorded) return;_budgetRecorded = true;- try {- tracker.record({- modelId: modelLabel,- inputTokens,- outputTokens,- label: 'gateway.chat',- });- } catch {- // BudgetExhausted (TX1) raised here; surface via next reserve()- }+ recordOnTracker(tracker, { ...chatRecord, modelId: `${recipe.id}:${modelId}`, ...usage });};// The actual Anthropic system-prompt cache breakpoint. A bare string@@ -3814,7 +3756,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {const anthropicCache = providerMetadata?.anthropic ?? {};const { inputTokens: inTok, outputTokens: outTok } = normalizeSdkUsage(usage);- _recordBudget(`${recipe.id}:${modelId}`, inTok, outTok);+ _recordBudget({ inputTokens: inTok, outputTokens: outTok });const usageOut = {input_tokens: inTok,@@ -3847,11 +3789,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {if (isAIInvocationPolicyError(err)) throw err;// Pessimistic fallback (A3 amended): when err.usage isn't there, charge// the worst-case ceiling — better to overcount on failure than under.- const fallback = _extractUsageFromError(err, {- inputTokens: estimatedInputTokens,- outputTokens: maxOutputTokens,- });- _recordBudget(`${recipe.id}:${modelId}`, fallback.inputTokens, fallback.outputTokens);+ _recordBudget(failedCallUsage(err, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }));throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`);}}@@ -3909,6 +3847,8 @@ export interface ToolLoopOpts {* Silently ignored on recipes that declare no prompt caching.*/cacheSystem?: boolean;+ /** Forwarded to every `chat()` turn; see `ChatOpts.purpose`. */+ purpose?: string;/** Crash-replay state. When set, the loop resumes from the recorded position. */replayState?: ToolLoopReplayState;@@ -4057,6 +3997,7 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {? (opts.abortSignal ? AbortSignal.any([opts.abortSignal, turnPermitSignal]) : turnPermitSignal): opts.abortSignal,cacheSystem: opts.cacheSystem,+ purpose: opts.purpose,});} catch (err) {if (isAIInvocationPolicyError(err)) throw err;@@ -4407,21 +4348,19 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {}let _rerankRecorded = false;- const _rerankRecord = (): void => {- if (!tracker || _rerankRecorded) return;+ const _rerankRecord = (failed: boolean): void => {+ if (_rerankRecorded) return;_rerankRecorded = true;- try {- const totalChars = input.query.length + input.documents.reduce((s, d) => s + d.length, 0);- tracker.record({- modelId: modelStr,- inputTokens: Math.ceil(totalChars / 4),- outputTokens: 0,- kind: 'rerank',- label: 'gateway.rerank',- });- } catch {- // BudgetExhausted (TX1) suppressed; surfaces on next reserve().- }+ const totalChars = input.query.length + input.documents.reduce((s, d) => s + d.length, 0);+ recordOnTracker(tracker, {+ modelId: modelStr,+ inputTokens: Math.ceil(totalChars / 4),+ outputTokens: 0,+ kind: 'rerank',+ label: 'gateway.rerank',+ estimated: true,+ failed,+ });};try {const transport: RerankTransport = _rerankTransport ?? ((u, init) => fetch(u, init));@@ -4466,11 +4405,11 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {index: typeof r.index === 'number' ? r.index : 0,relevanceScore: typeof r.relevance_score === 'number' ? r.relevance_score : 0,}));- _rerankRecord();+ _rerankRecord(false);return mapped;} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- _rerankRecord();+ _rerankRecord(true);if (err instanceof RerankError) throw err;// AbortError on timeout — classify cleanly.if (err && typeof err === 'object' && (err as any).name === 'AbortError') {diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.tsindex 7176617a07..3d3dc4e348 100644--- a/src/core/budget/budget-tracker.ts+++ b/src/core/budget/budget-tracker.ts@@ -31,14 +31,20 @@import { mkdirSync, appendFileSync } from 'node:fs';import { dirname } from 'node:path';import { gbrainPath } from '../config.ts';-import { ANTHROPIC_PRICING, type ModelPricing } from '../anthropic-pricing.ts';-import { canonicalLookup } from '../model-pricing.ts';-import { EMBEDDING_PRICING, lookupEmbeddingPrice } from '../embedding-pricing.ts';-import { splitProviderModelId } from '../model-id.ts';-import { resolveRecipe } from '../ai/model-resolver.ts';+import { ANTHROPIC_PRICING } from '../anthropic-pricing.ts';+import { EMBEDDING_PRICING } from '../embedding-pricing.ts';import { isoWeekFilename, resolveAuditDir } from '../audit-week-file.ts';--export type BudgetKind = 'chat' | 'embed' | 'rerank';+import {+ canonicalPricingKey,+ reservationCostUsd,+ usageCostUsd,+ type BudgetKind,+ type PricingOverrides,+} from './reservation-cost.ts';+import { ModelLedger, type ModelUsageRow } from './models-used.ts';++export { isModelPriceable } from './reservation-cost.ts';+export type { BudgetKind, PricingOverrides };export type BudgetReason = 'cost' | 'runtime' | 'no_pricing';@@ -59,6 +65,16 @@ export interface BudgetActualUsage {embeddingDims?: number;/** Optional label echo for the audit row. */label?: string;+ /** Model string the caller asked for, before alias/default resolution. Defaults to the served model. */+ requestedModelId?: string;+ /** Caller-declared purpose (`skillopt.optimizer`, …); engine-internal calls leave it unset. */+ purpose?: string;+ /** The call failed. A `.failed` label implies it. */+ failed?: boolean;+ /** False for an extra attempt inside one gateway operation (structured-output fallback). Default true. */+ countsAsCall?: boolean;+ /** Token counts are a heuristic (char estimate or pessimistic failure fallback), not provider-reported. */+ estimated?: boolean;}export interface BudgetSnapshot {@@ -68,6 +84,8 @@ export interface BudgetSnapshot {maxCostUsd?: number;maxRuntimeMs?: number;callsRecorded: number;+ /** Per-model ledger of every recorded call (see models-used.ts). */+ models: ModelUsageRow[];}export interface BudgetTrackerOpts {@@ -90,15 +108,6 @@ export interface BudgetTrackerOpts {pricingOverrides?: PricingOverrides;}-/**- * #4312 — normalized operator price overrides: model string (lowercased) →- * per-1M-token pricing. Declared in the config plane as JSON, e.g.- * gbrain config set pricing.overrides '{"litellm:gpt-4o": {"input": 2.5, "output": 10}, "litellm:text-embedding-3-large": 0.13}'- * A bare number means one rate for input AND output tokens (embeddings only- * ever bill input, so a scalar is the natural spelling there).- */-export type PricingOverrides = Record<string, ModelPricing>;-/*** Parse the raw `pricing.overrides` config value (JSON string or object) into* a normalized PricingOverrides map. Invalid entries are DROPPED (the model@@ -154,33 +163,6 @@ export async function loadPricingOverrides(}}-/**- * Recipe-alias normalization shared by the override and table lookups:- * `claude-cli:haiku` → `claude-cli:claude-haiku-4-5-20251001`. Bare ids and- * unknown providers throw out of resolveRecipe and keep the raw id, so the- * downstream chains decide those exactly as before.- */-function canonicalPricingKey(modelId: string): string {- try {- const { parsed } = resolveRecipe(modelId);- return `${parsed.providerId}:${parsed.modelId}`;- } catch {- return modelId;- }-}--/**- * Override lookup (keys normalized to lowercase at parse time): the raw key- * first, then the recipe-canonical key — an override written against the- * dated id must also price the alias the operator configured, or the alias- * silently bills at list price while the table lookup below resolves it.- */-function overrideFor(modelId: string, overrides?: PricingOverrides): ModelPricing | null {- if (!overrides) return null;- const raw = modelId.trim().toLowerCase();- return overrides[raw] ?? overrides[canonicalPricingKey(modelId.trim()).toLowerCase()] ?? null;-}-export class BudgetExhausted extends Error {readonly tag = 'BUDGET_EXHAUSTED' as const;reason: BudgetReason;@@ -226,142 +208,6 @@ function defaultAuditPath(): string {return `${dir}/${isoWeekFilename('budget')}`;}-/**- * Provider id prefixes that always price at $0 for the rerank kind- * (electricity, not API tokens). Centralized here so `--max-cost` callers- * don't hard-fail TX2 when a local rerank provider is configured. Matched- * against the provider half of the `provider:model` string. Extend this set- * when adding new local-inference rerank recipes.- */-const FREE_LOCAL_RERANK_PROVIDERS: ReadonlySet<string> = new Set([- 'llama-server-reranker',-]);--/**- * Provider id prefixes whose embeddings run on local inference (electricity,- * not API tokens) and so price at $0. Without this, a `--max-cost`-bounded- * embed/reindex job configured for a local provider TX2 hard-fails because- * lookupEmbeddingPrice has no entry for them. Matched against the provider- * half of the `provider:model` string.- *- * 'litellm' is excluded — a LiteLLM proxy can front a paid provider, so- * pricing-unknown is the honest state there.- *- * Sibling to FREE_LOCAL_RERANK_PROVIDERS; v0.41+ TODO unifies them via- * recipe-cost-driven resolution.- */-const FREE_LOCAL_EMBED_PROVIDERS: ReadonlySet<string> = new Set([- 'ollama',- 'llama-server',- 'lmstudio',-]);--/**- * Chat sibling of FREE_LOCAL_EMBED_PROVIDERS / FREE_LOCAL_RERANK_PROVIDERS.- *- * Local inference costs electricity, not tokens, so these providers price at- * $0 rather than TX2 hard-failing. Without this a caller that sets ANY cost cap- * cannot use a local chat model at all: CANONICAL_PRICING has no `ollama:*`- * keys, so `reserve()` throws no_pricing before the first call and every work- * item is skipped with `budget_exhausted: true` at $0 spent.- *- * That is not theoretical — `cycle.extract_atoms` always constructs its tracker- * with `maxCostUsd` (config only accepts `n > 0`, so the cap can't be unset),- * which made `models.dream.extract_atoms: ollama:*` silently extract nothing.- *- * `litellm` is excluded on purpose, matching the embed set: a LiteLLM proxy can- * front a paid provider, so pricing-unknown is the honest state there.- */-const FREE_LOCAL_CHAT_PROVIDERS: ReadonlySet<string> = new Set([- 'ollama',- 'llama-server',-]);--function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {- if (kind === 'embed') {- const hit = lookupEmbeddingPrice(modelId);- if (hit.kind === 'known') {- return { input: hit.pricePerMTok, output: 0 };- }- // v0.40.x: local-inference embed providers cost electricity, not tokens.- if (hit.kind === 'unknown' && FREE_LOCAL_EMBED_PROVIDERS.has(hit.provider)) {- return { input: 0, output: 0 };- }- return null;- }- // chat or rerank: try bare key first, then provider:model or provider/model.- // v0.41.21.0: route through splitProviderModelId so slash-prefixed ids- // (the form `--judge-model` and OpenRouter recipes emit) hit the pricing- // table. Pre-fix, slash-form silently no_pricing-failed `--max-cost` on- // brainstorm/lsd.- const bare = ANTHROPIC_PRICING[modelId];- if (bare) return bare;- // Recipe aliases (`claude-cli:haiku`, `anthropic:sonnet`) are not pricing- // keys, and the gateway reserves with the string the user configured —- // BEFORE alias resolution — so `claude-cli:haiku` under a cap used to TX2- // hard-fail with no_pricing while the dated id it maps to priced fine.- // Normalize once here; the chain below then prices the canonical id, and- // alias vs dated id agree at reserve(), record() and isModelPriceable().- // Bare ids and unknown providers keep the raw id (canonicalPricingKey): the- // existing chain decides those exactly as before.- const key = canonicalPricingKey(modelId);- const { provider: providerId, model: modelTail } = splitProviderModelId(key);- if (modelTail) {- const tailHit = ANTHROPIC_PRICING[modelTail];- if (tailHit) return tailHit;- }- if (kind === 'rerank') {- const hit = lookupEmbeddingPrice(key);- if (hit.kind === 'known') return { input: hit.pricePerMTok, output: 0 };- }- // v0.40.6.1: zero-price local-inference rerank providers so the budget- // tracker's TX2 hard-fail doesn't trip on `llama-server-reranker:<model>`- // under `--max-cost`. Only the rerank kind — chat/embed already have- // their own provider-specific pricing surfaces.- if (kind === 'rerank' && providerId && FREE_LOCAL_RERANK_PROVIDERS.has(providerId)) {- return { input: 0, output: 0 };- }- // Fall back to the full canonical pricing table so non-Anthropic chat- // models with a known price (openai:*, google:*, deepseek:*) resolve under- // --max-cost instead of TX2 no_pricing hard-failing at $0. ANTHROPIC_PRICING- // above is only the bare-keyed Claude view.- const canon = canonicalLookup(key);- if (canon) return canon;- // Local-inference chat providers cost electricity, not tokens. Checked AFTER- // the canonical table so an explicitly-priced local entry, should one ever be- // added, still wins over the blanket zero.- if (kind === 'chat' && providerId && FREE_LOCAL_CHAT_PROVIDERS.has(providerId)) {- return { input: 0, output: 0 };- }- return null;-}--/**- * True when the budget tracker can price this model, i.e. when setting a cost- * cap is meaningful. Callers that apply a *default* cap (rather than one the- * user asked for) should skip the cap when this returns false — otherwise- * `reserve()` hard-fails with BudgetExhausted(reason:'no_pricing') and the- * caller silently does no work.- */-export function isModelPriceable(modelId: string, kind: BudgetKind, overrides?: PricingOverrides): boolean {- return overrideFor(modelId, overrides) !== null || lookupPricing(modelId, kind) !== null;-}--function costForUsage(- modelId: string,- inputTokens: number,- outputTokens: number,- kind: BudgetKind,- overrides?: PricingOverrides,-): number | null {- // #4312: operator overrides win — the operator owns their bill (negotiated- // rates, proxy routes the shipped tables can't know about). Missing both →- // null, and the TX2 fail-closed contract in reserve() still applies.- const p = overrideFor(modelId, overrides) ?? lookupPricing(modelId, kind);- if (!p) return null;- return (inputTokens / 1_000_000) * p.input + (outputTokens / 1_000_000) * p.output;-}-export class BudgetTracker {private cumulativeUsd = 0;/**@@ -374,6 +220,7 @@ export class BudgetTracker {/** FIFO of unsettled projections keyed `${modelId}|${kind}` (gateway pairs reserve→record 1:1). */private readonly outstandingByKey = new Map<string, number[]>();private callsRecorded = 0;+ private readonly ledger = new ModelLedger();private readonly startedAt: number;private readonly auditPath: string;private readonly onExhaustedCbs: Array<() => void> = [];@@ -423,11 +270,11 @@ export class BudgetTracker {reserve(estimate: BudgetEstimate): void {this.assertRuntime(estimate.modelId);- const projected = costForUsage(+ const projected = reservationCostUsd(estimate.modelId,+ estimate.kind,estimate.estimatedInputTokens,estimate.maxOutputTokens,- estimate.kind,this.opts.pricingOverrides,);@@ -544,13 +391,28 @@ export class BudgetTracker {record(actual: BudgetActualUsage & { kind?: BudgetKind }): void {this.callsRecorded++;const kind: BudgetKind = actual.kind ?? 'chat';- const cost = costForUsage(+ const cost = usageCostUsd(actual.modelId,actual.inputTokens,actual.outputTokens ?? 0,kind,this.opts.pricingOverrides,);+ // The ledger sees every record — before the unpriced return and the TX1+ // throw below — so an over-cap or unpriced call is never invisible.+ const servedModel = canonicalPricingKey(actual.modelId);+ this.ledger.add({+ requestedModel: actual.requestedModelId ?? servedModel,+ model: servedModel,+ label: actual.label,+ purpose: actual.purpose,+ failed: actual.failed === true || (actual.label?.endsWith('.failed') ?? false),+ countsAsCall: actual.countsAsCall !== false,+ estimated: actual.estimated === true,+ inputTokens: actual.inputTokens,+ outputTokens: actual.outputTokens ?? 0,+ costUsd: cost,+ });if (cost === null) {// Unpriced model: record audit but skip cumulative math. Cap (if set)@@ -607,6 +469,7 @@ export class BudgetTracker {maxCostUsd: this.opts.maxCostUsd,maxRuntimeMs: this.opts.maxRuntimeMs,callsRecorded: this.callsRecorded,+ models: this.ledger.rows(),};}@@ -685,24 +548,28 @@ export function extractUsageFromError(err: unknown,fallback: { inputTokens: number; outputTokens: number },): { inputTokens: number; outputTokens: number } {- if (err && typeof err === 'object') {- const top = (err as { usage?: unknown }).usage;- const nested = (err as { response?: { usage?: unknown } }).response?.usage;- const candidate = (top && typeof top === 'object' ? top : nested && typeof nested === 'object' ? nested : null) as- | { input_tokens?: number; output_tokens?: number; inputTokens?: number; outputTokens?: number }- | null;- if (candidate) {- const inputTokens = numericOrNull(candidate.input_tokens ?? candidate.inputTokens);- const outputTokens = numericOrNull(candidate.output_tokens ?? candidate.outputTokens);- if (inputTokens !== null || outputTokens !== null) {- return {- inputTokens: inputTokens ?? fallback.inputTokens,- outputTokens: outputTokens ?? fallback.outputTokens,- };- }- }- }- return { inputTokens: fallback.inputTokens, outputTokens: fallback.outputTokens };+ const found = usageFromError(err);+ return {+ inputTokens: found?.inputTokens ?? fallback.inputTokens,+ outputTokens: found?.outputTokens ?? fallback.outputTokens,+ };+}++/**+ * The usage an SDK error envelope reports, or null when it reports none.+ * Either side may be null when the provider reported only the other.+ */+export function usageFromError(err: unknown): { inputTokens: number | null; outputTokens: number | null } | null {+ if (!err || typeof err !== 'object') return null;+ const top = (err as { usage?: unknown }).usage;+ const nested = (err as { response?: { usage?: unknown } }).response?.usage;+ const candidate = (top && typeof top === 'object' ? top : nested && typeof nested === 'object' ? nested : null) as+ | { input_tokens?: number; output_tokens?: number; inputTokens?: number; outputTokens?: number }+ | null;+ if (!candidate) return null;+ const inputTokens = numericOrNull(candidate.input_tokens ?? candidate.inputTokens);+ const outputTokens = numericOrNull(candidate.output_tokens ?? candidate.outputTokens);+ return inputTokens !== null || outputTokens !== null ? { inputTokens, outputTokens } : null;}function numericOrNull(v: unknown): number | null {diff --git a/src/core/budget/models-used.ts b/src/core/budget/models-used.tsnew file mode 100644index 0000000000..c6fba05f6e--- /dev/null+++ b/src/core/budget/models-used.ts@@ -0,0 +1,158 @@+/**+ * Per-model spend ledger behind `BudgetTracker.snapshot().models` and the+ * `models_used` receipt field (#5585). Rows key on (requested model, served+ * model, touchpoint, purpose) so a caller can see which model every gateway+ * touchpoint actually called — including engine-internal calls (query+ * expansion, embeddings, rerank) that no command flag names.+ *+ * `calls` counts gateway operations; `attempts` counts every recorded+ * provider round-trip. SDK-internal retries and a structured-output fallback+ * inside one operation are ONE call (the fallback adds an attempt). A row's+ * `cost_usd` is null when the served model is unpriced, and `cost_basis` is+ * `estimated` when any contributing record was priced from a heuristic token+ * count (char-estimated embed/rerank input, or a failed call's pessimistic+ * fallback) instead of provider-reported usage.+ */++export type ModelTouchpoint = 'chat' | 'expansion' | 'embedding' | 'rerank' | 'ocr' | 'other';++export interface ModelUsageRow {+ requested_model: string;+ /** Served (reported) model, pricing-canonicalized. */+ model: string;+ touchpoint: ModelTouchpoint;+ purpose: string | null;+ calls: number;+ attempts: number;+ failed_calls: number;+ input_tokens: number;+ output_tokens: number;+ cost_usd: number | null;+ cost_basis: 'measured' | 'estimated';+}++export interface LedgerEntry {+ requestedModel: string;+ model: string;+ label?: string;+ purpose?: string;+ failed: boolean;+ countsAsCall: boolean;+ estimated: boolean;+ inputTokens: number;+ outputTokens: number;+ costUsd: number | null;+}++const TOUCHPOINT_ORDER: readonly ModelTouchpoint[] = ['chat', 'expansion', 'embedding', 'rerank', 'ocr', 'other'];++const LABEL_TOUCHPOINTS: ReadonlyArray<[string, ModelTouchpoint]> = [+ ['gateway.chat', 'chat'],+ ['gateway.expand', 'expansion'],+ ['gateway.embed', 'embedding'],+ ['gateway.rerank', 'rerank'],+ ['gateway.ocr', 'ocr'],+];++/** Map a gateway record label (`gateway.expand.failed`, …) to its touchpoint. */+export function touchpointForLabel(label: string | undefined): ModelTouchpoint {+ if (!label) return 'other';+ for (const [prefix, touchpoint] of LABEL_TOUCHPOINTS) {+ if (label === prefix || label.startsWith(`${prefix}.`)) return touchpoint;+ }+ return 'other';+}++function rowKey(r: Pick<ModelUsageRow, 'requested_model' | 'model' | 'touchpoint' | 'purpose'>): string {+ return JSON.stringify([r.requested_model, r.model, r.touchpoint, r.purpose]);+}++function combine(a: ModelUsageRow, b: ModelUsageRow): ModelUsageRow {+ return {+ ...a,+ calls: a.calls + b.calls,+ attempts: a.attempts + b.attempts,+ failed_calls: a.failed_calls + b.failed_calls,+ input_tokens: a.input_tokens + b.input_tokens,+ output_tokens: a.output_tokens + b.output_tokens,+ cost_usd: a.cost_usd === null || b.cost_usd === null ? null : a.cost_usd + b.cost_usd,+ cost_basis: a.cost_basis === 'estimated' || b.cost_basis === 'estimated' ? 'estimated' : 'measured',+ };+}++function rowForEntry(e: LedgerEntry): ModelUsageRow {+ return {+ requested_model: e.requestedModel,+ model: e.model,+ touchpoint: touchpointForLabel(e.label),+ purpose: e.purpose ?? null,+ calls: e.countsAsCall ? 1 : 0,+ attempts: 1,+ failed_calls: e.failed && e.countsAsCall ? 1 : 0,+ input_tokens: e.inputTokens,+ output_tokens: e.outputTokens,+ cost_usd: e.costUsd,+ cost_basis: e.estimated ? 'estimated' : 'measured',+ };+}++function sortRows(rows: ModelUsageRow[]): ModelUsageRow[] {+ return rows.sort((a, b) =>+ TOUCHPOINT_ORDER.indexOf(a.touchpoint) - TOUCHPOINT_ORDER.indexOf(b.touchpoint)+ || (a.purpose ?? '').localeCompare(b.purpose ?? '')+ || a.model.localeCompare(b.model)+ || a.requested_model.localeCompare(b.requested_model));+}++/** In-memory aggregation of recorded usage; one instance per BudgetTracker. */+export class ModelLedger {+ private readonly rowsByKey = new Map<string, ModelUsageRow>();++ add(entry: LedgerEntry): void {+ const row = rowForEntry(entry);+ const key = rowKey(row);+ const prev = this.rowsByKey.get(key);+ this.rowsByKey.set(key, prev ? combine(prev, row) : row);+ }++ rows(): ModelUsageRow[] {+ return sortRows([...this.rowsByKey.values()].map(r => ({ ...r })));+ }+}++/** Merge row sets (e.g. prior resume segments + this segment) on the ledger key. */+export function mergeModelUsageRows(...sets: ModelUsageRow[][]): ModelUsageRow[] {+ const merged = new Map<string, ModelUsageRow>();+ for (const row of sets.flat()) {+ const key = rowKey(row);+ const prev = merged.get(key);+ merged.set(key, prev ? combine(prev, row) : { ...row });+ }+ return sortRows([...merged.values()]);+}++/**+ * Receipt-ready `models_used` rows from a tracker snapshot, merged with rows+ * persisted by earlier segments of the same run (resume).+ */+export function buildModelsUsed(snapshot: { models: ModelUsageRow[] }, priorRows: ModelUsageRow[] = []): ModelUsageRow[] {+ return mergeModelUsageRows(priorRows, snapshot.models);+}++/**+ * Fixed-width table lines (header first) for CLI summaries. `requested ->+ * served` shows only when they differ; `~` marks an estimated cost.+ */+export function formatModelsUsedTable(rows: ModelUsageRow[]): string[] {+ const header = ['touchpoint', 'purpose', 'model', 'calls', 'tokens in/out', 'cost'];+ const cells = rows.map(r => [+ r.touchpoint,+ r.purpose ?? 'engine',+ r.requested_model === r.model ? r.model : `${r.requested_model} -> ${r.model}`,+ `${r.calls}${r.attempts !== r.calls ? ` (${r.attempts} attempts)` : ''}${r.failed_calls > 0 ? `, ${r.failed_calls} failed` : ''}`,+ `${r.input_tokens}/${r.output_tokens}`,+ r.cost_usd === null ? 'unpriced' : `${r.cost_basis === 'estimated' ? '~' : ''}$${r.cost_usd.toFixed(4)}`,+ ]);+ const widths = header.map((h, i) => Math.max(h.length, ...cells.map(c => c[i]!.length)));+ return [header, ...cells].map(c => c.map((v, i) => v.padEnd(widths[i]!)).join(' ').trimEnd());+}diff --git a/src/core/budget/reservation-cost.ts b/src/core/budget/reservation-cost.tsnew file mode 100644index 0000000000..8195871f6f--- /dev/null+++ b/src/core/budget/reservation-cost.ts@@ -0,0 +1,202 @@+/**+ * Pure pricing math shared by BudgetTracker (reserve + record) and callers+ * that must predict a tracker decision before any spend (skillopt preflight's+ * impossible-reservation check). One lookup chain: operator overrides, then+ * the shipped tables with recipe-alias normalization, then the free+ * local-inference providers; `null` means unpriced (TX2 applies under a cap).+ */++import { ANTHROPIC_PRICING, type ModelPricing } from '../anthropic-pricing.ts';+import { canonicalLookup } from '../model-pricing.ts';+import { lookupEmbeddingPrice } from '../embedding-pricing.ts';+import { splitProviderModelId } from '../model-id.ts';+import { resolveRecipe } from '../ai/model-resolver.ts';++export type BudgetKind = 'chat' | 'embed' | 'rerank';++/**+ * #4312 — normalized operator price overrides: model string (lowercased) →+ * per-1M-token pricing. Declared in the config plane as JSON, e.g.+ * gbrain config set pricing.overrides '{"litellm:gpt-4o": {"input": 2.5, "output": 10}, "litellm:text-embedding-3-large": 0.13}'+ * A bare number means one rate for input AND output tokens (embeddings only+ * ever bill input, so a scalar is the natural spelling there).+ */+export type PricingOverrides = Record<string, ModelPricing>;++/**+ * Recipe-alias normalization shared by the override and table lookups:+ * `claude-cli:haiku` → `claude-cli:claude-haiku-4-5-20251001`. Bare ids and+ * unknown providers throw out of resolveRecipe and keep the raw id, so the+ * downstream chains decide those exactly as before.+ */+export function canonicalPricingKey(modelId: string): string {+ try {+ const { parsed } = resolveRecipe(modelId);+ return `${parsed.providerId}:${parsed.modelId}`;+ } catch {+ return modelId;+ }+}++/**+ * Override lookup (keys normalized to lowercase at parse time): the raw key+ * first, then the recipe-canonical key — an override written against the+ * dated id must also price the alias the operator configured, or the alias+ * silently bills at list price while the table lookup below resolves it.+ */+function overrideFor(modelId: string, overrides?: PricingOverrides): ModelPricing | null {+ if (!overrides) return null;+ const raw = modelId.trim().toLowerCase();+ return overrides[raw] ?? overrides[canonicalPricingKey(modelId.trim()).toLowerCase()] ?? null;+}++/**+ * Provider id prefixes that always price at $0 for the rerank kind+ * (electricity, not API tokens). Centralized here so `--max-cost` callers+ * don't hard-fail TX2 when a local rerank provider is configured. Matched+ * against the provider half of the `provider:model` string. Extend this set+ * when adding new local-inference rerank recipes.+ */+const FREE_LOCAL_RERANK_PROVIDERS: ReadonlySet<string> = new Set([+ 'llama-server-reranker',+]);++/**+ * Provider id prefixes whose embeddings run on local inference (electricity,+ * not API tokens) and so price at $0. Without this, a `--max-cost`-bounded+ * embed/reindex job configured for a local provider TX2 hard-fails because+ * lookupEmbeddingPrice has no entry for them. Matched against the provider+ * half of the `provider:model` string.+ *+ * 'litellm' is excluded — a LiteLLM proxy can front a paid provider, so+ * pricing-unknown is the honest state there.+ *+ * Sibling to FREE_LOCAL_RERANK_PROVIDERS; v0.41+ TODO unifies them via+ * recipe-cost-driven resolution.+ */+const FREE_LOCAL_EMBED_PROVIDERS: ReadonlySet<string> = new Set([+ 'ollama',+ 'llama-server',+ 'lmstudio',+]);++/**+ * Chat sibling of FREE_LOCAL_EMBED_PROVIDERS / FREE_LOCAL_RERANK_PROVIDERS.+ *+ * Local inference costs electricity, not tokens, so these providers price at+ * $0 rather than TX2 hard-failing. Without this a caller that sets ANY cost cap+ * cannot use a local chat model at all: CANONICAL_PRICING has no `ollama:*`+ * keys, so `reserve()` throws no_pricing before the first call and every work+ * item is skipped with `budget_exhausted: true` at $0 spent.+ *+ * That is not theoretical — `cycle.extract_atoms` always constructs its tracker+ * with `maxCostUsd` (config only accepts `n > 0`, so the cap can't be unset),+ * which made `models.dream.extract_atoms: ollama:*` silently extract nothing.+ *+ * `litellm` is excluded on purpose, matching the embed set: a LiteLLM proxy can+ * front a paid provider, so pricing-unknown is the honest state there.+ */+const FREE_LOCAL_CHAT_PROVIDERS: ReadonlySet<string> = new Set([+ 'ollama',+ 'llama-server',+]);++function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {+ if (kind === 'embed') {+ const hit = lookupEmbeddingPrice(modelId);+ if (hit.kind === 'known') {+ return { input: hit.pricePerMTok, output: 0 };+ }+ // v0.40.x: local-inference embed providers cost electricity, not tokens.+ if (hit.kind === 'unknown' && FREE_LOCAL_EMBED_PROVIDERS.has(hit.provider)) {+ return { input: 0, output: 0 };+ }+ return null;+ }+ // chat or rerank: try bare key first, then provider:model or provider/model.+ // v0.41.21.0: route through splitProviderModelId so slash-prefixed ids+ // (the form `--judge-model` and OpenRouter recipes emit) hit the pricing+ // table. Pre-fix, slash-form silently no_pricing-failed `--max-cost` on+ // brainstorm/lsd.+ const bare = ANTHROPIC_PRICING[modelId];+ if (bare) return bare;+ // Recipe aliases (`claude-cli:haiku`, `anthropic:sonnet`) are not pricing+ // keys, and the gateway reserves with the string the user configured —+ // BEFORE alias resolution — so `claude-cli:haiku` under a cap used to TX2+ // hard-fail with no_pricing while the dated id it maps to priced fine.+ // Normalize once here; the chain below then prices the canonical id, and+ // alias vs dated id agree at reserve(), record() and isModelPriceable().+ // Bare ids and unknown providers keep the raw id (canonicalPricingKey): the+ // existing chain decides those exactly as before.+ const key = canonicalPricingKey(modelId);+ const { provider: providerId, model: modelTail } = splitProviderModelId(key);+ if (modelTail) {+ const tailHit = ANTHROPIC_PRICING[modelTail];+ if (tailHit) return tailHit;+ }+ if (kind === 'rerank') {+ const hit = lookupEmbeddingPrice(key);+ if (hit.kind === 'known') return { input: hit.pricePerMTok, output: 0 };+ }+ // v0.40.6.1: zero-price local-inference rerank providers so the budget+ // tracker's TX2 hard-fail doesn't trip on `llama-server-reranker:<model>`+ // under `--max-cost`. Only the rerank kind — chat/embed already have+ // their own provider-specific pricing surfaces.+ if (kind === 'rerank' && providerId && FREE_LOCAL_RERANK_PROVIDERS.has(providerId)) {+ return { input: 0, output: 0 };+ }+ // Fall back to the full canonical pricing table so non-Anthropic chat+ // models with a known price (openai:*, google:*, deepseek:*) resolve under+ // --max-cost instead of TX2 no_pricing hard-failing at $0. ANTHROPIC_PRICING+ // above is only the bare-keyed Claude view.+ const canon = canonicalLookup(key);+ if (canon) return canon;+ // Local-inference chat providers cost electricity, not tokens. Checked AFTER+ // the canonical table so an explicitly-priced local entry, should one ever be+ // added, still wins over the blanket zero.+ if (kind === 'chat' && providerId && FREE_LOCAL_CHAT_PROVIDERS.has(providerId)) {+ return { input: 0, output: 0 };+ }+ return null;+}++/**+ * True when the budget tracker can price this model, i.e. when setting a cost+ * cap is meaningful. Callers that apply a *default* cap (rather than one the+ * user asked for) should skip the cap when this returns false — otherwise+ * `reserve()` hard-fails with BudgetExhausted(reason:'no_pricing') and the+ * caller silently does no work.+ */+export function isModelPriceable(modelId: string, kind: BudgetKind, overrides?: PricingOverrides): boolean {+ return overrideFor(modelId, overrides) !== null || lookupPricing(modelId, kind) !== null;+}++export function usageCostUsd(+ modelId: string,+ inputTokens: number,+ outputTokens: number,+ kind: BudgetKind,+ overrides?: PricingOverrides,+): number | null {+ // #4312: operator overrides win — the operator owns their bill (negotiated+ // rates, proxy routes the shipped tables can't know about). Missing both →+ // null, and the TX2 fail-closed contract in reserve() still applies.+ const p = overrideFor(modelId, overrides) ?? lookupPricing(modelId, kind);+ if (!p) return null;+ return (inputTokens / 1_000_000) * p.input + (outputTokens / 1_000_000) * p.output;+}++/**+ * USD a `reserve()` projects for one call: the input estimate plus the full+ * output ceiling. `null` when the model is unpriced — under a cost cap the+ * tracker then hard-fails with `no_pricing`.+ */+export function reservationCostUsd(+ modelId: string,+ kind: BudgetKind,+ inputTokens: number,+ maxOutputTokens: number,+ overrides?: PricingOverrides,+): number | null {+ return usageCostUsd(modelId, inputTokens, maxOutputTokens, kind, overrides);+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 98b70744e7..ae6a9fd878 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -68,7 +68,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -106,7 +106,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],'serve': ['--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--port', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],- 'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models'],+ 'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],diff --git a/src/core/config.ts b/src/core/config.tsindex 64df4a4bb7..aa919f57ba 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1530,6 +1530,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`// works without --force, as the compiled-truth guide documents.'auto_timeline',+ // #5584: skillopt optimizer output cap (default 32000 thinking / 4096 otherwise).+ 'skillopt.reflect_max_tokens',+ // #5585: skillopt strict model provenance (true|1|yes|on; other values count as on).+ 'skillopt.models_strict',// #2606: chronicle judge output-token cap (default 4000). Event-dense// pages overflowed the old hardcoded 1500 and were misrecorded as// no_events; the cap is now configurable and truncation is surfaced.diff --git a/src/core/model-config.ts b/src/core/model-config.tsindex 3a1f81c915..5bc5ddde2c 100644--- a/src/core/model-config.ts+++ b/src/core/model-config.ts@@ -401,6 +401,42 @@ export type ResolveSource =| 'tier_default'| 'fallback';+/**+ * A resolved model plus the chain step that produced it. When the subagent+ * capability gate replaced the configured model, `substituted_from` is what+ * was configured and `substitution_reason` says why (`no_tools`,+ * `no_subagent_loop`, `unknown_provider`).+ */+export interface ResolvedModel {+ model: string;+ source: ResolveSource;+ substituted_from?: string;+ substitution_reason?: SubagentSubstitutionReason;+}++export type SubagentSubstitutionReason = 'no_tools' | 'no_subagent_loop' | 'unknown_provider';++/**+ * Human-facing origin of a resolution step: the flag, config key or env var+ * that supplied the model (`models.tier.deep`, `models.default`,+ * `GBRAIN_MODEL`), or `built-in default`. Key names only, never values.+ */+export function describeResolveOrigin(+ source: ResolveSource,+ opts: Pick<ResolveModelOpts, 'configKey' | 'deprecatedConfigKey' | 'envVar' | 'tier'> & { flag?: string },+): string {+ switch (source) {+ case 'cli_flag': return opts.flag ?? 'flag';+ case 'config_key': return opts.configKey ?? 'config';+ case 'deprecated_key': return opts.deprecatedConfigKey ?? 'config';+ case 'tier_config': return `models.tier.${opts.tier}`;+ case 'models_default': return 'models.default';+ case 'env': return opts.envVar ?? 'GBRAIN_MODEL';+ case 'tier_default':+ case 'fallback': return 'built-in default';+ }+}+/*** Resolve a model name through the precedence chain, reporting WHICH step* produced it. Async because it reads config from the engine. Pass@@ -413,7 +449,7 @@ export type ResolveSource =export async function resolveModelDetailed(engine: ConfigReader | null,opts: ResolveModelOpts,-): Promise<{ model: string; source: ResolveSource }> {+): Promise<ResolvedModel> {const envVar = opts.envVar ?? 'GBRAIN_MODEL';// 1. CLI flag wins@@ -454,7 +490,7 @@ export async function resolveModelDetailed(const tierVal = await engine.getConfig(`models.tier.${opts.tier}`);if (tierVal && tierVal.trim()) {const resolved = await resolveAlias(engine, tierVal.trim());- return { model: enforceSubagentCapable(resolved, opts.tier, `models.tier.${opts.tier}`), source: 'tier_config' };+ return withSubagentGate(resolved, opts.tier, `models.tier.${opts.tier}`, 'tier_config');}}@@ -462,7 +498,7 @@ export async function resolveModelDetailed(const def = await engine.getConfig('models.default');if (def && def.trim()) {const resolved = await resolveAlias(engine, def.trim());- return { model: enforceSubagentCapable(resolved, opts.tier, 'models.default'), source: 'models_default' };+ return withSubagentGate(resolved, opts.tier, 'models.default', 'models_default');}}@@ -470,7 +506,7 @@ export async function resolveModelDetailed(const env = process.env[envVar];if (env && env.trim()) {const resolved = await resolveAlias(engine, env.trim());- return { model: enforceSubagentCapable(resolved, opts.tier, `env:${envVar}`), source: 'env' };+ return withSubagentGate(resolved, opts.tier, `env:${envVar}`, 'env');}// 7. Key-aware tier default — when no override beats us, the tier's@@ -478,7 +514,7 @@ export async function resolveModelDetailed(// caller-supplied fallback.if (opts.tier && TIER_DEFAULTS[opts.tier]) {const resolved = await resolveAlias(engine, resolveTierDefault(opts.tier));- return { model: enforceSubagentCapable(resolved, opts.tier, 'tier-default'), source: 'tier_default' };+ return withSubagentGate(resolved, opts.tier, 'tier-default', 'tier_default');}// 8. Hardcoded fallback (caller-supplied)@@ -528,7 +564,22 @@ export async function resolveModel(* suppression key) so doctor + first-call surfaces don't double-warn.*/function enforceSubagentCapable(resolved: string, tier: ModelTier | undefined, source: string): string {- if (tier !== 'subagent') return resolved;+ return subagentGate(resolved, tier, source).model;+}++function withSubagentGate(resolved: string, tier: ModelTier | undefined, sourceLabel: string, source: ResolveSource): ResolvedModel {+ const gate = subagentGate(resolved, tier, sourceLabel);+ return gate.reason+ ? { model: gate.model, source, substituted_from: resolved, substitution_reason: gate.reason }+ : { model: gate.model, source };+}++function subagentGate(+ resolved: string,+ tier: ModelTier | undefined,+ source: string,+): { model: string; reason?: SubagentSubstitutionReason } {+ if (tier !== 'subagent') return { model: resolved };// Lazy import keeps capabilities.ts out of model-config's eager-load surface// (capabilities → model-resolver → recipes; this would create a cycle if@@ -546,26 +597,29 @@ function enforceSubagentCapable(resolved: string, tier: ModelTier | undefined, s// If the import fails (e.g. malformed recipe registry during boot), be// permissive and just return the resolved model — surface the underlying// issue at gateway call time.- return resolved;+ return { model: resolved };}const key = `${source}:${resolved}`;if (verdict === 'unusable:no_tools' || verdict === 'unusable:no_subagent_loop' || verdict === 'unknown') {+ const reason: SubagentSubstitutionReason = verdict === 'unusable:no_tools'+ ? 'no_tools'+ : verdict === 'unusable:no_subagent_loop' ? 'no_subagent_loop' : 'unknown_provider';if (!_subagentTierWarningsEmitted.has(key)) {_subagentTierWarningsEmitted.add(key);- const reason = verdict === 'unusable:no_tools'+ const prose = reason === 'no_tools'? `lacks tool-calling support`- : verdict === 'unusable:no_subagent_loop'+ : reason === 'no_subagent_loop'? `declares the subagent loop unsupported (supports_subagent_loop: false)`: `is an unrecognized provider`;process.stderr.write(- `[models] tier.subagent resolved to "${resolved}" via "${source}", which ${reason}. ` ++ `[models] tier.subagent resolved to "${resolved}" via "${source}", which ${prose}. ` +`The subagent tool loop cannot run on this model — falling back to ${TIER_DEFAULTS.subagent}. ` +`Fix: gbrain config set models.tier.subagent <provider>:<model> ` +`(the provider's recipe must declare supports_subagent_loop: true)\n`,);}- return TIER_DEFAULTS.subagent;+ return { model: TIER_DEFAULTS.subagent, reason };}if (verdict === 'degraded:no_caching') {@@ -579,7 +633,7 @@ function enforceSubagentCapable(resolved: string, tier: ModelTier | undefined, s}}// degraded:no_parallel and ok return resolved unchanged (no warn).- return resolved;+ return { model: resolved };}/**diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.tsindex 8109e78149..b134ce1309 100644--- a/src/core/ops/skillopt.ts+++ b/src/core/ops/skillopt.ts@@ -133,10 +133,11 @@ const run_skillopt: Operation = {batch_size: { type: 'number', description: 'Default 8' },lr: { type: 'number', description: 'Default 4' },max_cost_usd: { type: 'number', description: 'Default 5.00' },+ reflect_max_tokens: { type: 'number', description: 'Optimizer output cap (positive integer, clamped to 256..32000). Default: skillopt.reflect_max_tokens config, else 32000 for thinking optimizers and 4096 otherwise.' },no_mutate: { type: 'boolean', description: 'Write proposed.md without replacing SKILL.md' },allow_mutate_bundled: { type: 'boolean', description: 'Required to mutate bundled skills' },held_out_path: { type: 'string', description: 'Path to a held-out test set (JSONL). REQUIRED (>=5 rows) to mutate a bundled skill in place — otherwise the run hard-refuses. Remote callers: must resolve within the skills directory.' },- dry_run: { type: 'boolean', description: 'Cost preview, no LLM calls' },+ dry_run: { type: 'boolean', description: 'Preview: models plan, strict verdict and cost estimate, no LLM calls' },shared_skill: { type: 'boolean', description: 'Optimize an exact shared catalog revision in a private proposal workspace and publish the accepted body through put_skill.' },source_id: { type: 'string', description: 'Required with shared_skill: canonical source.' },source_incarnation: { type: 'string', description: 'Required with shared_skill: exact catalog source incarnation.' },@@ -172,9 +173,16 @@ const run_skillopt: Operation = {throw new OperationError('permission_denied', `run_skillopt: skill '${skillName}' is not in skillopt.allowed_skills allowlist (default deny-all for remote callers)`);}}+ const { clampRemoteReflectMaxTokens } = await import('../skillopt/output-cap.ts');+ let reflectMaxTokens: number | undefined;+ try {+ reflectMaxTokens = clampRemoteReflectMaxTokens(p.reflect_max_tokens);+ } catch (err) {+ throw new OperationError('invalid_params', `run_skillopt: ${err instanceof Error ? err.message : String(err)}`);+ }const { runSkillOpt } = await import('../skillopt/orchestrator.ts');const { autoDetectSkillsDirReadOnly } = await import('../repo-root.ts');- const { resolveModel } = await import('../model-config.ts');+ const { resolveSkillOptModels, skillOptModelOpts } = await import('../skillopt/models-plan.ts');let sharedSkill: import('../skillopt/types.ts').SkillOptOpts['sharedSkill'];if (p.shared_skill === true) {for (const field of ['source_id', 'source_incarnation', 'pack_id', 'expected_revision', 'request_id']) {@@ -191,9 +199,7 @@ const run_skillopt: Operation = {if (!skillsDir) {throw new OperationError('config_error', 'run_skillopt: skills directory not found');}- const optimizerModel = await resolveModel(ctx.engine, { tier: 'deep', fallback: 'anthropic:claude-opus-4-7' });- const targetModel = await resolveModel(ctx.engine, { tier: 'subagent', fallback: 'anthropic:claude-sonnet-4-6' });- const judgeModel = await resolveModel(ctx.engine, { tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' });+ const models = await resolveSkillOptModels(ctx.engine);const skillName = p.skill_name as string;const benchmarkPath = (p.benchmark_path as string) ??`${skillsDir}/${skillName}/skillopt-benchmark.jsonl`;@@ -240,9 +246,8 @@ const run_skillopt: Operation = {lr: (p.lr as number) ?? 4,lrSchedule: 'cosine',split: [4, 1, 5],- optimizerModel,- targetModel,- judgeModel,+ ...skillOptModelOpts(models),+ ...(reflectMaxTokens !== undefined ? { reflectMaxTokens } : {}),mode: 'patch',dryRun: (p.dry_run as boolean) === true,noMutate: (p.no_mutate as boolean) === true,diff --git a/src/core/skillopt/audit.ts b/src/core/skillopt/audit.tsindex 110a215694..e730a4f389 100644--- a/src/core/skillopt/audit.ts+++ b/src/core/skillopt/audit.ts@@ -12,6 +12,8 @@import { createHash } from 'node:crypto';import { createAuditWriter, type AuditWriter } from '../audit/audit-writer.ts';+import type { ModelUsageRow } from '../budget/models-used.ts';+import type { ModelsPlanEntry } from './models-plan.ts';import type { EditOp } from './types.ts';/** Discriminated union of every event kind emitted to the audit trail. */@@ -19,11 +21,13 @@ export type SkilloptEvent =| { kind: 'run_start'; run_id: string; skill: string; skill_sha8: string;benchmark_sha8: string; target_model: string; optimizer_model: string;judge_model: string; epochs: number; batch_size: number; lr: number;- lr_schedule: string; max_cost_usd: number; ts: string }+ lr_schedule: string; max_cost_usd: number; models_plan?: ModelsPlanEntry[];+ ts: string }| { kind: 'step'; run_id: string; skill: string; epoch: number; step: number;sel_score_median: number; sel_score_runs: number[]; accepted: boolean;edits_attempted: number; edits_applied: number; delta: number;- reason?: string; cumulative_cost_usd: number; ts: string }+ reason?: string; cumulative_cost_usd: number; reflect_errors?: string[];+ invalid_edits_dropped?: number; ts: string }| { kind: 'edit_rejected'; run_id: string; skill: string; epoch: number;step: number; edit_kind: EditOp['op']; rejection_reason: string;ts: string }@@ -33,7 +37,9 @@ export type SkilloptEvent ='no_improvement' | 'aborted' | 'errored'; epochs_completed: number;total_steps: number; baseline_sel_score?: number; best_sel_score?: number;baseline_test_score?: number; test_score?: number; final_cost_usd: number;- ts: string }+ stop_reason?: 'completed' | 'early_stop_unusable_output' | 'aborted';+ abort_detail?: string; models_used?: ModelUsageRow[];+ models_used_scope?: 'full_run' | 'since_resume'; ts: string }// #3516: 'error' is the truthful catch-all for unrecognized failures// (provider errors, no_pricing hard-fails, bugs). 'sigint' is reserved for// an actual SIGINT interrupt — pre-fix the catch-all logged every error asdiff --git a/src/core/skillopt/batch.ts b/src/core/skillopt/batch.tsindex a2e9c77684..a62478660d 100644--- a/src/core/skillopt/batch.ts+++ b/src/core/skillopt/batch.ts@@ -17,6 +17,7 @@ import { assertLegacySkillFilesystemWrite, assertLegacySkillWriter } from '../skimport * as fs from 'node:fs';import * as path from 'node:path';import type { BrainEngine } from '../engine.ts';+import { sanitizeEcho, type ModelsPlanEntry, type SkillOptModels } from './models-plan.ts';import { runSkillOpt } from './orchestrator.ts';import type { RunReceipt, SkillOptOpts } from './types.ts';@@ -31,6 +32,14 @@ export interface BatchAllOpts {optimizerModel: string;targetModel: string;judgeModel: string;+ /** Role provenance (resolveSkillOptModels); absent -> `unknown`. */+ models?: SkillOptModels;+ /** `--models-strict`, applied to every skill's run. */+ modelsStrict?: boolean;+ /** Invocation banner the caller printed; each skill prints only differing rows. */+ modelsBannerBaseline?: ModelsPlanEntry[];+ /** Explicit optimizer output cap (`--reflect-max-tokens`). */+ reflectMaxTokens?: number;epochs: number;batchSize: number;lr: number;@@ -99,6 +108,10 @@ export async function runBatchAll(opts: BatchAllOpts): Promise<BatchAllResult> {optimizerModel: opts.optimizerModel,targetModel: opts.targetModel,judgeModel: opts.judgeModel,+ ...(opts.models ? { models: opts.models } : {}),+ ...(opts.modelsStrict ? { modelsStrict: true } : {}),+ ...(opts.modelsBannerBaseline ? { modelsBannerBaseline: opts.modelsBannerBaseline } : {}),+ ...(opts.reflectMaxTokens !== undefined ? { reflectMaxTokens: opts.reflectMaxTokens } : {}),mode: 'patch',dryRun: opts.dryRun,noMutate: opts.noMutate,@@ -143,6 +156,12 @@ export interface FleetOpts {targetModels: string[];optimizerModel: string;judgeModel: string;+ /** Optimizer + judge provenance; each fleet run's target is `--target-models`. */+ models?: Pick<SkillOptModels, 'optimizer' | 'judge'>;+ /** `--models-strict`, applied to every fleet run. */+ modelsStrict?: boolean;+ /** Explicit optimizer output cap (`--reflect-max-tokens`). */+ reflectMaxTokens?: number;epochs: number;batchSize: number;lr: number;@@ -227,6 +246,11 @@ export async function runFleet(opts: FleetOpts): Promise<FleetResult> {optimizerModel: opts.optimizerModel,targetModel,judgeModel: opts.judgeModel,+ ...(opts.models ? {+ models: { ...opts.models, target: { model: sanitizeEcho(targetModel), source: 'cli_flag' as const, origin: '--target-models' } },+ } : {}),+ ...(opts.modelsStrict ? { modelsStrict: true } : {}),+ ...(opts.reflectMaxTokens !== undefined ? { reflectMaxTokens: opts.reflectMaxTokens } : {}),mode: 'patch',dryRun: opts.dryRun,noMutate,diff --git a/src/core/skillopt/bootstrap-benchmark.ts b/src/core/skillopt/bootstrap-benchmark.tsindex 92fd1fbcf3..f10a17a44b 100644--- a/src/core/skillopt/bootstrap-benchmark.ts+++ b/src/core/skillopt/bootstrap-benchmark.ts@@ -17,6 +17,11 @@* drops instead of zeroing the run; a task is kept only when >=2 valid rule* checks survive (D6). The generated checks are weak DRAFTS the reviewer is* expected to strengthen.+ *+ * Both size their calls with `skilloptOutputCap` (thinking optimizers get the+ * 8192 floor), skip length-stopped output as `truncated` (routing rows are+ * skipped; the from-skill reply's cut final line is dropped), and rethrow+ * budget / runtime / SIGINT aborts before anything is written.*/import { assertLegacySkillFilesystemWrite } from '../skillpack/writer-guard.ts';@@ -25,7 +30,9 @@ import * as path from 'node:path';import { chat as gatewayChat } from '../ai/gateway.ts';import { errorFor } from '../errors.ts';import { atomicWrite } from './apply-edits.ts';-import { BOOTSTRAP_PENDING_REVIEW, type RuleCheck } from './types.ts';+import { isSkilloptMustAbort } from './must-abort.ts';+import { skilloptOutputCap } from './output-cap.ts';+import { BOOTSTRAP_PENDING_REVIEW, SKILLOPT_PURPOSE, type RuleCheck } from './types.ts';const BOOTSTRAP_SYSTEM = `You are SkillOpt's bootstrap-benchmark generator. Given a user intent that triggers a SKILL, generate 2-4 deterministic rule checks that would verify a successful execution.@@ -122,9 +129,15 @@ export async function runBootstrap(opts: BootstrapOpts): Promise<BootstrapResultmodel: optimizerModel,system: BOOTSTRAP_SYSTEM,messages: [{ role: 'user', content: userMsg }],- maxTokens: 500,+ maxTokens: skilloptOutputCap(optimizerModel, 500),cacheSystem: true,+ purpose: SKILLOPT_PURPOSE.optimizer,});+ if (result.stopReason === 'length') {+ skipped += 1;+ process.stderr.write(`[skillopt] bootstrap row ${i + 1} skipped: truncated (reply hit max_tokens)\n`);+ continue;+ }const checks = parseChecksResponse(result.text);if (checks.length === 0) {skipped += 1;@@ -136,6 +149,7 @@ export async function runBootstrap(opts: BootstrapOpts): Promise<BootstrapResultjudge: { kind: 'rule', checks },}));} catch (err) {+ if (isSkilloptMustAbort(err)) throw err;skipped += 1;const msg = err instanceof Error ? err.message : String(err);process.stderr.write(`[skillopt] bootstrap row ${i + 1} failed: ${msg}\n`);@@ -235,11 +249,12 @@ export async function runBootstrapFromSkill(opts: BootstrapFromSkillOpts): Promimodel: optimizerModel,system: BOOTSTRAP_FROM_SKILL_SYSTEM,messages: [{ role: 'user', content: userMsg }],- maxTokens: Math.min(8000, Math.max(4000, taskCount * 220)),+ maxTokens: skilloptOutputCap(optimizerModel, Math.min(8000, Math.max(4000, taskCount * 220))),cacheSystem: true,+ purpose: SKILLOPT_PURPOSE.optimizer,});- const { generated, skipped } = parseSkillBenchmarkJsonl(result.text, skillName);+ const { generated, skipped } = parseSkillBenchmarkJsonl(result.text, skillName, result.stopReason === 'length');if (generated.length === 0) {throw errorFor({@@ -272,15 +287,21 @@ export async function runBootstrapFromSkill(opts: BootstrapFromSkillOpts): Promi* the rest survive. A task is kept only when >=2 valid rule checks survive* validation (D6); otherwise the whole task is dropped and counted. task_ids are* assigned contiguously over KEPT tasks (<skillName>-001..NNN) so they're unique- * and stable for loadBenchmark's duplicate-id check.+ * and stable for loadBenchmark's duplicate-id check. A length-stopped reply's+ * final line is cut by definition and is dropped as `truncated`.*/-function parseSkillBenchmarkJsonl(raw: string, skillName: string): { generated: string[]; skipped: number } {+function parseSkillBenchmarkJsonl(raw: string, skillName: string, truncated: boolean): { generated: string[]; skipped: number } {const fence = raw.match(/```(?:json|jsonl)?\s*\n?([\s\S]*?)```/i);const body = fence ? fence[1]! : raw;const lines = body.split('\n').map((l) => l.trim()).filter((l) => l.length > 0);const generated: string[] = [];let skipped = 0;+ if (truncated && lines.length > 0) {+ lines.pop();+ skipped += 1;+ process.stderr.write(`[skillopt] bootstrap-from-skill reply hit max_tokens; final line skipped: truncated\n`);+ }for (const line of lines) {let parsed: unknown;try {diff --git a/src/core/skillopt/bootstrap-run.ts b/src/core/skillopt/bootstrap-run.tsnew file mode 100644index 0000000000..a186c6b8c8--- /dev/null+++ b/src/core/skillopt/bootstrap-run.ts@@ -0,0 +1,71 @@+/**+ * Guarded bootstrap runs (`--bootstrap-from-skill` / `--bootstrap-from-routing`).+ *+ * Bootstrap calls only the optimizer, so its models plan is one row. The+ * optimizer comes from `resolveSkillOptModels` like every other skillopt+ * path, prints its banner row, honors strict mode, and runs inside a+ * BudgetTracker bounded by `--max-cost-usd` (0 = uncapped), so a call whose+ * reservation cannot fit the cap is refused before it is made. `--dry-run`+ * previews the plan and strict verdict with no model call.+ */++import { withBudgetTracker, type chat as gatewayChat } from '../ai/gateway.ts';+import { BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';+import type { BrainEngine } from '../engine.ts';+import { runBootstrap, runBootstrapFromSkill, type BootstrapResult } from './bootstrap-benchmark.ts';+import {+ formatModelsBanner,+ modelsStrictError,+ resolveModelsStrict,+ strictVerdict,+ type ModelResolution,+ type ModelsPlanEntry,+ type StrictVerdict,+} from './models-plan.ts';++export interface GuardedBootstrapOpts {+ engine: BrainEngine;+ mode: 'routing' | 'skill';+ skillsDir: string;+ skillName: string;+ optimizer: ModelResolution;+ /** Starter task count for `--bootstrap-from-skill`. */+ taskCount?: number;+ force?: boolean;+ dryRun: boolean;+ modelsStrict?: boolean;+ /** USD cap for the bootstrap calls; 0 = uncapped. */+ maxCostUsd: number;+ /** Test seam — substitute gateway.chat. */+ chatFn?: typeof gatewayChat;+}++export type GuardedBootstrapResult =+ | { dry_run: true; models_plan: ModelsPlanEntry[]; strict: StrictVerdict }+ | { dry_run: false; models_plan: ModelsPlanEntry[]; strict: StrictVerdict; result: BootstrapResult; cost_usd: number };++export async function runGuardedBootstrap(opts: GuardedBootstrapOpts): Promise<GuardedBootstrapResult> {+ const plan: ModelsPlanEntry[] = [{ touchpoint: 'optimizer', ...opts.optimizer, active: true }];+ process.stderr.write(formatModelsBanner(plan, { skill: opts.skillName }));+ const strict = strictVerdict(plan, await resolveModelsStrict(opts.engine, opts.modelsStrict));+ if (opts.dryRun) return { dry_run: true, models_plan: plan, strict };+ if (strict.enabled && !strict.ok) throw modelsStrictError(strict);++ const pricingOverrides = await loadPricingOverrides(opts.engine);+ const tracker = new BudgetTracker({+ ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd } : {}),+ ...(pricingOverrides ? { pricingOverrides } : {}),+ label: `skillopt-bootstrap:${opts.skillName}`,+ });+ const common = {+ skillsDir: opts.skillsDir,+ skillName: opts.skillName,+ optimizerModel: opts.optimizer.model,+ force: opts.force,+ ...(opts.chatFn ? { chatFn: opts.chatFn } : {}),+ };+ const result = await withBudgetTracker(tracker, () => opts.mode === 'routing'+ ? runBootstrap(common)+ : runBootstrapFromSkill({ ...common, taskCount: opts.taskCount ?? 15 }));+ return { dry_run: false, models_plan: plan, strict, result, cost_usd: tracker.snapshot().cumulativeCostUsd };+}diff --git a/src/core/skillopt/checkpoint.ts b/src/core/skillopt/checkpoint.tsindex f13c17a9be..34539e2222 100644--- a/src/core/skillopt/checkpoint.ts+++ b/src/core/skillopt/checkpoint.ts@@ -8,24 +8,83 @@* epochs, batch_size, lr, lr_schedule,* best_sel_score, best_skill_text,* last_completed_epoch, last_completed_step,- * cumulative_cost_usd,+ * next_epoch, next_step, // authoritative resume cursor+ * run_spec, // what --resume must match+ * tally, // reflect usability + early-stop counter+ * cumulative_cost_usd, // every segment of the run+ * models_used, models_used_scope, // #5585 ledger rows, every segment* started_at, last_updated_at* }*- * Atomic write via .tmp + rename. On --resume <run_id>, the orchestrator- * reads this file and skips epochs/steps that completed.+ * Atomic write via .tmp + rename. The cursor advances after EVERY completed+ * step (accepted, rejected or no candidate) and cost/tally are persisted on+ * completed steps AND handled aborts, so --resume <run_id> continues at the+ * first step that did not complete. Legacy checkpoints (no cursor) convert via+ * `resumeCursor`. `assertResumeCompatible` refuses a resume whose benchmark,+ * held-out set, split, target/judge model or batch size changed, or whose+ * mutate policy would widen (no-mutate -> mutate); the optimizer model, reflect+ * cap and cost cap may change.*- * 7-day GC: stale checkpoints older than 7 days are removed by the dream- * cycle's purge phase (T6 wiring).+ * Accounting (#5585): `bankAccounting` folds this segment's tracker snapshot+ * onto what earlier segments banked, so a resumed run's receipt reports the+ * whole run. A legacy checkpoint without ledger rows marks the resumed run's+ * `models_used` as `since_resume`.+ *+ * 7-day GC: stale checkpoints older than 7 days are removed at the start of+ * the dream cycle's skillopt phase.*/import { assertLegacySkillFilesystemWrite } from '../skillpack/writer-guard.ts';import * as fs from 'node:fs';import * as path from 'node:path';+import { errorFor } from '../errors.ts';import { atomicWrite } from './apply-edits.ts';+import type { BudgetSnapshot } from '../budget/budget-tracker.ts';+import { buildModelsUsed, type ModelUsageRow } from '../budget/models-used.ts';const CHECKPOINT_SCHEMA = 1;+/** The run's reproducible shape: resume refusal + the printed resume command read it. */+export interface RunSpec {+ skills_dir: string;+ benchmark_path: string;+ benchmark_sha8: string;+ held_out_path: string | null;+ held_out_sha8: string | null;+ split: [number, number, number];+ /** Effective mutate decision (false for --no-mutate and bundled-without-allow). */+ mutate: boolean;+ no_mutate: boolean;+ allow_mutate_bundled: boolean;+ bootstrap_reviewed: boolean;+ optimizer_model: string;+ target_model: string;+ judge_model: string;+ epochs: number;+ batch_size: number;+ lr: number;+ lr_schedule: 'cosine' | 'linear' | 'constant';+ reflect_max_tokens: number;+}++/** Whole-run optimizer-reply accounting (survives resume). */+export interface ReflectTally {+ /** Optimizer calls attempted (reflect + one-shot). */+ reflect_calls: number;+ /** Calls whose reply was usable (edits or a deliberate empty). */+ usable_replies: number;+ /** Consecutive steps whose every optimizer call errored. */+ unusable_streak: number;+ /** Steps whose candidate was accepted (SKILL.md / proposed.md truth). */+ accepted_steps: number;+ reflect_errors: string[];+ invalid_edits_dropped: number;+}++export function emptyTally(): ReflectTally {+ return { reflect_calls: 0, usable_replies: 0, unusable_streak: 0, accepted_steps: 0, reflect_errors: [], invalid_edits_dropped: 0 };+}+export interface RunCheckpoint {schema: 1;run_id: string;@@ -43,14 +102,111 @@ export interface RunCheckpoint {best_sel_score: number;/** The skill text that produced best_sel_score. */best_skill_text: string;- /** Most recent successfully-completed (epoch, step). 0/0 = nothing yet. */+ /** Fully-completed epochs, and the last completed step inside the current epoch. */last_completed_epoch: number;last_completed_step: number;+ /** First (epoch, step) not yet completed. Absent on legacy checkpoints. */+ next_epoch?: number;+ next_step?: number;+ run_spec?: RunSpec;+ tally?: ReflectTally;cumulative_cost_usd: number;+ /** Ledger rows banked across segments. Absent on legacy checkpoints. */+ models_used?: ModelUsageRow[];+ models_used_scope?: ModelsUsedScope;started_at: string;last_updated_at: string;}+export type ModelsUsedScope = 'full_run' | 'since_resume';++/** What earlier segments of this run banked before the current tracker started. */+export interface PriorSegments {+ costUsd: number;+ rows: ModelUsageRow[];+ scope: ModelsUsedScope;+}++export function priorSegments(cp: RunCheckpoint | null): PriorSegments {+ if (!cp) return { costUsd: 0, rows: [], scope: 'full_run' };+ return {+ costUsd: cp.cumulative_cost_usd,+ rows: cp.models_used ?? [],+ scope: cp.models_used ? (cp.models_used_scope ?? 'full_run') : 'since_resume',+ };+}++/** Bank spend + ledger rows (prior segments + this one) on completed steps and handled aborts. */+export function bankAccounting(cp: RunCheckpoint, prior: PriorSegments, snapshot: BudgetSnapshot): void {+ cp.cumulative_cost_usd = prior.costUsd + snapshot.cumulativeCostUsd;+ cp.models_used = buildModelsUsed(snapshot, prior.rows);+ cp.models_used_scope = prior.scope;+}++/**+ * Where a resumed run continues. Legacy checkpoints recorded only the last+ * completed (epoch, step): step 0 or a full epoch means the next epoch starts;+ * otherwise the same epoch continues at the next step.+ */+export function resumeCursor(cp: RunCheckpoint, stepsPerEpoch: number): { epoch: number; step: number } {+ if (cp.next_epoch !== undefined && cp.next_step !== undefined) return { epoch: cp.next_epoch, step: cp.next_step };+ const e = cp.last_completed_epoch;+ const s = cp.last_completed_step;+ if (s === 0 || s >= stepsPerEpoch) return { epoch: e + 1, step: 1 };+ return { epoch: Math.max(1, e), step: s + 1 };+}++/** Advance the cursor past a completed (epoch, step). */+export function advanceCursor(cp: RunCheckpoint, epoch: number, step: number, stepsPerEpoch: number): void {+ const epochDone = step >= stepsPerEpoch;+ cp.next_epoch = epochDone ? epoch + 1 : epoch;+ cp.next_step = epochDone ? 1 : step + 1;+ cp.last_completed_epoch = epochDone ? epoch : epoch - 1;+ cp.last_completed_step = epochDone ? 0 : step;+}++/** Point the checkpoint's cursor at (epoch, step) as the next step to run. */+export function setCursor(cp: RunCheckpoint, cursor: { epoch: number; step: number }): void {+ cp.next_epoch = cursor.epoch;+ cp.next_step = cursor.step;+ cp.last_completed_epoch = cursor.epoch - 1;+ cp.last_completed_step = cursor.step === 1 ? 0 : cursor.step - 1;+}++/** Move a cursor back `steps` steps, never before epoch 1 step 1. */+export function rewindCursor(+ cursor: { epoch: number; step: number },+ steps: number,+ stepsPerEpoch: number,+): { epoch: number; step: number } {+ if (steps <= 0) return cursor;+ const index = Math.max(0, (cursor.epoch - 1) * stepsPerEpoch + (cursor.step - 1) - steps);+ return { epoch: Math.floor(index / stepsPerEpoch) + 1, step: (index % stepsPerEpoch) + 1 };+}++const RESUME_LOCKED_FIELDS = ['benchmark_sha8', 'held_out_sha8', 'split', 'target_model', 'judge_model', 'batch_size'] as const;++/** Refuse a resume that would change what the checkpoint measured, naming the field. */+export function assertResumeCompatible(cp: RunCheckpoint, current: RunSpec): void {+ const stored = cp.run_spec;+ const refuse = (field: string, was: unknown, now: unknown): never => {+ throw errorFor({+ class: 'ResumeMismatch',+ code: 'resume_spec_mismatch',+ message: `Cannot resume run ${cp.run_id}: ${field} changed (checkpoint ${JSON.stringify(was)}, now ${JSON.stringify(now)}).`,+ hint: `Resume with the original settings (the run's resume command reproduces them), or start a fresh run without --resume.`,+ });+ };+ if (!stored) {+ if (cp.benchmark_sha8 !== current.benchmark_sha8) refuse('benchmark_sha8', cp.benchmark_sha8, current.benchmark_sha8);+ return;+ }+ for (const field of RESUME_LOCKED_FIELDS) {+ if (JSON.stringify(stored[field]) !== JSON.stringify(current[field])) refuse(field, stored[field], current[field]);+ }+ if (!stored.mutate && current.mutate) refuse('mutate policy', 'no-mutate', 'mutate');+}+export function checkpointPath(skillsDir: string, skillName: string, runId: string): string {return path.join(skillsDir, skillName, 'skillopt', `checkpoint-${runId}.json`);}@@ -85,8 +241,8 @@ export function deleteCheckpoint(skillsDir: string, skillName: string, runId: st}/**- * GC stale checkpoints older than `maxAgeDays` (default 7). Called by the- * dream cycle's purge phase. Returns the count of removed files.+ * GC stale checkpoints older than `maxAgeDays` (default 7). Called at the+ * start of the dream cycle's skillopt phase. Returns the count of removed files.*/export function gcStaleCheckpoints(skillsDir: string, maxAgeDays: number = 7): number {if (!fs.existsSync(skillsDir)) return 0;diff --git a/src/core/skillopt/cycle-phase.ts b/src/core/skillopt/cycle-phase.tsindex b3fcb6bae1..05fbb1c774 100644--- a/src/core/skillopt/cycle-phase.ts+++ b/src/core/skillopt/cycle-phase.ts@@ -9,7 +9,22 @@** Per-skill last-run state lives in `config` table keyed* `cycle.skillopt.last_run.<skill>` so the cycle is cheap to re-enter- * (don't re-run the same skill every cycle).+ * (don't re-run the same skill every cycle). An `errored` run (or a thrown+ * error) does NOT bank last_run: it records `cycle.skillopt.last_error.<skill>`+ * instead, and the skill is retried no sooner than 24h after that error.+ * Each result row forwards the run's abort_reason / abort_detail / run_id /+ * remediation so the cycle report says why a skill failed.+ *+ * Admission (#5585): when one call of the run can never fit the per-skill cap+ * (preflight's `reservation_exceeds_cap: ...` abort, raised before any model call) the+ * skill is recorded `skipped_budget` with remediation, and+ * `cycle.skillopt.last_skip.<skill>` stores a fingerprint of everything the+ * reservation check prices: the resolved optimizer, target and judge models,+ * `cycle.skillopt.per_skill_cap_usd`, `skillopt.reflect_max_tokens`,+ * `pricing.overrides`, the gbrain version (built-in prices and default caps)+ * and the skill's benchmark (per-task judge models); the skill is not retried+ * until one of them changes. Models resolve once per cycle through `resolveSkillOptModels`; the+ * models banner prints once and each run prints only rows that differ.** Each per-skill invocation runs with epochs=1 (incremental nightly* improvement, not full optimization). Users who want a full multi-epoch@@ -20,9 +35,15 @@ import * as fs from 'node:fs';import * as path from 'node:path';import type { BrainEngine } from '../engine.ts';import { autoDetectSkillsDirReadOnly } from '../repo-root.ts';-import { resolveModel } from '../model-config.ts';+import { StructuredAgentError } from '../errors.ts';+import { buildModelsPlan, formatModelsBanner, resolveSkillOptModels, skillOptModelOpts } from './models-plan.ts';import { runSkillOpt } from './orchestrator.ts';+import { REFLECT_MAX_TOKENS_CONFIG_KEY } from './output-cap.ts';import { parseSplit } from './benchmark.ts';+import { gcStaleCheckpoints } from './checkpoint.ts';+import { sha8 } from './audit.ts';+import { VERSION } from '../../version.ts';+import { buildRemediation, errorCode } from './remediation.ts';import type { SkillOptOpts } from './types.ts';export interface SkilloptPhaseOpts {@@ -51,12 +72,25 @@ interface SkillCandidate {lastRunAt: number | null;}+interface SkillResult {+ skill: string;+ outcome: string;+ cost_usd: number;+ reason?: string;+ abort_reason?: string;+ abort_detail?: string;+ run_id?: string;+ remediation?: Array<{ code: string; fix: string; docs: string }>;+}+/** Default per-skill cost cap for the phase. */const DEFAULT_PER_SKILL_CAP_USD = 0.50;/** Default brain-wide cost cap for one cycle. */const DEFAULT_BRAIN_WIDE_CAP_USD = 2.00;/** Default stale threshold (skip skills that ran within this window). */const DEFAULT_STALE_DAYS = 7;+/** An errored skill is retried no sooner than this after its last error. */+const ERROR_RETRY_MS = 24 * 3600 * 1000;export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<SkilloptPhaseResult> {const { engine } = opts;@@ -102,8 +136,34 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skillop};}+ // Cycle runs never resume, so kept checkpoints (errored / early-stopped)+ // are reclaimed here once they age past the 7-day window.+ if (!opts.dryRun) {+ try { gcStaleCheckpoints(skillsDir); } catch { /* best effort; never blocks the phase */ }+ }++ // Resolve models once. Tiers default to deep/subagent/reasoning.+ const models = await resolveSkillOptModels(engine);+ const admission = {+ optimizer: models.optimizer.model,+ target: models.target.model,+ judge: models.judge.model,+ per_skill_cap_usd: perSkillCap,+ reflect_max_tokens: await engine.getConfig(REFLECT_MAX_TOKENS_CONFIG_KEY).catch(() => null) ?? null,+ pricing_overrides: await engine.getConfig('pricing.overrides').catch(() => null) ?? null,+ // Built-in prices and default caps move with releases.+ gbrain_version: VERSION,+ };+ // An unreadable benchmark hashes as null (never matches a stored skip), so the+ // skill is re-admitted and fails on its own instead of throwing the phase.+ const fingerprint = (benchmarkPath: string): string => {+ let benchmarkSha8: string | null = null;+ try { benchmarkSha8 = sha8(fs.readFileSync(benchmarkPath, 'utf8')); } catch { /* re-admit */ }+ return JSON.stringify({ ...admission, benchmark_sha8: benchmarkSha8 });+ };+// Walk skills dir; pick candidates with skillopt-benchmark.jsonl + stale last_run_at.- const candidates = await collectCandidates(engine, skillsDir, staleDays);+ const candidates = await collectCandidates(engine, skillsDir, staleDays, fingerprint);if (candidates.length === 0) {return {phase: 'skillopt',@@ -114,16 +174,15 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skillop};}- // Resolve models once. Tiers default to deep/subagent/reasoning.- const optimizerModel = await resolveModel(engine, { tier: 'deep', fallback: 'anthropic:claude-opus-4-7' });- const targetModel = await resolveModel(engine, { tier: 'subagent', fallback: 'anthropic:claude-sonnet-4-6' });- const judgeModel = await resolveModel(engine, { tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' });+ const basePlan = await buildModelsPlan(engine, models);+ process.stderr.write(formatModelsBanner(basePlan));// Run per-skill. Each invocation gets its own per-skill cap; we track// cumulative cost across the cycle and bail when brain-wide cap hit.- const results: Array<{ skill: string; outcome: string; cost_usd: number; reason?: string }> = [];+ const results: SkillResult[] = [];let cumulativeCostUsd = 0;let skipped_brain_wide_cap = 0;+ let skipped_budget = 0;for (const c of candidates) {if (opts.signal?.aborted) break;@@ -148,9 +207,8 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skilloplr: 4,lrSchedule: 'cosine',split,- optimizerModel,- targetModel,- judgeModel,+ ...skillOptModelOpts(models),+ modelsBannerBaseline: basePlan,mode: 'patch',dryRun: opts.dryRun ?? false,// Bundled-skill safety: dream-cycle NEVER auto-mutates bundled skills.@@ -165,18 +223,38 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skillopforce: false,};const result = await runSkillOpt(skillOptOpts);- const spent = result.receipt.final_cost_usd ?? 0;+ const receipt = result.receipt;+ const spent = receipt.final_cost_usd ?? 0;cumulativeCostUsd += spent;results.push({skill: c.name,outcome: result.outcome,cost_usd: spent,+ ...(receipt.abort_reason ? { abort_reason: receipt.abort_reason } : {}),+ ...(receipt.abort_detail ? { abort_detail: receipt.abort_detail } : {}),+ ...(receipt.run_id ? { run_id: receipt.run_id } : {}),+ ...(receipt.remediation?.length ? { remediation: receipt.remediation } : {}),});- // Persist last_run_at so we don't re-enter every cycle.- await engine.setConfig(`cycle.skillopt.last_run.${c.name}`, String(Date.now()));+ // Persist last_run_at so we don't re-enter every cycle; an errored run+ // records last_error instead so it is retried (after the 24h gate).+ const stateKey = result.outcome === 'errored' ? 'last_error' : 'last_run';+ await engine.setConfig(`cycle.skillopt.${stateKey}.${c.name}`, String(Date.now()));} catch (err) {const msg = err instanceof Error ? err.message : String(err);+ if (err instanceof StructuredAgentError && errorCode(err.envelope.message) === 'reservation_exceeds_cap') {+ if (effectiveCap < perSkillCap) {+ skipped_brain_wide_cap += 1;+ results.push({ skill: c.name, outcome: 'skipped', cost_usd: 0, reason: 'brain_wide_cap_reached' });+ } else {+ skipped_budget += 1;+ results.push({ skill: c.name, outcome: 'skipped_budget', cost_usd: 0, reason: err.envelope.message,+ remediation: buildRemediation(['reservation_exceeds_cap']) });+ await engine.setConfig(`cycle.skillopt.last_skip.${c.name}`, fingerprint(c.benchmarkPath)).catch(() => {});+ }+ continue;+ }results.push({ skill: c.name, outcome: 'errored', cost_usd: 0, reason: msg });+ await engine.setConfig(`cycle.skillopt.last_error.${c.name}`, String(Date.now())).catch(() => {});}}@@ -188,13 +266,14 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skillopphase: 'skillopt',status: errored > 0 ? 'warn' : 'ok',duration_ms: Date.now() - start,- summary: `optimized ${accepted}/${candidates.length} skills (${noImprovement} no-improvement, ${errored} errored, ${skipped_brain_wide_cap} skipped over brain-wide cap)`,+ summary: `optimized ${accepted}/${candidates.length} skills (${noImprovement} no-improvement, ${errored} errored, ${skipped_brain_wide_cap} skipped over brain-wide cap${skipped_budget > 0 ? `, ${skipped_budget} skipped: one call exceeds the per-skill cap` : ''})`,details: {skills_scanned: candidates.length,accepted,no_improvement: noImprovement,errored,skipped_brain_wide_cap,+ skipped_budget,cumulative_cost_usd: cumulativeCostUsd,brain_wide_cap_usd: brainWideCap,per_skill_cap_usd: perSkillCap,@@ -205,12 +284,14 @@ export async function runPhaseSkillopt(opts: SkilloptPhaseOpts): Promise<Skillop/*** Walk skillsDir and return skills that have a benchmark file AND a stale- * last_run_at (older than staleDays, or never run).+ * last_run_at (older than staleDays, or never run) AND no error within the+ * last 24h AND no budget skip under the current admission fingerprint.*/async function collectCandidates(engine: BrainEngine,skillsDir: string,staleDays: number,+ fingerprint: (benchmarkPath: string) => string,): Promise<SkillCandidate[]> {const out: SkillCandidate[] = [];if (!fs.existsSync(skillsDir)) return out;@@ -229,6 +310,16 @@ async function collectCandidates(if (lastRunAt !== null && lastRunAt >= cutoffMs) {continue; // ran recently; skip}+ let lastErrorAt: number | null = null;+ try {+ const v = await engine.getConfig(`cycle.skillopt.last_error.${entry}`);+ if (v) lastErrorAt = Number(v);+ } catch { /* fall through */ }+ if (lastErrorAt !== null && Date.now() - lastErrorAt < ERROR_RETRY_MS) {+ continue; // errored recently; retry after the 24h gate+ }+ const lastSkip = await engine.getConfig(`cycle.skillopt.last_skip.${entry}`).catch(() => null);+ if (lastSkip && !lastSkip.includes('"benchmark_sha8":null') && lastSkip === fingerprint(benchPath)) continue; // budget-skipped; wait for a config changeout.push({ name: entry, benchmarkPath: benchPath, lastRunAt });}return out;diff --git a/src/core/skillopt/help.ts b/src/core/skillopt/help.tsindex f8a544a028..b7895b95a4 100644--- a/src/core/skillopt/help.ts+++ b/src/core/skillopt/help.ts@@ -34,11 +34,25 @@ Models:--optimizer-model MODEL Reflects + proposes. Default models.tier.deep--target-model MODEL Executes the skill. Default models.tier.subagent--judge-model MODEL Scores rollouts. Default models.tier.reasoning+ --reflect-max-tokens N Output cap for every optimizer call (patch and+ rewrite reflect). Beats the+ skillopt.reflect_max_tokens config; default+ 32000 for thinking optimizers, 4096 otherwise.+ Raise it when the receipt reports+ reflect_*_truncated. Judge/bootstrap caps are+ separate.+ --models-strict Abort before any spend unless every active+ model (optimizer, target, judge, expansion,+ chat, embedding, reranker when enabled) was+ chosen by touchpoint-specific configuration,+ not models.default or a built-in default.+ Same as skillopt.models_strict=true.Modes:--patch Edit ops only (default; safer)--rewrite Allow full rewrites of sections- --dry-run Plan + cost estimate, no LLM calls+ --dry-run Models plan, strict verdict + cost estimate,+ no LLM calls (exit 1 only on a strict failure)--no-mutate Write proposed.md without replacing SKILL.md--allow-mutate-bundled Required to mutate a bundled skill in place.ALSO requires --held-out (>=5 rows); without it@@ -74,8 +88,17 @@ Batch + fleet + background:Exit codes:0 = improved + accepted (or --no-mutate proposed.md written)- 1 = no improvement (best skill unchanged)- 2 = aborted by gate (dirty tree / over budget / bench validation / etc.)+ 1 = no improvement (the optimizer replied usably; best skill unchanged)+ 2 = aborted (dirty tree / over budget / bench validation / etc.) or errored,+ including a run whose optimizer never produced a usable reply+ (optimizer_output_unusable). Errored and aborted runs keep their+ checkpoint and print the exact resume command.++Diagnostics:+ Every run prints a models banner (each touchpoint, its model and the flag or+ key that chose it) before any spend, and a "Models called" table (including+ engine-internal query expansion and embeddings) at the end. Each error code+ in the summary links to its fix in docs/guides/skillopt.md#<code>.Examples:# Generate a starter benchmark from the skill itself (recommended):diff --git a/src/core/skillopt/job.ts b/src/core/skillopt/job.tsnew file mode 100644index 0000000000..78b1513e11--- /dev/null+++ b/src/core/skillopt/job.ts@@ -0,0 +1,130 @@+/**+ * SkillOpt background job (`gbrain skillopt --background`, Minion handler+ * `skillopt`): job-data shape and the handler body.+ *+ * The job records the CLI's model FLAGS (not just the models they resolved+ * to), the enqueue-time role sources and the strict flag. At execution time+ * the handler re-resolves the roles through `resolveSkillOptModels` against+ * the brain's current config, so provenance and the strict check reflect the+ * configuration the run actually uses, not the one at enqueue. Legacy jobs+ * (no `model_flags`) keep their stored models with source `unknown`, which+ * strict mode refuses (fail-closed).+ */++import type { BrainEngine } from '../engine.ts';+import { TIER_DEFAULTS } from '../model-config.ts';+import {+ resolveSkillOptModels,+ skillOptModelOpts,+ unknownProvenanceModels,+ type SkillOptModelFlags,+ type SkillOptModels,+} from './models-plan.ts';+import { runSkillOpt } from './orchestrator.ts';+import { clampRemoteReflectMaxTokens } from './output-cap.ts';+import type { SkillOptOpts } from './types.ts';++export type SkillOptJobInput = Pick<SkillOptOpts,+ | 'skillsDir' | 'skillName' | 'benchmarkPath' | 'epochs' | 'batchSize' | 'lr' | 'lrSchedule' | 'split'+ | 'reflectMaxTokens' | 'mode' | 'dryRun' | 'noMutate' | 'allowMutateBundled' | 'heldOutPath'+ | 'bootstrapReviewed' | 'maxCostUsd' | 'maxRuntimeMin' | 'force'+> & { models: SkillOptModels; modelFlags: SkillOptModelFlags; modelsStrict: boolean };++export function buildSkillOptJobData(input: SkillOptJobInput): Record<string, unknown> {+ const flags = input.modelFlags;+ return {+ skills_dir: input.skillsDir,+ skill_name: input.skillName,+ benchmark_path: input.benchmarkPath,+ epochs: input.epochs,+ batch_size: input.batchSize,+ lr: input.lr,+ lr_schedule: input.lrSchedule,+ split: input.split,+ optimizer_model: input.models.optimizer.model,+ target_model: input.models.target.model,+ judge_model: input.models.judge.model,+ model_flags: {+ ...(flags.optimizerModel !== undefined ? { optimizer: flags.optimizerModel } : {}),+ ...(flags.targetModel !== undefined ? { target: flags.targetModel } : {}),+ ...(flags.judgeModel !== undefined ? { judge: flags.judgeModel } : {}),+ },+ model_sources: {+ optimizer: input.models.optimizer.source,+ target: input.models.target.source,+ judge: input.models.judge.source,+ },+ ...(input.modelsStrict ? { models_strict: true } : {}),+ ...(input.reflectMaxTokens !== undefined ? { reflect_max_tokens: input.reflectMaxTokens } : {}),+ mode: input.mode,+ dry_run: input.dryRun,+ no_mutate: input.noMutate,+ allow_mutate_bundled: input.allowMutateBundled,+ ...(input.heldOutPath ? { held_out_path: input.heldOutPath } : {}),+ bootstrap_reviewed: input.bootstrapReviewed,+ max_cost_usd: input.maxCostUsd,+ max_runtime_min: input.maxRuntimeMin,+ force: input.force,+ };+}++const optionalString = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v : undefined);++/** Role models for a job: re-resolved from its flags, or legacy stored models with unknown provenance. */+export async function resolveJobModels(engine: BrainEngine, data: Record<string, unknown>): Promise<SkillOptModels> {+ const flags = data.model_flags;+ if (flags && typeof flags === 'object' && !Array.isArray(flags)) {+ const f = flags as Record<string, unknown>;+ return resolveSkillOptModels(engine, {+ optimizerModel: optionalString(f.optimizer),+ targetModel: optionalString(f.target),+ judgeModel: optionalString(f.judge),+ });+ }+ return unknownProvenanceModels({+ optimizerModel: String(data.optimizer_model ?? TIER_DEFAULTS.deep),+ targetModel: String(data.target_model ?? TIER_DEFAULTS.subagent),+ judgeModel: String(data.judge_model ?? TIER_DEFAULTS.reasoning),+ }, 'legacy job data');+}++export async function runSkillOptJob(engine: BrainEngine, rawData: unknown): Promise<Record<string, unknown>> {+ const data = (rawData ?? {}) as Record<string, unknown>;+ const skillsDir = String(data.skills_dir ?? '');+ const skillName = String(data.skill_name ?? '');+ const benchmarkPath = String(data.benchmark_path ?? '');+ if (!skillsDir || !skillName || !benchmarkPath) {+ throw new Error(`skillopt handler: missing required job.data fields (skills_dir, skill_name, benchmark_path)`);+ }+ const models = await resolveJobModels(engine, data);+ const result = await runSkillOpt({+ engine,+ skillName,+ skillsDir,+ benchmarkPath,+ epochs: Number(data.epochs ?? 4),+ batchSize: Number(data.batch_size ?? 8),+ lr: Number(data.lr ?? 4),+ lrSchedule: (data.lr_schedule as 'cosine' | 'linear' | 'constant') ?? 'cosine',+ split: (data.split as [number, number, number]) ?? [4, 1, 5],+ ...skillOptModelOpts(models),+ modelsStrict: data.models_strict === true,+ reflectMaxTokens: clampRemoteReflectMaxTokens(data.reflect_max_tokens),+ mode: (data.mode as 'patch' | 'rewrite') ?? 'patch',+ dryRun: Boolean(data.dry_run),+ noMutate: Boolean(data.no_mutate),+ allowMutateBundled: Boolean(data.allow_mutate_bundled),+ bootstrapReviewed: Boolean(data.bootstrap_reviewed),+ ...(data.held_out_path ? { heldOutPath: String(data.held_out_path) } : {}),+ json: true,+ maxCostUsd: Number(data.max_cost_usd ?? 5.0),+ maxRuntimeMin: Number(data.max_runtime_min ?? 30),+ force: Boolean(data.force),+ });+ return {+ outcome: result.outcome,+ receipt: result.receipt,+ mutated_skill_file: result.mutatedSkillFile,+ proposed_path: result.proposedPath,+ };+}diff --git a/src/core/skillopt/models-plan.ts b/src/core/skillopt/models-plan.tsnew file mode 100644index 0000000000..6de0087000--- /dev/null+++ b/src/core/skillopt/models-plan.ts@@ -0,0 +1,407 @@+/**+ * SkillOpt models plan: which model every touchpoint of a run will call and+ * which configuration chose it.+ *+ * `resolveSkillOptModels` is the ONE resolution of the optimizer / target /+ * judge roles (tiers deep / subagent / reasoning) shared by the CLI, the+ * `run_skillopt` MCP op, the cycle phase and the background job handler.+ * `buildModelsPlan` adds the engine-internal touchpoints a run can reach:+ * per-task `judge.model` overrides (benchmark + held-out), the gateway's+ * expansion and chat models (provenance retained by+ * `reconfigureGatewayWithEngine`), the embedding model of the column search+ * actually reads, and the reranker when search enables it.+ *+ * Strict mode (`--models-strict` / `skillopt.models_strict`) guarantees that+ * every ACTIVE model was chosen by explicit, touchpoint-specific+ * configuration: a touchpoint resolved through `models.default`, a built-in+ * default, a capability substitution or unknown provenance aborts the run+ * before any spend with a copy-paste fix per touchpoint. Aliases are allowed;+ * the guarantee is about who chose the model, not a fixed identity.+ *+ * Every echoed string (model ids, origins, raw config values) passes+ * `sanitizeEcho`: control characters stripped, capped at 200 chars.+ */++import { getChatModel, getExpansionModel } from '../ai/gateway.ts';+import { getGatewayModelSource } from '../ai/gateway-model-sources.ts';+import { loadConfig, loadConfigFileOnly, loadConfigWithEngine } from '../config.ts';+import type { ConfigReader } from '../config-snapshot.ts';+import type { BrainEngine } from '../engine.ts';+import { errorFor } from '../errors.ts';+import {+ describeResolveOrigin,+ resolveModelDetailed,+ TIER_DEFAULTS,+ type ModelTier,+ type ResolveSource,+} from '../model-config.ts';+import { DEFAULT_COLUMN_NAME, resolveEmbeddingColumn } from '../search/embedding-column.ts';+import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';+import type { ReflectCap } from './output-cap.ts';+import type { BenchmarkTask } from './types.ts';++export type ModelSource = ResolveSource | 'file_config' | 'benchmark' | 'unknown';++export interface ModelResolution {+ model: string;+ source: ModelSource;+ /** Flag / config key / env var that supplied the model, or `built-in default`. */+ origin: string;+ substituted_from?: string;+ substitution_reason?: string;+}++export type SkillOptRole = 'optimizer' | 'target' | 'judge';++export type SkillOptModels = Record<SkillOptRole, ModelResolution>;++export type PlanTouchpoint = SkillOptRole | 'expansion' | 'chat' | 'embedding' | 'reranker';++export interface ModelsPlanEntry extends ModelResolution {+ touchpoint: PlanTouchpoint;+ active: boolean;+ inactive_reason?: string;+}++export interface StrictViolation {+ touchpoint: PlanTouchpoint;+ model: string;+ source: ModelSource;+ origin: string;+ /** Copy-paste remediation (a `gbrain config set` line, or the embedding config path). */+ fix: string;+}++export interface StrictVerdict {+ enabled: boolean;+ ok: boolean;+ violations: StrictViolation[];+ /** Raw `skillopt.models_strict` value that was not recognized (treated as on). */+ unrecognized_value?: string;+}++export const MODELS_STRICT_CONFIG_KEY = 'skillopt.models_strict';++const ECHO_MAX_CHARS = 200;++/** Strip control characters / newlines and cap at 200 chars. */+export function sanitizeEcho(value: string): string {+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, ECHO_MAX_CHARS);+}++const ROLE_RESOLUTION: Record<SkillOptRole, { tier: ModelTier; flag: string }> = {+ optimizer: { tier: 'deep', flag: '--optimizer-model' },+ target: { tier: 'subagent', flag: '--target-model' },+ judge: { tier: 'reasoning', flag: '--judge-model' },+};++export interface SkillOptModelFlags {+ optimizerModel?: string;+ targetModel?: string;+ judgeModel?: string;+}++/**+ * Resolve the three skillopt roles: flag > role config chain (tier config,+ * `models.default`, env, key-aware tier default). Reports the source, the+ * origin key and any subagent capability substitution.+ */+export async function resolveSkillOptModels(+ engine: ConfigReader | null,+ flags: SkillOptModelFlags = {},+): Promise<SkillOptModels> {+ const flagFor: Record<SkillOptRole, string | undefined> = {+ optimizer: flags.optimizerModel,+ target: flags.targetModel,+ judge: flags.judgeModel,+ };+ const out = {} as SkillOptModels;+ for (const role of ['optimizer', 'target', 'judge'] as const) {+ const { tier, flag } = ROLE_RESOLUTION[role];+ const r = await resolveModelDetailed(engine, { cliFlag: flagFor[role], tier, fallback: TIER_DEFAULTS[tier] });+ out[role] = {+ model: sanitizeEcho(r.model),+ source: r.source,+ origin: describeResolveOrigin(r.source, { tier, flag }),+ ...(r.substituted_from ? { substituted_from: sanitizeEcho(r.substituted_from), substitution_reason: r.substitution_reason } : {}),+ };+ }+ return out;+}++/** Role provenance for models handed over without one (programmatic callers, legacy jobs): fail-closed `unknown`. */+export function unknownProvenanceModels(+ models: { optimizerModel: string; targetModel: string; judgeModel: string },+ origin: string,+): SkillOptModels {+ const entry = (model: string): ModelResolution => ({ model: sanitizeEcho(model), source: 'unknown', origin });+ return { optimizer: entry(models.optimizerModel), target: entry(models.targetModel), judge: entry(models.judgeModel) };+}++/** Spread into SkillOptOpts: the role models plus their provenance. */+export function skillOptModelOpts(models: SkillOptModels): {+ optimizerModel: string; targetModel: string; judgeModel: string; models: SkillOptModels;+} {+ return { optimizerModel: models.optimizer.model, targetModel: models.target.model, judgeModel: models.judge.model, models };+}++function judgeUsage(tasks: readonly BenchmarkTask[] | undefined): {+ defaultActive: boolean; inactiveReason?: string; overrides: Map<string, number>;+} {+ const overrides = new Map<string, number>();+ if (!tasks) return { defaultActive: true, overrides };+ let llmTasks = 0;+ let defaultActive = false;+ for (const t of tasks) {+ const judge = t.judge as { kind?: string; model?: unknown };+ if (judge.kind === 'rule' || judge.kind === 'qrels') continue;+ llmTasks += 1;+ const override = judge.kind === 'llm' && typeof judge.model === 'string' ? judge.model.trim() : '';+ if (override) overrides.set(override, (overrides.get(override) ?? 0) + 1);+ else defaultActive = true;+ }+ if (defaultActive) return { defaultActive, overrides };+ return { defaultActive, inactiveReason: llmTasks === 0 ? 'rule/qrels benchmark' : 'every LLM task sets judge.model', overrides };+}++function gatewayEntry(touchpoint: 'expansion' | 'chat'): ModelsPlanEntry {+ let model: string;+ try {+ model = touchpoint === 'expansion' ? getExpansionModel() : getChatModel();+ } catch {+ return { touchpoint, model: '(gateway unconfigured)', source: 'unknown', origin: 'gateway unconfigured', active: true };+ }+ const src = getGatewayModelSource(touchpoint, model);+ return {+ touchpoint,+ model: sanitizeEcho(model),+ source: src?.source ?? 'unknown',+ origin: src?.origin ?? 'unrecorded: gateway not resolved against this brain',+ active: true,+ };+}++/**+ * Embedding provenance from the resolver search itself uses: the active+ * column (`search_embedding_column` / `embedding_columns`), else the+ * file-plane `embedding_model` or `GBRAIN_EMBEDDING_MODEL`. DB-plane+ * `embedding_model` rows are never merged into search config, so they are+ * never reported as the source.+ */+async function embeddingEntry(engine: BrainEngine): Promise<ModelsPlanEntry> {+ const unknown = (origin: string): ModelsPlanEntry =>+ ({ touchpoint: 'embedding', model: '(unresolved)', source: 'unknown', origin, active: true });+ let column;+ let explicitDefaultColumn = false;+ try {+ const cfg = (await loadConfigWithEngine(engine).catch(() => null)) ?? loadConfig() ?? { engine: engine.kind };+ column = resolveEmbeddingColumn(undefined, cfg);+ const userColumns: unknown = cfg.embedding_columns;+ explicitDefaultColumn = typeof userColumns === 'object' && userColumns !== null && Object.hasOwn(userColumns, DEFAULT_COLUMN_NAME);+ } catch (err) {+ return unknown(sanitizeEcho(`embedding column unresolved: ${err instanceof Error ? err.message : String(err)}`));+ }+ if (!column.embeddingModel) return unknown('unverified embedding identity (gbrain migrate embeddings --status)');+ const model = sanitizeEcho(column.embeddingModel);+ if (column.name !== DEFAULT_COLUMN_NAME) {+ return { touchpoint: 'embedding', model, source: 'config_key', origin: sanitizeEcho(`search_embedding_column=${column.name} (embedding_columns)`), active: true };+ }+ if (explicitDefaultColumn) {+ return { touchpoint: 'embedding', model, source: 'config_key', origin: `embedding_columns.${DEFAULT_COLUMN_NAME}`, active: true };+ }+ if (process.env.GBRAIN_EMBEDDING_MODEL?.trim()) {+ return { touchpoint: 'embedding', model, source: 'env', origin: 'GBRAIN_EMBEDDING_MODEL', active: true };+ }+ let fileModel: string | undefined;+ try { fileModel = loadConfigFileOnly()?.embedding_model?.trim(); } catch { /* unreadable file plane */ }+ return fileModel+ ? { touchpoint: 'embedding', model, source: 'file_config', origin: 'embedding_model (config.json)', active: true }+ : { touchpoint: 'embedding', model, source: 'fallback', origin: 'built-in default', active: true };+}++/** Reranker entry, only when search enables reranking. */+async function rerankerEntry(engine: BrainEngine): Promise<ModelsPlanEntry | null> {+ let input;+ try { input = await loadSearchModeConfig(engine); } catch { return null; }+ const knobs = resolveSearchMode(input);+ if (!knobs.reranker_enabled) return null;+ const explicit = input.overrides?.reranker_model !== undefined;+ return {+ touchpoint: 'reranker',+ model: sanitizeEcho(knobs.reranker_model),+ source: explicit ? 'config_key' : 'fallback',+ origin: explicit ? 'search.reranker.model' : `built-in default, search.mode ${knobs.resolved_mode}`,+ active: true,+ };+}++/**+ * Full plan for one run. `tasks` are every task the run can judge+ * (benchmark + held-out); omitted, the default judge is assumed active.+ */+export async function buildModelsPlan(+ engine: BrainEngine,+ models: SkillOptModels,+ tasks?: readonly BenchmarkTask[],+): Promise<ModelsPlanEntry[]> {+ const judges = judgeUsage(tasks);+ const plan: ModelsPlanEntry[] = [+ { touchpoint: 'optimizer', ...models.optimizer, active: true },+ { touchpoint: 'target', ...models.target, active: true },+ {+ touchpoint: 'judge',+ ...models.judge,+ active: judges.defaultActive,+ ...(judges.inactiveReason ? { inactive_reason: judges.inactiveReason } : {}),+ },+ ];+ for (const [model, count] of judges.overrides) {+ plan.push({+ touchpoint: 'judge',+ model: sanitizeEcho(model),+ source: 'benchmark',+ origin: `benchmark judge.model, ${count} task${count === 1 ? '' : 's'}`,+ active: true,+ });+ }+ plan.push(gatewayEntry('expansion'), gatewayEntry('chat'), await embeddingEntry(engine));+ const reranker = await rerankerEntry(engine);+ if (reranker) plan.push(reranker);+ return plan;+}++const FALLBACK_SOURCES: ReadonlySet<ModelSource> = new Set(['models_default', 'tier_default', 'fallback', 'unknown']);++/** Origin as echoed: the key, plus the substitution when the capability gate replaced the configured model. */+function originText(e: ModelResolution): string {+ return e.substituted_from+ ? `${e.origin} -> substituted: ${e.substitution_reason ?? 'unsupported'}; configured ${e.substituted_from}`+ : e.origin;+}++/** True when strict mode counts this entry's choice as a fallback (not explicit configuration). */+export function isFallbackChoice(entry: ModelResolution): boolean {+ return FALLBACK_SOURCES.has(entry.source) || entry.substituted_from !== undefined;+}++const FIX_KEY: Record<Exclude<PlanTouchpoint, 'embedding'>, string> = {+ optimizer: 'models.tier.deep',+ target: 'models.tier.subagent',+ judge: 'models.tier.reasoning',+ expansion: 'models.tier.utility',+ chat: 'models.chat',+ reranker: 'search.reranker.model',+};++function fixFor(entry: ModelsPlanEntry): string {+ if (entry.touchpoint === 'embedding') {+ return `set embedding_model in ~/.gbrain/config.json or export GBRAIN_EMBEDDING_MODEL=${entry.model} (changing the embedding model needs a migration: gbrain migrate embeddings --status)`;+ }+ return `gbrain config set ${FIX_KEY[entry.touchpoint]} ${entry.model}`;+}++export function strictVerdict(+ plan: readonly ModelsPlanEntry[],+ strict: { on: boolean; unrecognized?: string },+): StrictVerdict {+ const violations = plan+ .filter((e) => e.active && isFallbackChoice(e))+ .map((e) => ({ touchpoint: e.touchpoint, model: e.model, source: e.source, origin: originText(e), fix: fixFor(e) }));+ return {+ enabled: strict.on,+ ok: violations.length === 0,+ violations,+ ...(strict.unrecognized !== undefined ? { unrecognized_value: strict.unrecognized } : {}),+ };+}++const STRICT_ON = new Set(['true', '1', 'yes', 'on']);+const STRICT_OFF = new Set(['false', '0', 'no', 'off', '']);+const warnedStrictValues = new Set<string>();++/** `true|1|yes|on` on; `false|0|no|off|empty` off; anything else warns once and counts as ON. */+export function parseModelsStrict(raw: string | null | undefined): { on: boolean; unrecognized?: string } {+ if (raw === null || raw === undefined) return { on: false };+ const v = raw.trim().toLowerCase();+ if (STRICT_ON.has(v)) return { on: true };+ if (STRICT_OFF.has(v)) return { on: false };+ const unrecognized = sanitizeEcho(raw);+ if (!warnedStrictValues.has(unrecognized)) {+ warnedStrictValues.add(unrecognized);+ process.stderr.write(`[skillopt] ${MODELS_STRICT_CONFIG_KEY}='${unrecognized}' is not a recognized value (true/false); treating it as on\n`);+ }+ return { on: true, unrecognized };+}++/** `--models-strict` (flag) wins; otherwise `skillopt.models_strict` config. */+export async function resolveModelsStrict(+ engine: ConfigReader,+ flag?: boolean,+): Promise<{ on: boolean; unrecognized?: string }> {+ if (flag === true) return { on: true };+ let raw: string | null | undefined = null;+ try {+ raw = await engine.getConfig(MODELS_STRICT_CONFIG_KEY);+ } catch {+ // Fail closed: an unreadable policy must not silently disable enforcement.+ process.stderr.write(`[skillopt] could not read ${MODELS_STRICT_CONFIG_KEY}; treating strict mode as on\n`);+ return { on: true };+ }+ return parseModelsStrict(raw);+}++/** Multi-line verdict: pass, or each offending touchpoint with its copy-paste fix. */+export function describeStrictVerdict(verdict: StrictVerdict): string {+ if (verdict.ok) return 'models strict check: pass (every active model was chosen by explicit configuration)';+ const lines = [+ `models strict check: ${verdict.violations.length} active model touchpoint(s) were not chosen by touchpoint-specific configuration:`,+ ];+ for (const v of verdict.violations) {+ lines.push(` ${v.touchpoint} ${v.model} (${v.origin})`, ` ${v.fix}`);+ }+ if (verdict.unrecognized_value !== undefined) {+ lines.push(`(${MODELS_STRICT_CONFIG_KEY}='${verdict.unrecognized_value}' treated as on)`);+ }+ return lines.join('\n');+}++/** Pre-spend strict abort listing each offending touchpoint with its fix. */+export function modelsStrictError(verdict: StrictVerdict): Error {+ return errorFor({+ class: 'ModelsStrict',+ code: 'models_strict_violation',+ message: describeStrictVerdict(verdict),+ hint: `run the listed commands, or turn strict mode off (drop --models-strict; gbrain config set ${MODELS_STRICT_CONFIG_KEY} false)`,+ });+}++const FALLBACK_FOOTNOTE = '* not chosen by touchpoint-specific configuration (models.default, a built-in default, a substitution or unknown provenance); --models-strict aborts on these';++function bannerRow(e: ModelsPlanEntry): string {+ const origin = e.active ? originText(e) : `inactive: ${e.inactive_reason ?? 'unused'}`;+ const mark = e.active && isFallbackChoice(e) ? ' *' : '';+ return `${e.touchpoint.padEnd(9)} ${e.model} (${origin})${mark}`;+}++const sameEntry = (a: ModelsPlanEntry, b: ModelsPlanEntry): boolean =>+ a.touchpoint === b.touchpoint && a.model === b.model && a.source === b.source && a.origin === b.origin && a.active === b.active;++/**+ * Stderr banner. With `baseline` (batch / cycle runs after the invocation+ * banner) only rows that differ from it print, and nothing when none do.+ */+export function formatModelsBanner(+ plan: readonly ModelsPlanEntry[],+ opts: { skill?: string; baseline?: readonly ModelsPlanEntry[]; reflectCap?: ReflectCap } = {},+): string {+ const rows = opts.baseline ? plan.filter((e) => !opts.baseline!.some((b) => sameEntry(b, e))) : plan;+ if (rows.length === 0) return '';+ const scope = opts.skill ? ` for ${sanitizeEcho(opts.skill)}` : '';+ const lines = [opts.baseline ? `[skillopt] Models${scope} (differs from the run banner):` : `[skillopt] Models${scope}:`];+ for (const e of rows) lines.push(`[skillopt] ${bannerRow(e)}`);+ if (opts.reflectCap && !opts.baseline) {+ lines.push(`[skillopt] optimizer output cap ${opts.reflectCap.maxTokens} tokens (${opts.reflectCap.source === 'flag' ? '--reflect-max-tokens' : opts.reflectCap.source === 'config' ? 'skillopt.reflect_max_tokens' : 'default'})`);+ }+ if (rows.some((e) => e.active && isFallbackChoice(e))) lines.push(`[skillopt] ${FALLBACK_FOOTNOTE}`);+ return lines.join('\n') + '\n';+}diff --git a/src/core/skillopt/must-abort.ts b/src/core/skillopt/must-abort.tsnew file mode 100644index 0000000000..8ac483f91b--- /dev/null+++ b/src/core/skillopt/must-abort.ts@@ -0,0 +1,21 @@+/**+ * SkillOpt must-abort classification.+ *+ * Budget exhaustion (BudgetExhausted, tagged BUDGET_EXHAUSTED), AI spend-policy+ * refusals, the run's wall-clock deadline and SIGINT are never per-call noise: every optimizer,+ * judge, held-out and bootstrap call site rethrows them before converting any+ * other error into a reflect error, a judge score of 0 or a skipped row, so the+ * run ends `aborted` with its real reason instead of a fabricated measurement.+ */++import { isAIInvocationPolicyError } from '../ai/invocation-guard.ts';+import { isMustAbortError } from '../worker-pool.ts';++/** #4119 — the runtime-deadline breach error, shared with validate-gate + orchestrator. */+export const SKILLOPT_RUNTIME_EXCEEDED = 'skillopt_runtime_exceeded';++export function isSkilloptMustAbort(err: unknown): boolean {+ if (isMustAbortError(err) || isAIInvocationPolicyError(err)) return true;+ const msg = err instanceof Error ? err.message : String(err);+ return msg.includes(SKILLOPT_RUNTIME_EXCEEDED) || msg.includes('SIGINT');+}diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.tsindex f1d211d82c..c82ce1fd65 100644--- a/src/core/skillopt/orchestrator.ts+++ b/src/core/skillopt/orchestrator.ts@@ -19,7 +19,9 @@** ┌─ Run state machine ────────────────────────────────────────────────────┐* │ │- * │ start ──► lock_acquire ──► preflight ──► resume_or_init │+ * │ start ──► models_plan ──► preflight ──► lock_acquire ──► resume │+ * │ (banner; strict abort; reservation check: all before any spend) │+ * │ (resume: cursor next_epoch/next_step, spec check) │* │ │ │* │ ▼ │* │ ┌──── epoch_start ◄────┐ │@@ -30,7 +32,9 @@* │ │ │ │ │* │ │ ▼ │ │* │ │ backward_pass │ │- * │ │ (reflect ×2 D7) │ │+ * │ │ (reflect ×2 D7; each │ │+ * │ │ call: edits | empty │ │+ * │ │ | exactly 1 error) │ │* │ │ │ │ │* │ │ ▼ │ │* │ │ rank_and_clip │ │@@ -49,12 +53,27 @@* │ │ └─►◄──┘ │* │ │ │ │* │ │ ▼ │- * │ │ epoch_end ──► slow_update (D6) │- * │ │ │ │- * │ └───────────┘ │- * │ │ all epochs done │- * │ ▼ │- * │ final_test ──► run_end │+ * │ │ step_end: advance cursor, │+ * │ │ save cost + tally ──► 2 fully │+ * │ │ │ unusable steps in a │+ * │ │ │ row ──► EARLY STOP ─┐ │+ * │ │ ▼ │ │+ * │ │ epoch_end ──► slow_update (D6) │ │+ * │ │ │ │ │+ * │ └───────────┘ │ │+ * │ │ all epochs done │ │+ * │ ▼ │ │+ * │ final_test ──► run_end ◄───────┘ │+ * │ │+ * │ run_end outcome (stop_reason completed | early_stop_unusable_output │+ * │ | aborted): │+ * │ caught abort/error ──────────────► aborted | errored (checkpoint │+ * │ kept, resume_command) │+ * │ any step accepted ───────────────► accepted │+ * │ optimizer called, 0 usable replies ► errored │+ * │ (optimizer_output_unusable, │+ * │ checkpoint kept, remediation) │+ * │ otherwise ───────────────────────► no_improvement │* └────────────────────────────────────────────────────────────────────────┘** ┌─ Validation gate decision tree (D12) ──────────────────────────────────┐@@ -80,20 +99,57 @@import { assertLegacySkillWriter } from '../skillpack/writer-guard.ts';import { randomUUID } from 'node:crypto';import * as fs from 'node:fs';-import { BudgetExhausted, BudgetTracker } from '../budget/budget-tracker.ts';+import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';+import type { PricingOverrides } from '../budget/reservation-cost.ts';+import { buildModelsUsed } from '../budget/models-used.ts';import { withBudgetTracker } from '../ai/gateway.ts';import { errorFor } from '../errors.ts';import { applyEditBatch, getWorkingTreeStatusForFile, splitFrontmatter } from './apply-edits.ts';import { logEvent, sha8 } from './audit.ts';import { loadBenchmark, splitBench, parseSplit } from './benchmark.ts';import { getBundledSkillContext, shouldMutateSkillFile, assertBundledMutationHeldOut } from './bundled-skill-gate.ts';-import { loadCheckpoint, saveCheckpoint, deleteCheckpoint, type RunCheckpoint } from './checkpoint.ts';+import {+ advanceCursor,+ assertResumeCompatible,+ bankAccounting,+ deleteCheckpoint,+ emptyTally,+ loadCheckpoint,+ priorSegments,+ resumeCursor,+ rewindCursor,+ saveCheckpoint,+ setCursor,+ type ReflectTally,+ type RunSpec,+} from './checkpoint.ts';import { loadHeldOut, runHeldOutGate } from './held-out.ts';import { withSkilloptLock } from './lock.ts';import { resolveLrSchedule } from './lr-schedule.ts';+import { SKILLOPT_RUNTIME_EXCEEDED } from './must-abort.ts';+import {+ buildModelsPlan,+ formatModelsBanner,+ modelsStrictError,+ resolveModelsStrict,+ strictVerdict,+ unknownProvenanceModels,+ type ModelsPlanEntry,+ type StrictVerdict,+} from './models-plan.ts';+import { resolveReflectMaxTokens, type ReflectCap } from './output-cap.ts';import { preflight, formatPreflightReport } from './preflight.ts';import { isRejected, loadRejectedBuffer, makeRejectedEntry, saveRejectedBuffer } from './rejected-buffer.ts';-import { runReflect, runOneShotRewrite, describeJudges } from './reflect.ts';+import { runReflect, runOneShotRewrite, describeJudges, type SkillBodyTruncation } from './reflect.ts';+import { buildRemediation, errorCode } from './remediation.ts';+import {+ buildResumeCommand,+ recordOptimizerStep,+ resolveRunOutcome,+ shouldEarlyStop,+ unusableClasses,+ EARLY_STOP_UNUSABLE_STEPS,+} from './run-outcome.ts';import {acceptCandidate,proposedPath as proposedFilePath,@@ -139,7 +195,7 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResult// Working-tree gate.if (!opts.force) {const status = getWorkingTreeStatusForFile(skillFile);- if (status === 'dirty') {+ if (status === 'dirty' && !isOwnResumeEdit(skillsDir, skillName, skillFile, opts.resumeRunId)) {throw errorFor({class: 'DirtyTree',code: 'dirty_tree',@@ -192,6 +248,19 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResult}}+ // ── Models plan + strict mode (#5585) — banner and verdict before any spend+ const reflectCap = await resolveReflectMaxTokens(engine, opts.optimizerModel, opts.reflectMaxTokens);+ const modelsPlan = await buildModelsPlan(+ engine,+ opts.models ?? unknownProvenanceModels(opts, 'caller-supplied'),+ [...bench.tasks, ...heldOutTasks],+ );+ const banner = formatModelsBanner(modelsPlan, { skill: skillName, baseline: opts.modelsBannerBaseline, reflectCap });+ if (banner) process.stderr.write(banner);+ const strict = strictVerdict(modelsPlan, await resolveModelsStrict(engine, opts.modelsStrict));+ if (strict.enabled && !strict.ok && !opts.dryRun) throw modelsStrictError(strict);+ const pricingOverrides = await loadPricingOverrides(engine);+// ── Cost preflight (D3) ─────────────────────────────────────────────────const preflightResult = preflight({epochs: opts.epochs,@@ -205,6 +274,9 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResultmaxCostUsd: opts.maxCostUsd,heldOutSize: heldOutTasks.length,interactive: process.stderr.isTTY === true,+ reflectMaxTokens: reflectCap.maxTokens,+ judgeModels: modelsPlan.filter((e) => e.touchpoint === 'judge' && e.active).map((e) => e.model),+ ...(pricingOverrides ? { pricingOverrides } : {}),});if (opts.json !== true) {process.stderr.write(formatPreflightReport(preflightResult.estimate, {@@ -219,7 +291,9 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResultclass: 'CostCapExceeded',code: 'cost_cap_exceeded',message: preflightResult.abort_reason ?? 'preflight refused to proceed',- hint: `Raise --max-cost-usd or reduce knobs.`,+ hint: preflightResult.abort_code === 'reservation_exceeds_cap'+ ? `No model call was made.`+ : `Raise --max-cost-usd or reduce knobs.`,});}@@ -240,13 +314,19 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResultmax_cost_usd: opts.maxCostUsd,started_at: new Date().toISOString(),outcome: 'aborted',+ reflect_max_tokens: reflectCap.maxTokens,+ reflect_max_tokens_source: reflectCap.source,+ models_plan: modelsPlan,+ models_strict: strict,};return { outcome: 'aborted', receipt, finalText: fs.readFileSync(skillFile, 'utf8'), mutatedSkillFile: false };}// ── Acquire per-skill lock (D14) ────────────────────────────────────────return await withSkilloptLock(engine, skillName, async () => {- return runOptimizationLoop(opts, bench, split, bundledCtx, mutateDecision, heldOutTasks);+ return runOptimizationLoop(opts, bench, split, bundledCtx, mutateDecision, heldOutTasks, {+ reflectCap, modelsPlan, strict, pricingOverrides,+ });});}@@ -269,6 +349,22 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResult* through to the generic catch-all instead, misreporting outcome='errored'* / abortReason='error' on the receipt and audit trail.*/+/**+ * A resume may start on a SKILL.md this run itself rewrote: the file is dirty,+ * but it is exactly the checkpoint's best text. Any other edit still trips the+ * dirty-tree gate, so a hand edit between segments is never overwritten.+ */+function isOwnResumeEdit(skillsDir: string, skillName: string, skillFile: string, resumeRunId: string | undefined): boolean {+ if (!resumeRunId) return false;+ const cp = loadCheckpoint(skillsDir, skillName, resumeRunId);+ if (!cp) return false;+ try {+ return sha8(fs.readFileSync(skillFile, 'utf8')) === sha8(cp.best_skill_text);+ } catch {+ return false;+ }+}+export function classifyAbortError(err: unknown,opts: { maxRuntimeMin: number },@@ -284,7 +380,7 @@ export function classifyAbortError(abortReason: err.reason === 'runtime' ? 'runtime_exceeded' : 'budget_exhausted',abortDetail: msg,};- } else if (msg.includes('skillopt_runtime_exceeded')) {+ } else if (msg.includes(SKILLOPT_RUNTIME_EXCEEDED)) {return {outcome: 'aborted',abortReason: 'runtime_exceeded',@@ -300,6 +396,9 @@ export function classifyAbortError(}}+/** Appended to a cost-cap abort: optimizer calls reserve their whole output cap up front. */+const BUDGET_ADMISSION_HINT = ' (raise --max-cost-usd; each optimizer call reserves its full output cap, so lowering --reflect-max-tokens / skillopt.reflect_max_tokens also helps)';+async function runOptimizationLoop(opts: SkillOptOpts,bench: ReturnType<typeof loadBenchmark>,@@ -307,8 +406,15 @@ async function runOptimizationLoop(bundledCtx: ReturnType<typeof getBundledSkillContext>,mutateDecision: ReturnType<typeof shouldMutateSkillFile>,heldOutTasks: BenchmarkTask[],+ resolved: {+ reflectCap: ReflectCap;+ modelsPlan: ModelsPlanEntry[];+ strict: StrictVerdict;+ pricingOverrides: PricingOverrides | undefined;+ },): Promise<RunSkillOptResult> {const { skillName, skillsDir } = opts;+ const { reflectCap, modelsPlan } = resolved;const skillFile = skillPath(skillsDir, skillName);// Plain-English success criteria from the benchmark judges, fed to the@@ -327,10 +433,35 @@ async function runOptimizationLoop(const baselineText = fs.readFileSync(skillFile, 'utf8');const baselineSha8 = sha8(baselineText);- // Resume or init checkpoint.+ const runSpec: RunSpec = {+ skills_dir: skillsDir,+ benchmark_path: opts.benchmarkPath,+ benchmark_sha8: bench.benchmark_sha8,+ held_out_path: opts.heldOutPath ?? null,+ held_out_sha8: opts.heldOutPath ? sha8(fs.readFileSync(opts.heldOutPath, 'utf8')) : null,+ split: opts.split,+ mutate: mutateDecision.mutate,+ no_mutate: opts.noMutate,+ allow_mutate_bundled: opts.allowMutateBundled,+ bootstrap_reviewed: opts.bootstrapReviewed,+ optimizer_model: opts.optimizerModel,+ target_model: opts.targetModel,+ judge_model: opts.judgeModel,+ epochs: opts.epochs,+ batch_size: opts.batchSize,+ lr: opts.lr,+ lr_schedule: opts.lrSchedule,+ reflect_max_tokens: reflectCap.maxTokens,+ };++ // Resume or init checkpoint. A resume must match what the checkpoint measured.const runId = opts.resumeRunId ?? randomUUID();let checkpoint = opts.resumeRunId ? loadCheckpoint(skillsDir, skillName, opts.resumeRunId) : null;- if (!checkpoint) {+ const prior = priorSegments(checkpoint);+ if (checkpoint) {+ assertResumeCompatible(checkpoint, runSpec);+ checkpoint.run_spec = runSpec;+ } else {checkpoint = {schema: 1,run_id: runId,@@ -348,7 +479,13 @@ async function runOptimizationLoop(best_skill_text: baselineText,last_completed_epoch: 0,last_completed_step: 0,+ next_epoch: 1,+ next_step: 1,+ run_spec: runSpec,+ tally: emptyTally(),cumulative_cost_usd: 0,+ models_used: [],+ models_used_scope: 'full_run',started_at: new Date().toISOString(),last_updated_at: new Date().toISOString(),};@@ -374,6 +511,7 @@ async function runOptimizationLoop(validation_gate_disabled: opts.disableValidationGate === true,optimizer_mode: opts.optimizerMode ?? 'reflect',held_out_size: heldOutTasks.length,+ models_plan: modelsPlan,} as never);// Budget tracker for the whole run. BudgetExhausted propagates as@@ -385,6 +523,7 @@ async function runOptimizationLoop(// unpriced model ids (openrouter:*, litellm:*) can run at the user's own risk.const tracker = new BudgetTracker({...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd } : {}),+ ...(resolved.pricingOverrides ? { pricingOverrides: resolved.pricingOverrides } : {}),label: `skillopt:${skillName}`,});@@ -392,13 +531,33 @@ async function runOptimizationLoop(const totalSteps = opts.epochs * Math.max(1, Math.floor(split.train.length / opts.batchSize));// Run the loop inside withBudgetTracker so every nested gateway call composes.- let outcome: 'accepted' | 'no_improvement' | 'aborted' | 'errored' = 'no_improvement';- // #3516: why a run aborted/errored — surfaced on the receipt + CLI, not- // just the audit JSONL, so a failed run is never a silent "Outcome: errored".- let abortReason: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error' | undefined;- let abortDetail: string | undefined;let finalText = checkpoint.best_skill_text;let totalStepsRun = 0;+ // A legacy checkpoint (no tally) that already moved past the baseline text+ // accepted a candidate in an earlier segment.+ const tally = checkpoint.tally+ ?? { ...emptyTally(), accepted_steps: sha8(checkpoint.best_skill_text) !== checkpoint.skill_sha8 ? 1 : 0 };+ // A resume is a fresh attempt (usually after a fix): the trailing fully+ // unusable steps are re-run instead of skipped, and the early-stop streak+ // restarts instead of stopping the resumed run after one step.+ // The rewound cursor is written to the checkpoint together with the reset+ // streak, so a resume that aborts before its first step still retries them.+ const stepsPerEpoch = Math.max(1, Math.floor(split.train.length / opts.batchSize));+ if (opts.resumeRunId && opts.optimizerMode !== 'one-shot-rewrite' && tally.unusable_streak > 0) {+ setCursor(checkpoint, rewindCursor(resumeCursor(checkpoint, stepsPerEpoch), tally.unusable_streak, stepsPerEpoch));+ }+ tally.unusable_streak = 0;+ checkpoint.tally = tally;+ // Tally as of the start of the in-flight step. A handled abort re-runs that+ // step on --resume, so the checkpoint keeps this copy (the receipt keeps the+ // live tally, which includes the calls this segment actually made).+ let stepStartTally: ReflectTally | undefined;+ // First error of the most recent fully unusable step (the receipt's error+ // list is deduped and capped, so it cannot say what caused an early stop).+ let lastUnusableError: string | undefined;+ let earlyStopped = false;+ let skillBodyTruncated: SkillBodyTruncation | undefined;+ let caught: ReturnType<typeof classifyAbortError> | undefined;// Hoisted for the receipt (computed inside the budget-tracker closure).let baselineSelScore = 0;let testScore: number | undefined;@@ -440,6 +599,7 @@ async function runOptimizationLoop(// Sets last_completed_epoch = epochs so the epoch loop below no-ops, then// falls through to the shared final-test + receipt path.if (opts.optimizerMode === 'one-shot-rewrite') {+ stepStartTally = structuredClone(tally);const { body: baselineBody, bodyStart } = splitFrontmatter(baselineText);const fmBlock = baselineText.slice(0, bodyStart);const fwd = await runValidationGate({@@ -460,7 +620,15 @@ async function runOptimizationLoop(rejected: [],criteria: benchmarkCriteria,optimizerModel: opts.optimizerModel,+ maxTokens: reflectCap.maxTokens,});+ recordOptimizerStep(tally, {+ calls: 1,+ usableReplies: rewrite.error ? 0 : 1,+ errors: rewrite.error ? [rewrite.error] : [],+ invalidEditsDropped: 0,+ });+ if (rewrite.error) process.stderr.write(`[skillopt] one-shot rewrite produced no candidate (${rewrite.error})\n`);if (rewrite.newBody) {const candidate = fmBlock + rewrite.newBody;// Held-out gate still applies (independent signal); skipped when unset.@@ -500,23 +668,26 @@ async function runOptimizationLoop(} else {writeProposed(skillsDir, skillName, candidate);}- outcome = 'accepted';+ tally.accepted_steps += 1;finalText = candidate;}}- checkpoint!.last_completed_epoch = opts.epochs; // no-op the epoch loop below+ advanceCursor(checkpoint!, opts.epochs, 1, 1); // no-op the epoch loop below+ bankAccounting(checkpoint!, prior, tracker.snapshot());saveCheckpoint(skillsDir, skillName, checkpoint!);+ stepStartTally = undefined;}- // Epoch loop.- for (let epoch = checkpoint!.last_completed_epoch + 1; epoch <= opts.epochs; epoch++) {- const stepsPerEpoch = Math.max(1, Math.floor(split.train.length / opts.batchSize));- const startStep = epoch === checkpoint!.last_completed_epoch + 1 ? checkpoint!.last_completed_step + 1 : 1;+ // Epoch loop. The cursor names the first step that has not completed.+ const cursor = resumeCursor(checkpoint!, stepsPerEpoch);+ epochs: for (let epoch = cursor.epoch; epoch <= opts.epochs; epoch++) {+ const startStep = epoch === cursor.epoch ? cursor.step : 1;const epochStartBest = checkpoint!.best_sel_score;for (let step = startStep; step <= stepsPerEpoch; step++) {- if (Date.now() > deadline) throw new Error('skillopt_runtime_exceeded');+ if (Date.now() > deadline) throw new Error(SKILLOPT_RUNTIME_EXCEEDED);totalStepsRun += 1;+ stepStartTally = structuredClone(tally);const globalStep = (epoch - 1) * stepsPerEpoch + step;const lrBudget = scheduleFn(opts.lr, globalStep, totalSteps);@@ -545,202 +716,224 @@ async function runOptimizationLoop(const successes = forwardGate.scoredRollouts.filter((r) => r.score >= ROLLOUT_SUCCESS_THRESHOLD);const failures = forwardGate.scoredRollouts.filter((r) => r.score < ROLLOUT_SUCCESS_THRESHOLD);- // BACKWARD PASS: D7 two reflect calls (failures + successes).- const rejected = loadRejectedBuffer(skillsDir, skillName);- const reflectResult = await runReflect({- skillBodyText: checkpoint!.best_skill_text,- successes,- failures,- rejected,- criteria: benchmarkCriteria,- optimizerModel: opts.optimizerModel,- ...(opts.reflectMode ? { reflectMode: opts.reflectMode } : {}),- abortSignal: undefined,- });+ stepBody: {+ // BACKWARD PASS: D7 two reflect calls (failures + successes).+ const rejected = loadRejectedBuffer(skillsDir, skillName);+ const reflectResult = await runReflect({+ skillBodyText: checkpoint!.best_skill_text,+ successes,+ failures,+ rejected,+ criteria: benchmarkCriteria,+ optimizerModel: opts.optimizerModel,+ maxTokens: reflectCap.maxTokens,+ ...(opts.reflectMode ? { reflectMode: opts.reflectMode } : {}),+ abortSignal: undefined,+ });+ recordOptimizerStep(tally, reflectResult);+ if (reflectResult.calls > 0 && reflectResult.usableReplies === 0) lastUnusableError = reflectResult.errors[0];+ if (reflectResult.skillBodyTruncated) skillBodyTruncated = reflectResult.skillBodyTruncated;- // Merge + rank + LR-clip.- const allEdits: EditOp[] = [...reflectResult.failureEdits, ...reflectResult.successEdits];- // Drop edits already in rejected buffer.- const fresh = allEdits.filter((e) => !isRejected(rejected, checkpoint!.best_skill_text, [e]));- // Apply under LR budget.- const applied = applyEditBatch(checkpoint!.best_skill_text, fresh, lrBudget);-- if (fresh.length === 0) {- // #4741: the optimizer proposed NOTHING (reflect returned/parsed no- // edits, or every edit was already in the rejected buffer). This- // used to fall into the all-rejected branch below ([].every() is- // true) and log the same 'no_edits_applied' as "gated N candidates- // and rejected all" — so a whole run of zero candidates read as a- // real `no_improvement`. Say so per step; nothing to reject-buffer.- const why = reflectResult.errors[0]- ? `no_edits_proposed: ${reflectResult.errors[0]}`- : 'no_edits_proposed';- process.stderr.write(`[skillopt] epoch ${epoch} step ${step}: optimizer proposed no edits (${why})\n`);- logEvent({- kind: 'step',- run_id: runId,- skill: skillName,- epoch,- step,- sel_score_median: checkpoint!.best_sel_score,- sel_score_runs: [],- accepted: false,- edits_attempted: 0,- edits_applied: 0,- delta: 0,- reason: why,- cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,- } as never);- continue;- }+ // Merge + rank + LR-clip.+ const allEdits: EditOp[] = [...reflectResult.failureEdits, ...reflectResult.successEdits];+ // Drop edits already in rejected buffer.+ const fresh = allEdits.filter((e) => !isRejected(rejected, checkpoint!.best_skill_text, [e]));+ // Apply under LR budget.+ const applied = applyEditBatch(checkpoint!.best_skill_text, fresh, lrBudget);- if (applied.results.every((r) => r.outcome === 'rejected')) {- // Nothing applied; record rejected entries + skip gate.- const newRejections = fresh.map((e) =>- makeRejectedEntry(checkpoint!.best_skill_text, [e], 'apply_failed'),- );- saveRejectedBuffer(skillsDir, skillName, newRejections);- logEvent({- kind: 'step',- run_id: runId,- skill: skillName,- epoch,- step,- sel_score_median: checkpoint!.best_sel_score,- sel_score_runs: [],- accepted: false,- edits_attempted: fresh.length,- edits_applied: 0,- delta: 0,- reason: 'no_edits_applied',- cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,- } as never);- continue;- }+ if (fresh.length === 0) {+ // #4741: the optimizer proposed NOTHING (reflect returned/parsed no+ // edits, or every edit was already in the rejected buffer). This+ // used to fall into the all-rejected branch below ([].every() is+ // true) and log the same 'no_edits_applied' as "gated N candidates+ // and rejected all" — so a whole run of zero candidates read as a+ // real `no_improvement`. Say so per step; nothing to reject-buffer.+ const why = reflectResult.errors[0]+ ? `no_edits_proposed: ${reflectResult.errors[0]}`+ : 'no_edits_proposed';+ process.stderr.write(`[skillopt] epoch ${epoch} step ${step}: optimizer proposed no edits (${why})\n`);+ logEvent({+ kind: 'step',+ run_id: runId,+ skill: skillName,+ epoch,+ step,+ sel_score_median: checkpoint!.best_sel_score,+ sel_score_runs: [],+ accepted: false,+ edits_attempted: 0,+ edits_applied: 0,+ delta: 0,+ reason: why,+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,+ ...(reflectResult.errors.length > 0 ? { reflect_errors: reflectResult.errors } : {}),+ ...(reflectResult.invalidEditsDropped > 0 ? { invalid_edits_dropped: reflectResult.invalidEditsDropped } : {}),+ } as never);+ break stepBody;+ }- // VALIDATION GATE (D12 median-of-3 + epsilon=0.05, D4 parallel).- const gate = await runValidationGate({- engine: opts.engine,- operationContext: opts.operationContext,- candidateSkillText: applied.newText,- selSet: split.sel,- bestScore: checkpoint!.best_sel_score,- targetModel: opts.targetModel,- judgeModel: opts.judgeModel,- deadlineMs: deadline,- });+ if (applied.results.every((r) => r.outcome === 'rejected')) {+ // Nothing applied; record rejected entries + skip gate.+ const newRejections = fresh.map((e) =>+ makeRejectedEntry(checkpoint!.best_skill_text, [e], 'apply_failed'),+ );+ saveRejectedBuffer(skillsDir, skillName, newRejections);+ logEvent({+ kind: 'step',+ run_id: runId,+ skill: skillName,+ epoch,+ step,+ sel_score_median: checkpoint!.best_sel_score,+ sel_score_runs: [],+ accepted: false,+ edits_attempted: fresh.length,+ edits_applied: 0,+ delta: 0,+ reason: 'no_edits_applied',+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,+ ...(reflectResult.invalidEditsDropped > 0 ? { invalid_edits_dropped: reflectResult.invalidEditsDropped } : {}),+ } as never);+ break stepBody;+ }- // Ablation (cat31 config D): disableValidationGate greedy-accepts any- // applied edit, bypassing the D12 median+epsilon check. We still ran- // the gate above to GET the score (so sel_score tracking is honest),- // but ignore its accept verdict. We only reach here when at least one- // edit applied (the all-rejected case `continue`d earlier).- const stepAccepted = opts.disableValidationGate === true ? true : gate.accepted;- if (stepAccepted) {- // F11 HELD-OUT GATE — guards CHECKPOINT ACCEPTANCE (not just file- // mutation), so the no-mutate / proposed.md paths can't promote a- // held-out-failing candidate either. Independent signal: a candidate- // that improved D_sel but regresses on the held-out set is refused- // (benchmark-gaming defense). Skipped when no held-out is configured.- if (heldOutTasks.length > 0) {- const ho = await runHeldOutGate({- engine: opts.engine,- operationContext: opts.operationContext,- candidateSkillText: applied.newText,- baselineSkillText: baselineText,- heldOutTasks,- deadlineMs: deadline,- targetModel: opts.targetModel,- judgeModel: opts.judgeModel,- });- if (!ho.passed) {- const newRejections = fresh.map((e) =>- makeRejectedEntry(checkpoint!.best_skill_text, [e], 'held_out_regression'),- );- saveRejectedBuffer(skillsDir, skillName, newRejections);- logEvent({- kind: 'step',- run_id: runId,- skill: skillName,+ // VALIDATION GATE (D12 median-of-3 + epsilon=0.05, D4 parallel).+ const gate = await runValidationGate({+ engine: opts.engine,+ operationContext: opts.operationContext,+ candidateSkillText: applied.newText,+ selSet: split.sel,+ bestScore: checkpoint!.best_sel_score,+ targetModel: opts.targetModel,+ judgeModel: opts.judgeModel,+ deadlineMs: deadline,+ });++ // Ablation (cat31 config D): disableValidationGate greedy-accepts any+ // applied edit, bypassing the D12 median+epsilon check. We still ran+ // the gate above to GET the score (so sel_score tracking is honest),+ // but ignore its accept verdict. We only reach here when at least one+ // edit applied (the all-rejected case exits via `break stepBody` earlier,+ // which still advances the cursor).+ const stepAccepted = opts.disableValidationGate === true ? true : gate.accepted;+ if (stepAccepted) {+ // F11 HELD-OUT GATE — guards CHECKPOINT ACCEPTANCE (not just file+ // mutation), so the no-mutate / proposed.md paths can't promote a+ // held-out-failing candidate either. Independent signal: a candidate+ // that improved D_sel but regresses on the held-out set is refused+ // (benchmark-gaming defense). Skipped when no held-out is configured.+ if (heldOutTasks.length > 0) {+ const ho = await runHeldOutGate({+ engine: opts.engine,+ operationContext: opts.operationContext,+ candidateSkillText: applied.newText,+ baselineSkillText: baselineText,+ heldOutTasks,+ deadlineMs: deadline,+ targetModel: opts.targetModel,+ judgeModel: opts.judgeModel,+ });+ if (!ho.passed) {+ const newRejections = fresh.map((e) =>+ makeRejectedEntry(checkpoint!.best_skill_text, [e], 'held_out_regression'),+ );+ saveRejectedBuffer(skillsDir, skillName, newRejections);+ logEvent({+ kind: 'step',+ run_id: runId,+ skill: skillName,+ epoch,+ step,+ sel_score_median: gate.selScore,+ sel_score_runs: gate.perTaskMedians.map((t) => t.median),+ accepted: false,+ edits_attempted: fresh.length,+ edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,+ delta: gate.selScore - checkpoint!.best_sel_score,+ reason: 'held_out_regression',+ held_out_baseline: ho.baselineScore,+ held_out_candidate: ho.candidateScore,+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,+ } as never);+ break stepBody; // do NOT promote+ }+ }++ const delta = gate.selScore - checkpoint!.best_sel_score;+ // ACCEPT: D8 commit via version-store (mutate) OR write proposed.md+ // for the --no-mutate / bundled-without-allow paths.+ if (mutateDecision.mutate) {+ acceptCandidate({+ skillsDir,+ skillName,+ runId,epoch,step,- sel_score_median: gate.selScore,- sel_score_runs: gate.perTaskMedians.map((t) => t.median),- accepted: false,- edits_attempted: fresh.length,- edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,- delta: gate.selScore - checkpoint!.best_sel_score,- reason: 'held_out_regression',- held_out_baseline: ho.baselineScore,- held_out_candidate: ho.candidateScore,- cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,- } as never);- continue; // do NOT promote+ edits: fresh,+ candidateText: applied.newText,+ selScore: gate.selScore,+ delta,+ });+ } else {+ writeProposed(skillsDir, skillName, applied.newText);}- }+ checkpoint!.best_sel_score = gate.selScore;+ checkpoint!.best_skill_text = applied.newText;+ tally.accepted_steps += 1;- const delta = gate.selScore - checkpoint!.best_sel_score;- // ACCEPT: D8 commit via version-store (mutate) OR write proposed.md- // for the --no-mutate / bundled-without-allow paths.- if (mutateDecision.mutate) {- acceptCandidate({- skillsDir,- skillName,- runId,+ logEvent({+ kind: 'step',+ run_id: runId,+ skill: skillName,epoch,step,- edits: fresh,- candidateText: applied.newText,- selScore: gate.selScore,+ sel_score_median: gate.selScore,+ sel_score_runs: gate.perTaskMedians.map((t) => t.median),+ accepted: true,+ edits_attempted: fresh.length,+ edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,delta,- });+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,+ ...(reflectResult.invalidEditsDropped > 0 ? { invalid_edits_dropped: reflectResult.invalidEditsDropped } : {}),+ } as never);+ finalText = applied.newText;} else {- writeProposed(skillsDir, skillName, applied.newText);+ // REJECT: push to rejected-buffer.+ const newRejections = fresh.map((e) =>+ makeRejectedEntry(checkpoint!.best_skill_text, [e], `validation_gate_${gate.reason ?? 'rejected'}`),+ );+ saveRejectedBuffer(skillsDir, skillName, newRejections);+ logEvent({+ kind: 'step',+ run_id: runId,+ skill: skillName,+ epoch,+ step,+ sel_score_median: gate.selScore,+ sel_score_runs: gate.perTaskMedians.map((t) => t.median),+ accepted: false,+ edits_attempted: fresh.length,+ edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,+ delta: gate.selScore - checkpoint!.best_sel_score,+ reason: gate.reason ?? 'rejected',+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,+ ...(reflectResult.invalidEditsDropped > 0 ? { invalid_edits_dropped: reflectResult.invalidEditsDropped } : {}),+ } as never);}- checkpoint!.best_sel_score = gate.selScore;- checkpoint!.best_skill_text = applied.newText;- checkpoint!.last_completed_epoch = epoch;- checkpoint!.last_completed_step = step;- checkpoint!.cumulative_cost_usd = tracker.snapshot().cumulativeCostUsd;- saveCheckpoint(skillsDir, skillName, checkpoint!);-- logEvent({- kind: 'step',- run_id: runId,- skill: skillName,- epoch,- step,- sel_score_median: gate.selScore,- sel_score_runs: gate.perTaskMedians.map((t) => t.median),- accepted: true,- edits_attempted: fresh.length,- edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,- delta,- cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,- } as never);- outcome = 'accepted';- finalText = applied.newText;- } else {- // REJECT: push to rejected-buffer.- const newRejections = fresh.map((e) =>- makeRejectedEntry(checkpoint!.best_skill_text, [e], `validation_gate_${gate.reason ?? 'rejected'}`),+ }++ // Step completed (accepted, rejected or no candidate): advance the+ // cursor and persist accounting so --resume continues after it.+ advanceCursor(checkpoint!, epoch, step, stepsPerEpoch);+ bankAccounting(checkpoint!, prior, tracker.snapshot());+ saveCheckpoint(skillsDir, skillName, checkpoint!);+ stepStartTally = undefined;+ if (shouldEarlyStop(tally)) {+ earlyStopped = true;+ process.stderr.write(+ `[skillopt] stopped after ${EARLY_STOP_UNUSABLE_STEPS} steps of ${unusableClasses(tally)}; remaining budget not spent\n`,);- saveRejectedBuffer(skillsDir, skillName, newRejections);- logEvent({- kind: 'step',- run_id: runId,- skill: skillName,- epoch,- step,- sel_score_median: gate.selScore,- sel_score_runs: gate.perTaskMedians.map((t) => t.median),- accepted: false,- edits_attempted: fresh.length,- edits_applied: applied.results.filter((r) => r.outcome === 'applied').length,- delta: gate.selScore - checkpoint!.best_sel_score,- reason: gate.reason ?? 'rejected',- cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,- } as never);+ break epochs;}}@@ -756,16 +949,14 @@ async function runOptimizationLoop(} as never);}- checkpoint!.last_completed_epoch = epoch;- checkpoint!.last_completed_step = 0;- saveCheckpoint(skillsDir, skillName, checkpoint!);}// FINAL TEST: score the best skill AND the baseline on D_test so the// receipt carries an honest held-out generalization signal (the eval// harnesses also compute this themselves, but a truthful receipt removes- // the prior hardcoded-0 lie). Skipped when D_test is empty.- if (split.test.length > 0) {+ // the prior hardcoded-0 lie). Skipped when D_test is empty, and after an+ // early stop with nothing accepted (best === baseline; budget not spent).+ if (split.test.length > 0 && !(earlyStopped && tally.accepted_steps === 0)) {testScore = await scoreSkillOnTasks({engine: opts.engine,operationContext: opts.operationContext,@@ -787,33 +978,52 @@ async function runOptimizationLoop(}});} catch (err) {- const classified = classifyAbortError(err, opts);- outcome = classified.outcome;- abortReason = classified.abortReason;- abortDetail = classified.abortDetail;+ caught = classifyAbortError(err, opts);+ if (err instanceof BudgetExhausted && err.reason === 'cost') caught.abortDetail += BUDGET_ADMISSION_HINT;logEvent({kind: 'abort',run_id: runId,skill: skillName,- reason: abortReason,- detail: abortDetail,+ reason: caught.abortReason,+ detail: caught.abortDetail,} as never);+ // Handled abort: bank the spend; the cursor stays on the interrupted step+ // so --resume re-runs it, and the saved tally is the step-start copy so+ // that re-run does not count the step's optimizer calls twice.+ bankAccounting(checkpoint, prior, tracker.snapshot());+ if (stepStartTally) checkpoint.tally = stepStartTally;+ saveCheckpoint(skillsDir, skillName, checkpoint);+ checkpoint.tally = tally;}- // If --no-mutate or bundled+!allowMutateBundled: write proposed.md instead.- let mutatedSkillFile = false;- let proposedPath: string | undefined;- // Widen back to the full union — TS narrowed `outcome` inside the try/catch- // to the catch's assignment values only (it can't prove the async callback ran).- const finalOutcome = outcome as 'accepted' | 'no_improvement' | 'aborted' | 'errored';- if (!mutateDecision.mutate && finalOutcome === 'accepted') {- // writeProposed() emitted both the best pointer and the stable review- // artifact in the accept branch. SKILL.md remains untouched.- proposedPath = proposedFilePath(skillsDir, skillName);- } else if (mutateDecision.mutate) {- mutatedSkillFile = finalOutcome === 'accepted';+ const { outcome, stopReason, abortReason, abortDetail } = resolveRunOutcome({ caught, tally, earlyStopped });+ if (outcome === 'errored' && !caught) {+ logEvent({ kind: 'abort', run_id: runId, skill: skillName, reason: 'error', detail: abortDetail } as never);}+ // Acceptance history (not the final loop state) decides what was written:+ // an abort or early stop after an accepted step still mutated SKILL.md /+ // wrote proposed.md.+ const acceptedAny = tally.accepted_steps > 0;+ const mutatedSkillFile = mutateDecision.mutate && acceptedAny;+ const proposedPath = !mutateDecision.mutate && acceptedAny ? proposedFilePath(skillsDir, skillName) : undefined;+ // An early stop left work undone even when it resolves to no_improvement.+ const checkpointRetained = outcome === 'aborted' || outcome === 'errored' || earlyStopped;+ if (checkpointRetained && !caught) {+ // The final evaluation ran after the last step save; bank its spend too.+ bankAccounting(checkpoint, prior, tracker.snapshot());+ saveCheckpoint(skillsDir, skillName, checkpoint);+ }+ const remediation = buildRemediation([...tally.reflect_errors, ...(abortDetail ? [abortDetail] : [])], abortReason);+ // An early stop that still resolved accepted/no_improvement takes its+ // resume remedy from the trailing unusable errors.+ const failureCode = caught+ ? errorCode(caught.abortDetail)+ : earlyStopped && lastUnusableError ? errorCode(lastUnusableError)+ : abortDetail ? errorCode(abortDetail) : undefined;+ const budget = tracker.snapshot();+ const modelsUsed = buildModelsUsed(budget, prior.rows);+// Final receipt.const receipt: RunReceipt = {run_id: runId,@@ -835,11 +1045,28 @@ async function runOptimizationLoop(// CLI's stderr summary both see WHY, not just that the run died....(abortReason !== undefined ? { abort_reason: abortReason } : {}),...(abortDetail !== undefined ? { abort_detail: abortDetail } : {}),+ stop_reason: stopReason,+ ...(tally.reflect_errors.length > 0 ? { reflect_errors: [...tally.reflect_errors] } : {}),+ ...(tally.invalid_edits_dropped > 0 ? { reflect_invalid_edits_dropped: tally.invalid_edits_dropped } : {}),+ ...(skillBodyTruncated ? { skill_body_truncated: skillBodyTruncated } : {}),+ ...(remediation.length > 0 ? { remediation } : {}),+ reflect_max_tokens: reflectCap.maxTokens,+ reflect_max_tokens_source: reflectCap.source,+ ...(checkpointRetained ? { resume_command: buildResumeCommand(skillName, runId, runSpec, failureCode, {+ mode: opts.mode, maxCostUsd: opts.maxCostUsd, maxRuntimeMin: opts.maxRuntimeMin,+ force: opts.force,+ modelsStrict: opts.modelsStrict === true,+ }) } : {}),baseline_sel_score: baselineSelScore,best_sel_score: checkpoint.best_sel_score,...(testScore !== undefined ? { test_score: testScore } : {}),...(baselineTestScore !== undefined ? { baseline_test_score: baselineTestScore } : {}),- final_cost_usd: tracker.snapshot().cumulativeCostUsd,+ final_cost_usd: budget.cumulativeCostUsd,+ prior_segments_cost_usd: prior.costUsd,+ models_used: modelsUsed,+ models_used_scope: prior.scope,+ models_plan: modelsPlan,+ models_strict: resolved.strict,total_steps: totalStepsRun,epochs_completed: checkpoint.last_completed_epoch,// Ablation provenance (cat31 replayability) — only when a non-default knob set.@@ -856,11 +1083,15 @@ async function runOptimizationLoop(epochs_completed: checkpoint.last_completed_epoch,total_steps: totalStepsRun,best_sel_score: checkpoint.best_sel_score,- final_cost_usd: tracker.snapshot().cumulativeCostUsd,+ final_cost_usd: budget.cumulativeCostUsd,+ models_used: modelsUsed,+ models_used_scope: prior.scope,+ stop_reason: stopReason,+ ...(abortDetail !== undefined ? { abort_detail: abortDetail } : {}),} as never);// Clean checkpoint on success (resume not needed).- if (finalOutcome === 'accepted' || finalOutcome === 'no_improvement') {+ if (!checkpointRetained) {deleteCheckpoint(skillsDir, skillName, runId);}diff --git a/src/core/skillopt/output-cap.ts b/src/core/skillopt/output-cap.tsnew file mode 100644index 0000000000..beca1cee29--- /dev/null+++ b/src/core/skillopt/output-cap.ts@@ -0,0 +1,80 @@+/**+ * SkillOpt output-token caps.+ *+ * Thinking-by-default optimizers (Claude 5, recipe-declared+ * `thinking_by_default`) spend reasoning tokens inside `maxTokens`, so the+ * small fixed caps skillopt used to send cut replies off mid-JSON. Two caps:+ *+ * - The REFLECT cap governs every optimizer call (patch + rewrite reflect+ * and the eval-internal one-shot ablation). Precedence: explicit value+ * (`--reflect-max-tokens`, MCP / job `reflect_max_tokens`) >+ * `skillopt.reflect_max_tokens` config > `defaultMaxOutputTokens(optimizer)`+ * (32000 thinking, 4096 otherwise). Configured values are honored exactly,+ * including values below the default.+ * - `skilloptOutputCap` gives the judge and bootstrap-row sites headroom on+ * thinking models (`max(siteCap, 8192)`) and leaves every other model on+ * its site cap. The gateway's own maxTokens semantics are untouched.+ */++import type { BrainEngine } from '../engine.ts';+import { defaultMaxOutputTokens, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../ai/gateway.ts';++export const REFLECT_MAX_TOKENS_CONFIG_KEY = 'skillopt.reflect_max_tokens';+/** Floor for remote (MCP / job) reflect caps; local flag + config are honored exactly. */+export const REFLECT_MAX_TOKENS_MIN = 256;+/** Judge + bootstrap-row output floor for thinking models. */+export const SKILLOPT_THINKING_SITE_FLOOR = 8192;++export type ReflectCapSource = 'flag' | 'config' | 'default';++export interface ReflectCap {+ maxTokens: number;+ source: ReflectCapSource;+}++export function skilloptOutputCap(model: string | undefined, siteCap: number): number {+ return isThinkingModel(model) ? Math.max(siteCap, SKILLOPT_THINKING_SITE_FLOOR) : siteCap;+}++/** Positive-integer parse shared by the CLI flag, config value and remote params. */+export function parsePositiveInt(raw: unknown): number | undefined {+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw.trim()) : NaN;+ return Number.isInteger(n) && n > 0 ? n : undefined;+}++/**+ * Validate an untrusted reflect cap (MCP op param, background job data):+ * absent -> undefined; not a positive integer -> throws; otherwise clamped to+ * [REFLECT_MAX_TOKENS_MIN, THINKING_MODEL_MAX_OUTPUT_TOKENS].+ */+export function clampRemoteReflectMaxTokens(raw: unknown): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ const n = parsePositiveInt(raw);+ if (n === undefined) {+ throw new Error(`reflect_max_tokens must be a positive integer (got ${JSON.stringify(raw)})`);+ }+ return Math.min(THINKING_MODEL_MAX_OUTPUT_TOKENS, Math.max(REFLECT_MAX_TOKENS_MIN, n));+}++const warnedInvalidConfig = new Set<string>();++export async function resolveReflectMaxTokens(+ engine: Pick<BrainEngine, 'getConfig'>,+ optimizerModel: string,+ explicit?: number,+): Promise<ReflectCap> {+ if (explicit !== undefined) return { maxTokens: explicit, source: 'flag' };+ let raw: string | null = null;+ try {+ raw = await engine.getConfig(REFLECT_MAX_TOKENS_CONFIG_KEY);+ } catch { /* unreadable config -> default */ }+ if (raw !== null && raw !== undefined && raw.trim() !== '') {+ const n = parsePositiveInt(raw);+ if (n !== undefined) return { maxTokens: n, source: 'config' };+ if (!warnedInvalidConfig.has(raw)) {+ warnedInvalidConfig.add(raw);+ process.stderr.write(`[skillopt] ignoring ${REFLECT_MAX_TOKENS_CONFIG_KEY}=${JSON.stringify(raw.slice(0, 200))} (not a positive integer); using the default\n`);+ }+ }+ return { maxTokens: defaultMaxOutputTokens(optimizerModel), source: 'default' };+}diff --git a/src/core/skillopt/preflight.ts b/src/core/skillopt/preflight.tsindex 7310420921..cedbc7f222 100644--- a/src/core/skillopt/preflight.ts+++ b/src/core/skillopt/preflight.ts@@ -20,13 +20,26 @@* - epochs × 1 slow-update reflect call (if no improvement that epoch)* - 1× final test eval on D_test*+ * Expected cost is a heuristic. Separately, every run role's largest single+ * call is priced exactly as `BudgetTracker.reserve()` will price it (shared+ * `reservationCostUsd`, effective output caps: the reflect cap, the target's+ * default output cap, `skilloptOutputCap` for each active judge, same+ * pricing overrides, input counted as 0 so the check never over-refuses).+ * When one call's reservation alone exceeds the cap the run can never make+ * that call, so preflight refuses before any spend and names the role and+ * the control that fixes it (`reservation_exceeds_cap`).+ ** Prices come from the canonical pricing table (model-pricing.ts) via* canonicalLookup. For unknown providers `lookupPrice` returns a warn-only* Sonnet-tier fallback (preflight estimates, never gates) — the actual* fail-loud gate is BudgetTracker's TX2 contract at run time.*/+import { defaultMaxOutputTokens } from '../ai/gateway.ts';+import { reservationCostUsd, type PricingOverrides } from '../budget/reservation-cost.ts';import { canonicalLookup } from '../model-pricing.ts';+import { skilloptOutputCap } from './output-cap.ts';+import { JUDGE_SITE_MAX_TOKENS } from './score.ts';import { VALIDATION_RUNS_PER_TASK } from './types.ts';/** Conservative per-rollout token estimates (input + output). */@@ -56,6 +69,51 @@ export interface PreflightOpts {heldOutSize?: number;/** When true, print the prompt to stderr + use Ctrl-C grace. Default false (non-TTY). */interactive?: boolean;+ /** Effective optimizer output cap; default `defaultMaxOutputTokens(optimizerModel)`. */+ reflectMaxTokens?: number;+ /**+ * Every judge model the run can call (default judge when active + task+ * `judge.model` overrides). Empty = no LLM judge (rule/qrels benchmark).+ * Default `[judgeModel]`.+ */+ judgeModels?: string[];+ /** Operator `pricing.overrides`, the same map the run's BudgetTracker uses. */+ pricingOverrides?: PricingOverrides;+}++export type ReservationRole = 'optimizer' | 'target' | 'judge';++/** What one call of a role reserves up front (input counted as 0). */+export interface CallReservation {+ role: ReservationRole;+ model: string;+ max_output_tokens: number;+ /** null = unpriced (left to the tracker's no_pricing contract at run time). */+ reservation_usd: number | null;+}++const RESERVATION_CONTROL: Record<ReservationRole, string> = {+ optimizer: 'lower --reflect-max-tokens / skillopt.reflect_max_tokens, or raise --max-cost-usd',+ target: 'use a cheaper --target-model (models.tier.subagent), or raise --max-cost-usd',+ judge: 'use a cheaper --judge-model (models.tier.reasoning) or task judge.model, or raise --max-cost-usd',+};++export function singleCallReservations(opts: PreflightOpts): CallReservation[] {+ const reserve = (role: ReservationRole, model: string, maxOut: number): CallReservation =>+ ({ role, model, max_output_tokens: maxOut, reservation_usd: reservationCostUsd(model, 'chat', 0, maxOut, opts.pricingOverrides) });+ return [+ reserve('optimizer', opts.optimizerModel, opts.reflectMaxTokens ?? defaultMaxOutputTokens(opts.optimizerModel)),+ reserve('target', opts.targetModel, defaultMaxOutputTokens(opts.targetModel)),+ ...(opts.judgeModels ?? [opts.judgeModel]).map((m) => reserve('judge', m, skilloptOutputCap(m, JUDGE_SITE_MAX_TOKENS))),+ ];+}++function largestReservation(opts: PreflightOpts): CallReservation | undefined {+ let best: CallReservation | undefined;+ for (const r of singleCallReservations(opts)) {+ if (r.reservation_usd !== null && (!best || r.reservation_usd > best.reservation_usd!)) best = r;+ }+ return best;}export interface PreflightEstimate {@@ -71,6 +129,8 @@ export interface PreflightEstimate {per_model_cost_usd: Record<string, number>;/** True when est_cost_usd > maxCostUsd (caller should refuse or prompt). */exceeds_cap: boolean;+ /** The priciest single call any role will reserve (separate from expected cost). */+ largest_reservation?: CallReservation;}export interface PreflightResult {@@ -79,6 +139,8 @@ export interface PreflightResult {proceed: boolean;/** Reason for abort, if proceed=false. */abort_reason?: string;+ /** Machine code for the abort: one call can never fit the cap, or the expected total exceeds it. */+ abort_code?: 'reservation_exceeds_cap' | 'cost_cap_exceeded';}export function estimateCost(opts: PreflightOpts): PreflightEstimate {@@ -105,15 +167,20 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {+ heldOutRollouts; // F11 held-out gate (baseline+candidate per accepted step)const reflect_calls = totalSteps * reflectsPerStep+ opts.epochs; // slow-update meta calls- const judge_calls = opts.selSize // baseline (1 per task; median-of-3 is in the rollout count already? — no, judge runs per rollout)+ const judgeModels = opts.judgeModels ?? [opts.judgeModel];+ const judgeCallsRaw = opts.selSize // baseline (1 per task; median-of-3 is in the rollout count already? — no, judge runs per rollout)+ opts.selSize * VALIDATION_RUNS_PER_TASK * totalSteps // per-step validation+ opts.testSize * 2 // final test judges (best + baseline)+ heldOutRollouts; // F11 held-out judges (1 per held-out rollout)+ const judge_calls = judgeModels.length > 0 ? judgeCallsRaw : 0;- // Cost per call type.+ // Cost per call type. Judge calls price at the priciest judge the run can reach.const targetPrice = lookupPrice(opts.targetModel);const optimizerPrice = lookupPrice(opts.optimizerModel);- const judgePrice = lookupPrice(opts.judgeModel);+ const judgePrice = judgeModels.map(lookupPrice).reduce(+ (a, b) => (b.input + b.output > a.input + a.output ? b : a),+ { input: 0, output: 0 },+ );const rolloutCost = rollout_calls * ((ROLLOUT_INPUT_TOKENS * targetPrice.input) / 1_000_000@@ -135,6 +202,7 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {const total = rolloutCost + cachedReflectCost + cachedJudgeCost;void sel_runs_per_step;+ const largest = largestReservation(opts);return {steps_per_epoch: stepsPerEpoch,@@ -152,6 +220,7 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {},// #3516: maxCostUsd === 0 means uncapped (--no-max-cost) — never refuse.exceeds_cap: opts.maxCostUsd > 0 && total > opts.maxCostUsd,+ ...(largest ? { largest_reservation: largest } : {}),};}@@ -167,6 +236,9 @@ export function formatPreflightReport(est: PreflightEstimate, opts: PreflightOpt` Judges: ${est.judge_calls.toLocaleString()} calls`,` Tokens: ~${(est.est_input_tokens / 1000).toFixed(0)}K in / ~${(est.est_output_tokens / 1000).toFixed(0)}K out`,` Est. cost: $${est.est_cost_usd.toFixed(2)} (cap: ${opts.maxCostUsd > 0 ? `$${opts.maxCostUsd.toFixed(2)}` : 'uncapped'})`,+ est.largest_reservation+ ? ` Per call: largest single call reserves $${est.largest_reservation.reservation_usd!.toFixed(2)} (${est.largest_reservation.role} ${est.largest_reservation.model}, ${est.largest_reservation.max_output_tokens} output tokens)`+ : '',est.exceeds_cap ? ` WARNING: estimate exceeds --max-cost-usd cap.` : '',].filter(Boolean).join('\n');}@@ -179,10 +251,20 @@ export function formatPreflightReport(est: PreflightEstimate, opts: PreflightOpt*/export function preflight(opts: PreflightOpts): PreflightResult {const estimate = estimateCost(opts);+ const big = estimate.largest_reservation;+ if (opts.maxCostUsd > 0 && big && big.reservation_usd! > opts.maxCostUsd) {+ return {+ estimate,+ proceed: false,+ abort_code: 'reservation_exceeds_cap',+ abort_reason: `reservation_exceeds_cap: a single ${big.role} call reserves $${big.reservation_usd!.toFixed(2)} (${big.model}, ${big.max_output_tokens} output tokens), which exceeds the $${opts.maxCostUsd.toFixed(2)} cap on its own, so it can never run. Fix: ${RESERVATION_CONTROL[big.role]}.`,+ };+ }if (estimate.exceeds_cap) {return {estimate,proceed: false,+ abort_code: 'cost_cap_exceeded',abort_reason: `estimated cost $${estimate.est_cost_usd.toFixed(2)} exceeds --max-cost-usd $${opts.maxCostUsd.toFixed(2)}. Raise the cap with --max-cost-usd ${Math.ceil(estimate.est_cost_usd)} or reduce --epochs/--batch-size.`,};}diff --git a/src/core/skillopt/reflect.ts b/src/core/skillopt/reflect.tsindex 1a48fb82c7..cc6cf6460c 100644--- a/src/core/skillopt/reflect.ts+++ b/src/core/skillopt/reflect.ts@@ -11,10 +11,25 @@** The reflect call also receives the rejected-edit buffer as anti-bias* context so the optimizer doesn't re-propose previously-failing edits.+ *+ * Fail loud (#5584): every reflect call yields edits, a deliberate empty+ * `{"edits": []}`, or EXACTLY ONE error, by precedence:+ * 1. stopReason 'length' -> reflect_<mode>_truncated (edits dropped)+ * 2. empty / whitespace reply -> reflect_<mode>_empty_reply+ * 3. no parseable edits array -> reflect_<mode>_no_parseable_edits+ * 4. every proposed edit invalid -> reflect_<mode>_invalid_edits+ * Partial drops push nothing and are counted in `invalidEditsDropped`.+ *+ * Context budgeting: the full skill body is sent when it fits the optimizer's+ * window (3 chars/token after the output cap and the bounded non-body+ * sections); otherwise it is truncated WITH an explicit disclosure in the+ * prompt and `skillBodyTruncated` on the result. Unknown window -> 120k chars.*/-import { chat as gatewayChat } from '../ai/gateway.ts';-import type { EditOp, ScoredRollout, Judge, RuleCheck } from './types.ts';+import { chat as gatewayChat, defaultMaxOutputTokens, type ChatResult } from '../ai/gateway.ts';+import { resolveChatContextTokens } from '../ai/model-resolver.ts';+import { isSkilloptMustAbort } from './must-abort.ts';+import { SKILLOPT_PURPOSE, type EditOp, type ScoredRollout, type Judge, type RuleCheck } from './types.ts';import type { RejectedEntry } from './rejected-buffer.ts';/**@@ -106,6 +121,8 @@ export interface ReflectOpts {*/criteria?: string;optimizerModel: string;+ /** Output cap for every optimizer call. Default `defaultMaxOutputTokens(optimizerModel)`. */+ maxTokens?: number;/*** Ablation (cat31 config B): 'failure-only' skips the D7 success-reflect call* entirely (even when successes are present). Default 'both' (paper-faithful).@@ -116,6 +133,11 @@ export interface ReflectOpts {abortSignal?: AbortSignal;}+export interface SkillBodyTruncation {+ sent_chars: number;+ total_chars: number;+}+export interface ReflectResult {/** Edits proposed from FAILURE analysis. */failureEdits: EditOp[];@@ -128,8 +150,28 @@ export interface ReflectResult {cache_read_tokens: number;cache_creation_tokens: number;};- /** Any per-call errors (for audit). */+ /** At most one error per reflect call (for audit + receipt). */errors: string[];+ /** Reflect calls attempted (a context_too_small refusal counts; it is a call that could not be made). */+ calls: number;+ /** Calls whose reply was usable: edits or a deliberate empty. */+ usableReplies: number;+ /** Malformed edits dropped from otherwise-usable replies. */+ invalidEditsDropped: number;+ /** Set when the skill body had to be truncated to fit the optimizer window. */+ skillBodyTruncated?: SkillBodyTruncation;+}++type ReflectAccumulator = Omit<ReflectResult, 'failureEdits' | 'successEdits'>;++const emptyUsage = (): ReflectResult['usage'] =>+ ({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 });++function addUsage(into: ReflectResult['usage'], from: ChatResult['usage']): void {+ into.input_tokens += from.input_tokens;+ into.output_tokens += from.output_tokens;+ into.cache_read_tokens += from.cache_read_tokens;+ into.cache_creation_tokens += from.cache_creation_tokens;}/**@@ -137,18 +179,17 @@ export interface ReflectResult {* their reflect call (no point asking for edits without data).*/export async function runReflect(opts: ReflectOpts): Promise<ReflectResult> {- const usage = { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 };- const errors: string[] = [];+ const acc: ReflectAccumulator = { usage: emptyUsage(), errors: [], calls: 0, usableReplies: 0, invalidEditsDropped: 0 };const failureEdits = opts.failures.length > 0- ? await callReflect('failure', opts, FAILURE_REFLECT_SYSTEM, opts.failures, usage, errors)+ ? await callReflect('failure', opts, FAILURE_REFLECT_SYSTEM, opts.failures, acc): [];// Ablation: 'failure-only' skips the success-reflect call regardless of data.const successEdits = opts.reflectMode !== 'failure-only' && opts.successes.length > 0- ? await callReflect('success', opts, SUCCESS_REFLECT_SYSTEM, opts.successes, usage, errors)+ ? await callReflect('success', opts, SUCCESS_REFLECT_SYSTEM, opts.successes, acc): [];- return { failureEdits, successEdits, usage, errors };+ return { failureEdits, successEdits, ...acc };}const ONE_SHOT_REWRITE_SYSTEM = `You are SkillOpt's optimizer in ONE-SHOT REWRITE mode. Given a SKILL document body and a batch of agent rollouts (some failing, some succeeding), rewrite the ENTIRE body ONCE to make the agent succeed more often.@@ -159,45 +200,65 @@ export interface OneShotRewriteResult {/** The rewritten skill body (frontmatter NOT included — caller re-attaches). */newBody: string;usage: ReflectResult['usage'];- /** Set when the rewrite call errored (caller treats as "no change"). */+ /** Set when the rewrite errored or was refused (caller treats as "no change" and surfaces it). */error?: string;}+/** Output headroom one-shot needs beyond the rewritten body itself. */+const ONE_SHOT_OUTPUT_SLACK_TOKENS = 1024;+/*** Ablation baseline (cat31 config C): a single LLM rewrite of the whole skill* body, no optimization loop and no validation gate. A real method (one-shot* prompt rewrite) — the honest "do you even need the loop?" comparison. Runs* through the SAME apply/score path as the loop (the orchestrator feeds the* returned body to the gate), so the comparison is apples-to-apples.+ *+ * Refuses (no chat call, nothing promoted) when the body cannot be sent whole+ * or its rewrite cannot fit the output cap; a length-stopped reply is never+ * returned as a body — it would be promoted as a shorter skill.*/export async function runOneShotRewrite(opts: ReflectOpts): Promise<OneShotRewriteResult> {- const usage = { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 };+ const usage = emptyUsage();const chat = opts.chatFn ?? gatewayChat;- const userMsg = buildReflectUserMessage(opts.skillBodyText, [...opts.failures, ...opts.successes], opts.rejected, opts.criteria);+ const maxTokens = opts.maxTokens ?? defaultMaxOutputTokens(opts.optimizerModel);+ const total = opts.skillBodyText.length;+ const plan = planReflectPrompt(opts, ONE_SHOT_REWRITE_SYSTEM, [...opts.failures, ...opts.successes], maxTokens);+ if (plan.kind !== 'ok' || plan.truncated) {+ const sent = plan.kind === 'ok' && plan.truncated ? plan.truncated.sent_chars : 0;+ return { newBody: '', usage, error: `one_shot_rewrite_body_truncated: sent ${sent} of ${total} chars` };+ }+ const need = Math.ceil(total / CHARS_PER_TOKEN) + ONE_SHOT_OUTPUT_SLACK_TOKENS;+ if (need > maxTokens) {+ return { newBody: '', usage, error: `one_shot_rewrite_output_cap_too_small: need ~${need} tokens, cap ${maxTokens}; set skillopt.reflect_max_tokens` };+ }+ let result: ChatResult;try {- const result = await chat({+ result = await chat({model: opts.optimizerModel,system: ONE_SHOT_REWRITE_SYSTEM,- messages: [{ role: 'user', content: userMsg }],- maxTokens: 4096,+ messages: [{ role: 'user', content: plan.userMsg }],+ maxTokens,cacheSystem: true,abortSignal: opts.abortSignal,+ purpose: SKILLOPT_PURPOSE.optimizer,});- usage.input_tokens += result.usage.input_tokens;- usage.output_tokens += result.usage.output_tokens;- usage.cache_read_tokens += result.usage.cache_read_tokens;- usage.cache_creation_tokens += result.usage.cache_creation_tokens;- // Unwrap a fence ONLY when the model wrapped the ENTIRE response in one- // (anchored ^```...```$). A non-anchored match would truncate a legitimate- // body that contains a code sample down to just that first fenced block.- const trimmed = result.text.trim();- const wholeFence = trimmed.match(/^```(?:markdown)?\s*\n([\s\S]*)\n```$/i);- const newBody = (wholeFence ? wholeFence[1]! : trimmed).trim();- return { newBody, usage };} catch (err) {- const msg = err instanceof Error ? err.message : String(err);- return { newBody: '', usage, error: `one_shot_rewrite_failed: ${msg}` };+ if (isSkilloptMustAbort(err)) throw err;+ return { newBody: '', usage, error: `one_shot_rewrite_failed: ${errMsg(err)}` };}+ addUsage(usage, result.usage);+ if (result.stopReason === 'length') {+ return { newBody: '', usage, error: `one_shot_rewrite_truncated: ${result.usage.output_tokens} output tokens, max_tokens=${maxTokens}` };+ }+ // Unwrap a fence ONLY when the model wrapped the ENTIRE response in one+ // (anchored ^```...```$). A non-anchored match would truncate a legitimate+ // body that contains a code sample down to just that first fenced block.+ const trimmed = result.text.trim();+ const wholeFence = trimmed.match(/^```(?:markdown)?\s*\n([\s\S]*)\n```$/i);+ const newBody = (wholeFence ? wholeFence[1]! : trimmed).trim();+ if (!newBody) return { newBody: '', usage, error: `one_shot_rewrite_empty_reply: stop=${result.stopReason}` };+ return { newBody, usage };}async function callReflect(@@ -205,30 +266,114 @@ async function callReflect(opts: ReflectOpts,system: string,scoredRollouts: ScoredRollout[],- cumUsage: ReflectResult['usage'],- errors: string[],+ acc: ReflectAccumulator,): Promise<EditOp[]> {const chat = opts.chatFn ?? gatewayChat;- const userMsg = buildReflectUserMessage(opts.skillBodyText, scoredRollouts, opts.rejected, opts.criteria);+ const maxTokens = opts.maxTokens ?? defaultMaxOutputTokens(opts.optimizerModel);+ acc.calls += 1;+ const plan = planReflectPrompt(opts, system, scoredRollouts, maxTokens);+ if (plan.kind === 'too_small') {+ acc.errors.push(`reflect_${mode}_context_too_small: need ${plan.need}, window ${plan.window}`);+ return [];+ }+ if (plan.truncated) acc.skillBodyTruncated = plan.truncated;+ let result: ChatResult;try {- const result = await chat({+ result = await chat({model: opts.optimizerModel,system,- messages: [{ role: 'user', content: userMsg }],- maxTokens: 2048,+ messages: [{ role: 'user', content: plan.userMsg }],+ maxTokens,cacheSystem: true, // D11abortSignal: opts.abortSignal,+ purpose: SKILLOPT_PURPOSE.optimizer,});- cumUsage.input_tokens += result.usage.input_tokens;- cumUsage.output_tokens += result.usage.output_tokens;- cumUsage.cache_read_tokens += result.usage.cache_read_tokens;- cumUsage.cache_creation_tokens += result.usage.cache_creation_tokens;- return parseEditsResponse(result.text);} catch (err) {- const msg = err instanceof Error ? err.message : String(err);- errors.push(`reflect_${mode}_failed: ${msg}`);+ if (isSkilloptMustAbort(err)) throw err;+ const kind = isContextOverflowError(err) ? 'context_overflow' : 'failed';+ acc.errors.push(`reflect_${mode}_${kind}: ${errMsg(err)}`);+ return [];+ }+ addUsage(acc.usage, result.usage);+ const classified = classifyEditsReply(result, maxTokens);+ if ('error' in classified) {+ acc.errors.push(`reflect_${mode}_${classified.error}`);return [];}+ acc.usableReplies += 1;+ acc.invalidEditsDropped += classified.dropped;+ return classified.edits;+}++function classifyEditsReply(+ result: Pick<ChatResult, 'text' | 'stopReason' | 'usage'>,+ maxTokens: number,+): { edits: EditOp[]; dropped: number } | { error: string } {+ const outTokens = result.usage.output_tokens;+ if (result.stopReason === 'length') return { error: `truncated: ${outTokens} output tokens, max_tokens=${maxTokens}` };+ if (!result.text.trim()) return { error: `empty_reply: stop=${result.stopReason}` };+ const raw = extractEditsArray(result.text);+ if (raw === null) return { error: `no_parseable_edits: ${outTokens} output tokens, stop=${result.stopReason}` };+ const edits = validateEdits(raw);+ if (raw.length > 0 && edits.length === 0) return { error: `invalid_edits: ${raw.length} proposed, 0 valid` };+ return { edits, dropped: raw.length - edits.length };+}++const errMsg = (e: unknown): string => (e instanceof Error ? e.message : String(e));++/** Provider context-length rejections (Anthropic "prompt is too long", OpenAI context_length_exceeded), through wrapped causes. */+function isContextOverflowError(err: unknown): boolean {+ let cur: unknown = err;+ for (let depth = 0; depth < 3 && cur != null; depth++) {+ const msgs = [(cur as { message?: unknown }).message, (cur as { error?: { message?: unknown } }).error?.message];+ if (msgs.some((m) => typeof m === 'string' && /prompt is too long|context[_ ]length|maximum context|context window/i.test(m))) return true;+ cur = (cur as { cause?: unknown }).cause;+ }+ return false;+}++/** Body budget when the optimizer's context window is unknown. */+const UNKNOWN_CONTEXT_BODY_CHARS = 120_000;+/** Conservative chars-per-token for budgeting the prompt against the window. */+const CHARS_PER_TOKEN = 3;+const MAX_ROLLOUT_OUTPUT_CHARS = 2000;+const MAX_REJECTED_CHARS = 8000;+const MAX_CRITERIA_CHARS = 8000;++type PromptPlan =+ | { kind: 'ok'; userMsg: string; truncated?: SkillBodyTruncation }+ | { kind: 'too_small'; need: number; window: number };++function optimizerContextTokens(model: string): number | undefined {+ try {+ return resolveChatContextTokens(model);+ } catch {+ return undefined;+ }+}++function planReflectPrompt(+ opts: ReflectOpts,+ system: string,+ rollouts: ScoredRollout[],+ outputCap: number,+): PromptPlan {+ const body = opts.skillBodyText;+ const build = (b: string) => buildReflectUserMessage(b, rollouts, opts.rejected, opts.criteria);+ const window = optimizerContextTokens(opts.optimizerModel);+ let budgetChars = UNKNOWN_CONTEXT_BODY_CHARS;+ if (window !== undefined) {+ const need = Math.ceil((system.length + build('').length) / CHARS_PER_TOKEN) + outputCap;+ if (need > window) return { kind: 'too_small', need, window };+ budgetChars = (window - need) * CHARS_PER_TOKEN;+ }+ if (body.length <= budgetChars) return { kind: 'ok', userMsg: build(body) };+ const sent = body.slice(0, budgetChars);+ return {+ kind: 'ok',+ userMsg: build(`${sent}\n(skill body truncated: sent ${sent.length} of ${body.length} chars)`),+ truncated: { sent_chars: sent.length, total_chars: body.length },+ };}function buildReflectUserMessage(@@ -246,20 +391,20 @@ TASK: ${r.trajectory.task}TOOL CALLS:${tcSummary || ' (none)'}OUTPUT:-${truncate(r.trajectory.final_text, 2000)}+${truncate(r.trajectory.final_text, MAX_ROLLOUT_OUTPUT_CHARS)}${r.rationale ? `JUDGE RATIONALE: ${r.rationale}` : ''}`;}).join('\n\n');const rejectedSummary = rejected.length > 0- ? `\n\n--- PREVIOUSLY REJECTED EDITS (do not re-propose) ---\n${rejected.slice(0, 20).map((r) => `- ${r.reason}: ${JSON.stringify(r.edits)}`).join('\n')}`+ ? `\n\n--- PREVIOUSLY REJECTED EDITS (do not re-propose) ---\n${truncate(rejected.slice(0, 20).map((r) => `- ${r.reason}: ${JSON.stringify(r.edits)}`).join('\n'), MAX_REJECTED_CHARS)}`: '';const criteriaBlock = criteria- ? `\n\nSUCCESS CRITERIA (exactly how the agent's output is scored — make the agent satisfy these through genuine, high-quality content, never empty keywords):\n${criteria}`+ ? `\n\nSUCCESS CRITERIA (exactly how the agent's output is scored — make the agent satisfy these through genuine, high-quality content, never empty keywords):\n${truncate(criteria, MAX_CRITERIA_CHARS)}`: '';return `CURRENT SKILL BODY:-${truncate(skillBody, 5000)}${criteriaBlock}+${skillBody}${criteriaBlock}OBSERVED ROLLOUTS:${trajectoryBlocks}${rejectedSummary}@@ -274,8 +419,8 @@ function truncate(s: string, max: number): string {/*** Parse `{edits: [...]}` from optimizer output. Tolerates ```fenced blocks```,* trailing commas, prose-wrapped JSON. Returns [] when no recoverable edits- * are found (caller treats as "this reflect call produced no usable edits"- * — same effect as the optimizer returning {edits: []}).+ * are found. `callReflect` classifies the same extraction (a fenced+ * `{"edits": []}` is a deliberate empty, not a parse failure).** EXPORTED so reflect.test.ts can pin the parser independently of the chat* transport. Pre-v0.42.0.1 this lived behind a `parseJudgeJson` early-return@@ -285,10 +430,11 @@ function truncate(s: string, max: number): string {* `successes/failures: []` hardcoding masked it end-to-end too.*/export function parseEditsResponse(raw: string): EditOp[] {- return tryExtractEdits(raw);+ return validateEdits(extractEditsArray(raw) ?? []);}-function tryExtractEdits(raw: string): EditOp[] {+/** The raw `edits` array from optimizer output, or null when none is recoverable. */+function extractEditsArray(raw: string): unknown[] | null {try {// Strip fences first.const fenced = raw.match(/```(?:json)?\s*\n?([\s\S]*?)```/i);@@ -296,19 +442,19 @@ function tryExtractEdits(raw: string): EditOp[] {// Try direct parse.const direct = JSON.parse(cleaned);if (direct && typeof direct === 'object' && Array.isArray((direct as { edits?: unknown }).edits)) {- return validateEdits((direct as { edits: unknown[] }).edits);+ return (direct as { edits: unknown[] }).edits;}} catch { /* try next strategy */ }// Fallback: extract first {...} substring.const match = raw.match(/\{[\s\S]*\}/);- if (!match) return [];+ if (!match) return null;try {const parsed = JSON.parse(match[0]);if (parsed && typeof parsed === 'object' && Array.isArray((parsed as { edits?: unknown }).edits)) {- return validateEdits((parsed as { edits: unknown[] }).edits);+ return (parsed as { edits: unknown[] }).edits;}} catch { /* fall through */ }- return [];+ return null;}function validateEdits(raw: unknown[]): EditOp[] {diff --git a/src/core/skillopt/remediation.ts b/src/core/skillopt/remediation.tsnew file mode 100644index 0000000000..6cfa41bb00--- /dev/null+++ b/src/core/skillopt/remediation.ts@@ -0,0 +1,79 @@+/**+ * SkillOpt error codes -> remediation.+ *+ * Every optimizer-reply error string starts with a machine code+ * (`reflect_failure_truncated: ...`, `one_shot_rewrite_output_cap_too_small: ...`).+ * Reflect codes are normalized mode-agnostically (`reflect_truncated`), so one+ * remediation entry + one docs anchor covers both reflect calls. The receipt+ * carries one `{code, fix, docs}` entry per distinct code across+ * `reflect_errors`, `abort_detail` and the abort reason.+ */++export interface RemediationEntry {+ code: string;+ fix: string;+ docs: string;+}++const DOCS_PATH = 'docs/guides/skillopt.md';++const RAISE_CAP = 'The optimizer ran out of output tokens. Raise the cap: --reflect-max-tokens <n> or gbrain config set skillopt.reflect_max_tokens <n>.';+const CONTRACT = 'The optimizer is not following the edits JSON contract. Try a different --optimizer-model.';+const PROVIDER = 'The optimizer provider call failed. Check the provider (gbrain models doctor), then resume the run.';+const CONTEXT = 'The optimizer context window cannot hold the prompt plus the output cap. Lower --reflect-max-tokens / skillopt.reflect_max_tokens, or use an --optimizer-model with a larger context window.';++const FIXES: Readonly<Record<string, string>> = {+ reflect_truncated: RAISE_CAP,+ reflect_empty_reply: CONTRACT,+ reflect_no_parseable_edits: CONTRACT,+ reflect_invalid_edits: CONTRACT,+ reflect_context_too_small: CONTEXT,+ reflect_context_overflow: CONTEXT,+ reflect_failed: PROVIDER,+ one_shot_rewrite_truncated: RAISE_CAP,+ one_shot_rewrite_output_cap_too_small: 'Raise --reflect-max-tokens / skillopt.reflect_max_tokens, or use the default reflect mode.',+ one_shot_rewrite_body_truncated: 'The skill body does not fit the optimizer context. Lower --reflect-max-tokens / skillopt.reflect_max_tokens (the output cap shares the window), use a larger-context --optimizer-model, or use the default reflect mode.',+ one_shot_rewrite_empty_reply: CONTRACT,+ one_shot_rewrite_failed: PROVIDER,+ budget_exhausted: 'Raise --max-cost-usd (cycle runs: gbrain config set cycle.skillopt.per_skill_cap_usd <usd>). Each optimizer call reserves its full output cap, so lowering --reflect-max-tokens / skillopt.reflect_max_tokens also helps.',+ runtime_exceeded: 'Raise --max-runtime-min, then resume the run.',+ reservation_exceeds_cap: 'One call alone reserves more than the cost cap, so no model call was made. Lower --reflect-max-tokens / skillopt.reflect_max_tokens, pick a cheaper model, or raise --max-cost-usd (cycle runs: gbrain config set cycle.skillopt.per_skill_cap_usd <usd>).',+};++/** Every code that can appear in `remediation[].code` (docs table pins this). */+export const SKILLOPT_REMEDIATION_CODES: readonly string[] = Object.keys(FIXES);++export const OPTIMIZER_OUTPUT_UNUSABLE = 'optimizer_output_unusable';++/** Normalized code of an error string, or undefined when it carries none we map. */+export function errorCode(message: string): string | undefined {+ let head = message.trim();+ if (head.startsWith(`${OPTIMIZER_OUTPUT_UNUSABLE}:`)) head = head.slice(OPTIMIZER_OUTPUT_UNUSABLE.length + 1).trim();+ const raw = head.split(':', 1)[0]!.trim();+ const reflect = raw.match(/^reflect_(?:failure|success)_(.+)$/);+ const code = reflect ? `reflect_${reflect[1]}` : raw;+ return Object.hasOwn(FIXES, code) ? code : undefined;+}++export function buildRemediation(+ messages: readonly string[],+ abortReason?: string,+): RemediationEntry[] {+ const codes = new Set<string>();+ for (const m of messages) {+ const c = errorCode(m);+ if (c) codes.add(c);+ }+ if (abortReason === 'budget_exhausted' || abortReason === 'runtime_exceeded') codes.add(abortReason);+ return [...codes].map((code) => ({ code, fix: FIXES[code]!, docs: `${DOCS_PATH}#${code}` }));+}++const MAX_RECORDED_ERRORS = 20;+const MAX_ERROR_CHARS = 300;++/** Append to a receipt error list: deduped, at most 20 entries of 300 chars. */+export function recordReflectError(list: string[], message: string): void {+ const clipped = message.length > MAX_ERROR_CHARS ? message.slice(0, MAX_ERROR_CHARS) : message;+ if (list.length >= MAX_RECORDED_ERRORS || list.includes(clipped)) return;+ list.push(clipped);+}diff --git a/src/core/skillopt/rollout.ts b/src/core/skillopt/rollout.tsindex 8f8fe2587e..cf7e0d1069 100644--- a/src/core/skillopt/rollout.ts+++ b/src/core/skillopt/rollout.ts@@ -22,7 +22,7 @@ import { paramDefToSchema } from '../../mcp/tool-defs.ts';import { operations, type OperationContext } from '../operations.ts';import { loadConfig } from '../config.ts';import type { BrainEngine } from '../engine.ts';-import type { BenchmarkTask, Trajectory } from './types.ts';+import { SKILLOPT_PURPOSE, type BenchmarkTask, type Trajectory } from './types.ts';import { sharedSkillToolAccess } from '../shared-skills/tool-access.ts';import { authorizeSkillRead } from '../shared-skills/policy.ts';@@ -110,6 +110,7 @@ export async function runRollout(opts: RolloutOpts): Promise<Trajectory> {maxTurns: opts.maxTurns ?? 20,cacheSystem: true, // D11: candidate skill is stable for a step's batch.abortSignal: opts.abortSignal,+ purpose: SKILLOPT_PURPOSE.target,onToolCallStart: async (_turnIdx, _messageIdx, _ordinal, toolName, input, providerToolCallId) => {const gbrainToolUseId = `skillopt-${nextOrdinal++}-${providerToolCallId}`;const idx = toolCalls.length;diff --git a/src/core/skillopt/run-outcome.ts b/src/core/skillopt/run-outcome.tsnew file mode 100644index 0000000000..bc4119e303--- /dev/null+++ b/src/core/skillopt/run-outcome.ts@@ -0,0 +1,148 @@+/**+ * SkillOpt truthful outcome (#5584).+ *+ * caught abort/error ............................ aborted | errored (stop_reason 'aborted')+ * any candidate accepted ........................ accepted (even after an early stop)+ * optimizer called, never a usable reply ........ errored, abort_detail 'optimizer_output_unusable: <first error>'+ * otherwise ..................................... no_improvement+ *+ * A step is "fully unusable" when it made optimizer calls and every one+ * errored (any class). After EARLY_STOP_UNUSABLE_STEPS consecutive fully+ * unusable steps the loop stops instead of spending the remaining budget.+ */++import type { ReflectTally, RunSpec } from './checkpoint.ts';+import type { ReflectResult } from './reflect.ts';+import { errorCode, OPTIMIZER_OUTPUT_UNUSABLE, recordReflectError } from './remediation.ts';+import type { RunReceipt } from './types.ts';++export const EARLY_STOP_UNUSABLE_STEPS = 2;++export type RunOutcome = NonNullable<RunReceipt['outcome']>;+export type StopReason = NonNullable<RunReceipt['stop_reason']>;++/** Fold one step's optimizer calls into the tally; returns true when the step was fully unusable. */+export function recordOptimizerStep(+ tally: ReflectTally,+ step: Pick<ReflectResult, 'calls' | 'usableReplies' | 'errors' | 'invalidEditsDropped'>,+): boolean {+ tally.reflect_calls += step.calls;+ tally.usable_replies += step.usableReplies;+ tally.invalid_edits_dropped += step.invalidEditsDropped;+ for (const e of step.errors) recordReflectError(tally.reflect_errors, e);+ const fullyUnusable = step.calls > 0 && step.usableReplies === 0;+ if (fullyUnusable) tally.unusable_streak += 1;+ else if (step.usableReplies > 0) tally.unusable_streak = 0;+ return fullyUnusable;+}++export function shouldEarlyStop(tally: ReflectTally): boolean {+ return tally.unusable_streak >= EARLY_STOP_UNUSABLE_STEPS;+}++export interface ResolvedOutcome {+ outcome: RunOutcome;+ stopReason: StopReason;+ abortReason?: NonNullable<RunReceipt['abort_reason']>;+ abortDetail?: string;+}++export function resolveRunOutcome(input: {+ caught?: { outcome: 'aborted' | 'errored'; abortReason: NonNullable<RunReceipt['abort_reason']>; abortDetail: string };+ tally: ReflectTally;+ earlyStopped: boolean;+}): ResolvedOutcome {+ const { caught, tally } = input;+ if (caught) {+ return { outcome: caught.outcome, stopReason: 'aborted', abortReason: caught.abortReason, abortDetail: caught.abortDetail };+ }+ const stopReason: StopReason = input.earlyStopped ? 'early_stop_unusable_output' : 'completed';+ if (tally.accepted_steps > 0) return { outcome: 'accepted', stopReason };+ if (tally.reflect_calls > 0 && tally.usable_replies === 0) {+ return {+ outcome: 'errored',+ stopReason,+ abortReason: 'error',+ abortDetail: `${OPTIMIZER_OUTPUT_UNUSABLE}: ${tally.reflect_errors[0] ?? 'no usable optimizer reply'}`,+ };+ }+ return { outcome: 'no_improvement', stopReason };+}++/** Human class label for the early-stop line (distinct codes, e.g. `reflect_truncated`). */+export function unusableClasses(tally: ReflectTally): string {+ const codes = [...new Set(tally.reflect_errors.map((e) => errorCode(e) ?? e.split(':', 1)[0]!))];+ return codes.join(', ') || 'unusable optimizer output';+}++const CONTROL_CHARS = /[\u0000-\u001f\u007f]/g;++function shellArg(v: string | number): string {+ const s = String(v).replace(CONTROL_CHARS, '');+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;+}++/** Output-cap failures: resuming with a doubled reflect cap is the fix. */+const CAP_TOO_SMALL_CODES: ReadonlySet<string> = new Set([+ 'reflect_truncated',+ 'one_shot_rewrite_truncated',+ 'one_shot_rewrite_output_cap_too_small',+]);++/** Run-level flags that are not part of the resume-compatibility spec. */+export interface ResumeRunFlags {+ mode: 'patch' | 'rewrite';+ /** 0 = uncapped (`--no-max-cost`). */+ maxCostUsd: number;+ maxRuntimeMin: number;+ /** The run used --force, or it accepted a candidate that left SKILL.md dirty. */+ force?: boolean;+ modelsStrict?: boolean;+}++/**+ * The exact command that resumes this run, rebuilt from the stored spec plus+ * the run's mode and cost/runtime caps. An output-cap failure doubles the+ * reflect cap; an edits-contract failure replaces the optimizer with an+ * `<other-model>` placeholder to fill in.+ */+export function buildResumeCommand(+ skill: string,+ runId: string,+ spec: RunSpec,+ failureCode?: string,+ run?: ResumeRunFlags,+): string {+ const cap = failureCode !== undefined && CAP_TOO_SMALL_CODES.has(failureCode) ? spec.reflect_max_tokens * 2 : spec.reflect_max_tokens;+ const contract = failureCode !== undefined && /(_empty_reply|_no_parseable_edits|_invalid_edits)$/.test(failureCode);+ const args: Array<string | number> = [+ 'gbrain', 'skillopt', skill, '--resume', runId,+ '--skills-dir', spec.skills_dir,+ '--benchmark', spec.benchmark_path,+ '--split', spec.split.join(':'),+ '--epochs', spec.epochs,+ '--batch-size', spec.batch_size,+ '--lr', spec.lr,+ '--lr-schedule', spec.lr_schedule,+ '--optimizer-model', spec.optimizer_model,+ '--target-model', spec.target_model,+ '--judge-model', spec.judge_model,+ '--reflect-max-tokens', cap,+ ];+ if (spec.held_out_path) args.push('--held-out', spec.held_out_path);+ if (spec.no_mutate) args.push('--no-mutate');+ if (spec.allow_mutate_bundled) args.push('--allow-mutate-bundled');+ if (spec.bootstrap_reviewed) args.push('--bootstrap-reviewed');+ if (run) {+ if (run.mode === 'rewrite') args.push('--rewrite');+ if (run.maxCostUsd > 0) args.push('--max-cost-usd', run.maxCostUsd);+ else args.push('--no-max-cost');+ args.push('--max-runtime-min', run.maxRuntimeMin);+ if (run.force) args.push('--force');+ if (run.modelsStrict) args.push('--models-strict');+ }+ const rendered = args.map(shellArg);+ // Quoted: a bare `<other-model>` would be read by the shell as a redirection.+ if (contract) rendered[rendered.indexOf('--optimizer-model') + 1] = `'<other-model>'`;+ return rendered.join(' ');+}diff --git a/src/core/skillopt/score.ts b/src/core/skillopt/score.tsindex a567c4f165..a5d8143719 100644--- a/src/core/skillopt/score.ts+++ b/src/core/skillopt/score.ts@@ -9,7 +9,10 @@* `judge: llm` uses gateway.chat with the v0.40+ 4-strategy JSON repair* (parseModelJSON from cross-modal-eval). On parse failure the scorer* returns score=0 (pessimistic fallback) AND records the error string on- * `ScoredRollout.judge_error` so the audit trail can surface it.+ * `ScoredRollout.judge_error` so the audit trail can surface it+ * (`llm_truncated` when the reply hit the output cap). Budget / runtime /+ * SIGINT aborts are rethrown, never scored 0. Thinking judges get+ * `skilloptOutputCap` headroom over the 200-token site cap.** `judge: qrels` reuses src/core/search/eval.ts IR metrics. Score is* nDCG@k (more discriminating than P@k for the optimization signal).@@ -17,7 +20,9 @@import { chat as gatewayChat } from '../ai/gateway.ts';import { ndcgAtK } from '../search/eval.ts';-import type { Judge, RuleCheck, ScoredRollout, Trajectory } from './types.ts';+import { isSkilloptMustAbort } from './must-abort.ts';+import { skilloptOutputCap } from './output-cap.ts';+import { SKILLOPT_PURPOSE, type Judge, type RuleCheck, type ScoredRollout, type Trajectory } from './types.ts';/** Score a trajectory against a judge. Returns a ScoredRollout. */export async function scoreTrajectory(@@ -154,6 +159,8 @@ function tryJsonParse(s: string): unknown | null {try { return JSON.parse(s); } catch { return null; }}+export const JUDGE_SITE_MAX_TOKENS = 200;+async function scoreLlm(trajectory: Trajectory,rubric: string,@@ -167,12 +174,13 @@ async function scoreLlm(model: judgeModel,system: LLM_JUDGE_SYSTEM,messages: [{ role: 'user', content: userMsg }],- maxTokens: 200,+ maxTokens: skilloptOutputCap(judgeModel, JUDGE_SITE_MAX_TOKENS),cacheSystem: true, // D11: judge system prompt is stable across calls.+ purpose: SKILLOPT_PURPOSE.judge,});const parsed = parseJudgeJson(result.text);if (!parsed) {- return { trajectory, score: 0, judge_error: 'llm_parse_failed' };+ return { trajectory, score: 0, judge_error: result.stopReason === 'length' ? 'llm_truncated' : 'llm_parse_failed' };}if (!('score' in parsed)) {return { trajectory, score: 0, judge_error: 'llm_parse_no_score_field' };@@ -189,6 +197,7 @@ async function scoreLlm(? { trajectory, score, rationale }: { trajectory, score };} catch (err) {+ if (isSkilloptMustAbort(err)) throw err;const msg = err instanceof Error ? err.message : String(err);// Pessimistic fallback (D12 paper-faithful: judge failure = score 0,// not throw; the median-of-3 + epsilon gate handles a single errordiff --git a/src/core/skillopt/types.ts b/src/core/skillopt/types.tsindex 2a222f75e7..43ee4b10e5 100644--- a/src/core/skillopt/types.ts+++ b/src/core/skillopt/types.ts@@ -15,6 +15,8 @@import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';import type { ToolLoopStopReason } from '../ai/gateway.ts';+import type { ModelUsageRow } from '../budget/models-used.ts';+import type { ModelsPlanEntry, SkillOptModels, StrictVerdict } from './models-plan.ts';// ─── Benchmarks + judges ──────────────────────────────────────────────────@@ -154,6 +156,24 @@ export interface SkillOptOpts {optimizerModel: string;targetModel: string;judgeModel: string;+ /**+ * Explicit optimizer output cap (`--reflect-max-tokens`, MCP / job+ * `reflect_max_tokens`). Beats `skillopt.reflect_max_tokens` config, which+ * beats `defaultMaxOutputTokens(optimizerModel)`; resolved once per run.+ */+ reflectMaxTokens?: number;+ /**+ * #5585: provenance of the three role models (from resolveSkillOptModels).+ * Absent -> every role reports source `unknown` (fail-closed under strict).+ */+ models?: SkillOptModels;+ /** #5585: `--models-strict`; OR'ed with the `skillopt.models_strict` config. */+ modelsStrict?: boolean;+ /**+ * #5585: invocation banner already printed by a batch / cycle caller; the+ * run prints only the plan rows that differ from it.+ */+ modelsBannerBaseline?: ModelsPlanEntry[];// Modes.mode: 'patch' | 'rewrite';@@ -230,6 +250,31 @@ export interface RunReceipt {// reason + the underlying error message, mirrored from the audit trail.abort_reason?: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error';abort_detail?: string;+ /** #5584: why the loop stopped. */+ stop_reason?: 'completed' | 'early_stop_unusable_output' | 'aborted';+ /** #5584: optimizer-reply errors (reflect + one-shot), deduped, max 20 x 300 chars. */+ reflect_errors?: string[];+ /** #5584: malformed edits dropped from otherwise-usable optimizer replies. */+ reflect_invalid_edits_dropped?: number;+ /** #5584: set when the skill body had to be truncated to fit the optimizer window. */+ skill_body_truncated?: { sent_chars: number; total_chars: number };+ /** #5584: one entry per distinct error code in reflect_errors / abort_detail. */+ remediation?: Array<{ code: string; fix: string; docs: string }>;+ /** #5584: effective optimizer output cap and where it came from. */+ reflect_max_tokens?: number;+ reflect_max_tokens_source?: 'flag' | 'config' | 'default';+ /** #5584: exact command that resumes this run (present when the checkpoint is retained). */+ resume_command?: string;+ /** #5585: every model the run called, one row per (requested, served, touchpoint, purpose). */+ models_used?: ModelUsageRow[];+ /** #5585: `since_resume` when an earlier segment's checkpoint predates ledger persistence. */+ models_used_scope?: 'full_run' | 'since_resume';+ /** #5585: spend banked by earlier segments of a resumed run; `final_cost_usd` is this segment. */+ prior_segments_cost_usd?: number;+ /** #5585: every touchpoint the run can call, with the source that chose its model. */+ models_plan?: ModelsPlanEntry[];+ /** #5585: strict-mode verdict over `models_plan` (computed even when strict mode is off). */+ models_strict?: StrictVerdict;// Ablation provenance (cat31 replayability) — present when a non-default// ablation knob was set.reflect_mode?: 'both' | 'failure-only';@@ -261,6 +306,13 @@ export const VALIDATION_RUNS_PER_TASK = 3;*/export const ROLLOUT_SUCCESS_THRESHOLD = 0.5;+/** #5585: `purpose` stamped on skillopt's gateway calls, one BudgetTracker ledger row per role. */+export const SKILLOPT_PURPOSE = {+ optimizer: 'skillopt.optimizer',+ target: 'skillopt.target',+ judge: 'skillopt.judge',+} as const;+export interface GateInput {candidateSkillText: string;selSet: BenchmarkTask[];diff --git a/src/core/skillopt/validate-gate.ts b/src/core/skillopt/validate-gate.tsindex b97fff4e31..af61250432 100644--- a/src/core/skillopt/validate-gate.ts+++ b/src/core/skillopt/validate-gate.ts@@ -20,7 +20,8 @@* which is cached (D11), so the effective cost ~1.3x not 3x.*/-import { runWithLimit, isMustAbortError } from '../worker-pool.ts';+import { runWithLimit } from '../worker-pool.ts';+import { isSkilloptMustAbort, SKILLOPT_RUNTIME_EXCEEDED } from './must-abort.ts';import { runRollout, type RolloutOpts } from './rollout.ts';import { scoreTrajectory } from './score.ts';import type { BenchmarkTask, GateInput, GateResult, ScoredRollout } from './types.ts';@@ -58,8 +59,7 @@ export interface ValidateGateOpts extends Omit<GateInput, 'selSet'> {scoreFn?: typeof scoreTrajectory;}-/** #4119 — the runtime-deadline breach error, shared with the orchestrator. */-export const SKILLOPT_RUNTIME_EXCEEDED = 'skillopt_runtime_exceeded';+export { SKILLOPT_RUNTIME_EXCEEDED };function isRuntimeExceeded(e: unknown): boolean {return e instanceof Error && e.message === SKILLOPT_RUNTIME_EXCEEDED;}@@ -124,7 +124,7 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRessignal: opts.abortSignal,});- // MUST-ABORT errors (budget exhaustion / no-pricing) are NOT scoring noise —+ // MUST-ABORT errors (budget exhaustion / no-pricing / spend-policy refusals) are NOT scoring noise —// swallowing them as score=0 turns a pricing/cap crash into a fake "0/N" run// (the bug the SkillOpt eval surfaced: a Haiku run with --max-cost hit// no_pricing on every rollout and the whole gate reported a vacuous 0). Surface@@ -132,7 +132,7 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRes// #4119: a deadline breach is not scoring noise either — it must surface as// the orchestrator's runtime-exceeded abort, never a fake 0-score task.const aborter = settled.find(- (s) => s && !s.ok && (isMustAbortError(s.error) || isRuntimeExceeded(s.error)),+ (s) => s && !s.ok && (isSkilloptMustAbort(s.error) || isRuntimeExceeded(s.error)),);if (aborter && !aborter.ok) throw aborter.error;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 32583b466d..0c5be0619f 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.59.0.0 -->+<!-- gbrain-template-stamp: 0.59.2.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/ai/anthropic-model-ids.test.ts b/test/ai/anthropic-model-ids.test.tsnew file mode 100644index 0000000000..d3c00f139e--- /dev/null+++ b/test/ai/anthropic-model-ids.test.ts@@ -0,0 +1,76 @@+import { describe, test, expect } from 'bun:test';+import {+ compareAnthropicVersions,+ newerAnthropicModel,+ parseAnthropicModelId,+} from '../../src/core/ai/anthropic-model-ids.ts';++describe('parseAnthropicModelId', () => {+ test('parses family, major, minor and the 8-digit date segment', () => {+ expect(parseAnthropicModelId('anthropic:claude-haiku-4-5-20251001')).toEqual({+ id: 'claude-haiku-4-5-20251001', family: 'haiku', major: 4, minor: 5, date: '20251001',+ });+ expect(parseAnthropicModelId('claude-sonnet-5')).toEqual({ id: 'claude-sonnet-5', family: 'sonnet', major: 5, minor: 0 });+ expect(parseAnthropicModelId('anthropic/claude-opus-4-7')).toEqual({ id: 'claude-opus-4-7', family: 'opus', major: 4, minor: 7 });+ });++ test('an 8-digit segment after the major is a date, not a minor', () => {+ expect(parseAnthropicModelId('claude-sonnet-5-20260101')).toEqual({+ id: 'claude-sonnet-5-20260101', family: 'sonnet', major: 5, minor: 0, date: '20260101',+ });+ });++ test('fable, non-Anthropic providers and unknown shapes parse to null', () => {+ for (const id of [+ 'anthropic:claude-fable-5-1',+ 'openrouter:anthropic/claude-sonnet-4-6',+ 'openai:gpt-5.6',+ 'claude-3-5-sonnet-20241022',+ 'claude-sonnet-latest',+ 'claude-sonnet-4-6-extra',+ '',+ ]) {+ expect(parseAnthropicModelId(id)).toBeNull();+ }+ });+});++describe('compareAnthropicVersions', () => {+ test('orders by major then minor and ignores snapshot dates', () => {+ const p = (id: string) => parseAnthropicModelId(id)!;+ expect(compareAnthropicVersions(p('claude-sonnet-5'), p('claude-sonnet-4-6'))).toBeGreaterThan(0);+ expect(compareAnthropicVersions(p('claude-opus-4-7'), p('claude-opus-4-8'))).toBeLessThan(0);+ expect(compareAnthropicVersions(p('claude-haiku-4-5'), p('claude-haiku-4-5-20251001'))).toBe(0);+ });+});++describe('newerAnthropicModel', () => {+ test('returns the newest priced same-family recipe id when the model is older', () => {+ expect(newerAnthropicModel('anthropic:claude-sonnet-4-6')?.id).toBe('claude-sonnet-5');+ expect(newerAnthropicModel('anthropic:claude-opus-4-7')?.id).toBe('claude-opus-5');+ });++ test('dated and undated forms of the current version get no hint', () => {+ expect(newerAnthropicModel('claude-haiku-4-5')).toBeNull();+ expect(newerAnthropicModel('anthropic:claude-haiku-4-5-20251001')).toBeNull();+ });++ test('current, newer-than-recipe, fable, non-Anthropic and unparseable ids get none', () => {+ for (const id of [+ 'anthropic:claude-sonnet-5',+ 'anthropic:claude-sonnet-6',+ 'anthropic:claude-opus-5-2',+ 'anthropic:claude-fable-5',+ 'openai:gpt-5.6',+ 'not-a-model',+ ]) {+ expect(newerAnthropicModel(id)).toBeNull();+ }+ });++ test('unpriced recipe ids are never suggested', () => {+ const ids = ['claude-sonnet-4-6', 'claude-sonnet-6'];+ expect(newerAnthropicModel('claude-sonnet-4-6', ids, (id) => id !== 'claude-sonnet-6')).toBeNull();+ expect(newerAnthropicModel('claude-sonnet-4-6', ids, () => true)?.id).toBe('claude-sonnet-6');+ });+});diff --git a/test/ai/gateway-ledger-records.serial.test.ts b/test/ai/gateway-ledger-records.serial.test.tsnew file mode 100644index 0000000000..41a8756e59--- /dev/null+++ b/test/ai/gateway-ledger-records.serial.test.ts@@ -0,0 +1,133 @@+/**+ * #5585 — every gateway record site stamps the ledger contract fields+ * (requested model, purpose, failed, estimated) so `snapshot().models`+ * attributes each call to the right touchpoint and caller.+ *+ * Serial lane: installs gateway module state (chat / embed / rerank test+ * transports, configureGateway) and redirects GBRAIN_AUDIT_DIR.+ */++import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ chat,+ configureGateway,+ embed,+ rerank,+ resetGateway,+ toolLoop,+ withBudgetTracker,+ __setChatTransportForTests,+ __setEmbedTransportForTests,+ __setRerankTransportForTests,+ type ChatOpts,+ type ChatResult,+} from '../../src/core/ai/gateway.ts';+import { BudgetTracker } from '../../src/core/budget/budget-tracker.ts';+import { DEFAULT_RERANKER_MODEL } from '../../src/core/ai/defaults.ts';+import { withEnv } from '../helpers/with-env.ts';++const SONNET = 'anthropic:claude-sonnet-4-6';++let tmp: string;+let tracker: BudgetTracker;++function reply(model: string): ChatResult {+ return {+ text: 'ok', blocks: [{ type: 'text', text: 'ok' }], stopReason: 'end',+ usage: { input_tokens: 120, output_tokens: 30, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model, providerId: 'anthropic',+ };+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-ledger-records-'));+ tracker = new BudgetTracker({ label: 'ledger-records', auditPath: join(tmp, 'budget.jsonl') });+});++afterEach(() => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ __setRerankTransportForTests(null);+ resetGateway();+ rmSync(tmp, { recursive: true, force: true });+});++describe('chat() record site', () => {+ test('success carries requested model + purpose; measured usage', async () => {+ __setChatTransportForTests(async (opts: ChatOpts) => reply(opts.model!));+ await withBudgetTracker(tracker, () => chat({ model: SONNET, messages: [{ role: 'user', content: 'hi' }], purpose: 'skillopt.judge' }));+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ requested_model: SONNET, model: SONNET, touchpoint: 'chat', purpose: 'skillopt.judge',+ calls: 1, failed_calls: 0, input_tokens: 120, output_tokens: 30, cost_basis: 'measured',+ })]);+ });++ test('failure without reported usage -> failed call at the pessimistic estimate', async () => {+ __setChatTransportForTests(async () => { throw new Error('provider 500'); });+ await expect(withBudgetTracker(tracker, () =>+ chat({ model: SONNET, messages: [{ role: 'user', content: 'hi' }], maxTokens: 777, purpose: 'skillopt.optimizer' }),+ )).rejects.toThrow('provider 500');+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ purpose: 'skillopt.optimizer', calls: 1, failed_calls: 1, output_tokens: 777, cost_basis: 'estimated',+ })]);+ });++ test('failure WITH reported usage stays measured', async () => {+ __setChatTransportForTests(async () => {+ throw Object.assign(new Error('cut'), { usage: { input_tokens: 50, output_tokens: 9 } });+ });+ await expect(withBudgetTracker(tracker, () => chat({ model: SONNET, messages: [{ role: 'user', content: 'hi' }] }))).rejects.toThrow();+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ purpose: null, failed_calls: 1, input_tokens: 50, output_tokens: 9, cost_basis: 'measured',+ })]);+ });++ test('toolLoop forwards purpose to every chat turn', async () => {+ __setChatTransportForTests(async (opts: ChatOpts) => reply(opts.model!));+ await withBudgetTracker(tracker, () => toolLoop({+ model: SONNET, initialMessages: [{ role: 'user', content: 'go' }], tools: [], toolHandlers: new Map(),+ purpose: 'skillopt.target',+ }));+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({ touchpoint: 'chat', purpose: 'skillopt.target', calls: 1 })]);+ });+});++describe('embed() record site', () => {+ test('char-estimated tokens -> estimated embedding row with the requested model', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 8, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({+ embeddings: args.values.map(() => Array.from({ length: 8 }, () => 0.1)),+ usage: { tokens: 3 },+ })) as never);+ await withBudgetTracker(tracker, () => embed(['alpha beta', 'gamma']));+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ requested_model: 'openai:text-embedding-3-small', model: 'openai:text-embedding-3-small',+ touchpoint: 'embedding', calls: 1, failed_calls: 0, cost_basis: 'estimated',+ })]);+ });+});++describe('rerank() record site', () => {+ const gw = () => configureGateway({+ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test', VOYAGE_API_KEY: 'pa-test' },+ });++ test('success -> estimated rerank row; HTTP failure -> failed call', async () => {+ await withEnv({ GBRAIN_AUDIT_DIR: tmp }, async () => {+ gw();+ __setRerankTransportForTests(async () => new Response(+ JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }), { status: 200, headers: { 'content-type': 'application/json' } },+ ));+ await withBudgetTracker(tracker, () => rerank({ query: 'q', documents: ['d1'] }));+ __setRerankTransportForTests(async () => new Response('boom', { status: 500 }));+ await expect(withBudgetTracker(tracker, () => rerank({ query: 'q', documents: ['d1'] }))).rejects.toThrow();+ });+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ model: DEFAULT_RERANKER_MODEL, touchpoint: 'rerank', calls: 2, attempts: 2, failed_calls: 1, cost_basis: 'estimated',+ })]);+ });+});diff --git a/test/ai/gateway-model-sources.serial.test.ts b/test/ai/gateway-model-sources.serial.test.tsnew file mode 100644index 0000000000..fb82ed82d4--- /dev/null+++ b/test/ai/gateway-model-sources.serial.test.ts@@ -0,0 +1,106 @@+/**+ * #5585 — reconfigureGatewayWithEngine retains WHICH resolution step chose the+ * expansion and chat models (plus a key-name origin), read back through+ * getGatewayModelSource. A later configureGateway with a different model makes+ * the record stale (undefined), never silently inherited.+ *+ * Serial lane: mutates gateway module state and provider/home env vars.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ configureGateway,+ getChatModel,+ getExpansionModel,+ reconfigureGatewayWithEngine,+ resetGateway,+} from '../../src/core/ai/gateway.ts';+import { getGatewayModelSource } from '../../src/core/ai/gateway-model-sources.ts';+import { _resetDeprecationWarningsForTest } from '../../src/core/model-config.ts';+import { withEnv } from '../helpers/with-env.ts';++class StubEngine {+ readonly kind = 'pglite' as const;+ private cfg = new Map<string, string>();+ set(key: string, value: string) { this.cfg.set(key, value); }+ async getConfig(key: string) { return this.cfg.get(key) ?? null; }+ async setConfig() {}+}++let tmpHome: string;+let stub: StubEngine;+const origWrite = process.stderr.write.bind(process.stderr);++function env(extra: Record<string, string | undefined> = {}) {+ return {+ GBRAIN_HOME: tmpHome, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined,+ GBRAIN_MODEL: undefined, GBRAIN_CHAT_MODEL: undefined, GBRAIN_EXPANSION_MODEL: undefined,+ GBRAIN_MODEL_DISCOVERY: 'off', ...extra,+ };+}++async function reconfigure(extra: Record<string, string | undefined> = {}) {+ await withEnv(env(extra), async () => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ await reconfigureGatewayWithEngine(stub as never);+ });+}++beforeEach(() => {+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-gw-sources-'));+ stub = new StubEngine();+ resetGateway();+ _resetDeprecationWarningsForTest();+ process.stderr.write = (() => true) as typeof process.stderr.write;+});++afterEach(() => {+ process.stderr.write = origWrite;+ resetGateway();+ rmSync(tmpHome, { recursive: true, force: true });+});++describe('gateway model provenance', () => {+ test('tier config and models.default are attributed to their keys', async () => {+ stub.set('models.tier.utility', 'anthropic:claude-haiku-4-5-20251001');+ stub.set('models.default', 'anthropic:claude-sonnet-4-6');+ await reconfigure();+ expect(getGatewayModelSource('expansion', getExpansionModel())).toEqual({ source: 'tier_config', origin: 'models.tier.utility' });+ expect(getGatewayModelSource('chat', getChatModel())).toEqual({ source: 'models_default', origin: 'models.default' });+ });++ test('models.chat config key wins and is named', async () => {+ stub.set('models.chat', 'anthropic:claude-sonnet-4-6');+ await reconfigure();+ expect(getGatewayModelSource('chat', getChatModel())).toEqual({ source: 'config_key', origin: 'models.chat' });+ });++ test('a servable config.json pin reports file_config; its env override reports env', async () => {+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', chat_model: 'anthropic:claude-opus-4-7' }));+ await reconfigure();+ expect(getChatModel()).toBe('anthropic:claude-opus-4-7');+ expect(getGatewayModelSource('chat', getChatModel())).toEqual({ source: 'file_config', origin: 'chat_model (config.json)' });++ await reconfigure({ GBRAIN_EXPANSION_MODEL: 'anthropic:claude-haiku-4-5-20251001' });+ expect(getGatewayModelSource('expansion', getExpansionModel())).toEqual({ source: 'env', origin: 'GBRAIN_EXPANSION_MODEL' });+ });++ test('nothing configured -> tier_default / built-in default', async () => {+ await reconfigure();+ expect(getGatewayModelSource('expansion', getExpansionModel())).toEqual({ source: 'tier_default', origin: 'built-in default' });+ expect(getGatewayModelSource('chat', getChatModel())).toEqual({ source: 'tier_default', origin: 'built-in default' });+ });++ test('a later configureGateway with a different model makes the record stale; resetGateway clears it', async () => {+ stub.set('models.tier.utility', 'anthropic:claude-haiku-4-5-20251001');+ await reconfigure();+ const expansion = getExpansionModel();+ configureGateway({ expansion_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ expect(getGatewayModelSource('expansion', getExpansionModel())).toBeUndefined();+ resetGateway();+ expect(getGatewayModelSource('expansion', expansion)).toBeUndefined();+ });+});diff --git a/test/ai/gateway-ocr-budget.test.ts b/test/ai/gateway-ocr-budget.test.tsindex 11a9b5ca94..5406931de5 100644--- a/test/ai/gateway-ocr-budget.test.ts+++ b/test/ai/gateway-ocr-budget.test.ts@@ -73,6 +73,10 @@ describe('generateOcrText budget accounting (#4121)', () => {expect(row.model).toBe('anthropic:claude-haiku-4-5-20251001');expect(row.input_tokens).toBe(900);expect(row.output_tokens).toBe(12);+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ touchpoint: 'ocr', model: 'anthropic:claude-haiku-4-5-20251001', purpose: null,+ calls: 1, attempts: 1, failed_calls: 0, input_tokens: 900, output_tokens: 12, cost_basis: 'measured',+ })]);});test('transport failure records gateway.ocr.failed with a sane estimate and re-throws', async () => {@@ -98,6 +102,9 @@ describe('generateOcrText budget accounting (#4121)', () => {expect(row.input_tokens).toBeGreaterThan(1000);expect(row.input_tokens).toBeLessThan(10_000);expect(row.output_tokens).toBeGreaterThan(0);+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ touchpoint: 'ocr', calls: 1, failed_calls: 1, cost_basis: 'estimated',+ })]);});test('outside any withBudgetTracker scope, OCR is a budget no-op', async () => {diff --git a/test/core/budget/expand-records-budget.test.ts b/test/core/budget/expand-records-budget.test.tsindex 6725b1f8a2..afe7e70c05 100644--- a/test/core/budget/expand-records-budget.test.ts+++ b/test/core/budget/expand-records-budget.test.ts@@ -299,6 +299,12 @@ describe('expand() failure-path accounting (#4121 extension — .failed pessimisexpect(result).toContain('alt one'); // fallback recovered the expansionexpect(tracker.snapshot().callsRecorded).toBe(2); // the failed attempt is NOT a free call+ // #5585 ledger: one expand() operation = one call, two billed attempts.+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({+ requested_model: 'synthetic-structured-litellm-2:my-proxied-model',+ touchpoint: 'expansion', purpose: null, calls: 1, attempts: 2, failed_calls: 1,+ input_tokens: expect.any(Number), cost_basis: 'estimated',+ })]);const rows = readAudit().filter(r => r.event === 'record' || r.event === 'record_unpriced');const labels = rows.map(r => r.sub_label).sort();@@ -324,6 +330,7 @@ describe('expand() failure-path accounting (#4121 extension — .failed pessimis});expect(result).toEqual(['original query']); // outer catch degrades, never throws+ expect(tracker.snapshot().models).toEqual([expect.objectContaining({ touchpoint: 'expansion', calls: 1, attempts: 2, failed_calls: 1 })]);const rows = readAudit().filter(r => r.event === 'record' || r.event === 'record_unpriced');expect(rows.map(r => r.sub_label)).toEqual(['gateway.expand.failed', 'gateway.expand.failed']);});diff --git a/test/core/budget/model-ledger.test.ts b/test/core/budget/model-ledger.test.tsnew file mode 100644index 0000000000..c29f21b685--- /dev/null+++ b/test/core/budget/model-ledger.test.ts@@ -0,0 +1,200 @@+/**+ * #5585 — BudgetTracker per-model ledger (`snapshot().models`), the shared+ * `reservationCostUsd` pricing helper, and the `models_used` builders.+ *+ * Hermetic: every tracker writes its audit JSONL to a per-test tempdir; no+ * gateway, provider or network is touched.+ */++import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { BudgetExhausted, BudgetTracker } from '../../../src/core/budget/budget-tracker.ts';+import { reservationCostUsd } from '../../../src/core/budget/reservation-cost.ts';+import {+ buildModelsUsed,+ formatModelsUsedTable,+ mergeModelUsageRows,+ touchpointForLabel,+ type ModelUsageRow,+} from '../../../src/core/budget/models-used.ts';++const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++let tmp: string;+let auditPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-model-ledger-'));+ auditPath = join(tmp, 'budget.jsonl');+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const tracker = (maxCostUsd?: number) =>+ new BudgetTracker({ label: 'ledger-test', auditPath, ...(maxCostUsd !== undefined ? { maxCostUsd } : {}) });++describe('touchpointForLabel', () => {+ test('maps gateway labels (incl. .failed) and falls back to other', () => {+ expect(touchpointForLabel('gateway.chat')).toBe('chat');+ expect(touchpointForLabel('gateway.expand.failed')).toBe('expansion');+ expect(touchpointForLabel('gateway.embed')).toBe('embedding');+ expect(touchpointForLabel('gateway.rerank')).toBe('rerank');+ expect(touchpointForLabel('gateway.ocr.failed')).toBe('ocr');+ expect(touchpointForLabel('gateway.chatter')).toBe('other');+ expect(touchpointForLabel(undefined)).toBe('other');+ });+});++describe('BudgetTracker ledger', () => {+ test('aggregates per (requested, served, touchpoint, purpose) with tokens and cost', () => {+ const t = tracker();+ t.record({ modelId: HAIKU, inputTokens: 1000, outputTokens: 100, label: 'gateway.chat', purpose: 'skillopt.judge' });+ t.record({ modelId: HAIKU, inputTokens: 500, outputTokens: 50, label: 'gateway.chat', purpose: 'skillopt.judge' });+ const [row, ...rest] = t.snapshot().models;+ expect(rest).toEqual([]);+ expect(row).toEqual({+ requested_model: HAIKU, model: HAIKU, touchpoint: 'chat', purpose: 'skillopt.judge',+ calls: 2, attempts: 2, failed_calls: 0, input_tokens: 1500, output_tokens: 150,+ cost_usd: expect.any(Number), cost_basis: 'measured',+ });+ expect(row!.cost_usd).toBeCloseTo(t.totalSpent, 12);+ });++ test('same model, two purposes -> two rows; engine-internal calls carry purpose null', () => {+ const t = tracker();+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 1, label: 'gateway.chat', purpose: 'skillopt.optimizer' });+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 1, label: 'gateway.chat', purpose: 'skillopt.judge' });+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 1, label: 'gateway.expand' });+ const rows = t.snapshot().models;+ expect(rows.map(r => [r.touchpoint, r.purpose])).toEqual([+ ['chat', 'skillopt.judge'],+ ['chat', 'skillopt.optimizer'],+ ['expansion', null],+ ]);+ });++ test('.failed labels and explicit failed both count as failed calls; estimated sets cost_basis', () => {+ const t = tracker();+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 5, label: 'gateway.embed.failed', kind: 'chat' });+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 5, label: 'gateway.chat', failed: true, estimated: true });+ t.record({ modelId: HAIKU, inputTokens: 10, outputTokens: 5, label: 'gateway.chat' });+ const rows = t.snapshot().models;+ expect(rows.find(r => r.touchpoint === 'chat')).toMatchObject({ calls: 2, failed_calls: 1, cost_basis: 'estimated' });+ expect(rows.find(r => r.touchpoint === 'embedding')).toMatchObject({ calls: 1, failed_calls: 1, cost_basis: 'measured' });+ });++ test('countsAsCall:false adds an attempt, not a call', () => {+ const t = tracker();+ t.record({ modelId: HAIKU, inputTokens: 10, label: 'gateway.expand.failed' });+ t.record({ modelId: HAIKU, inputTokens: 10, label: 'gateway.expand', countsAsCall: false });+ expect(t.snapshot().models).toEqual([expect.objectContaining({ calls: 1, attempts: 2, failed_calls: 1 })]);+ });++ test('unpriced record stays in the ledger with cost_usd null', () => {+ const t = tracker();+ t.record({ modelId: 'litellm:mystery', inputTokens: 42, outputTokens: 7, label: 'gateway.chat' });+ expect(t.totalSpent).toBe(0);+ expect(t.snapshot().models).toEqual([expect.objectContaining({+ model: 'litellm:mystery', calls: 1, input_tokens: 42, output_tokens: 7, cost_usd: null,+ })]);+ });++ test('a TX1 over-cap record throws AND is still in the ledger', () => {+ const t = tracker(0.000001);+ expect(() => t.record({ modelId: HAIKU, inputTokens: 100_000, outputTokens: 10_000, label: 'gateway.chat' }))+ .toThrow(BudgetExhausted);+ expect(t.snapshot().models).toEqual([expect.objectContaining({ calls: 1, input_tokens: 100_000, cost_usd: expect.any(Number) })]);+ });++ test('requested vs served stay distinct; alias and canonical served ids aggregate to one row', () => {+ const t = tracker();+ t.record({ modelId: 'claude-cli:haiku', requestedModelId: 'claude-cli:haiku', inputTokens: 10, label: 'gateway.chat' });+ t.record({ modelId: 'claude-cli:claude-haiku-4-5-20251001', requestedModelId: 'claude-cli:haiku', inputTokens: 10, label: 'gateway.chat' });+ expect(t.snapshot().models).toEqual([expect.objectContaining({+ requested_model: 'claude-cli:haiku', model: 'claude-cli:claude-haiku-4-5-20251001', calls: 2,+ })]);+ });++ test('two trackers keep isolated ledgers', () => {+ const a = tracker();+ const b = tracker();+ a.record({ modelId: HAIKU, inputTokens: 10, label: 'gateway.chat' });+ expect(a.snapshot().models).toHaveLength(1);+ expect(b.snapshot().models).toEqual([]);+ });++ test('snapshot rows are copies (mutating them does not touch the ledger)', () => {+ const t = tracker();+ t.record({ modelId: HAIKU, inputTokens: 10, label: 'gateway.chat' });+ t.snapshot().models[0]!.calls = 99;+ expect(t.snapshot().models[0]!.calls).toBe(1);+ });+});++describe('reservationCostUsd', () => {+ test('free local chat model prices at 0 and never trips a cap', () => {+ expect(reservationCostUsd('ollama:llama3', 'chat', 1_000_000, 32_000)).toBe(0);+ expect(() => tracker(0.0001).reserve({ modelId: 'ollama:llama3', estimatedInputTokens: 1_000_000, maxOutputTokens: 32_000, kind: 'chat' }))+ .not.toThrow();+ });++ test('pricing override is honored; unknown price is null', () => {+ expect(reservationCostUsd('litellm:x', 'chat', 1_000_000, 1_000_000)).toBeNull();+ expect(reservationCostUsd('litellm:x', 'chat', 1_000_000, 1_000_000, { 'litellm:x': { input: 2, output: 4 } })).toBe(6);+ });++ test('parity: reserve() admits exactly when the projection fits the cap', () => {+ const projected = reservationCostUsd(HAIKU, 'chat', 10_000, 4096)!;+ expect(projected).toBeGreaterThan(0);+ const estimate = { modelId: HAIKU, estimatedInputTokens: 10_000, maxOutputTokens: 4096, kind: 'chat' as const };+ expect(() => tracker(projected * 1.01).reserve(estimate)).not.toThrow();+ expect(() => tracker(projected * 0.99).reserve(estimate)).toThrow(BudgetExhausted);+ });+});++const row = (over: Partial<ModelUsageRow>): ModelUsageRow => ({+ requested_model: HAIKU, model: HAIKU, touchpoint: 'chat', purpose: null,+ calls: 1, attempts: 1, failed_calls: 0, input_tokens: 10, output_tokens: 1, cost_usd: 0.5, cost_basis: 'measured',+ ...over,+});++describe('buildModelsUsed / mergeModelUsageRows', () => {+ test('prior-segment rows merge with the snapshot on the ledger key', () => {+ const merged = buildModelsUsed(+ { models: [row({ calls: 2, cost_usd: 1 }), row({ touchpoint: 'expansion' })] },+ [row({ calls: 3, cost_usd: 0.25, cost_basis: 'estimated' })],+ );+ expect(merged).toEqual([+ row({ calls: 5, attempts: 2, input_tokens: 20, output_tokens: 2, cost_usd: 1.25, cost_basis: 'estimated' }),+ row({ touchpoint: 'expansion' }),+ ]);+ });++ test('an unpriced contribution makes the merged cost null', () => {+ expect(mergeModelUsageRows([row({})], [row({ cost_usd: null })])[0]!.cost_usd).toBeNull();+ });+});++describe('formatModelsUsedTable', () => {+ test('header + one aligned line per row; requested -> served, attempts, failures, estimated and unpriced marks', () => {+ const lines = formatModelsUsedTable([+ row({ purpose: 'skillopt.judge', cost_usd: 0.0123 }),+ row({ touchpoint: 'expansion', requested_model: 'anthropic:haiku', attempts: 2, failed_calls: 1, cost_basis: 'estimated' }),+ row({ touchpoint: 'rerank', model: 'litellm:x', requested_model: 'litellm:x', cost_usd: null }),+ ]);+ expect(lines).toHaveLength(4);+ expect(lines[0]).toMatch(/^touchpoint\s+purpose\s+model\s+calls\s+tokens in\/out\s+cost$/);+ expect(lines[1]).toContain('skillopt.judge');+ expect(lines[1]).toContain('$0.0123');+ expect(lines[2]).toContain('engine');+ expect(lines[2]).toContain(`anthropic:haiku -> ${HAIKU}`);+ expect(lines[2]).toContain('1 (2 attempts), 1 failed');+ expect(lines[2]).toContain('~$0.5000');+ expect(lines[3]).toContain('unpriced');+ expect(lines[1]!.indexOf('10/1')).toBe(lines[3]!.indexOf('10/1'));+ });+});diff --git a/test/e2e/skillopt-loop.serial.test.ts b/test/e2e/skillopt-loop.serial.test.tsindex 8da89dad2a..c473dd2267 100644--- a/test/e2e/skillopt-loop.serial.test.ts+++ b/test/e2e/skillopt-loop.serial.test.ts@@ -446,18 +446,19 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {}});- test('broken: malformed reflect JSON (no edits parsed, no acceptance, zero-candidate step is SAID on stderr)', async () => {- // The optimizer returns syntactically broken JSON. The reflect module's- // forgiving parser yields zero valid edits; applyEditBatch sees an empty- // batch; the orchestrator hits the zero-candidate branch; the sel- // gate is never invoked. SKILL.md stays untouched. Critically: the run- // does NOT crash on malformed optimizer output (graceful degradation).+ test('broken: malformed reflect JSON ends errored (optimizer_output_unusable), early-stops, keeps the checkpoint', async () => {+ // The optimizer returns syntactically broken JSON. Every reflect call+ // records reflect_<mode>_no_parseable_edits; the orchestrator hits the+ // zero-candidate branch; the sel gate is never invoked. SKILL.md stays+ // untouched and the run does NOT crash.//- // #4741: a step where the optimizer proposed NOTHING must be- // distinguishable from "gated N candidates and rejected all" — both used- // to log reason 'no_edits_applied' and print nothing, so a whole run of- // zero candidates read as a real `no_improvement` measurement. Now the- // step says so on stderr and logs reason 'no_edits_proposed'.+ // #4741: a step where the optimizer proposed NOTHING is said on stderr+ // and logs reason 'no_edits_proposed' (distinct from apply-rejected).+ // #5584: a run where the optimizer NEVER produced a usable reply is not a+ // `no_improvement` measurement — it ends `errored` with+ // abort_detail 'optimizer_output_unusable: ...', stops after 2 fully+ // unusable steps, keeps its checkpoint and carries remediation + the+ // exact resume command.const fixture = setupFixture(SKILL_PEOPLE_ONLY);const stderrLines: string[] = [];const realWrite = process.stderr.write.bind(process.stderr);@@ -476,7 +477,15 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {_resetAuditWriterForTests();const result = await runOnce(fixture);- expect(result.outcome).toBe('no_improvement');+ expect(result.outcome).toBe('errored');+ expect(result.receipt.abort_reason).toBe('error');+ expect(result.receipt.abort_detail).toMatch(/^optimizer_output_unusable: reflect_(failure|success)_no_parseable_edits: /);+ expect(result.receipt.stop_reason).toBe('early_stop_unusable_output');+ expect(result.receipt.total_steps).toBe(2);+ expect(result.receipt.reflect_errors!.length).toBeGreaterThan(0);+ expect(result.receipt.remediation!.map((r) => r.code)).toContain('reflect_no_parseable_edits');+ expect(result.receipt.resume_command).toContain(`--resume ${result.receipt.run_id}`);+ expect(fs.existsSync(path.join(fixture.skillsDir, SKILL, 'skillopt', `checkpoint-${result.receipt.run_id}.json`))).toBe(true);expect(result.mutatedSkillFile).toBe(false);expect(fs.readFileSync(skillPath(fixture.skillsDir, SKILL), 'utf8')).toBe(SKILL_PEOPLE_ONLY);@@ -484,14 +493,16 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {.toHaveLength(0);// #4741: the operator is told, per step, that no candidate existed.- expect(stderrLines.join('')).toMatch(/optimizer proposed no edits/);+ const stderrText = stderrLines.join('');+ expect(stderrText).toMatch(/optimizer proposed no edits/);+ expect(stderrText).toMatch(/stopped after 2 steps of reflect_no_parseable_edits; remaining budget not spent/);// …and the audit step carries a reason distinct from apply-rejected.const auditFile = path.join(resolveAuditDir(), currentAuditFilename());const steps = fs.readFileSync(auditFile, 'utf8').trim().split('\n').map((l) => JSON.parse(l) as { kind: string; reason?: string }).filter((e) => e.kind === 'step');- expect(steps.length).toBeGreaterThan(0);- for (const st of steps) expect(st.reason).toMatch(/^no_edits_proposed/);+ expect(steps.length).toBe(2);+ for (const st of steps) expect(st.reason).toMatch(/^no_edits_proposed: reflect_/);});} finally {uninstallStub();diff --git a/test/e2e/skillopt-models-strict.serial.test.ts b/test/e2e/skillopt-models-strict.serial.test.tsnew file mode 100644index 0000000000..fd8998be34--- /dev/null+++ b/test/e2e/skillopt-models-strict.serial.test.ts@@ -0,0 +1,390 @@+/**+ * #5585 — models plan + strict mode + pre-spend admission through the real+ * runSkillOpt and every caller that funnels into it, with stub transports (no+ * real LLM, no network): banner/receipt/run_start `models_plan`, strict aborts+ * with zero model calls (config, substitution, legacy job, batch --all,+ * --target-models fleet, bootstrap), `--dry-run` previews, execution-time job+ * re-resolution, the impossible-reservation abort, guarded bootstrap under a+ * tiny cap, and the cycle's `skipped_budget` admission fingerprint.+ *+ * Serial lane: installs gateway module state and a repo-root mock, pins+ * provider/home env vars, walks shared disk state (audit JSONL, checkpoints).+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, mock } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++let cycleSkillsDir = '';+mock.module('../../src/core/repo-root.ts', () => ({+ autoDetectSkillsDirReadOnly: () => ({ dir: cycleSkillsDir }),+}));++import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { withEnv } from '../helpers/with-env.ts';+import {+ __setChatTransportForTests,+ configureGateway,+ reconfigureGatewayWithEngine,+ resetGateway,+ type ChatOpts,+ type ChatResult,+} from '../../src/core/ai/gateway.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';+import { StructuredAgentError } from '../../src/core/errors.ts';+import { _resetDeprecationWarningsForTest } from '../../src/core/model-config.ts';+import { runSkillOpt } from '../../src/core/skillopt/orchestrator.ts';+import { runBatchAll, runFleet } from '../../src/core/skillopt/batch.ts';+import { runGuardedBootstrap } from '../../src/core/skillopt/bootstrap-run.ts';+import { buildSkillOptJobData, runSkillOptJob } from '../../src/core/skillopt/job.ts';+import { resolveSkillOptModels, skillOptModelOpts } from '../../src/core/skillopt/models-plan.ts';+import { _resetAuditWriterForTests, currentAuditFilename } from '../../src/core/skillopt/audit.ts';+import type { SkillOptOpts } from '../../src/core/skillopt/types.ts';++const SKILL = 'strict-skill';+const OPUS = 'anthropic:claude-opus-4-7';+const OPUS5 = 'anthropic:claude-opus-5';+const SONNET = 'anthropic:claude-sonnet-4-6';+const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++const SKILL_TEXT = `---+name: strict-skill+version: 0.1.0+description: Test skill for skillopt strict model provenance.+triggers:+ - "do the strict task"+brain_first: exempt+---++# Strict Skill++Answer the question.+`;+const BENCH = Array.from({ length: 50 }, (_, i) => ({+ task_id: `st-${String(i + 1).padStart(3, '0')}`,+ task: `Question ${i + 1}`,+ judge: { kind: 'llm', rubric: 'Is the answer complete?' },+}));++let engine: PGLiteEngine;+let skillsDir: string;+let tmpHome: string;+let benchmarkPath: string;+let chatCalls = 0;+const origWrite = process.stderr.write.bind(process.stderr);+let stderr = '';++const ENV = () => ({+ GBRAIN_HOME: tmpHome, GBRAIN_AUDIT_DIR: skillsDir, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined,+ GBRAIN_MODEL: undefined, GBRAIN_CHAT_MODEL: undefined, GBRAIN_EXPANSION_MODEL: undefined,+ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_MODEL_DISCOVERY: 'off',+});+const inEnv = <T>(fn: () => Promise<T>) => withEnv(ENV(), fn);++function reply(text: string, model: string): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 200, output_tokens: 40, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model, providerId: 'anthropic',+ };+}++function writeSkill(dir: string, name = SKILL): string {+ fs.mkdirSync(path.join(dir, name), { recursive: true });+ fs.writeFileSync(path.join(dir, name, 'SKILL.md'), SKILL_TEXT);+ const bench = path.join(dir, name, 'skillopt-benchmark.jsonl');+ fs.writeFileSync(bench, BENCH.map((t) => JSON.stringify(t)).join('\n') + '\n');+ return bench;+}++/** Every active touchpoint chosen by touchpoint-specific configuration. */+async function explicitEverything(deep = OPUS): Promise<void> {+ await engine.setConfig('models.tier.deep', deep);+ await engine.setConfig('models.tier.subagent', HAIKU);+ await engine.setConfig('models.tier.reasoning', SONNET);+ await engine.setConfig('models.tier.utility', HAIKU);+ await engine.setConfig('models.chat', SONNET);+ await engine.setConfig('search.reranker.model', 'voyage:rerank-2.5');+ fs.mkdirSync(path.join(tmpHome, '.gbrain'), { recursive: true });+ fs.writeFileSync(path.join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_model: 'openai:text-embedding-3-large' }));+ await reconfigureGatewayWithEngine(engine);+}++async function baseOpts(over: Partial<SkillOptOpts> = {}): Promise<SkillOptOpts> {+ return {+ engine, skillName: SKILL, skillsDir, benchmarkPath,+ epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5],+ ...skillOptModelOpts(await resolveSkillOptModels(engine)),+ mode: 'patch', dryRun: false, noMutate: false, allowMutateBundled: true, bootstrapReviewed: false,+ json: true, maxCostUsd: 100, maxRuntimeMin: 2, force: true,+ ...over,+ };+}++async function strictCode(p: Promise<unknown>): Promise<string> {+ try {+ await p;+ } catch (err) {+ expect(err).toBeInstanceOf(StructuredAgentError);+ expect((err as StructuredAgentError).envelope.code).toBe('models_strict_violation');+ return (err as StructuredAgentError).envelope.message;+ }+ throw new Error('expected a models strict abort');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-strict-'));+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-strict-home-'));+ benchmarkPath = writeSkill(skillsDir);+ chatCalls = 0;+ stderr = '';+ _resetAuditWriterForTests();+ _resetDeprecationWarningsForTest();+ resetGateway();+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ __setChatTransportForTests(async (opts: ChatOpts) => {+ chatCalls += 1;+ if (opts.purpose === 'skillopt.optimizer') return reply('{"edits": []}', opts.model!);+ if (opts.purpose === 'skillopt.judge') return reply('{"score": 0.4, "rationale": "partial"}', opts.model!);+ return reply('an answer', opts.model!);+ });+ process.stderr.write = ((c: string | Uint8Array) => { stderr += String(c); return true; }) as typeof process.stderr.write;+});++afterEach(() => {+ process.stderr.write = origWrite;+ __setChatTransportForTests(null);+ resetGateway();+ _resetAuditWriterForTests();+ fs.rmSync(skillsDir, { recursive: true, force: true });+ fs.rmSync(tmpHome, { recursive: true, force: true });+});++describe('runSkillOpt models plan', () => {+ test('banner before spend; models_plan on the receipt and the run_start audit row; strict verdict ok when all explicit', async () => {+ await inEnv(async () => {+ await explicitEverything();+ const res = await runSkillOpt(await baseOpts());+ expect(chatCalls).toBeGreaterThan(0);+ const plan = res.receipt.models_plan!;+ expect(plan.map((e) => e.touchpoint)).toEqual(['optimizer', 'target', 'judge', 'expansion', 'chat', 'embedding', 'reranker']);+ expect(res.receipt.models_strict).toEqual({ enabled: false, ok: true, violations: [] });+ expect(stderr).toContain('[skillopt] Models for strict-skill:');+ const runStart = fs.readFileSync(path.join(skillsDir, currentAuditFilename()), 'utf8').trim().split('\n')+ .map((l) => JSON.parse(l)).find((e) => e.kind === 'run_start' && e.run_id === res.receipt.run_id);+ expect(runStart.models_plan).toEqual(plan);+ });+ }, 60_000);++ test('strict (config) with fallback sources aborts before any model call, listing each touchpoint with its fix', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.default', SONNET);+ await engine.setConfig('skillopt.models_strict', 'true');+ await reconfigureGatewayWithEngine(engine);+ const msg = await strictCode(runSkillOpt(await baseOpts()));+ expect(chatCalls).toBe(0);+ expect(msg).toContain(`gbrain config set models.tier.deep ${SONNET}`);+ expect(msg).toContain(`gbrain config set models.tier.utility ${SONNET}`);+ expect(fs.existsSync(path.join(skillsDir, currentAuditFilename()))).toBe(false);+ });+ });++ test('--models-strict with a substituted subagent model aborts with zero model calls', async () => {+ await inEnv(async () => {+ await explicitEverything();+ await engine.setConfig('models.tier.subagent', 'bogus-provider:some-model');+ const msg = await strictCode(runSkillOpt(await baseOpts({ modelsStrict: true })));+ expect(chatCalls).toBe(0);+ expect(msg).toContain('target');+ expect(msg).toContain('substituted');+ });+ });++ test('--dry-run: zero model calls; plan + strict verdict on the receipt; strict violations reported, not thrown', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.default', SONNET);+ const off = await runSkillOpt(await baseOpts({ dryRun: true }));+ expect(chatCalls).toBe(0);+ expect(off.receipt.models_plan!.length).toBeGreaterThan(0);+ expect(off.receipt.models_strict).toMatchObject({ enabled: false, ok: false });++ const on = await runSkillOpt(await baseOpts({ dryRun: true, modelsStrict: true }));+ expect(chatCalls).toBe(0);+ expect(on.receipt.models_strict).toMatchObject({ enabled: true, ok: false });+ });+ });++ test('an impossible single-call reservation aborts before any model call, naming the role and control', async () => {+ await inEnv(async () => {+ await explicitEverything(OPUS5);+ let caught: unknown;+ try { await runSkillOpt(await baseOpts({ maxCostUsd: 0.5 })); } catch (err) { caught = err; }+ expect(caught).toBeInstanceOf(StructuredAgentError);+ const env = (caught as StructuredAgentError).envelope;+ expect(env.code).toBe('cost_cap_exceeded');+ expect(env.message).toStartWith('reservation_exceeds_cap: a single optimizer call reserves $0.80');+ expect(env.message).toContain('skillopt.reflect_max_tokens');+ expect(chatCalls).toBe(0);+ });+ });+});++describe('background job', () => {+ test('re-resolves models at execution time (config changed after enqueue)', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.tier.deep', OPUS);+ const models = await resolveSkillOptModels(engine);+ const data = buildSkillOptJobData({+ skillsDir, skillName: SKILL, benchmarkPath, epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5],+ mode: 'patch', dryRun: true, noMutate: false, allowMutateBundled: true, bootstrapReviewed: false,+ maxCostUsd: 100, maxRuntimeMin: 2, force: true, models, modelFlags: {}, modelsStrict: false,+ });+ expect(data.model_sources).toEqual({ optimizer: 'tier_config', target: 'tier_default', judge: 'tier_default' });+ await engine.setConfig('models.tier.deep', HAIKU);+ const out = await runSkillOptJob(engine, data) as { receipt: { optimizer_model: string; models_plan: Array<{ touchpoint: string; source: string }> } };+ expect(out.receipt.optimizer_model).toBe(HAIKU);+ expect(out.receipt.models_plan.find((e) => e.touchpoint === 'optimizer')!.source).toBe('tier_config');+ expect(chatCalls).toBe(0);+ });+ });++ test('legacy job data (no model_flags) reports unknown provenance and aborts under strict', async () => {+ await inEnv(async () => {+ await explicitEverything();+ await engine.setConfig('skillopt.models_strict', 'on');+ const msg = await strictCode(runSkillOptJob(engine, {+ skills_dir: skillsDir, skill_name: SKILL, benchmark_path: benchmarkPath,+ optimizer_model: OPUS, target_model: HAIKU, judge_model: SONNET, force: true, allow_mutate_bundled: true,+ }));+ expect(msg).toContain('(legacy job data)');+ expect(chatCalls).toBe(0);+ });+ });+});++describe('strict propagation through batch and fleet', () => {+ test('--all: every skill aborts pre-spend under --models-strict', async () => {+ await inEnv(async () => {+ writeSkill(skillsDir, 'second-skill');+ const models = await resolveSkillOptModels(engine);+ const out = await runBatchAll({+ engine, skillsDir, perSkillMaxCostUsd: 100, brainWideMaxCostUsd: 100,+ ...skillOptModelOpts(models), modelsStrict: true,+ epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5],+ dryRun: false, noMutate: true, allowMutateBundled: true, force: true,+ });+ expect(out.per_skill.map((s) => s.outcome)).toEqual(['errored', 'errored']);+ expect(out.per_skill.every((s) => s.reason?.includes('models strict check'))).toBe(true);+ expect(chatCalls).toBe(0);+ });+ });++ test('--target-models fleet: every target run aborts pre-spend under --models-strict', async () => {+ await inEnv(async () => {+ const models = await resolveSkillOptModels(engine);+ const out = await runFleet({+ engine, skillName: SKILL, skillsDir, benchmarkPath, targetModels: [HAIKU, SONNET],+ optimizerModel: models.optimizer.model, judgeModel: models.judge.model,+ models: { optimizer: models.optimizer, judge: models.judge }, modelsStrict: true,+ epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5],+ dryRun: false, noMutate: true, allowMutateBundled: true, bootstrapReviewed: false,+ maxCostUsd: 100, maxRuntimeMin: 2, force: true,+ });+ expect(out.per_model.map((p) => p.outcome)).toEqual(['errored', 'errored']);+ expect(chatCalls).toBe(0);+ });+ });+});++describe('guarded bootstrap', () => {+ const bootstrap = async (over: Partial<Parameters<typeof runGuardedBootstrap>[0]> = {}) => {+ const models = await resolveSkillOptModels(engine);+ return runGuardedBootstrap({+ engine, mode: 'skill', skillsDir, skillName: 'fresh-skill', optimizer: models.optimizer,+ dryRun: false, maxCostUsd: 5, ...over,+ });+ };++ beforeEach(() => {+ fs.mkdirSync(path.join(skillsDir, 'fresh-skill'), { recursive: true });+ fs.writeFileSync(path.join(skillsDir, 'fresh-skill', 'SKILL.md'), SKILL_TEXT);+ });++ test('a tiny --max-cost-usd aborts before the call is made; nothing is written', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.tier.deep', HAIKU);+ await expect(bootstrap({ maxCostUsd: 0.001 })).rejects.toBeInstanceOf(BudgetExhausted);+ expect(chatCalls).toBe(0);+ expect(fs.existsSync(path.join(skillsDir, 'fresh-skill', 'skillopt-benchmark.jsonl'))).toBe(false);+ expect(stderr).toContain('[skillopt] Models for fresh-skill:');+ });+ });++ test('--dry-run previews the optimizer row with no call; strict aborts on a fallback optimizer', async () => {+ await inEnv(async () => {+ const preview = await bootstrap({ dryRun: true, modelsStrict: true });+ expect(preview.dry_run).toBe(true);+ expect(preview.strict).toMatchObject({ enabled: true, ok: false });+ expect(preview.models_plan.map((e) => e.touchpoint)).toEqual(['optimizer']);+ expect(chatCalls).toBe(0);+ const msg = await strictCode(bootstrap({ modelsStrict: true }));+ expect(msg).toContain('gbrain config set models.tier.deep');+ expect(chatCalls).toBe(0);+ });+ });+});++describe('cycle admission', () => {+ test('one call over the per-skill cap -> skipped_budget with zero calls; not retried until the fingerprint changes', async () => {+ await inEnv(async () => {+ cycleSkillsDir = skillsDir;+ const { runPhaseSkillopt } = await import('../../src/core/skillopt/cycle-phase.ts');+ await engine.setConfig('cycle.skillopt.enabled', 'true');+ await engine.setConfig('models.tier.deep', OPUS5);+ await engine.setConfig('cycle.skillopt.per_skill_cap_usd', '0.5');++ const first = await runPhaseSkillopt({ engine });+ const results = (first.details as { results: Array<{ skill: string; outcome: string; remediation?: Array<{ code: string }> }> }).results;+ expect(results).toEqual([expect.objectContaining({ skill: SKILL, outcome: 'skipped_budget' })]);+ expect(results[0]!.remediation!.map((r) => r.code)).toEqual(['reservation_exceeds_cap']);+ expect(chatCalls).toBe(0);+ expect(await engine.getConfig(`cycle.skillopt.last_skip.${SKILL}`)).toContain(OPUS5);+ expect(await engine.getConfig(`cycle.skillopt.last_error.${SKILL}`)).toBeNull();+ expect(await engine.getConfig(`cycle.skillopt.last_run.${SKILL}`)).toBeNull();++ const second = await runPhaseSkillopt({ engine });+ expect((second.details as { candidates?: number }).candidates).toBe(0);++ await engine.setConfig('cycle.skillopt.per_skill_cap_usd', '0.6');+ const third = await runPhaseSkillopt({ engine });+ expect((third.details as { results: Array<{ outcome: string }> }).results.map((r) => r.outcome)).toEqual(['skipped_budget']);+ expect(chatCalls).toBe(0);++ // Every priced role is in the fingerprint: a judge-tier change re-admits+ // the skill (a judge-role refusal would otherwise never be retried).+ expect((await runPhaseSkillopt({ engine }).then((r) => r.details as { candidates?: number })).candidates).toBe(0);+ await engine.setConfig('models.tier.reasoning', HAIKU);+ const judgeChanged = await runPhaseSkillopt({ engine });+ expect((judgeChanged.details as { results: Array<{ outcome: string }> }).results.map((r) => r.outcome)).toEqual(['skipped_budget']);++ // So is the skill's benchmark (per-task judge.model overrides live there).+ expect((await runPhaseSkillopt({ engine }).then((r) => r.details as { candidates?: number })).candidates).toBe(0);+ fs.appendFileSync(benchmarkPath, JSON.stringify({ ...BENCH[0], task_id: 'st-extra' }) + '\n');+ const benchChanged = await runPhaseSkillopt({ engine });+ expect((benchChanged.details as { results: Array<{ outcome: string }> }).results.map((r) => r.outcome)).toEqual(['skipped_budget']);+ expect(chatCalls).toBe(0);+ });+ });+});diff --git a/test/e2e/skillopt-models-used.serial.test.ts b/test/e2e/skillopt-models-used.serial.test.tsnew file mode 100644index 0000000000..94e49c74de--- /dev/null+++ b/test/e2e/skillopt-models-used.serial.test.ts@@ -0,0 +1,236 @@+/**+ * #5585 — skillopt receipt `models_used` built from the run's BudgetTracker+ * ledger, driven through the real runSkillOpt with stub transports (no real+ * LLM, no network): per-role purposes, an engine-internal expansion call made+ * inside a rollout, the `run_end` audit copy, and resume accounting (merged+ * prior segments, legacy checkpoints -> `since_resume`).+ *+ * Serial lane: installs gateway module state (chat / generateObject test+ * transports, configureGateway) and walks shared disk state (checkpoints,+ * audit JSONL).+ */++import { describe, expect, test, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { withEnv } from '../helpers/with-env.ts';+import {+ __setChatTransportForTests,+ __setGenerateObjectTransportForTests,+ configureGateway,+ expand,+ resetGateway,+ type ChatOpts,+ type ChatResult,+} from '../../src/core/ai/gateway.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';+import type { ModelUsageRow } from '../../src/core/budget/models-used.ts';+import { runSkillOpt } from '../../src/core/skillopt/orchestrator.ts';+import { checkpointPath, loadCheckpoint } from '../../src/core/skillopt/checkpoint.ts';+import { _resetAuditWriterForTests, currentAuditFilename } from '../../src/core/skillopt/audit.ts';+import { formatRunSummary } from '../../src/commands/skillopt.ts';+import type { SkillOptOpts } from '../../src/core/skillopt/types.ts';++const SKILL = 'ledger-skill';+const SONNET = 'anthropic:claude-sonnet-4-6';+const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++const SKILL_TEXT = `---+name: ledger-skill+version: 0.1.0+description: Test skill for the skillopt models_used receipt.+triggers:+ - "do the ledger task"+brain_first: exempt+---++# Ledger Skill++Answer the question.+`;++const BENCH = Array.from({ length: 50 }, (_, i) => ({+ task_id: `led-${String(i + 1).padStart(3, '0')}`,+ task: `Question ${i + 1}`,+ judge: { kind: 'llm', rubric: 'Is the answer complete?' },+}));++let engine: PGLiteEngine;+let skillsDir: string;+let benchmarkPath: string;+let optimizerCalls = 0;++function reply(text: string, model: string): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 200, output_tokens: 40, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model, providerId: 'anthropic',+ };+}++/** Routes on the purpose each skillopt role stamps; the target's "search" runs a real expand(). */+function installTransport(onOptimizer: (n: number) => void = () => {}): void {+ __setChatTransportForTests(async (opts: ChatOpts) => {+ if (opts.purpose === 'skillopt.optimizer') {+ optimizerCalls += 1;+ onOptimizer(optimizerCalls);+ return reply('{"edits": []}', opts.model!);+ }+ if (opts.purpose === 'skillopt.judge') return reply('{"score": 0.4, "rationale": "partial"}', opts.model!);+ await expand('what does the ledger say');+ return reply('an answer', opts.model!);+ });+}++async function run(over: Partial<SkillOptOpts> = {}) {+ return withEnv({ GBRAIN_AUDIT_DIR: skillsDir }, () => runSkillOpt({+ engine,+ skillName: SKILL,+ skillsDir,+ benchmarkPath,+ epochs: 1,+ batchSize: 2,+ lr: 4,+ lrSchedule: 'constant',+ split: [4, 1, 5],+ optimizerModel: SONNET,+ targetModel: HAIKU,+ judgeModel: SONNET,+ mode: 'patch',+ dryRun: false,+ noMutate: false,+ allowMutateBundled: true,+ bootstrapReviewed: false,+ json: true,+ maxCostUsd: 100,+ maxRuntimeMin: 2,+ force: true,+ ...over,+ }));+}++const pricedSum = (rows: ModelUsageRow[]) => rows.reduce((s, r) => s + (r.cost_usd ?? 0), 0);+const byRole = (rows: ModelUsageRow[]) => rows.map(r => [r.touchpoint, r.purpose, r.model]);+const callsOf = (rows: ModelUsageRow[], touchpoint: string, purpose: string | null) =>+ rows.find(r => r.touchpoint === touchpoint && r.purpose === purpose)?.calls ?? 0;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++let realWrite: typeof process.stderr.write;++beforeEach(async () => {+ await resetPgliteState(engine);+ skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-models-used-'));+ benchmarkPath = path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl');+ fs.mkdirSync(path.join(skillsDir, SKILL), { recursive: true });+ fs.writeFileSync(path.join(skillsDir, SKILL, 'SKILL.md'), SKILL_TEXT);+ fs.writeFileSync(benchmarkPath, BENCH.map(t => JSON.stringify(t)).join('\n') + '\n');+ optimizerCalls = 0;+ _resetAuditWriterForTests();+ configureGateway({ expansion_model: HAIKU, env: { ANTHROPIC_API_KEY: 'sk-test-fake' } });+ __setGenerateObjectTransportForTests(async () => ({+ object: { queries: ['ledger rewrite'] },+ usage: { inputTokens: 30, outputTokens: 10 },+ }) as never);+ realWrite = process.stderr.write.bind(process.stderr);+ process.stderr.write = (() => true) as typeof process.stderr.write;+});++afterEach(() => {+ process.stderr.write = realWrite;+ __setChatTransportForTests(null);+ __setGenerateObjectTransportForTests(null);+ resetGateway();+ _resetAuditWriterForTests();+ fs.rmSync(skillsDir, { recursive: true, force: true });+});++describe('receipt models_used', () => {+ test('one row per role (optimizer + judge on the same model stay apart) plus the engine-internal expansion', async () => {+ installTransport();+ const res = await run();+ const rows = res.receipt.models_used!;++ expect(byRole(rows)).toEqual([+ ['chat', 'skillopt.judge', SONNET],+ ['chat', 'skillopt.optimizer', SONNET],+ ['chat', 'skillopt.target', HAIKU],+ ['expansion', null, HAIKU],+ ]);+ expect(callsOf(rows, 'chat', 'skillopt.optimizer')).toBe(optimizerCalls);+ expect(callsOf(rows, 'expansion', null)).toBe(callsOf(rows, 'chat', 'skillopt.target'));+ expect(rows.every(r => r.cost_usd !== null && r.failed_calls === 0 && r.cost_basis === 'measured')).toBe(true);+ expect(res.receipt.models_used_scope).toBe('full_run');+ expect(res.receipt.prior_segments_cost_usd).toBe(0);+ expect(pricedSum(rows)).toBeCloseTo(res.receipt.final_cost_usd!, 10);++ const runEnd = fs.readFileSync(path.join(skillsDir, currentAuditFilename()), 'utf8').trim().split('\n')+ .map(l => JSON.parse(l)).find(e => e.kind === 'run_end' && e.run_id === res.receipt.run_id);+ expect(runEnd.models_used).toEqual(rows);+ expect(runEnd.models_used_scope).toBe('full_run');++ const summary = formatRunSummary(res.outcome, res.receipt, skillsDir);+ expect(summary).toContain('[skillopt] Models called (full run;');+ expect(summary).toMatch(/\[skillopt\] {3}expansion\s+engine\s+anthropic:claude-haiku-4-5-20251001/);+ });+});++describe('resume accounting', () => {+ async function abortAtThirdOptimizerCall() {+ installTransport((n) => {+ if (n === 3) throw new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 });+ });+ const first = await run();+ expect(first.outcome).toBe('aborted');+ return first;+ }++ test('checkpoint banks ledger rows on the handled abort; the resumed receipt merges every segment', async () => {+ const first = await abortAtThirdOptimizerCall();+ const runId = first.receipt.run_id;+ const cp = loadCheckpoint(skillsDir, SKILL, runId)!;+ expect(cp.models_used_scope).toBe('full_run');+ expect(cp.models_used).toEqual(first.receipt.models_used!);+ expect(cp.cumulative_cost_usd).toBeCloseTo(first.receipt.final_cost_usd!, 10);+ const firstOptimizerCalls = callsOf(cp.models_used!, 'chat', 'skillopt.optimizer');+ expect(firstOptimizerCalls).toBe(3);++ optimizerCalls = 0;+ installTransport();+ const second = await run({ resumeRunId: runId });+ const rows = second.receipt.models_used!;+ expect(second.receipt.models_used_scope).toBe('full_run');+ expect(second.receipt.prior_segments_cost_usd).toBeCloseTo(cp.cumulative_cost_usd, 10);+ expect(callsOf(rows, 'chat', 'skillopt.optimizer')).toBe(firstOptimizerCalls + optimizerCalls);+ expect(pricedSum(rows)).toBeCloseTo(second.receipt.prior_segments_cost_usd! + second.receipt.final_cost_usd!, 10);+ });++ test('legacy checkpoint without ledger rows -> models_used_scope since_resume', async () => {+ const first = await abortAtThirdOptimizerCall();+ const runId = first.receipt.run_id;+ const p = checkpointPath(skillsDir, SKILL, runId);+ const legacy = JSON.parse(fs.readFileSync(p, 'utf8'));+ delete legacy.models_used;+ delete legacy.models_used_scope;+ fs.writeFileSync(p, JSON.stringify(legacy));++ optimizerCalls = 0;+ installTransport();+ const second = await run({ resumeRunId: runId });+ expect(second.receipt.models_used_scope).toBe('since_resume');+ expect(callsOf(second.receipt.models_used!, 'chat', 'skillopt.optimizer')).toBe(optimizerCalls);+ expect(pricedSum(second.receipt.models_used!)).toBeCloseTo(second.receipt.final_cost_usd!, 10);+ expect(formatRunSummary(second.outcome, second.receipt, skillsDir)).toContain('Models called (since resume;');+ });+});diff --git a/test/e2e/skillopt-outcome.serial.test.ts b/test/e2e/skillopt-outcome.serial.test.tsnew file mode 100644index 0000000000..426a1e1b22--- /dev/null+++ b/test/e2e/skillopt-outcome.serial.test.ts@@ -0,0 +1,443 @@+/**+ * #5584 — orchestrator wiring for the truthful outcome, reflect cap, early+ * stop, must-abort classification and resume correctness, driven through the+ * real runSkillOpt with a stub chat transport (no real LLM, no network).+ *+ * Serial lane: installs gateway module state (`__setChatTransportForTests`)+ * and walks multi-step shared disk state (checkpoints, audit JSONL).+ */++import { describe, expect, test, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { withEnv } from '../helpers/with-env.ts';+import { __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';+import { runSkillOpt } from '../../src/core/skillopt/orchestrator.ts';+import { checkpointPath, loadCheckpoint } from '../../src/core/skillopt/checkpoint.ts';+import { skillPath } from '../../src/core/skillopt/version-store.ts';+import { _resetAuditWriterForTests, currentAuditFilename } from '../../src/core/skillopt/audit.ts';+import type { SkillOptOpts } from '../../src/core/skillopt/types.ts';++const SKILL = 'outcome-skill';+const THINKING = 'anthropic:claude-fable-5-1';+const PLAIN = 'anthropic:claude-opus-4-7';+const TARGET = 'anthropic:claude-sonnet-4-6';++const SKILL_TEXT = `---+name: outcome-skill+version: 0.1.0+description: Test skill for the skillopt outcome contract.+triggers:+ - "do the outcome task"+brain_first: exempt+---++# Outcome Skill++When asked, produce a structured output.++## People+List people mentioned.+`;++const task = (id: string, arg: string) => ({ task_id: id, task: `Process ${id}`, judge: { kind: 'rule', checks: [{ op: 'contains', arg }] } });+/** Every task fails at baseline -> one (failure-mode) optimizer call per step. */+const ALL_FAIL = Array.from({ length: 50 }, (_, i) => task(`cit-${String(i + 1).padStart(3, '0')}`, 'Citations'));+/** Alternating People / Citations -> baseline 0.5, the Citations edit reaches 1.0. */+const MIXED = Array.from({ length: 50 }, (_, i) => task(`mix-${String(i + 1).padStart(3, '0')}`, i % 2 === 0 ? 'People' : 'Citations'));++const ADD_CITATIONS = { op: 'add', anchor: 'People', content: '## Citations\nCite the source.', reason: 'add citations' };+const TRUNCATED_JSON = '{"edits":[{"op":"add",';++let engine: PGLiteEngine;+let skillsDir: string;+let benchmarkPath: string;++interface OptimizerCall { mode: 'failure' | 'success' | 'one-shot'; maxTokens?: number }+let optimizerCalls: OptimizerCall[] = [];++function result(text: string, stopReason: ChatResult['stopReason'] = 'end', outputTokens = 20): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason,+ usage: { input_tokens: 100, output_tokens: outputTokens, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'stub', providerId: 'anthropic',+ };+}++function installOptimizer(fn: (call: OptimizerCall, n: number) => ChatResult): void {+ __setChatTransportForTests(async (opts: ChatOpts) => {+ const sys = opts.system ?? '';+ if (sys.startsWith("You are SkillOpt's optimizer")) {+ const mode = sys.includes('ONE-SHOT REWRITE') ? 'one-shot' : sys.includes('FAILURE TRAJECTORIES') ? 'failure' : 'success';+ const call: OptimizerCall = { mode, maxTokens: opts.maxTokens };+ optimizerCalls.push(call);+ return fn(call, optimizerCalls.length);+ }+ const parts: string[] = [];+ if (sys.includes('## People')) parts.push('## People\nAlice.');+ if (sys.includes('## Citations')) parts.push('## Citations\nSource: example.com');+ return result(parts.join('\n\n') || 'nothing');+ });+}++function writeFixture(bench: ReadonlyArray<unknown>): void {+ fs.mkdirSync(path.join(skillsDir, SKILL), { recursive: true });+ fs.writeFileSync(path.join(skillsDir, SKILL, 'SKILL.md'), SKILL_TEXT);+ fs.writeFileSync(benchmarkPath, bench.map((t) => JSON.stringify(t)).join('\n') + '\n');+}++async function run(over: Partial<SkillOptOpts> = {}) {+ return withEnv({ GBRAIN_AUDIT_DIR: skillsDir }, () => runSkillOpt({+ engine,+ skillName: SKILL,+ skillsDir,+ benchmarkPath,+ epochs: 1,+ batchSize: 2,+ lr: 4,+ lrSchedule: 'constant',+ split: [4, 1, 5],+ optimizerModel: PLAIN,+ targetModel: TARGET,+ judgeModel: TARGET,+ mode: 'patch',+ dryRun: false,+ noMutate: false,+ allowMutateBundled: true,+ bootstrapReviewed: false,+ json: true,+ maxCostUsd: 100,+ maxRuntimeMin: 2,+ force: true,+ ...over,+ }));+}++function auditSteps(runId: string): Array<{ step: number; reason?: string }> {+ const file = path.join(skillsDir, currentAuditFilename());+ return fs.readFileSync(file, 'utf8').trim().split('\n')+ .map((l) => JSON.parse(l) as { kind: string; run_id: string; step: number; reason?: string })+ .filter((e) => e.kind === 'step' && e.run_id === runId);+}++let realWrite: typeof process.stderr.write;+let stderr: string[] = [];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-outcome-'));+ benchmarkPath = path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl');+ optimizerCalls = [];+ stderr = [];+ _resetAuditWriterForTests();+ realWrite = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((c: string | Uint8Array) => { stderr.push(String(c)); return true; }) as typeof process.stderr.write;+});++afterEach(() => {+ process.stderr.write = realWrite;+ __setChatTransportForTests(null);+ _resetAuditWriterForTests();+ fs.rmSync(skillsDir, { recursive: true, force: true });+});++describe('unusable optimizer output', () => {+ test('thinking optimizer truncated every call -> errored after 2 steps, resume command doubles the cap', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer(() => result(TRUNCATED_JSON, 'length', 32000));+ const res = await run({ optimizerModel: THINKING });++ expect(res.outcome).toBe('errored');+ expect(res.receipt.abort_reason).toBe('error');+ expect(res.receipt.abort_detail).toBe('optimizer_output_unusable: reflect_failure_truncated: 32000 output tokens, max_tokens=32000');+ expect(res.receipt.stop_reason).toBe('early_stop_unusable_output');+ expect(optimizerCalls).toHaveLength(2);+ expect(optimizerCalls.every((c) => c.maxTokens === 32000)).toBe(true);+ expect(res.receipt.reflect_max_tokens).toBe(32000);+ expect(res.receipt.reflect_max_tokens_source).toBe('default');+ expect(res.receipt.reflect_errors).toEqual(['reflect_failure_truncated: 32000 output tokens, max_tokens=32000']);+ expect(res.receipt.remediation!.map((r) => r.code)).toEqual(['reflect_truncated']);+ expect(res.receipt.resume_command).toContain(`--resume ${res.receipt.run_id}`);+ expect(res.receipt.resume_command).toContain('--reflect-max-tokens 64000');+ expect(res.receipt.test_score).toBeUndefined();+ expect(fs.existsSync(checkpointPath(skillsDir, SKILL, res.receipt.run_id))).toBe(true);+ expect(fs.readFileSync(skillPath(skillsDir, SKILL), 'utf8')).toBe(SKILL_TEXT);+ expect(stderr.join('')).toContain('stopped after 2 steps of reflect_truncated; remaining budget not spent');+ });++ test('accepted step, then unusable steps -> accepted (SKILL.md mutated), stop_reason early stop', async () => {+ writeFixture(MIXED);+ let proposed = false;+ installOptimizer((call) => {+ if (call.mode === 'failure' && !proposed) { proposed = true; return result(JSON.stringify({ edits: [ADD_CITATIONS] })); }+ return result(TRUNCATED_JSON, 'length', 4096);+ });+ const res = await run({ force: false });++ expect(res.outcome).toBe('accepted');+ expect(res.mutatedSkillFile).toBe(true);+ expect(res.receipt.stop_reason).toBe('early_stop_unusable_output');+ expect(res.receipt.abort_detail).toBeUndefined();+ expect(fs.readFileSync(skillPath(skillsDir, SKILL), 'utf8')).toContain('## Citations');+ // The early stop left steps undone: the checkpoint is kept. The resume+ // command never adds --force; the resume admits SKILL.md only when it is+ // exactly the run's own accepted text.+ expect(fs.existsSync(checkpointPath(skillsDir, SKILL, res.receipt.run_id))).toBe(true);+ expect(res.receipt.resume_command).not.toContain('--force');+ // The trailing truncation still drives the cap remedy.+ expect(res.receipt.resume_command).toContain('--reflect-max-tokens 8192');+ // The kept checkpoint's accounting matches the receipt (a resume merges it).+ expect(res.receipt.test_score).toBeDefined();+ expect(loadCheckpoint(skillsDir, SKILL, res.receipt.run_id)!.cumulative_cost_usd).toBeCloseTo(res.receipt.final_cost_usd!, 10);+ });++ test('usable reply, then unusable steps -> no_improvement, but the early stop keeps the checkpoint and resume finishes the run', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer((_c, n) => (n === 1 ? result('{"edits": []}') : result(TRUNCATED_JSON, 'length', 4096)));+ const first = await run();+ expect(first.outcome).toBe('no_improvement');+ expect(first.receipt.stop_reason).toBe('early_stop_unusable_output');+ expect(optimizerCalls).toHaveLength(3);+ const runId = first.receipt.run_id;+ expect(fs.existsSync(checkpointPath(skillsDir, SKILL, runId))).toBe(true);+ expect(first.receipt.resume_command).toContain(`--resume ${runId}`);+ expect(first.receipt.resume_command).toContain('--reflect-max-tokens 8192');+ const saved = loadCheckpoint(skillsDir, SKILL, runId)!;+ expect(saved.tally!.unusable_streak).toBe(2);+ expect({ epoch: saved.next_epoch, step: saved.next_step }).toEqual({ epoch: 1, step: 4 });+ expect(saved.cumulative_cost_usd).toBeCloseTo(first.receipt.final_cost_usd!, 10);++ optimizerCalls = [];+ installOptimizer(() => result('{"edits": []}'));+ const second = await run({ resumeRunId: runId });+ expect(second.outcome).toBe('no_improvement');+ expect(second.receipt.stop_reason).toBe('completed');+ // The two unusable steps (2 and 3) are re-run, then steps 4..10.+ expect(optimizerCalls).toHaveLength(9);+ expect(fs.existsSync(checkpointPath(skillsDir, SKILL, runId))).toBe(false);+ });++ test('one-shot rewrite cut off at max_tokens -> not promoted, errored, error in reflect_errors', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer(() => result('# Outcome Skill\n\n## People\nList peo', 'length', 4096));+ const res = await run({ optimizerMode: 'one-shot-rewrite' });++ expect(optimizerCalls.map((c) => c.mode)).toEqual(['one-shot']);+ expect(res.outcome).toBe('errored');+ expect(res.receipt.reflect_errors).toEqual(['one_shot_rewrite_truncated: 4096 output tokens, max_tokens=4096']);+ expect(res.receipt.abort_detail).toBe('optimizer_output_unusable: one_shot_rewrite_truncated: 4096 output tokens, max_tokens=4096');+ expect(res.mutatedSkillFile).toBe(false);+ expect(fs.readFileSync(skillPath(skillsDir, SKILL), 'utf8')).toBe(SKILL_TEXT);+ });+});++describe('reflect cap precedence through the orchestrator', () => {+ test('config value (below the default) is sent verbatim; an explicit value beats it', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer(() => result('{"edits": []}'));+ await engine.setConfig('skillopt.reflect_max_tokens', '1500');+ const fromConfig = await run({ optimizerModel: THINKING });+ expect(fromConfig.outcome).toBe('no_improvement');+ expect(new Set(optimizerCalls.map((c) => c.maxTokens))).toEqual(new Set([1500]));+ expect(fromConfig.receipt.reflect_max_tokens_source).toBe('config');++ optimizerCalls = [];+ const fromFlag = await run({ optimizerModel: THINKING, reflectMaxTokens: 2222 });+ expect(new Set(optimizerCalls.map((c) => c.maxTokens))).toEqual(new Set([2222]));+ expect(fromFlag.receipt.reflect_max_tokens_source).toBe('flag');+ });+});++describe('--rewrite mode', () => {+ test('mode rewrite still routes through reflect + the validation gate, never the one-shot ablation', async () => {+ writeFixture(MIXED);+ installOptimizer((call) => result(JSON.stringify({ edits: call.mode === 'failure' ? [ADD_CITATIONS] : [] })));+ const res = await run({ mode: 'rewrite' });+ expect(optimizerCalls.length).toBeGreaterThan(0);+ expect(optimizerCalls.some((c) => c.mode === 'one-shot')).toBe(false);+ expect(res.outcome).toBe('accepted');+ expect(res.receipt.optimizer_mode).toBeUndefined();+ });+});++describe('must-abort classification', () => {+ test('raised reflect cap trips reserve() -> aborted budget_exhausted naming both knobs, zero optimizer calls', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer(() => result('{"edits": []}'));+ // Preflight admits the run (heuristic ~$8; one 178k-token fable reservation+ // alone is ~$8.90 < $9), but the baseline spend plus that reservation+ // cannot fit the $9 cap at the first reflect call.+ const res = await run({ optimizerModel: THINKING, reflectMaxTokens: 178_000, maxCostUsd: 9 });++ expect(optimizerCalls).toHaveLength(0);+ expect(res.outcome).toBe('aborted');+ expect(res.receipt.abort_reason).toBe('budget_exhausted');+ expect(res.receipt.abort_detail).toContain('--max-cost-usd');+ expect(res.receipt.abort_detail).toContain('skillopt.reflect_max_tokens');+ expect(res.receipt.remediation!.map((r) => r.code)).toEqual(['budget_exhausted']);+ });+});++describe('resume correctness', () => {+ async function abortAtThirdStep(over: Partial<SkillOptOpts> = {}) {+ installOptimizer((_c, n) => {+ if (n === 3) throw new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 });+ return result('{"edits": []}');+ });+ return run(over);+ }++ test('exhaustion after usable replies -> aborted budget_exhausted (not unusable output); resume continues at the interrupted step', async () => {+ writeFixture(ALL_FAIL);+ const first = await abortAtThirdStep();+ const runId = first.receipt.run_id;+ expect(first.outcome).toBe('aborted');+ expect(first.receipt.abort_reason).toBe('budget_exhausted');+ expect(first.receipt.stop_reason).toBe('aborted');+ expect(first.receipt.abort_detail).not.toContain('optimizer_output_unusable');+ expect(auditSteps(runId).map((s) => s.step)).toEqual([1, 2]);+ const cp = loadCheckpoint(skillsDir, SKILL, runId)!;+ expect({ epoch: cp.next_epoch, step: cp.next_step }).toEqual({ epoch: 1, step: 3 });+ expect(cp.tally!.usable_replies).toBe(2);+ expect(first.receipt.resume_command).toContain(`--resume ${runId}`);++ optimizerCalls = [];+ installOptimizer(() => result('{"edits": []}'));+ const second = await run({ resumeRunId: runId });+ expect(second.outcome).toBe('no_improvement');+ expect(auditSteps(runId).map((s) => s.step)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);+ expect(optimizerCalls).toHaveLength(8);+ });++ test('abort after the step\'s optimizer call: the checkpoint keeps the step-start tally, so resume does not count the call twice', async () => {+ writeFixture(ALL_FAIL);+ let tripped = false;+ __setChatTransportForTests(async (opts: ChatOpts) => {+ if ((opts.system ?? '').startsWith("You are SkillOpt's optimizer")) {+ optimizerCalls.push({ mode: 'failure', maxTokens: opts.maxTokens });+ return result(optimizerCalls.length === 3 ? JSON.stringify({ edits: [ADD_CITATIONS] }) : '{"edits": []}');+ }+ // Step 3's candidate gate: the first target call after its reflect call aborts.+ if (optimizerCalls.length === 3 && !tripped) {+ tripped = true;+ throw new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 });+ }+ return result('nothing');+ });+ const first = await run();+ expect(first.outcome).toBe('aborted');+ expect(tripped).toBe(true);+ expect(optimizerCalls).toHaveLength(3);+ const cp = loadCheckpoint(skillsDir, SKILL, first.receipt.run_id)!;+ expect({ epoch: cp.next_epoch, step: cp.next_step }).toEqual({ epoch: 1, step: 3 });+ expect(cp.tally!.reflect_calls).toBe(2);+ expect(cp.tally!.usable_replies).toBe(2);+ });++ test('the early-stop remedy comes from the step that stopped the run, not the deduped error list', async () => {+ writeFixture(ALL_FAIL);+ // truncated, usable, empty reply, truncated again (a duplicate message the+ // receipt list drops): the stop was caused by truncation.+ const replies = [+ () => result(TRUNCATED_JSON, 'length', 4096),+ () => result('{"edits": []}'),+ () => result(''),+ () => result(TRUNCATED_JSON, 'length', 4096),+ ];+ installOptimizer((_c, n) => replies[Math.min(n, replies.length) - 1]!());+ const res = await run();+ expect(res.receipt.stop_reason).toBe('early_stop_unusable_output');+ expect(optimizerCalls).toHaveLength(4);+ expect(res.receipt.reflect_errors!.at(-1)).toStartWith('reflect_failure_empty_reply');+ expect(res.receipt.resume_command).toContain('--reflect-max-tokens 8192');+ expect(res.receipt.resume_command).not.toContain('<other-model>');+ });++ test('an all-unusable early stop takes its remedy from the last step: truncation then empty replies -> <other-model>', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer((_c, n) => (n === 1 ? result(TRUNCATED_JSON, 'length', 4096) : result('')));+ const res = await run();+ expect(res.outcome).toBe('errored');+ expect(res.receipt.abort_detail).toStartWith('optimizer_output_unusable: reflect_failure_truncated');+ expect(res.receipt.resume_command).toContain(`--optimizer-model '<other-model>'`);+ expect(res.receipt.resume_command).toContain('--reflect-max-tokens 4096');+ });++ test('a resume that aborts before its first rewound step keeps the rewound cursor', async () => {+ writeFixture(ALL_FAIL);+ installOptimizer(() => result(TRUNCATED_JSON, 'length', 4096));+ const first = await run();+ expect(first.outcome).toBe('errored');+ const runId = first.receipt.run_id;+ expect(loadCheckpoint(skillsDir, SKILL, runId)!.next_step).toBe(3);++ optimizerCalls = [];+ installOptimizer(() => { throw new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 }); });+ const second = await run({ resumeRunId: runId, reflectMaxTokens: 8192 });+ expect(second.outcome).toBe('aborted');+ const cp = loadCheckpoint(skillsDir, SKILL, runId)!;+ // Rewound to step 1 and persisted, so the next resume still retries both steps.+ expect({ epoch: cp.next_epoch, step: cp.next_step }).toEqual({ epoch: 1, step: 1 });+ expect(cp.tally!.unusable_streak).toBe(0);+ });++ test('in a git repo, a resume admits SKILL.md dirtied by its own accepted edit but refuses a hand edit', async () => {+ writeFixture(MIXED);+ const git = (...args: string[]) => execFileSync('git', args, { cwd: skillsDir, stdio: 'pipe' });+ git('init', '-q');+ git('-c', '[email protected]', '-c', 'user.name=t', 'add', '-A');+ git('-c', '[email protected]', '-c', 'user.name=t', 'commit', '-qm', 'fixture');+ let proposed = false;+ installOptimizer((call) => {+ if (call.mode === 'failure' && !proposed) { proposed = true; return result(JSON.stringify({ edits: [ADD_CITATIONS] })); }+ return result(TRUNCATED_JSON, 'length', 4096);+ });+ const first = await run({ force: false });+ expect(first.outcome).toBe('accepted');+ expect(first.receipt.resume_command).not.toContain('--force');+ const runId = first.receipt.run_id;+ const ownText = fs.readFileSync(skillPath(skillsDir, SKILL), 'utf8');+ expect(ownText).toContain('## Citations');++ // A hand edit on top of the run's own text is refused (never overwritten).+ fs.appendFileSync(skillPath(skillsDir, SKILL), '\nA hand edit.\n');+ await expect(run({ force: false, resumeRunId: runId })).rejects.toThrow(/uncommitted changes/);+ // An unknown run id admits nothing either.+ await expect(run({ force: false, resumeRunId: 'no-such-run' })).rejects.toThrow(/uncommitted changes/);++ // Exactly the run's own accepted text: the resume goes ahead without --force.+ fs.writeFileSync(skillPath(skillsDir, SKILL), ownText);+ installOptimizer(() => result('{"edits": []}'));+ const resumed = await run({ force: false, resumeRunId: runId });+ expect(resumed.outcome).toBe('accepted');+ });++ test('changed benchmark refuses the resume, naming the field', async () => {+ writeFixture(ALL_FAIL);+ const first = await abortAtThirdStep();+ writeFixture([...ALL_FAIL.slice(0, 49), task('cit-new', 'Citations')]);+ await expect(run({ resumeRunId: first.receipt.run_id })).rejects.toThrow(/benchmark_sha8 changed/);+ });++ test('--no-mutate is preserved: resuming with mutation enabled is refused', async () => {+ writeFixture(ALL_FAIL);+ const first = await abortAtThirdStep({ noMutate: true });+ expect(first.receipt.resume_command).toContain('--no-mutate');+ await expect(run({ resumeRunId: first.receipt.run_id, noMutate: false })).rejects.toThrow(/mutate policy changed/);+ });+});diff --git a/test/fixtures/e2e-unmapped-baseline.txt b/test/fixtures/e2e-unmapped-baseline.txtindex 4e28785199..a65fb4081e 100644--- a/test/fixtures/e2e-unmapped-baseline.txt+++ b/test/fixtures/e2e-unmapped-baseline.txt@@ -41,7 +41,6 @@ test/e2e/db-guard.test.tstest/e2e/db-singleton-shared-recovery.test.tstest/e2e/doctor-silent-death-parity.test.tstest/e2e/dream-allow-list-pglite.test.ts-test/e2e/dream-cycle-phase-order-pglite.test.tstest/e2e/dream-patterns-pglite.test.tstest/e2e/dream-synthesize-chunking.test.tstest/e2e/dream-synthesize-concurrency-postgres.test.ts@@ -115,8 +114,6 @@ test/e2e/serve-http-meta.test.tstest/e2e/serve-http-takes-holders.test.tstest/e2e/serve-stdio-roundtrip.test.tstest/e2e/skill-brain-first.test.ts-test/e2e/skillopt-loop.serial.test.ts-test/e2e/skillopt-pglite.serial.test.tstest/e2e/skillpack-flow.test.tstest/e2e/skillpack-third-party.test.tstest/e2e/source-isolation-pglite.test.tsdiff --git a/test/models-newer-hint.serial.test.ts b/test/models-newer-hint.serial.test.tsnew file mode 100644index 0000000000..1b18f97645--- /dev/null+++ b/test/models-newer-hint.serial.test.ts@@ -0,0 +1,134 @@+/**+ * `gbrain models` — advisory newer-available hint and source attribution+ * derived from resolveModelDetailed (models.tier.* attributed before+ * models.default). Serial: captures process.stdout and clears GBRAIN_MODEL.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { runModels } from '../src/commands/models.ts';++class StubConfigEngine {+ private readonly config = new Map<string, string>();++ set(key: string, value: string): void {+ this.config.set(key, value);+ }++ async getConfig(key: string): Promise<string | null> {+ return this.config.get(key) ?? null;+ }++ async getPage(): Promise<{ source_id: string }> {+ return { source_id: 'default' };+ }+}++interface Newer { family: string; model: string; command: string }+interface Report {+ tiers: Record<string, { resolved: string; source: string; newer_available?: Newer }>;+ per_task: Array<{ key: string; resolved: string; source: string; newer_available?: Newer }>;+}++async function capture(engine: StubConfigEngine, args: string[]): Promise<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, args);+ } finally {+ process.stdout.write = originalWrite;+ }+ return stdout;+}++const reportOf = async (engine: StubConfigEngine): Promise<Report> => JSON.parse(await capture(engine, ['--json']));++let savedModelEnv: string | undefined;+beforeEach(() => {+ savedModelEnv = process.env.GBRAIN_MODEL;+ delete process.env.GBRAIN_MODEL;+});+afterEach(() => {+ if (savedModelEnv === undefined) delete process.env.GBRAIN_MODEL;+ else process.env.GBRAIN_MODEL = savedModelEnv;+});++describe('gbrain models — newer-available hint', () => {+ test('an older configured sonnet prints the hint and the config command', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.tier.reasoning', 'anthropic:claude-sonnet-4-6');++ const report = await reportOf(engine);+ expect(report.tiers.reasoning.newer_available).toEqual({+ family: 'sonnet',+ model: 'claude-sonnet-5',+ command: 'gbrain config set models.tier.reasoning anthropic:claude-sonnet-5',+ });++ const text = await capture(engine, []);+ const row = text.split('\n').find((l) => l.includes('tier.reasoning'))!;+ expect(row).toContain('[newer sonnet available: claude-sonnet-5]');+ expect(row).toContain('gbrain config set models.tier.reasoning anthropic:claude-sonnet-5');+ });++ test('current, newer-than-recipe, dated/undated-equal and non-Anthropic models get no hint', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.tier.reasoning', 'anthropic:claude-sonnet-5');+ engine.set('models.tier.deep', 'anthropic:claude-opus-6');+ engine.set('models.tier.utility', 'claude-haiku-4-5');+ engine.set('models.tier.subagent', 'openai:gpt-5.6');++ const report = await reportOf(engine);+ for (const t of ['utility', 'reasoning', 'deep', 'subagent']) {+ expect(report.tiers[t].newer_available).toBeUndefined();+ }+ expect(await capture(engine, [])).not.toContain('[newer ');+ });++ test('per-task rows hint only when their own key supplied the model', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.tier.deep', 'anthropic:claude-opus-4-7');+ engine.set('models.drift', 'anthropic:claude-sonnet-4-6');++ const report = await reportOf(engine);+ const drift = report.per_task.find((r) => r.key === 'models.drift')!;+ expect(drift.newer_available?.command).toBe('gbrain config set models.drift anthropic:claude-sonnet-5');+ const think = report.per_task.find((r) => r.key === 'models.think')!;+ expect(think.resolved).toBe('anthropic:claude-opus-4-7');+ expect(think.newer_available).toBeUndefined();+ expect(report.tiers.deep.newer_available?.model).toBe('claude-opus-5');+ });+});++describe('gbrain models — source attribution', () => {+ test('models.tier.* is attributed before models.default on tier and per-task rows', async () => {+ const engine = new StubConfigEngine();+ engine.set('models.default', 'anthropic:claude-sonnet-5');+ engine.set('models.tier.utility', 'anthropic:claude-haiku-4-5-20251001');++ const report = await reportOf(engine);+ expect(report.tiers.utility).toMatchObject({+ resolved: 'anthropic:claude-haiku-4-5-20251001',+ source: 'config: models.tier.utility',+ });+ expect(report.tiers.reasoning).toMatchObject({+ resolved: 'anthropic:claude-sonnet-5',+ source: 'config: models.default',+ });+ const expansion = report.per_task.find((r) => r.key === 'models.expansion')!;+ expect(expansion).toMatchObject({+ resolved: 'anthropic:claude-haiku-4-5-20251001',+ source: 'config: models.tier.utility',+ });+ const chat = report.per_task.find((r) => r.key === 'models.chat')!;+ expect(chat.source).toBe('config: models.default');+ });++ test('unconfigured rows report the built-in default', async () => {+ const report = await reportOf(new StubConfigEngine());+ expect(report.tiers.deep.source).toBe('default');+ expect(report.per_task.find((r) => r.key === 'models.think')!.source).toBe('tier.deep');+ });+});diff --git a/test/skillopt/cycle-phase-caps.serial.test.ts b/test/skillopt/cycle-phase-caps.serial.test.tsindex 4f84714181..cb23b90549 100644--- a/test/skillopt/cycle-phase-caps.serial.test.ts+++ b/test/skillopt/cycle-phase-caps.serial.test.ts@@ -31,6 +31,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { errorFor } from '../../src/core/errors.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';// ─── Fixture skills trees (benchmark file existence is all the phase reads;@@ -55,12 +56,16 @@ let runnerCalls: Array<Record<string, unknown>> = [];let stubCosts: number[] = [];/** Optional per-call hook (used by the abort tests). */let onRunnerCall: ((opts: Record<string, unknown>, idx: number) => void) | null = null;+/** Optional per-call result override (used by the errored-run tests). */+let stubResult: ((idx: number) => { outcome: string; receipt: Record<string, unknown> } | null) | null = null;mock.module('../../src/core/skillopt/orchestrator.ts', () => ({runSkillOpt: async (opts: Record<string, unknown>) => {const idx = runnerCalls.length;runnerCalls.push(opts);onRunnerCall?.(opts, idx);+ const override = stubResult?.(idx);+ if (override) return { ...override, finalText: 'stub', mutatedSkillFile: false };return {outcome: 'accepted',receipt: { final_cost_usd: stubCosts[idx] ?? 0 },@@ -106,6 +111,7 @@ beforeEach(async () => {runnerCalls = [];stubCosts = [];onRunnerCall = null;+ stubResult = null;});async function enableFlag(): Promise<void> {@@ -243,6 +249,57 @@ describe('runPhaseSkillopt cost caps', () => {});});+describe('runPhaseSkillopt reservation refusals (#5585)', () => {+ const refuse = () => {+ throw errorFor({ class: 'CostCapExceeded', code: 'cost_cap_exceeded', message: 'reservation_exceeds_cap: a single optimizer call reserves $0.80' });+ };++ test('refusal under a brain-wide-reduced cap is brain_wide_cap_reached and writes no last_skip', async () => {+ await enableFlag();+ currentSkillsDir = skills2Dir;+ await engine.setConfig('cycle.skillopt.per_skill_cap_usd', '0.8');+ await engine.setConfig('cycle.skillopt.brain_wide_cap_usd', '1');+ stubCosts = [0.5];+ // Call 1 spends $0.50; call 2 gets min(0.8, 0.5) = $0.50 and is refused.+ onRunnerCall = (_opts, idx) => { if (idx === 1) refuse(); };+ const res = await runPhaseSkillopt({ engine });+ expect(runnerCalls.length).toBe(2);+ expect(runnerCalls[1]!.maxCostUsd).toBe(0.5);+ const d = res.details as PhaseDetails;+ expect(d.results![1]).toEqual({ skill: d.results![1]!.skill, outcome: 'skipped', cost_usd: 0, reason: 'brain_wide_cap_reached' });+ expect(d.skipped_brain_wide_cap).toBe(1);+ // Not a per-skill budget skip: tomorrow's full per-skill cap may fit it.+ expect(await engine.getConfig(`cycle.skillopt.last_skip.${d.results![1]!.skill}`)).toBeNull();+ });++ test('an unreadable benchmark never throws the phase: the skill is re-admitted', async () => {+ await enableFlag();+ const root = mkdtempSync(join(tmpdir(), 'cycle-phase-caps-unreadable-'));+ try {+ // The benchmark path exists but is a directory, so reading it fails.+ mkdirSync(join(root, 'skill-x', 'skillopt-benchmark.jsonl'), { recursive: true });+ currentSkillsDir = root;+ await engine.setConfig('cycle.skillopt.last_skip.skill-x', '{"stale":"fingerprint"}');+ const res = await runPhaseSkillopt({ engine });+ expect(runnerCalls.length).toBe(1);+ expect((res.details as PhaseDetails).results![0]!.skill).toBe('skill-x');+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test('refusal at the full per-skill cap is skipped_budget and records last_skip', async () => {+ await enableFlag();+ currentSkillsDir = skills1Dir;+ onRunnerCall = refuse;+ const res = await runPhaseSkillopt({ engine });+ const row = (res.details as PhaseDetails).results![0]!;+ expect(row.outcome).toBe('skipped_budget');+ expect(await engine.getConfig('cycle.skillopt.last_skip.skill-a')).toContain('"benchmark_sha8"');+ expect(await engine.getConfig('cycle.skillopt.last_error.skill-a')).toBeNull();+ });+});+describe('runPhaseSkillopt abort signal', () => {test('abort during the first run stops the loop — no further runner calls, no skipped rows', async () => {await enableFlag();@@ -270,3 +327,65 @@ describe('runPhaseSkillopt abort signal', () => {expect(res.status).toBe('ok');});});++describe('runPhaseSkillopt errored runs (#5584)', () => {+ const REMEDIATION = [{ code: 'reflect_truncated', fix: 'raise the cap', docs: 'docs/guides/skillopt.md#reflect_truncated' }];+ const ERRORED = {+ outcome: 'errored',+ receipt: {+ final_cost_usd: 0.2,+ run_id: 'run-err',+ abort_reason: 'error',+ abort_detail: 'optimizer_output_unusable: reflect_failure_truncated: 32000 output tokens, max_tokens=32000',+ remediation: REMEDIATION,+ },+ };++ test('errored run forwards diagnostics, leaves last_run unset, records last_error', async () => {+ await enableFlag();+ currentSkillsDir = skills1Dir;+ stubResult = () => ERRORED;+ const res = await runPhaseSkillopt({ engine });+ const row = (res.details as PhaseDetails).results![0] as Record<string, unknown>;+ expect(row).toEqual({+ skill: 'skill-a',+ outcome: 'errored',+ cost_usd: 0.2,+ abort_reason: 'error',+ abort_detail: ERRORED.receipt.abort_detail,+ run_id: 'run-err',+ remediation: REMEDIATION,+ });+ expect(res.status).toBe('warn');+ expect(await engine.getConfig('cycle.skillopt.last_run.skill-a')).toBeNull();+ expect(Number(await engine.getConfig('cycle.skillopt.last_error.skill-a'))).toBeGreaterThan(0);+ });++ test('an errored skill is not retried within 24h of its last error, and is retried after', async () => {+ await enableFlag();+ currentSkillsDir = skills1Dir;+ stubResult = () => ERRORED;+ await runPhaseSkillopt({ engine });+ expect(runnerCalls.length).toBe(1);++ const again = await runPhaseSkillopt({ engine });+ expect(runnerCalls.length).toBe(1);+ expect(again.summary).toBe('no stale skills with benchmarks; nothing to optimize');++ await engine.setConfig('cycle.skillopt.last_error.skill-a', String(Date.now() - 25 * 3600 * 1000));+ stubResult = null;+ await runPhaseSkillopt({ engine });+ expect(runnerCalls.length).toBe(2);+ expect(await engine.getConfig('cycle.skillopt.last_run.skill-a')).not.toBeNull();+ });++ test('a thrown run error also records last_error instead of last_run', async () => {+ await enableFlag();+ currentSkillsDir = skills1Dir;+ onRunnerCall = () => { throw new Error('d_sel_too_small'); };+ const res = await runPhaseSkillopt({ engine });+ expect((res.details as PhaseDetails).results![0]).toEqual({ skill: 'skill-a', outcome: 'errored', cost_usd: 0, reason: 'd_sel_too_small' });+ expect(await engine.getConfig('cycle.skillopt.last_run.skill-a')).toBeNull();+ expect(await engine.getConfig('cycle.skillopt.last_error.skill-a')).not.toBeNull();+ });+});diff --git a/test/skillopt/error-code-docs.test.ts b/test/skillopt/error-code-docs.test.tsnew file mode 100644index 0000000000..5bedee89e0--- /dev/null+++ b/test/skillopt/error-code-docs.test.ts@@ -0,0 +1,36 @@+/**+ * Every remediation code skillopt can emit links to+ * `docs/guides/skillopt.md#<code>`; the guide's error-code table must carry a+ * matching anchor row for each, and no anchor for a code that no longer exists.+ */++import { describe, test, expect } from 'bun:test';+import { readFileSync } from 'fs';+import { join } from 'path';+import { buildRemediation, SKILLOPT_REMEDIATION_CODES } from '../../src/core/skillopt/remediation.ts';+import { SKILLOPT_HELP_TEXT } from '../../src/core/skillopt/help.ts';++const root = join(import.meta.dir, '..', '..');+const guide = readFileSync(join(root, 'docs/guides/skillopt.md'), 'utf8');+const tableRows = guide.split('\n').filter((l) => l.startsWith('| <a id="'));+const anchoredCodes = tableRows.map((l) => l.match(/^\| <a id="([a-z_]+)"><\/a>`([a-z_]+)`/)?.slice(1));++describe('skillopt error-code table', () => {+ test('every emitted remediation code has an anchored table row', () => {+ for (const code of SKILLOPT_REMEDIATION_CODES) {+ const [entry] = buildRemediation([`${code}: x`], code);+ expect(entry?.docs).toBe(`docs/guides/skillopt.md#${code}`);+ expect(anchoredCodes).toContainEqual([code, code]);+ }+ });++ test('the table has no rows for codes skillopt does not emit', () => {+ expect(anchoredCodes.length).toBe(tableRows.length);+ expect(anchoredCodes.map((c) => c![0]).sort()).toEqual([...SKILLOPT_REMEDIATION_CODES].sort());+ });++ test('guide and help state the errored -> exit 2 contract', () => {+ expect(guide).toMatch(/\| 2 \| `aborted` \/ `errored` \|.*optimizer_output_unusable/);+ expect(SKILLOPT_HELP_TEXT).toMatch(/2 = aborted[\s\S]*errored[\s\S]*optimizer_output_unusable/);+ });+});diff --git a/test/skillopt/judge-bootstrap-caps.test.ts b/test/skillopt/judge-bootstrap-caps.test.tsnew file mode 100644index 0000000000..64aa2307c7--- /dev/null+++ b/test/skillopt/judge-bootstrap-caps.test.ts@@ -0,0 +1,150 @@+/**+ * #5584 — judge + bootstrap output caps, truncation handling and must-abort.+ *+ * - LLM judge: Claude 5 judge sends 8192 (skilloptOutputCap floor), a+ * non-thinking judge keeps 200; a length-stopped unparseable reply is+ * `llm_truncated`; BudgetExhausted is rethrown (never a score of 0) and+ * aborts the gate that is scoring (held-out gates score through the same+ * path).+ * - Bootstrap: routing rows and the from-skill call use the thinking floor;+ * length-stopped routing rows are skipped as `truncated`; the from-skill+ * reply's cut final line is dropped; exhaustion mid-rows aborts with no+ * benchmark written.+ */++import { describe, expect, test, beforeEach, afterEach } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { scoreTrajectory } from '../../src/core/skillopt/score.ts';+import { runValidationGate } from '../../src/core/skillopt/validate-gate.ts';+import { runBootstrap, runBootstrapFromSkill } from '../../src/core/skillopt/bootstrap-benchmark.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import type { BenchmarkTask, Trajectory } from '../../src/core/skillopt/types.ts';++const THINKING = 'anthropic:claude-opus-5';+const PLAIN = 'anthropic:claude-sonnet-4-6';+const SKILL = 'widget-example';++type AnyChat = (opts: ChatOpts) => Promise<ChatResult>;++function reply(text: string, stopReason: ChatResult['stopReason'] = 'end'): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason,+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: PLAIN, providerId: 'anthropic',+ };+}++function recorder(fn: (opts: ChatOpts, n: number) => ChatResult): { chatFn: AnyChat; calls: ChatOpts[] } {+ const calls: ChatOpts[] = [];+ return { calls, chatFn: async (opts) => { calls.push(opts); return fn(opts, calls.length); } };+}++const exhausted = () => new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 });++const trajectory = { task_id: 't', task: 'do', final_text: 'out', tool_calls: [], turns: 1 } as unknown as Trajectory;+const LLM_JUDGE = { kind: 'llm' as const, rubric: 'is it good?' };++describe('LLM judge', () => {+ test('Claude 5 judge sends 8192; non-thinking judge keeps 200', async () => {+ for (const [model, expected] of [[THINKING, 8192], [PLAIN, 200]] as const) {+ const r = recorder(() => reply('{"score": 1, "rationale": "ok"}'));+ await scoreTrajectory(trajectory, LLM_JUDGE, { judgeModel: model, chatFn: r.chatFn as never });+ expect(r.calls[0]!.maxTokens).toBe(expected);+ }+ });++ test('length stop with unparseable text -> llm_truncated; plain garbage stays llm_parse_failed', async () => {+ const cut = recorder(() => reply('{"score": 0.', 'length'));+ const a = await scoreTrajectory(trajectory, LLM_JUDGE, { judgeModel: THINKING, chatFn: cut.chatFn as never });+ expect(a).toMatchObject({ score: 0, judge_error: 'llm_truncated' });+ const junk = recorder(() => reply('no json here'));+ const b = await scoreTrajectory(trajectory, LLM_JUDGE, { judgeModel: THINKING, chatFn: junk.chatFn as never });+ expect(b.judge_error).toBe('llm_parse_failed');+ });++ test('BudgetExhausted is rethrown, not scored 0; other errors still fail open', async () => {+ const boom = recorder(() => { throw exhausted(); });+ await expect(scoreTrajectory(trajectory, LLM_JUDGE, { judgeModel: PLAIN, chatFn: boom.chatFn as never })).rejects.toBeInstanceOf(BudgetExhausted);+ const flaky = recorder(() => { throw new Error('503'); });+ const res = await scoreTrajectory(trajectory, LLM_JUDGE, { judgeModel: PLAIN, chatFn: flaky.chatFn as never });+ expect(res).toMatchObject({ score: 0, judge_error: 'llm_call_failed: 503' });+ });++ test('exhaustion during judging aborts the gate (the held-out gate scores through this path)', async () => {+ const tasks: BenchmarkTask[] = [+ { task_id: 'a', task: 'a', judge: LLM_JUDGE },+ { task_id: 'b', task: 'b', judge: LLM_JUDGE },+ ];+ let n = 0;+ const judgeChat: AnyChat = async () => { n += 1; if (n === 2) throw exhausted(); return reply('{"score": 1}'); };+ await expect(runValidationGate({+ engine: {} as never,+ candidateSkillText: 'skill',+ selSet: tasks,+ bestScore: -1,+ targetModel: PLAIN,+ judgeModel: PLAIN,+ runsPerTask: 1,+ concurrency: 1,+ rolloutFn: (async () => trajectory) as never,+ scoreFn: ((t: Trajectory, j: BenchmarkTask['judge'], o: { judgeModel?: string }) =>+ scoreTrajectory(t, j, { ...o, chatFn: judgeChat as never })) as never,+ })).rejects.toBeInstanceOf(BudgetExhausted);+ });+});++describe('bootstrap generators', () => {+ let skillsDir: string;+ beforeEach(() => {+ skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-caps-'));+ fs.mkdirSync(path.join(skillsDir, SKILL), { recursive: true });+ fs.writeFileSync(path.join(skillsDir, SKILL, 'SKILL.md'), '# Widget\n\nMakes a report.\n');+ const rows = [1, 2, 3].map((i) => JSON.stringify({ intent: `make report ${i}`, expected_skill: SKILL }));+ fs.writeFileSync(path.join(skillsDir, SKILL, 'routing-eval.jsonl'), rows.join('\n') + '\n');+ });+ afterEach(() => { fs.rmSync(skillsDir, { recursive: true, force: true }); });++ const benchPath = () => path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl');+ const CHECKS = '{"checks": [{"op": "contains", "arg": "Summary"}, {"op": "max_chars", "arg": 4000}]}';++ test('routing rows: thinking floor 8192 vs site cap 500; length-stopped rows skipped as truncated', async () => {+ const plain = recorder(() => reply(CHECKS));+ await runBootstrap({ skillsDir, skillName: SKILL, optimizerModel: PLAIN, chatFn: plain.chatFn as never });+ expect(plain.calls.map((c) => c.maxTokens)).toEqual([500, 500, 500]);++ const stderr: string[] = [];+ const realWrite = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((c: string | Uint8Array) => { stderr.push(String(c)); return true; }) as typeof process.stderr.write;+ try {+ const mixed = recorder((_o, n) => (n === 2 ? reply(CHECKS, 'length') : reply(CHECKS)));+ const res = await runBootstrap({ skillsDir, skillName: SKILL, optimizerModel: THINKING, force: true, chatFn: mixed.chatFn as never });+ expect(mixed.calls.map((c) => c.maxTokens)).toEqual([8192, 8192, 8192]);+ expect(res).toMatchObject({ rowsGenerated: 2, rowsSkipped: 1 });+ expect(stderr.join('')).toContain('bootstrap row 2 skipped: truncated');+ } finally {+ process.stderr.write = realWrite;+ }+ });++ test('routing rows: exhaustion mid-rows aborts and writes no benchmark', async () => {+ const r = recorder((_o, n) => { if (n === 2) throw exhausted(); return reply(CHECKS); });+ await expect(runBootstrap({ skillsDir, skillName: SKILL, optimizerModel: PLAIN, chatFn: r.chatFn as never })).rejects.toBeInstanceOf(BudgetExhausted);+ expect(fs.existsSync(benchPath())).toBe(false);+ });++ test('from-skill: thinking floor applies; a length-stopped reply drops its cut final line', async () => {+ const line = (i: number) => JSON.stringify({ task: `task ${i}`, checks: [{ op: 'contains', arg: `a${i}` }, { op: 'contains', arg: `b${i}` }] });+ const text = [line(1), line(2), line(3)].join('\n');+ const r = recorder(() => reply(text, 'length'));+ const res = await runBootstrapFromSkill({ skillsDir, skillName: SKILL, optimizerModel: THINKING, taskCount: 5, chatFn: r.chatFn as never });+ expect(r.calls[0]!.maxTokens).toBe(8192);+ expect(res).toMatchObject({ rowsGenerated: 2, rowsSkipped: 1 });++ const plain = recorder(() => reply(text));+ await runBootstrapFromSkill({ skillsDir, skillName: SKILL, optimizerModel: PLAIN, taskCount: 5, force: true, chatFn: plain.chatFn as never });+ expect(plain.calls[0]!.maxTokens).toBe(4000);+ });+});diff --git a/test/skillopt/models-four-paths.serial.test.ts b/test/skillopt/models-four-paths.serial.test.tsnew file mode 100644index 0000000000..ea93c1bb11--- /dev/null+++ b/test/skillopt/models-four-paths.serial.test.ts@@ -0,0 +1,204 @@+/**+ * #5585 — four-path golden test: the CLI, the run_skillopt MCP op, the cycle+ * phase and the background job handler all resolve the optimizer / target /+ * judge roles through resolveSkillOptModels, so they hand runSkillOpt the+ * identical {model, source} plan for every config (models.default set; tiers+ * set; neither; a CLI flag, which only the CLI and its background job carry).+ * Also pins the CLI `--models-strict` flag and the `--dry-run` exit contract.+ *+ * Serial lane (isolation rule R2): runSkillOpt and repo-root are mocked with+ * mock.module; every path is loaded after the mocks so its bindings resolve to+ * them. The runSkillOpt stub is mandatory — no path may launch a real run.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, mock } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const skillsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-four-paths-'));+const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-four-paths-home-'));+const SKILL = 'golden-skill';+fs.mkdirSync(path.join(skillsDir, SKILL), { recursive: true });+fs.writeFileSync(path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl'), '{}\n');++let captured: Array<Record<string, unknown>> = [];+mock.module('../../src/core/skillopt/orchestrator.ts', () => ({+ runSkillOpt: async (opts: Record<string, unknown>) => {+ captured.push(opts);+ const strictOn = opts.modelsStrict === true;+ return {+ outcome: 'no_improvement',+ receipt: {+ run_id: 'r', skill: SKILL, final_cost_usd: 0, best_sel_score: 0,+ models_plan: [{ touchpoint: 'optimizer', model: 'm', source: 'models_default', origin: 'models.default', active: true }],+ models_strict: { enabled: strictOn, ok: false, violations: [{ touchpoint: 'optimizer', model: 'm', source: 'models_default', origin: 'models.default', fix: 'gbrain config set models.tier.deep m' }] },+ },+ finalText: '',+ mutatedSkillFile: false,+ };+ },+ parseSplit: (s: string) => s.split(':').map(Number),+}));+mock.module('../../src/core/repo-root.ts', () => ({+ autoDetectSkillsDirReadOnly: () => ({ dir: skillsDir }),+}));++import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { withEnv } from '../helpers/with-env.ts';+import { _resetDeprecationWarningsForTest } from '../../src/core/model-config.ts';+import { runSkillOptCommand, parseFlags } from '../../src/commands/skillopt.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { runPhaseSkillopt } from '../../src/core/skillopt/cycle-phase.ts';+import { buildSkillOptJobData, runSkillOptJob } from '../../src/core/skillopt/job.ts';+import { resolveSkillOptModels, type SkillOptModelFlags, type SkillOptModels } from '../../src/core/skillopt/models-plan.ts';++const OPUS = 'anthropic:claude-opus-4-7';+const SONNET = 'anthropic:claude-sonnet-4-6';+const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++let engine: PGLiteEngine;+const origWrite = { out: process.stdout.write.bind(process.stdout), err: process.stderr.write.bind(process.stderr) };+const origExit = process.exit;+let stdout = '';+let exitCodes: number[] = [];++const ENV = {+ GBRAIN_HOME: tmpHome, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined,+ GBRAIN_MODEL: undefined, GBRAIN_MODEL_DISCOVERY: 'off',+};++class ExitSignal extends Error {}++type RolePlan = Record<'optimizer' | 'target' | 'judge', { model: string; source: string }>;+const roles = (opts: Record<string, unknown>): RolePlan => {+ const m = opts.models as SkillOptModels;+ const pick = (r: keyof SkillOptModels) => ({ model: m[r].model, source: m[r].source });+ return { optimizer: pick('optimizer'), target: pick('target'), judge: pick('judge') };+};++async function viaCli(args: string[] = []): Promise<Record<string, unknown>> {+ captured = [];+ try {+ await runSkillOptCommand(engine, [SKILL, '--skills-dir', skillsDir, '--json', ...args]);+ } catch (err) {+ if (!(err instanceof ExitSignal)) throw err;+ }+ return captured[0]!;+}++async function viaMcp(): Promise<Record<string, unknown>> {+ captured = [];+ const op = operations.find((o) => o.name === 'run_skillopt')!;+ await op.handler({ engine, config: {}, logger: console, dryRun: false, remote: false } as unknown as OperationContext, { skill_name: SKILL });+ return captured[0]!;+}++async function viaCycle(): Promise<Record<string, unknown>> {+ captured = [];+ await resetCycleState();+ await runPhaseSkillopt({ engine, once: true });+ return captured[0]!;+}++async function viaJob(flags: SkillOptModelFlags = {}): Promise<Record<string, unknown>> {+ captured = [];+ const data = buildSkillOptJobData({+ skillsDir, skillName: SKILL, benchmarkPath: path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl'),+ epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5], mode: 'patch', dryRun: false,+ noMutate: false, allowMutateBundled: false, bootstrapReviewed: false, maxCostUsd: 5, maxRuntimeMin: 30, force: false,+ models: await resolveSkillOptModels(engine, flags), modelFlags: flags, modelsStrict: false,+ });+ await runSkillOptJob(engine, JSON.parse(JSON.stringify(data)));+ return captured[0]!;+}++async function resetCycleState(): Promise<void> {+ await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'cycle.skillopt.%'`);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ fs.rmSync(skillsDir, { recursive: true, force: true });+ fs.rmSync(tmpHome, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetDeprecationWarningsForTest();+ stdout = '';+ exitCodes = [];+ process.stdout.write = ((c: string | Uint8Array) => { stdout += String(c); return true; }) as typeof process.stdout.write;+ process.stderr.write = (() => true) as typeof process.stderr.write;+ process.exit = ((code?: number) => { exitCodes.push(code ?? 0); throw new ExitSignal(); }) as typeof process.exit;+});++afterEach(() => {+ process.stdout.write = origWrite.out;+ process.stderr.write = origWrite.err;+ process.exit = origExit;+});++const MATRIX: Array<[string, Record<string, string>]> = [+ ['models.default set', { 'models.default': SONNET }],+ ['tiers set', { 'models.tier.deep': OPUS, 'models.tier.subagent': HAIKU, 'models.tier.reasoning': SONNET }],+ ['neither', {}],+];++describe('four-path golden role plans', () => {+ for (const [label, config] of MATRIX) {+ test(`${label}: CLI, MCP op, cycle phase and jobs handler hand runSkillOpt the same {model, source} plan`, async () => {+ await withEnv(ENV, async () => {+ for (const [k, v] of Object.entries(config)) await engine.setConfig(k, v);+ const cli = roles(await viaCli());+ expect(roles(await viaMcp())).toEqual(cli);+ expect(roles(await viaCycle())).toEqual(cli);+ expect(roles(await viaJob())).toEqual(cli);+ if (label === 'tiers set') expect(cli.optimizer).toEqual({ model: OPUS, source: 'tier_config' });+ if (label === 'models.default set') expect(cli.target).toEqual({ model: SONNET, source: 'models_default' });+ if (label === 'neither') expect(cli.judge.source).toBe('tier_default');+ });+ });+ }++ test('flag set: the CLI and its background job resolve the flag identically (source cli_flag)', async () => {+ await withEnv(ENV, async () => {+ await engine.setConfig('models.default', SONNET);+ const cli = roles(await viaCli(['--optimizer-model', 'opus']));+ expect(cli.optimizer).toEqual({ model: OPUS, source: 'cli_flag' });+ expect(roles(await viaJob({ optimizerModel: 'opus' }))).toEqual(cli);+ });+ });+});++describe('CLI strict + dry-run contract', () => {+ test('--models-strict parses and reaches runSkillOpt', async () => {+ expect(parseFlags([SKILL, '--models-strict']).modelsStrict).toBe(true);+ expect(parseFlags([SKILL]).modelsStrict).toBe(false);+ await withEnv(ENV, async () => {+ expect((await viaCli(['--models-strict'])).modelsStrict).toBe(true);+ });+ });++ test('--dry-run exits 0 when strict is off (verdict still reported) and 1 on a strict failure; --json carries the plan + verdict', async () => {+ await withEnv(ENV, async () => {+ await viaCli(['--dry-run']);+ expect(exitCodes[0]).toBe(0);+ const off = JSON.parse(stdout.trim());+ expect(off).toMatchObject({ dry_run: true, strict: { enabled: false, ok: false } });+ expect(off.models_plan).toHaveLength(1);++ stdout = '';+ exitCodes = [];+ await viaCli(['--dry-run', '--models-strict']);+ expect(exitCodes[0]).toBe(1);+ expect(JSON.parse(stdout.trim()).strict).toMatchObject({ enabled: true, ok: false });+ });+ });+});diff --git a/test/skillopt/models-plan.serial.test.ts b/test/skillopt/models-plan.serial.test.tsnew file mode 100644index 0000000000..049f160386--- /dev/null+++ b/test/skillopt/models-plan.serial.test.ts@@ -0,0 +1,321 @@+/**+ * #5585 — skillopt models plan: role resolution with provenance, task judge+ * overrides (benchmark + held-out), engine-internal touchpoints (expansion,+ * chat, embedding from the search column resolver, reranker when enabled),+ * the stderr banner, strict-mode verdict/value parsing and echo sanitizing.+ *+ * Serial lane: pins provider/home env vars and gateway module state.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { withEnv } from '../helpers/with-env.ts';+import { configureGateway, reconfigureGatewayWithEngine, resetGateway } from '../../src/core/ai/gateway.ts';+import { _resetDeprecationWarningsForTest, TIER_DEFAULTS } from '../../src/core/model-config.ts';+import { KNOWN_CONFIG_KEYS } from '../../src/core/config.ts';+import {+ buildModelsPlan,+ describeStrictVerdict,+ formatModelsBanner,+ modelsStrictError,+ parseModelsStrict,+ resolveModelsStrict,+ resolveSkillOptModels,+ sanitizeEcho,+ strictVerdict,+ unknownProvenanceModels,+ type ModelsPlanEntry,+} from '../../src/core/skillopt/models-plan.ts';+import { StructuredAgentError } from '../../src/core/errors.ts';+import type { BenchmarkTask } from '../../src/core/skillopt/types.ts';++const OPUS = 'anthropic:claude-opus-4-7';+const SONNET = 'anthropic:claude-sonnet-4-6';+const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++let engine: PGLiteEngine;+let tmpHome: string;+let stderr = '';+const origWrite = process.stderr.write.bind(process.stderr);++const ENV = () => ({+ GBRAIN_HOME: tmpHome, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined,+ GBRAIN_MODEL: undefined, GBRAIN_CHAT_MODEL: undefined, GBRAIN_EXPANSION_MODEL: undefined,+ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_MODEL_DISCOVERY: 'off',+});+const inEnv = <T>(fn: () => Promise<T>, extra: Record<string, string | undefined> = {}) => withEnv({ ...ENV(), ...extra }, fn);++const rule = (id: string): BenchmarkTask => ({ task_id: id, task: 't', judge: { kind: 'rule', checks: [{ op: 'contains', arg: 'x' }] } });+const llm = (id: string, model?: string): BenchmarkTask => ({ task_id: id, task: 't', judge: { kind: 'llm', rubric: 'r', ...(model ? { model } : {}) } });++async function explicitEverything(): Promise<void> {+ await engine.setConfig('models.tier.deep', OPUS);+ await engine.setConfig('models.tier.subagent', SONNET);+ await engine.setConfig('models.tier.reasoning', SONNET);+ await engine.setConfig('models.tier.utility', HAIKU);+ await engine.setConfig('models.chat', SONNET);+ await engine.setConfig('search.reranker.model', 'voyage:rerank-2.5');+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_model: 'openai:text-embedding-3-large' }));+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ await reconfigureGatewayWithEngine(engine);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ tmpHome = mkdtempSync(join(tmpdir(), 'skillopt-models-plan-'));+ resetGateway();+ _resetDeprecationWarningsForTest();+ stderr = '';+ process.stderr.write = ((c: string | Uint8Array) => { stderr += String(c); return true; }) as typeof process.stderr.write;+});++afterEach(() => {+ process.stderr.write = origWrite;+ resetGateway();+ rmSync(tmpHome, { recursive: true, force: true });+});++describe('resolveSkillOptModels', () => {+ test('flag > tier config > models.default > built-in default, each with its origin key', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.tier.deep', OPUS);+ await engine.setConfig('models.default', SONNET);+ const m = await resolveSkillOptModels(engine, { judgeModel: 'opus' });+ expect(m.optimizer).toEqual({ model: OPUS, source: 'tier_config', origin: 'models.tier.deep' });+ expect(m.target).toEqual({ model: SONNET, source: 'models_default', origin: 'models.default' });+ expect(m.judge).toEqual({ model: OPUS, source: 'cli_flag', origin: '--judge-model' });+ });+ await resetPgliteState(engine);+ await inEnv(async () => {+ const m = await resolveSkillOptModels(engine);+ expect(m.optimizer).toEqual({ model: TIER_DEFAULTS.deep, source: 'tier_default', origin: 'built-in default' });+ });+ });++ test('a subagent capability substitution is reported with the configured model and reason', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.tier.subagent', 'bogus-provider:some-model');+ const m = await resolveSkillOptModels(engine);+ expect(m.target).toEqual({+ model: TIER_DEFAULTS.subagent, source: 'tier_config', origin: 'models.tier.subagent',+ substituted_from: 'bogus-provider:some-model', substitution_reason: 'unknown_provider',+ });+ });+ });+});++describe('buildModelsPlan', () => {+ test('lists every touchpoint with sources; task judge overrides are listed with their task count', async () => {+ await inEnv(async () => {+ await explicitEverything();+ const models = await resolveSkillOptModels(engine);+ const plan = await buildModelsPlan(engine, models, [llm('a'), llm('b', 'openai:gpt-5.2'), llm('c', 'openai:gpt-5.2'), rule('d')]);+ expect(plan.map((e) => [e.touchpoint, e.model, e.source, e.active])).toEqual([+ ['optimizer', OPUS, 'tier_config', true],+ ['target', SONNET, 'tier_config', true],+ ['judge', SONNET, 'tier_config', true],+ ['judge', 'openai:gpt-5.2', 'benchmark', true],+ ['expansion', HAIKU, 'tier_config', true],+ ['chat', SONNET, 'config_key', true],+ ['embedding', 'openai:text-embedding-3-large', 'file_config', true],+ ['reranker', 'voyage:rerank-2.5', 'config_key', true],+ ]);+ expect(plan[3]!.origin).toBe('benchmark judge.model, 2 tasks');+ expect(strictVerdict(plan, { on: true })).toEqual({ enabled: true, ok: true, violations: [] });++ const banner = formatModelsBanner(plan, { skill: 'widget-example' });+ expect(banner).toContain('[skillopt] Models for widget-example:');+ expect(banner).toContain('[skillopt] optimizer anthropic:claude-opus-4-7 (models.tier.deep)\n');+ expect(banner).toContain('judge openai:gpt-5.2 (benchmark judge.model, 2 tasks)');+ expect(banner).toContain('embedding openai:text-embedding-3-large (embedding_model (config.json))');+ expect(banner).not.toContain(' *');+ });+ });++ test('rule-only benchmark marks the default judge inactive; an LLM-judged held-out task reactivates it', async () => {+ await inEnv(async () => {+ const models = await resolveSkillOptModels(engine);+ const ruleOnly = await buildModelsPlan(engine, models, [rule('a'), rule('b')]);+ const judge = ruleOnly.find((e) => e.touchpoint === 'judge')!;+ expect(judge).toMatchObject({ active: false, inactive_reason: 'rule/qrels benchmark' });+ expect(formatModelsBanner(ruleOnly)).toContain('(inactive: rule/qrels benchmark)');+ expect(strictVerdict(ruleOnly, { on: true }).violations.map((v) => v.touchpoint)).not.toContain('judge');++ const withHeldOut = await buildModelsPlan(engine, models, [rule('a'), llm('h1')]);+ expect(withHeldOut.find((e) => e.touchpoint === 'judge')!.active).toBe(true);++ const allOverridden = await buildModelsPlan(engine, models, [llm('a', 'openai:gpt-5.2')]);+ expect(allOverridden.find((e) => e.touchpoint === 'judge' && e.source !== 'benchmark')).toMatchObject({+ active: false, inactive_reason: 'every LLM task sets judge.model',+ });++ const unknownKind = await buildModelsPlan(engine, models, [{ task_id: 'x', task: 't', judge: { kind: 'vibes' } as never }]);+ expect(unknownKind.find((e) => e.touchpoint === 'judge')!.active).toBe(true);+ });+ });++ test('fallback sources are starred with a footnote; unresolved gateway provenance is unknown', async () => {+ await inEnv(async () => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ await engine.setConfig('models.default', SONNET);+ const plan = await buildModelsPlan(engine, await resolveSkillOptModels(engine));+ const banner = formatModelsBanner(plan);+ expect(banner).toContain('optimizer anthropic:claude-sonnet-4-6 (models.default) *');+ expect(banner).toContain('expansion anthropic:claude-haiku-4-5-20251001 (unrecorded: gateway not resolved against this brain) *');+ expect(banner).toContain('* not chosen by touchpoint-specific configuration');+ expect(plan.find((e) => e.touchpoint === 'expansion')!.source).toBe('unknown');+ });+ });++ test('embedding: a stale DB embedding_model row is never the source; a DB-selected column is', async () => {+ await inEnv(async () => {+ await engine.setConfig('embedding_model', 'voyage:voyage-3-large');+ const plain = await buildModelsPlan(engine, await resolveSkillOptModels(engine));+ const emb = plain.find((e) => e.touchpoint === 'embedding')!;+ expect(emb.model).not.toBe('voyage:voyage-3-large');+ expect(emb.source).toBe('fallback');++ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_voyage: { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' } }));+ await engine.setConfig('search_embedding_column', 'embedding_voyage');+ const col = (await buildModelsPlan(engine, await resolveSkillOptModels(engine))).find((e) => e.touchpoint === 'embedding')!;+ expect(col).toMatchObject({+ model: 'voyage:voyage-3-large', source: 'config_key',+ origin: 'search_embedding_column=embedding_voyage (embedding_columns)',+ });+ expect(strictVerdict([col], { on: true }).ok).toBe(true);+ });+ await resetPgliteState(engine);+ await inEnv(async () => {+ // An explicit override of the default column is configuration, not a fallback.+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding: { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' } }));+ const def = (await buildModelsPlan(engine, await resolveSkillOptModels(engine))).find((e) => e.touchpoint === 'embedding')!;+ expect(def).toMatchObject({ model: 'voyage:voyage-3-large', source: 'config_key', origin: 'embedding_columns.embedding' });+ expect(strictVerdict([def], { on: true }).ok).toBe(true);+ });+ await resetPgliteState(engine);+ await inEnv(async () => {+ const envEmb = (await buildModelsPlan(engine, await resolveSkillOptModels(engine))).find((e) => e.touchpoint === 'embedding')!;+ expect(envEmb).toMatchObject({ model: 'openai:text-embedding-3-large', source: 'env', origin: 'GBRAIN_EMBEDDING_MODEL' });+ }, { GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large' });+ });++ test('reranker appears only when search enables it; an explicit model is named', async () => {+ await inEnv(async () => {+ await engine.setConfig('search.reranker.enabled', 'false');+ const off = await buildModelsPlan(engine, await resolveSkillOptModels(engine));+ expect(off.some((e) => e.touchpoint === 'reranker')).toBe(false);++ await engine.setConfig('search.reranker.enabled', 'true');+ const def = (await buildModelsPlan(engine, await resolveSkillOptModels(engine))).find((e) => e.touchpoint === 'reranker')!;+ expect(def.source).toBe('fallback');+ expect(def.origin).toStartWith('built-in default, search.mode ');++ await engine.setConfig('search.reranker.model', 'voyage:rerank-2.5');+ const explicit = (await buildModelsPlan(engine, await resolveSkillOptModels(engine))).find((e) => e.touchpoint === 'reranker')!;+ expect(explicit).toMatchObject({ model: 'voyage:rerank-2.5', source: 'config_key', origin: 'search.reranker.model' });+ });+ });+});++describe('banner baseline (batch / cycle)', () => {+ test('only rows that differ from the invocation banner print; identical plans print nothing', async () => {+ await inEnv(async () => {+ const models = await resolveSkillOptModels(engine);+ const base = await buildModelsPlan(engine, models);+ expect(formatModelsBanner(base, { skill: 's', baseline: base })).toBe('');+ const ruleOnly = await buildModelsPlan(engine, models, [rule('a')]);+ const diff = formatModelsBanner(ruleOnly, { skill: 's', baseline: base });+ expect(diff).toContain('[skillopt] Models for s (differs from the run banner):');+ expect(diff).toContain('(inactive: rule/qrels benchmark)');+ expect(diff).not.toContain('optimizer');+ });+ });+});++describe('strict mode', () => {+ test('violations list each touchpoint with a copy-paste fix; embedding fix points at config.json/env, never config set', async () => {+ await inEnv(async () => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ await engine.setConfig('models.default', SONNET);+ await reconfigureGatewayWithEngine(engine);+ const plan = await buildModelsPlan(engine, await resolveSkillOptModels(engine));+ const verdict = strictVerdict(plan, { on: true });+ expect(verdict.ok).toBe(false);+ const fixes = Object.fromEntries(verdict.violations.map((v) => [v.touchpoint, v.fix]));+ expect(fixes.optimizer).toBe(`gbrain config set models.tier.deep ${SONNET}`);+ expect(fixes.target).toBe(`gbrain config set models.tier.subagent ${SONNET}`);+ expect(fixes.judge).toBe(`gbrain config set models.tier.reasoning ${SONNET}`);+ expect(fixes.expansion).toBe(`gbrain config set models.tier.utility ${SONNET}`);+ expect(fixes.chat).toBe(`gbrain config set models.chat ${SONNET}`);+ expect(fixes.embedding).toContain('~/.gbrain/config.json or export GBRAIN_EMBEDDING_MODEL=');+ expect(fixes.embedding).not.toContain('config set embedding_model');++ const err = modelsStrictError(verdict) as StructuredAgentError;+ expect(err.envelope.code).toBe('models_strict_violation');+ expect(err.envelope.message).toContain(' expansion anthropic:claude-sonnet-4-6 (models.default)');+ expect(err.envelope.message).toContain(` gbrain config set models.tier.utility ${SONNET}`);+ });+ });++ test('substitution and unknown provenance count as fallback; explicit sources pass', async () => {+ await inEnv(async () => {+ await engine.setConfig('models.tier.subagent', 'bogus-provider:some-model');+ const m = await resolveSkillOptModels(engine);+ const plan = await buildModelsPlan(engine, m);+ expect(strictVerdict(plan.filter((e) => e.touchpoint === 'target'), { on: true }).violations[0]!.fix)+ .toBe(`gbrain config set models.tier.subagent ${TIER_DEFAULTS.subagent}`);+ expect(formatModelsBanner(plan)).toContain('(models.tier.subagent -> substituted: unknown_provider; configured bogus-provider:some-model) *');++ const legacy = unknownProvenanceModels({ optimizerModel: OPUS, targetModel: SONNET, judgeModel: SONNET }, 'legacy job data');+ const legacyPlan: ModelsPlanEntry[] = [{ touchpoint: 'optimizer', ...legacy.optimizer, active: true }];+ expect(strictVerdict(legacyPlan, { on: true }).violations.map((v) => v.origin)).toEqual(['legacy job data']);+ });+ });++ test('value parsing: on/off spellings, unrecognized warns once, counts as on and is echoed sanitized', async () => {+ for (const v of ['true', '1', 'YES', ' on ']) expect(parseModelsStrict(v)).toEqual({ on: true });+ for (const v of ['false', '0', 'no', 'off', '', null, undefined]) expect(parseModelsStrict(v)).toEqual({ on: false });+ const odd = parseModelsStrict('maybe\n\u001b[31m');+ expect(odd).toEqual({ on: true, unrecognized: 'maybe[31m' });+ parseModelsStrict('maybe\n\u001b[31m');+ expect(stderr.match(/treating it as on/g)?.length).toBe(1);++ await engine.setConfig('skillopt.models_strict', 'sometimes');+ const strict = await resolveModelsStrict(engine);+ expect(strict).toEqual({ on: true, unrecognized: 'sometimes' });+ expect(await resolveModelsStrict(engine, true)).toEqual({ on: true });+ const text = describeStrictVerdict(strictVerdict([{ touchpoint: 'optimizer', model: OPUS, source: 'tier_default', origin: 'built-in default', active: true }], strict));+ expect(text).toContain("(skillopt.models_strict='sometimes' treated as on)");+ });++ test('an unreadable strict setting fails closed (on), never silently off', async () => {+ const throwing = { getConfig: async (): Promise<string | null> => { throw new Error('db down'); } };+ expect(await resolveModelsStrict(throwing as never)).toEqual({ on: true });+ expect(stderr).toContain('could not read skillopt.models_strict; treating strict mode as on');+ });++ test('skillopt.models_strict is a registered config key', () => {+ expect(KNOWN_CONFIG_KEYS).toContain('skillopt.models_strict');+ });+});++describe('sanitizeEcho', () => {+ test('strips control characters and newlines, caps at 200 chars', () => {+ expect(sanitizeEcho('a\nb\r\tc\u0000\u007f\u009bd')).toBe('abcd');+ expect(sanitizeEcho('x'.repeat(500))).toHaveLength(200);+ });+});diff --git a/test/skillopt/preflight-reservation.test.ts b/test/skillopt/preflight-reservation.test.tsnew file mode 100644index 0000000000..9ab6781c33--- /dev/null+++ b/test/skillopt/preflight-reservation.test.ts@@ -0,0 +1,88 @@+/**+ * #5585 — preflight's impossible-reservation check: each role's largest+ * single call priced exactly as BudgetTracker.reserve() prices it (shared+ * reservationCostUsd, effective output caps, same overrides, input 0), so a+ * call that can never fit the cap is refused before any spend, naming the role+ * and the control that fixes it. Expected cost stays a separate heuristic.+ */+import { describe, test, expect } from 'bun:test';+import { BudgetExhausted, BudgetTracker } from '../../src/core/budget/budget-tracker.ts';+import { preflight, formatPreflightReport, singleCallReservations, type PreflightOpts } from '../../src/core/skillopt/preflight.ts';++const OPUS5 = 'anthropic:claude-opus-5';+const FABLE = 'anthropic:claude-fable-5-1';+const HAIKU = 'anthropic:claude-haiku-4-5-20251001';++const base: PreflightOpts = {+ epochs: 1, batchSize: 4, trainSize: 8, selSize: 5, testSize: 5,+ optimizerModel: HAIKU, targetModel: HAIKU, judgeModel: HAIKU, maxCostUsd: 100,+};++describe('impossible single-call reservation', () => {+ test('thinking optimizer at the default reflect cap cannot fit a $0.50 cap: aborts naming role + control', () => {+ const r = preflight({ ...base, optimizerModel: OPUS5, maxCostUsd: 0.5 });+ expect(r.proceed).toBe(false);+ expect(r.abort_code).toBe('reservation_exceeds_cap');+ expect(r.abort_reason).toStartWith('reservation_exceeds_cap: a single optimizer call reserves $0.80 (anthropic:claude-opus-5, 32000 output tokens)');+ expect(r.abort_reason).toContain('--reflect-max-tokens / skillopt.reflect_max_tokens');+ });++ test('a lowered reflect cap admits the same run', () => {+ const r = preflight({ ...base, optimizerModel: OPUS5, reflectMaxTokens: 4096, maxCostUsd: 0.5 });+ expect(r.abort_code).not.toBe('reservation_exceeds_cap');+ });++ test('a task judge override is checked with the thinking judge floor and named as the judge role', () => {+ const r = preflight({ ...base, judgeModels: [HAIKU, FABLE], maxCostUsd: 0.3 });+ expect(r.abort_code).toBe('reservation_exceeds_cap');+ expect(r.abort_reason).toContain('a single judge call reserves $0.41 (anthropic:claude-fable-5-1, 8192 output tokens)');+ expect(r.abort_reason).toContain('--judge-model');+ });++ test('rule-only benchmark (no judge models): the judge is neither reserved nor priced', () => {+ const r = preflight({ ...base, judgeModels: [] });+ expect(r.estimate.judge_calls).toBe(0);+ expect(singleCallReservations({ ...base, judgeModels: [] }).map((c) => c.role)).toEqual(['optimizer', 'target']);+ });++ test('free local models and uncapped runs never trip; unpriced models are left to the run-time no_pricing contract', () => {+ expect(preflight({ ...base, optimizerModel: 'ollama:llama3', targetModel: 'ollama:llama3', judgeModel: 'ollama:llama3', maxCostUsd: 0.0001 }).abort_code)+ .not.toBe('reservation_exceeds_cap');+ expect(preflight({ ...base, optimizerModel: OPUS5, maxCostUsd: 0 }).proceed).toBe(true);+ const unpriced = singleCallReservations({ ...base, optimizerModel: 'litellm:mystery' });+ expect(unpriced[0]!.reservation_usd).toBeNull();+ });++ test('pricing overrides are honored', () => {+ const r = preflight({ ...base, optimizerModel: OPUS5, maxCostUsd: 0.5, pricingOverrides: { [OPUS5]: { input: 1, output: 1 } } });+ expect(r.abort_code).not.toBe('reservation_exceeds_cap');+ });++ test('the report shows expected cost and the per-call reservation requirement separately', () => {+ const est = preflight({ ...base, optimizerModel: OPUS5 }).estimate;+ const text = formatPreflightReport(est, { ...base, optimizerModel: OPUS5 });+ expect(text).toContain('Est. cost:');+ expect(text).toContain('Per call: largest single call reserves $0.80 (optimizer anthropic:claude-opus-5, 32000 output tokens)');+ });+});++describe('parity with BudgetTracker.reserve()', () => {+ const cases: Array<[string, number, number]> = [+ [OPUS5, 32000, 0.5], [OPUS5, 32000, 0.9], [FABLE, 8192, 0.4], [FABLE, 8192, 0.42], [HAIKU, 4096, 0.01], ['ollama:llama3', 32000, 0.0001],+ ];+ for (const [model, maxOut, cap] of cases) {+ test(`${model} ${maxOut} tokens vs $${cap}`, () => {+ const reservation = singleCallReservations({ ...base, optimizerModel: model, reflectMaxTokens: maxOut })[0]!;+ const impossible = reservation.reservation_usd !== null && reservation.reservation_usd > cap;+ const tracker = new BudgetTracker({ maxCostUsd: cap, label: 'parity' });+ let threw = false;+ try {+ tracker.reserve({ modelId: model, estimatedInputTokens: 0, maxOutputTokens: maxOut, kind: 'chat' });+ } catch (err) {+ expect(err).toBeInstanceOf(BudgetExhausted);+ threw = true;+ }+ expect(threw).toBe(impossible);+ });+ }+});diff --git a/test/skillopt/reflect-fail-loud.test.ts b/test/skillopt/reflect-fail-loud.test.tsnew file mode 100644index 0000000000..740a7eb6a6--- /dev/null+++ b/test/skillopt/reflect-fail-loud.test.ts@@ -0,0 +1,259 @@+/**+ * #5584 — reflect fails loud instead of silently proposing zero edits.+ *+ * Pins, through the real runReflect / runOneShotRewrite with a stubbed chat:+ * - the output cap is threaded (Claude 5 32000, non-thinking 4096, explicit+ * override sent verbatim even below the default);+ * - each reflect call yields edits, a deliberate empty, or EXACTLY ONE error+ * with the documented precedence (truncated > empty_reply >+ * no_parseable_edits > invalid_edits), fenced empty is deliberate;+ * - context budgeting (whole 33 KB body for a 1M window, disclosure ++ * truncation record when it cannot fit, context_too_small with zero calls,+ * provider context errors mapped, bounded rejected history, unknown window);+ * - one-shot guards (length stop, cap too small, truncated body) never+ * return a body and never call chat when refusing;+ * - budget exhaustion is rethrown, never converted to a reflect error.+ */++import { describe, expect, test } from 'bun:test';+import { runReflect, runOneShotRewrite } from '../../src/core/skillopt/reflect.ts';+import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import type { ScoredRollout } from '../../src/core/skillopt/types.ts';++const THINKING = 'anthropic:claude-fable-5-1'; // 1M window, thinking+const PLAIN = 'anthropic:claude-opus-4-7'; // 1M window, non-thinking+const SMALL_WINDOW = 'anthropic:claude-sonnet-4-6'; // 200k window+const UNKNOWN_WINDOW = 'stub:unregistered-model';++type ChatFn = NonNullable<Parameters<typeof runReflect>[0]['chatFn']>;++function scored(id: string, score: number): ScoredRollout {+ return {+ trajectory: {+ task_id: id, task: `Task ${id}`, final_text: `output ${id}`, tool_calls: [],+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ turns: 1, stop_reason: 'end', duration_ms: 1,+ },+ score,+ };+}++function reply(text: string, stopReason: ChatResult['stopReason'] = 'end', outputTokens = 20): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason,+ usage: { input_tokens: 100, output_tokens: outputTokens, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: PLAIN, providerId: 'anthropic',+ };+}++function recorder(fn: (opts: ChatOpts) => ChatResult | Promise<ChatResult>): { chatFn: ChatFn; calls: ChatOpts[] } {+ const calls: ChatOpts[] = [];+ return { calls, chatFn: (async (opts: ChatOpts) => { calls.push(opts); return fn(opts); }) as ChatFn };+}++const userMsg = (o: ChatOpts): string => o.messages[0]!.content as string;++const FAILURE_ONLY = { successes: [] as ScoredRollout[], failures: [scored('f', 0)], rejected: [] };+const EDIT = { op: 'add', anchor: 'People', content: 'More.' };++describe('reflect output cap', () => {+ test('Claude 5 optimizer defaults to 32000; non-thinking to 4096; explicit override verbatim', async () => {+ for (const [model, maxTokens, expected] of [[THINKING, undefined, 32000], [PLAIN, undefined, 4096], [THINKING, 1000, 1000]] as const) {+ const r = recorder(() => reply('{"edits":[]}'));+ await runReflect({ skillBodyText: '# S', ...FAILURE_ONLY, optimizerModel: model, ...(maxTokens ? { maxTokens } : {}), chatFn: r.chatFn });+ expect(r.calls[0]!.maxTokens).toBe(expected);+ }+ });+});++describe('reflect reply classification (exactly one error per call)', () => {+ async function classify(text: string, stop: ChatResult['stopReason'] = 'end') {+ const r = recorder(() => reply(text, stop, 777));+ return runReflect({ skillBodyText: '# S\n## People\n', ...FAILURE_ONLY, optimizerModel: PLAIN, chatFn: r.chatFn });+ }++ test('length stop mid-JSON -> one truncated error naming tokens + cap', async () => {+ const res = await classify('{"edits":[{"op":"add",', 'length');+ expect(res.errors).toEqual(['reflect_failure_truncated: 777 output tokens, max_tokens=4096']);+ expect(res.failureEdits).toEqual([]);+ expect(res.calls).toBe(1);+ expect(res.usableReplies).toBe(0);+ });++ test('length stop drops even parseable edits (the array may be cut short)', async () => {+ const res = await classify(JSON.stringify({ edits: [EDIT] }), 'length');+ expect(res.failureEdits).toEqual([]);+ expect(res.errors).toHaveLength(1);+ expect(res.errors[0]).toStartWith('reflect_failure_truncated');+ });++ test('length stop + all-invalid edits -> truncated wins (one error)', async () => {+ const res = await classify(JSON.stringify({ edits: [{ op: 'bogus' }] }), 'length');+ expect(res.errors).toHaveLength(1);+ expect(res.errors[0]).toStartWith('reflect_failure_truncated');+ });++ test('empty / whitespace reply -> empty_reply', async () => {+ const res = await classify(' \n ');+ expect(res.errors).toEqual(['reflect_failure_empty_reply: stop=end']);+ expect(res.usableReplies).toBe(0);+ });++ test('prose with no edits array -> no_parseable_edits', async () => {+ const res = await classify('I think the skill is fine as it is.');+ expect(res.errors).toEqual(['reflect_failure_no_parseable_edits: 777 output tokens, stop=end']);+ });++ test('every proposed edit invalid -> invalid_edits', async () => {+ const res = await classify(JSON.stringify({ edits: [{ op: 'add' }, { op: 'rename', target: 'x' }] }));+ expect(res.errors).toEqual(['reflect_failure_invalid_edits: 2 proposed, 0 valid']);+ });++ test('partial drop -> no error, valid edits kept, dropped count reported', async () => {+ const res = await classify(JSON.stringify({ edits: [EDIT, { op: 'add' }] }));+ expect(res.errors).toEqual([]);+ expect(res.failureEdits).toHaveLength(1);+ expect(res.invalidEditsDropped).toBe(1);+ expect(res.usableReplies).toBe(1);+ });++ test('deliberate {"edits": []} and its fenced form are silent + usable', async () => {+ for (const text of ['{"edits": []}', '```json\n{"edits": []}\n```']) {+ const res = await classify(text);+ expect(res.errors).toEqual([]);+ expect(res.usableReplies).toBe(1);+ expect(res.calls).toBe(1);+ }+ });++ test('both modes errored -> two errors, zero usable replies', async () => {+ const r = recorder(() => reply('nope'));+ const res = await runReflect({ skillBodyText: '# S', successes: [scored('s', 1)], failures: [scored('f', 0)], rejected: [], optimizerModel: PLAIN, chatFn: r.chatFn });+ expect(res.calls).toBe(2);+ expect(res.usableReplies).toBe(0);+ expect(res.errors.map((e) => e.split(':')[0])).toEqual(['reflect_failure_no_parseable_edits', 'reflect_success_no_parseable_edits']);+ });+});++describe('reflect context budgeting', () => {+ const BIG_BODY = '# Skill\n' + 'x'.repeat(33_000) + '\nTAIL-MARKER';++ test('33 KB body is sent whole to a 1M-context optimizer', async () => {+ const r = recorder(() => reply('{"edits":[]}'));+ const res = await runReflect({ skillBodyText: BIG_BODY, ...FAILURE_ONLY, optimizerModel: PLAIN, chatFn: r.chatFn });+ expect(userMsg(r.calls[0]!)).toContain('TAIL-MARKER');+ expect(userMsg(r.calls[0]!)).not.toContain('skill body truncated');+ expect(res.skillBodyTruncated).toBeUndefined();+ });++ test('body that cannot fit is truncated WITH disclosure + truncation record', async () => {+ const r = recorder(() => reply('{"edits":[]}'));+ // 200k window minus a 190k output cap leaves ~10k tokens (~30k chars) of room.+ const res = await runReflect({ skillBodyText: BIG_BODY, ...FAILURE_ONLY, optimizerModel: SMALL_WINDOW, maxTokens: 190_000, chatFn: r.chatFn });+ const msg = userMsg(r.calls[0]!);+ expect(msg).not.toContain('TAIL-MARKER');+ expect(res.skillBodyTruncated!.total_chars).toBe(BIG_BODY.length);+ expect(res.skillBodyTruncated!.sent_chars).toBeLessThan(BIG_BODY.length);+ expect(msg).toContain(`(skill body truncated: sent ${res.skillBodyTruncated!.sent_chars} of ${BIG_BODY.length} chars)`);+ });++ test('output cap larger than the window -> context_too_small, zero chat calls', async () => {+ const r = recorder(() => reply('{"edits":[]}'));+ const res = await runReflect({ skillBodyText: '# S', ...FAILURE_ONLY, optimizerModel: SMALL_WINDOW, maxTokens: 300_000, chatFn: r.chatFn });+ expect(r.calls).toHaveLength(0);+ expect(res.errors).toHaveLength(1);+ expect(res.errors[0]).toMatch(/^reflect_failure_context_too_small: need \d+, window 200000$/);+ expect(res.calls).toBe(1);+ expect(res.usableReplies).toBe(0);+ });++ test('unknown context window -> 120k-char body cap with disclosure', async () => {+ const r = recorder(() => reply('{"edits":[]}'));+ const huge = 'y'.repeat(130_000);+ const res = await runReflect({ skillBodyText: huge, ...FAILURE_ONLY, optimizerModel: UNKNOWN_WINDOW, chatFn: r.chatFn });+ expect(res.skillBodyTruncated).toEqual({ sent_chars: 120_000, total_chars: 130_000 });+ expect(userMsg(r.calls[0]!)).toContain('(skill body truncated: sent 120000 of 130000 chars)');+ });++ test('oversized rejected-edit history is bounded', async () => {+ const r = recorder(() => reply('{"edits":[]}'));+ const rejected = Array.from({ length: 20 }, (_, i) => ({+ key: `k${i}`, skill_sha8: 'deadbeef', reason: 'validation_gate_below_baseline', ts: '2026-01-01T00:00:00Z',+ edits: [{ op: 'add' as const, anchor: 'A', content: 'z'.repeat(5000) }],+ }));+ await runReflect({ skillBodyText: '# S', successes: [], failures: [scored('f', 0)], rejected, optimizerModel: PLAIN, chatFn: r.chatFn });+ const msg = userMsg(r.calls[0]!);+ expect(msg).toContain('PREVIOUSLY REJECTED EDITS');+ expect(msg.length).toBeLessThan(10_000);+ });++ test('provider context-length rejection -> context_overflow', async () => {+ const r = recorder(() => { throw new Error('prompt is too long: 1707509 tokens > 1000000 maximum'); });+ const res = await runReflect({ skillBodyText: '# S', ...FAILURE_ONLY, optimizerModel: PLAIN, chatFn: r.chatFn });+ expect(res.errors).toHaveLength(1);+ expect(res.errors[0]).toStartWith('reflect_failure_context_overflow: prompt is too long');+ });+});++describe('reflect must-abort rethrow', () => {+ const exhausted = () => new BudgetExhausted('skillopt:x: projected cost $2 exceeds --max-cost $1.00', { reason: 'cost', spent: 0.5, cap: 1 });++ test('BudgetExhausted from the optimizer call propagates (not a reflect error)', async () => {+ const r = recorder(() => { throw exhausted(); });+ await expect(runReflect({ skillBodyText: '# S', ...FAILURE_ONLY, optimizerModel: PLAIN, chatFn: r.chatFn })).rejects.toBeInstanceOf(BudgetExhausted);+ });++ test('exhaustion after one successful reflect call still propagates', async () => {+ let n = 0;+ const r = recorder(() => { n += 1; if (n === 2) throw exhausted(); return reply(JSON.stringify({ edits: [EDIT] })); });+ await expect(runReflect({ skillBodyText: '# S\n## People\n', successes: [scored('s', 1)], failures: [scored('f', 0)], rejected: [], optimizerModel: PLAIN, chatFn: r.chatFn }))+ .rejects.toBeInstanceOf(BudgetExhausted);+ expect(r.calls).toHaveLength(2);+ });++ test('runtime-deadline error propagates', async () => {+ const r = recorder(() => { throw new Error('skillopt_runtime_exceeded'); });+ await expect(runReflect({ skillBodyText: '# S', ...FAILURE_ONLY, optimizerModel: PLAIN, chatFn: r.chatFn })).rejects.toThrow('skillopt_runtime_exceeded');+ });+});++describe('one-shot rewrite guards', () => {+ const BASE = { successes: [] as ScoredRollout[], failures: [scored('f', 0)], rejected: [], optimizerModel: PLAIN };++ test('length stop -> one_shot_rewrite_truncated, no body returned', async () => {+ const r = recorder(() => reply('# Skill\n## People\nhalf a rewr', 'length', 4096));+ const res = await runOneShotRewrite({ ...BASE, skillBodyText: '# Skill', chatFn: r.chatFn });+ expect(res.newBody).toBe('');+ expect(res.error).toBe('one_shot_rewrite_truncated: 4096 output tokens, max_tokens=4096');+ });++ test('body too large for the cap -> refuses without calling chat', async () => {+ const r = recorder(() => reply('# never'));+ const res = await runOneShotRewrite({ ...BASE, skillBodyText: 'b'.repeat(33_000), chatFn: r.chatFn });+ expect(r.calls).toHaveLength(0);+ expect(res.newBody).toBe('');+ expect(res.error).toBe('one_shot_rewrite_output_cap_too_small: need ~12024 tokens, cap 4096; set skillopt.reflect_max_tokens');+ });++ test('truncated body -> refuses (one_shot_rewrite_body_truncated) without calling chat', async () => {+ const r = recorder(() => reply('# never'));+ const res = await runOneShotRewrite({ ...BASE, optimizerModel: UNKNOWN_WINDOW, maxTokens: 100_000, skillBodyText: 'b'.repeat(130_000), chatFn: r.chatFn });+ expect(r.calls).toHaveLength(0);+ expect(res.error).toBe('one_shot_rewrite_body_truncated: sent 120000 of 130000 chars');+ });++ test('empty reply -> one_shot_rewrite_empty_reply', async () => {+ const r = recorder(() => reply(' '));+ const res = await runOneShotRewrite({ ...BASE, skillBodyText: '# Skill', chatFn: r.chatFn });+ expect(res.error).toBe('one_shot_rewrite_empty_reply: stop=end');+ });++ test('cap threaded from opts and BudgetExhausted rethrown', async () => {+ const ok = recorder(() => reply('# Skill\n## People\n'));+ await runOneShotRewrite({ ...BASE, skillBodyText: '# Skill', maxTokens: 5000, chatFn: ok.chatFn });+ expect(ok.calls[0]!.maxTokens).toBe(5000);+ const boom = recorder(() => { throw new BudgetExhausted('cap', { reason: 'cost', spent: 0, cap: 1 }); });+ await expect(runOneShotRewrite({ ...BASE, skillBodyText: '# Skill', chatFn: boom.chatFn })).rejects.toBeInstanceOf(BudgetExhausted);+ });+});diff --git a/test/skillopt/run-outcome.test.ts b/test/skillopt/run-outcome.test.tsnew file mode 100644index 0000000000..8a7709b83c--- /dev/null+++ b/test/skillopt/run-outcome.test.ts@@ -0,0 +1,399 @@+/**+ * #5584 — truthful outcome, remediation, output caps and resume correctness+ * (pure helpers; the orchestrator wiring is pinned in+ * test/e2e/skillopt-outcome.serial.test.ts).+ */++import { describe, expect, test } from 'bun:test';+import {+ clampRemoteReflectMaxTokens,+ resolveReflectMaxTokens,+ skilloptOutputCap,+} from '../../src/core/skillopt/output-cap.ts';+import {+ buildRemediation,+ errorCode,+ recordReflectError,+ SKILLOPT_REMEDIATION_CODES,+} from '../../src/core/skillopt/remediation.ts';+import {+ buildResumeCommand,+ recordOptimizerStep,+ resolveRunOutcome,+ shouldEarlyStop,+} from '../../src/core/skillopt/run-outcome.ts';+import {+ advanceCursor,+ assertResumeCompatible,+ rewindCursor,+ emptyTally,+ resumeCursor,+ type RunCheckpoint,+ type RunSpec,+} from '../../src/core/skillopt/checkpoint.ts';+import { formatRunSummary, parseFlags } from '../../src/commands/skillopt.ts';+import type { RunReceipt } from '../../src/core/skillopt/types.ts';+import { KNOWN_CONFIG_KEYS } from '../../src/core/config.ts';+import { isSkilloptMustAbort } from '../../src/core/skillopt/must-abort.ts';+import { invokeAI, withAIInvocationGuard } from '../../src/core/ai/invocation-guard.ts';++const THINKING = 'anthropic:claude-opus-5';+const PLAIN = 'anthropic:claude-sonnet-4-6';++function fakeEngine(value: string | null) {+ return { getConfig: async () => value };+}++describe('skilloptOutputCap (judge / bootstrap headroom)', () => {+ test('Claude 5 judge gets the 8192 thinking floor; non-thinking keeps the site cap', () => {+ expect(skilloptOutputCap(THINKING, 200)).toBe(8192);+ expect(skilloptOutputCap(PLAIN, 200)).toBe(200);+ expect(skilloptOutputCap(THINKING, 10_000)).toBe(10_000);+ });+});++describe('reflect cap resolution (flag > config > default)', () => {+ test('skillopt.reflect_max_tokens is a registered config key (config set accepts it without --force)', () => {+ expect(KNOWN_CONFIG_KEYS).toContain('skillopt.reflect_max_tokens');+ });++ test('default is 32000 for thinking optimizers, 4096 otherwise', async () => {+ expect(await resolveReflectMaxTokens(fakeEngine(null), THINKING)).toEqual({ maxTokens: 32000, source: 'default' });+ expect(await resolveReflectMaxTokens(fakeEngine(null), PLAIN)).toEqual({ maxTokens: 4096, source: 'default' });+ });++ test('config is honored exactly, including below the default', async () => {+ expect(await resolveReflectMaxTokens(fakeEngine('1500'), THINKING)).toEqual({ maxTokens: 1500, source: 'config' });+ });++ test('explicit value beats config', async () => {+ expect(await resolveReflectMaxTokens(fakeEngine('1500'), THINKING, 9000)).toEqual({ maxTokens: 9000, source: 'flag' });+ });++ test('invalid config value falls back to the default', async () => {+ expect(await resolveReflectMaxTokens(fakeEngine('lots'), PLAIN)).toEqual({ maxTokens: 4096, source: 'default' });+ expect(await resolveReflectMaxTokens(fakeEngine('-5'), PLAIN)).toEqual({ maxTokens: 4096, source: 'default' });+ });++ test('unreadable config falls back to the default', async () => {+ const throwing = { getConfig: async (): Promise<string | null> => { throw new Error('db down'); } };+ expect(await resolveReflectMaxTokens(throwing, THINKING)).toEqual({ maxTokens: 32000, source: 'default' });+ });++ test('remote values are validated and clamped to [256, 32000]', () => {+ expect(clampRemoteReflectMaxTokens(undefined)).toBeUndefined();+ expect(clampRemoteReflectMaxTokens(10_000_000)).toBe(32000);+ expect(clampRemoteReflectMaxTokens(1)).toBe(256);+ expect(clampRemoteReflectMaxTokens(8000)).toBe(8000);+ expect(() => clampRemoteReflectMaxTokens(-1)).toThrow(/positive integer/);+ expect(() => clampRemoteReflectMaxTokens(1.5)).toThrow(/positive integer/);+ expect(() => clampRemoteReflectMaxTokens('abc')).toThrow(/positive integer/);+ });+});++describe('remediation', () => {+ test('Object.prototype keys are not remediation codes', () => {+ for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {+ expect(errorCode(`${k}: boom`)).toBeUndefined();+ expect(buildRemediation([`${k}: boom`])).toEqual([]);+ }+ });++ test('every emitted code class maps to a remediation entry with a docs anchor', () => {+ const emitted = [+ 'reflect_failure_truncated: 2048 output tokens, max_tokens=2048',+ 'reflect_success_empty_reply: stop=end',+ 'reflect_failure_no_parseable_edits: 12 output tokens, stop=end',+ 'reflect_failure_invalid_edits: 2 proposed, 0 valid',+ 'reflect_failure_context_too_small: need 1, window 0',+ 'reflect_failure_context_overflow: prompt is too long',+ 'reflect_failure_failed: 500',+ 'one_shot_rewrite_truncated: 1 output tokens, max_tokens=1',+ 'one_shot_rewrite_output_cap_too_small: need ~1 tokens, cap 1; set skillopt.reflect_max_tokens',+ 'one_shot_rewrite_body_truncated: sent 0 of 1 chars',+ 'one_shot_rewrite_empty_reply: stop=end',+ 'one_shot_rewrite_failed: boom',+ 'reservation_exceeds_cap',+ ];+ const entries = buildRemediation(emitted, 'budget_exhausted');+ const codes = entries.map((e) => e.code);+ expect(new Set(codes)).toEqual(new Set(SKILLOPT_REMEDIATION_CODES.filter((c) => c !== 'runtime_exceeded')));+ for (const e of entries) {+ expect(e.docs).toBe(`docs/guides/skillopt.md#${e.code}`);+ expect(e.fix.length).toBeGreaterThan(10);+ }+ expect(entries.find((e) => e.code === 'reflect_truncated')!.fix).toContain('--reflect-max-tokens');+ expect(entries.find((e) => e.code === 'reflect_invalid_edits')!.fix).toContain('--optimizer-model');+ const budget = entries.find((e) => e.code === 'budget_exhausted')!.fix;+ expect(budget).toContain('--max-cost-usd');+ expect(budget).toContain('cycle.skillopt.per_skill_cap_usd');+ });++ test('one entry per distinct code (both reflect modes collapse); abort_detail prefix unwrapped', () => {+ const entries = buildRemediation([+ 'reflect_failure_truncated: a',+ 'reflect_success_truncated: b',+ 'optimizer_output_unusable: reflect_failure_truncated: a',+ ]);+ expect(entries.map((e) => e.code)).toEqual(['reflect_truncated']);+ expect(errorCode('something unrelated: x')).toBeUndefined();+ });++ test('receipt error list is deduped and capped (20 x 300 chars)', () => {+ const list: string[] = [];+ recordReflectError(list, 'dup');+ recordReflectError(list, 'dup');+ recordReflectError(list, 'x'.repeat(500));+ expect(list).toEqual(['dup', 'x'.repeat(300)]);+ for (let i = 0; i < 30; i++) recordReflectError(list, `e${i}`);+ expect(list).toHaveLength(20);+ });+});++describe('outcome precedence + early stop', () => {+ const unusable = (err: string) => ({ calls: 2, usableReplies: 0, errors: [err, err], invalidEditsDropped: 0 });+ const usable = { calls: 2, usableReplies: 1, errors: ['reflect_success_truncated: x'], invalidEditsDropped: 1 };++ test('early stop after 2 consecutive fully-unusable steps of ANY class; usable step resets', () => {+ const t = emptyTally();+ expect(recordOptimizerStep(t, unusable('reflect_failure_truncated: a'))).toBe(true);+ expect(shouldEarlyStop(t)).toBe(false);+ recordOptimizerStep(t, usable);+ expect(t.unusable_streak).toBe(0);+ recordOptimizerStep(t, unusable('reflect_failure_truncated: a'));+ recordOptimizerStep(t, unusable('reflect_failure_invalid_edits: 2 proposed, 0 valid'));+ expect(shouldEarlyStop(t)).toBe(true);+ expect(t.invalid_edits_dropped).toBe(1);+ });++ test('a step with no optimizer calls neither counts nor resets the streak', () => {+ const t = emptyTally();+ recordOptimizerStep(t, unusable('reflect_failure_truncated: a'));+ expect(recordOptimizerStep(t, { calls: 0, usableReplies: 0, errors: [], invalidEditsDropped: 0 })).toBe(false);+ expect(t.unusable_streak).toBe(1);+ });++ test('mixed classes, all unusable -> errored optimizer_output_unusable with the first error', () => {+ const t = emptyTally();+ recordOptimizerStep(t, unusable('reflect_failure_truncated: 2048 output tokens, max_tokens=2048'));+ recordOptimizerStep(t, unusable('reflect_failure_no_parseable_edits: 3 output tokens, stop=end'));+ const r = resolveRunOutcome({ tally: t, earlyStopped: true });+ expect(r).toEqual({+ outcome: 'errored',+ stopReason: 'early_stop_unusable_output',+ abortReason: 'error',+ abortDetail: 'optimizer_output_unusable: reflect_failure_truncated: 2048 output tokens, max_tokens=2048',+ });+ });++ test('accepted step then early stop -> accepted (acceptance history wins)', () => {+ const t = emptyTally();+ recordOptimizerStep(t, { calls: 1, usableReplies: 1, errors: [], invalidEditsDropped: 0 });+ t.accepted_steps = 1;+ recordOptimizerStep(t, unusable('reflect_success_truncated: a'));+ recordOptimizerStep(t, unusable('reflect_success_truncated: a'));+ expect(resolveRunOutcome({ tally: t, earlyStopped: true })).toEqual({ outcome: 'accepted', stopReason: 'early_stop_unusable_output' });+ });++ test('one usable reply -> no_improvement; zero optimizer calls -> no_improvement', () => {+ const t = emptyTally();+ recordOptimizerStep(t, usable);+ expect(resolveRunOutcome({ tally: t, earlyStopped: false }).outcome).toBe('no_improvement');+ expect(resolveRunOutcome({ tally: emptyTally(), earlyStopped: false }).outcome).toBe('no_improvement');+ });++ test('caught abort wins over everything', () => {+ const t = emptyTally();+ t.accepted_steps = 1;+ const r = resolveRunOutcome({ tally: t, earlyStopped: false, caught: { outcome: 'aborted', abortReason: 'budget_exhausted', abortDetail: 'cap' } });+ expect(r).toEqual({ outcome: 'aborted', stopReason: 'aborted', abortReason: 'budget_exhausted', abortDetail: 'cap' });+ });+});++const SPEC: RunSpec = {+ skills_dir: '/tmp/my skills',+ benchmark_path: '/tmp/my skills/demo/skillopt-benchmark.jsonl',+ benchmark_sha8: 'aaaa1111',+ held_out_path: null,+ held_out_sha8: null,+ split: [4, 1, 5],+ mutate: false,+ no_mutate: true,+ allow_mutate_bundled: false,+ bootstrap_reviewed: false,+ optimizer_model: THINKING,+ target_model: PLAIN,+ judge_model: PLAIN,+ epochs: 2,+ batch_size: 4,+ lr: 4,+ lr_schedule: 'cosine',+ reflect_max_tokens: 32000,+};++function checkpoint(over: Partial<RunCheckpoint> = {}): RunCheckpoint {+ return {+ schema: 1, run_id: 'run-1', skill: 'demo', skill_sha8: 's', benchmark_sha8: SPEC.benchmark_sha8,+ optimizer_model: THINKING, target_model: PLAIN, judge_model: PLAIN, epochs: 2, batch_size: 4, lr: 4,+ lr_schedule: 'cosine', best_sel_score: 0.5, best_skill_text: 'x', last_completed_epoch: 0,+ last_completed_step: 0, cumulative_cost_usd: 0, started_at: '', last_updated_at: '', ...over,+ };+}++describe('resume cursor', () => {+ test('legacy checkpoints convert: step 0 / full epoch -> next epoch, else same epoch next step', () => {+ expect(resumeCursor(checkpoint({ last_completed_epoch: 1, last_completed_step: 0 }), 5)).toEqual({ epoch: 2, step: 1 });+ expect(resumeCursor(checkpoint({ last_completed_epoch: 1, last_completed_step: 5 }), 5)).toEqual({ epoch: 2, step: 1 });+ expect(resumeCursor(checkpoint({ last_completed_epoch: 1, last_completed_step: 2 }), 5)).toEqual({ epoch: 1, step: 3 });+ expect(resumeCursor(checkpoint(), 5)).toEqual({ epoch: 1, step: 1 });+ });++ test('advanceCursor moves past a completed step, rolling to the next epoch at the end', () => {+ const cp = checkpoint();+ advanceCursor(cp, 1, 2, 5);+ expect(resumeCursor(cp, 5)).toEqual({ epoch: 1, step: 3 });+ expect(cp.last_completed_epoch).toBe(0);+ advanceCursor(cp, 1, 5, 5);+ expect(resumeCursor(cp, 5)).toEqual({ epoch: 2, step: 1 });+ expect(cp.last_completed_epoch).toBe(1);+ });+});++describe('resume spec refusal', () => {+ const stored = checkpoint({ run_spec: SPEC });++ test('changed benchmark / held-out / split / target / batch size refused naming the field', () => {+ for (const [field, value] of [+ ['benchmark_sha8', 'bbbb2222'], ['held_out_sha8', 'cccc3333'], ['split', [1, 1, 1]],+ ['target_model', 'openai:gpt-4o'], ['judge_model', 'openai:gpt-4o'], ['batch_size', 8],+ ] as const) {+ expect(() => assertResumeCompatible(stored, { ...SPEC, [field]: value } as RunSpec)).toThrow(new RegExp(`${field} changed`));+ }+ });++ test('mutate widening (no-mutate -> mutate) refused; narrowing allowed', () => {+ expect(() => assertResumeCompatible(stored, { ...SPEC, mutate: true, no_mutate: false })).toThrow(/mutate policy changed/);+ expect(() => assertResumeCompatible(checkpoint({ run_spec: { ...SPEC, mutate: true } }), SPEC)).not.toThrow();+ });++ test('optimizer model, reflect cap and epochs may change', () => {+ expect(() => assertResumeCompatible(stored, { ...SPEC, optimizer_model: 'openai:gpt-5', reflect_max_tokens: 64000, epochs: 4 })).not.toThrow();+ });++ test('legacy checkpoint without a spec still refuses a changed benchmark', () => {+ expect(() => assertResumeCompatible(checkpoint(), { ...SPEC, benchmark_sha8: 'bbbb2222' })).toThrow(/benchmark_sha8 changed/);+ expect(() => assertResumeCompatible(checkpoint(), SPEC)).not.toThrow();+ });+});++describe('rewindCursor', () => {+ test('steps back across epoch boundaries and never before the first step', () => {+ expect(rewindCursor({ epoch: 1, step: 4 }, 2, 10)).toEqual({ epoch: 1, step: 2 });+ expect(rewindCursor({ epoch: 2, step: 1 }, 2, 10)).toEqual({ epoch: 1, step: 9 });+ expect(rewindCursor({ epoch: 2, step: 1 }, 1, 1)).toEqual({ epoch: 1, step: 1 });+ expect(rewindCursor({ epoch: 1, step: 2 }, 5, 10)).toEqual({ epoch: 1, step: 1 });+ expect(rewindCursor({ epoch: 3, step: 2 }, 0, 10)).toEqual({ epoch: 3, step: 2 });+ });+});++describe('resume command', () => {+ test('rebuilt from the stored spec; truncation doubles the cap; paths quoted', () => {+ const cmd = buildResumeCommand('demo', 'run-1', SPEC, 'reflect_truncated');+ expect(cmd).toStartWith('gbrain skillopt demo --resume run-1 ');+ expect(cmd).toContain(`--skills-dir '/tmp/my skills'`);+ expect(cmd).toContain(`--benchmark '/tmp/my skills/demo/skillopt-benchmark.jsonl'`);+ expect(cmd).toContain('--split 4:1:5 --epochs 2 --batch-size 4 --lr 4 --lr-schedule cosine');+ expect(cmd).toContain(`--optimizer-model ${THINKING}`);+ expect(cmd).toContain('--reflect-max-tokens 64000');+ expect(cmd).toContain('--no-mutate');+ });++ test('contract class swaps in an --optimizer-model placeholder; other failures keep the cap', () => {+ const cmd = buildResumeCommand('demo', 'run-1', SPEC, 'reflect_invalid_edits');+ // Quoted, so pasting the command never turns the placeholder into a shell redirection.+ expect(cmd).toContain(`--optimizer-model '<other-model>'`);+ expect(cmd).not.toContain(THINKING);+ expect(buildResumeCommand('demo', 'run-1', SPEC)).toContain('--reflect-max-tokens 32000');+ });++ test('only output-cap failures double the cap; a context-window failure keeps it', () => {+ expect(buildResumeCommand('demo', 'run-1', SPEC, 'one_shot_rewrite_truncated')).toContain('--reflect-max-tokens 64000');+ expect(buildResumeCommand('demo', 'run-1', SPEC, 'one_shot_rewrite_output_cap_too_small')).toContain('--reflect-max-tokens 64000');+ // The output cap shares the context window, so doubling it would make a+ // body-too-large refusal certain again.+ expect(buildResumeCommand('demo', 'run-1', SPEC, 'one_shot_rewrite_body_truncated')).toContain('--reflect-max-tokens 32000');+ expect(buildResumeCommand('demo', 'run-1', SPEC, 'reflect_context_too_small')).toContain('--reflect-max-tokens 32000');+ });++ test('carries the run mode, cost cap and runtime cap', () => {+ const capped = buildResumeCommand('demo', 'run-1', SPEC, undefined, { mode: 'rewrite', maxCostUsd: 20, maxRuntimeMin: 45 });+ expect(capped).toContain('--rewrite --max-cost-usd 20 --max-runtime-min 45');+ const uncapped = buildResumeCommand('demo', 'run-1', SPEC, undefined, { mode: 'patch', maxCostUsd: 0, maxRuntimeMin: 30 });+ expect(uncapped).toContain('--no-max-cost --max-runtime-min 30');+ expect(uncapped).not.toContain('--rewrite');+ expect(uncapped).not.toContain('--max-cost-usd');+ expect(uncapped).not.toContain('--force');+ expect(uncapped).not.toContain('--models-strict');+ const forced = buildResumeCommand('demo', 'run-1', SPEC, undefined, { mode: 'patch', maxCostUsd: 5, maxRuntimeMin: 30, force: true, modelsStrict: true });+ expect(forced).toEndWith('--max-runtime-min 30 --force --models-strict');+ });++ test('optional spec flags and shell quoting of quotes and control characters', () => {+ const cmd = buildResumeCommand('demo', 'run-1', {+ ...SPEC,+ held_out_path: "/tmp/it's\nheld.jsonl",+ allow_mutate_bundled: true,+ bootstrap_reviewed: true,+ });+ expect(cmd).toContain(`--held-out '/tmp/it'\\''sheld.jsonl'`);+ expect(cmd).toContain('--allow-mutate-bundled --bootstrap-reviewed');+ expect(cmd).not.toContain('\n');+ });+});++describe('CLI', () => {+ test('--reflect-max-tokens parses a positive integer and rejects anything else', () => {+ expect(parseFlags(['demo', '--reflect-max-tokens', '12000']).reflectMaxTokens).toBe(12000);+ expect(parseFlags(['demo']).reflectMaxTokens).toBeUndefined();+ for (const bad of ['0', '-3', '1.5', 'many']) {+ expect(() => parseFlags(['demo', '--reflect-max-tokens', bad])).toThrow(/--reflect-max-tokens requires a positive integer/);+ }+ });++ test('errored summary names the warning, the fix, the run id, the checkpoint and the resume command', () => {+ const receipt = {+ run_id: 'run-1', skill: 'demo', outcome: 'errored', abort_reason: 'error',+ abort_detail: 'optimizer_output_unusable: reflect_failure_truncated: 32000 output tokens, max_tokens=32000',+ stop_reason: 'early_stop_unusable_output',+ reflect_errors: ['reflect_failure_truncated: 32000 output tokens, max_tokens=32000'],+ remediation: buildRemediation(['reflect_failure_truncated: x']),+ reflect_max_tokens: 32000,+ resume_command: 'gbrain skillopt demo --resume run-1 --reflect-max-tokens 64000',+ } as RunReceipt;+ const out = formatRunSummary('errored', receipt, '/tmp/skills');+ expect(out).toContain('[skillopt] Outcome: errored');+ expect(out).toContain('[skillopt] Detail: optimizer_output_unusable: reflect_failure_truncated');+ expect(out).toContain('[skillopt] Warning: 1 optimizer reply error(s) (optimizer output cap 32000)');+ expect(out).toContain('[skillopt] Fix (reflect_truncated): ');+ expect(out).toContain('docs/guides/skillopt.md#reflect_truncated');+ expect(out).toContain('[skillopt] Stopped early');+ expect(out).toContain('[skillopt] Run id: run-1');+ expect(out).toContain('[skillopt] Checkpoint: /tmp/skills/demo/skillopt/checkpoint-run-1.json');+ expect(out).toContain('[skillopt] Resume: gbrain skillopt demo --resume run-1 --reflect-max-tokens 64000');+ });++ test('a clean no_improvement summary prints no warnings', () => {+ const out = formatRunSummary('no_improvement', { run_id: 'r', skill: 'demo' } as RunReceipt, '/tmp/skills');+ expect(out).toBe('[skillopt] Outcome: no_improvement\n');+ });+});++describe('must-abort', () => {+ test('an AI spend-policy refusal is a must-abort, never a per-call reflect/judge error', async () => {+ const denied = new Error('spend policy refused');+ await withAIInvocationGuard(async () => { throw denied; }, () =>+ invokeAI({ operation: 'test', kind: 'chat', model: 'test:model' }, async () => 'unreached', () => null)).catch(() => {});+ expect(isSkilloptMustAbort(denied)).toBe(true);+ expect(isSkilloptMustAbort(new Error('provider 500'))).toBe(false);+ });+});diff --git a/test/skillopt/run-skillopt-op.serial.test.ts b/test/skillopt/run-skillopt-op.serial.test.tsindex 94e98bbdd5..27da8a4614 100644--- a/test/skillopt/run-skillopt-op.serial.test.ts+++ b/test/skillopt/run-skillopt-op.serial.test.ts@@ -35,10 +35,11 @@ symlinkSync(join(outsideDir, 'secret.jsonl'), join(realSkillsRoot, 'evil', 'escamkdirSync(join(realSkillsRoot, 'test-skill'), { recursive: true });let runSkillOptCalls: unknown[] = [];+let stubReceipt: Record<string, unknown> | null = null;mock.module('../../src/core/skillopt/orchestrator.ts', () => ({runSkillOpt: async (opts: unknown) => {runSkillOptCalls.push(opts);- return { outcome: 'stubbed-run', receipt: null, mutatedSkillFile: null, proposedPath: null };+ return { outcome: 'stubbed-run', receipt: stubReceipt, mutatedSkillFile: null, proposedPath: null };},}));mock.module('../../src/core/repo-root.ts', () => ({@@ -125,6 +126,18 @@ describe('run_skillopt remote allowlist (default deny-all)', () => {expect(runSkillOptCalls.length).toBe(1);});+ test('the op result carries the receipt diagnostics (remediation, resume command) unchanged', async () => {+ const remediation = [{ code: 'reflect_truncated', fix: 'raise the cap', docs: 'docs/guides/skillopt.md#reflect_truncated' }];+ stubReceipt = { outcome: 'errored', remediation, resume_command: 'gbrain skillopt test-skill --resume r1' };+ try {+ const res = await run_skillopt.handler(ctxOf({ remote: false }), { skill_name: 'test-skill' }) as { receipt?: Record<string, unknown> };+ expect(res.receipt?.remediation).toEqual(remediation);+ expect(res.receipt?.resume_command).toBe('gbrain skillopt test-skill --resume r1');+ } finally {+ stubReceipt = null;+ }+ });+test('local caller (remote === false) bypasses the allowlist entirely', async () => {const res = await run_skillopt.handler(ctxOf({ remote: false }), { skill_name: 'never-allowlisted' }) as { outcome?: string };expect(res.outcome).toBe('stubbed-run');@@ -174,3 +187,24 @@ describe('run_skillopt remote path confinement', () => {expect(runSkillOptCalls.length).toBe(1);});});++describe('run_skillopt reflect_max_tokens (#5584)', () => {+ beforeEach(async () => {+ await engine.setConfig('skillopt.allowed_skills', JSON.stringify(['test-skill']));+ });++ test('remote caller: huge value clamped to 32000, tiny value raised to 256', async () => {+ await run_skillopt.handler(ctxOf({ remote: true }), { skill_name: 'test-skill', reflect_max_tokens: 10_000_000 });+ await run_skillopt.handler(ctxOf({ remote: true }), { skill_name: 'test-skill', reflect_max_tokens: 3 });+ expect(runSkillOptCalls.map((c) => (c as { reflectMaxTokens?: number }).reflectMaxTokens)).toEqual([32000, 256]);+ });++ test('absent -> not passed (orchestrator resolves config/default); invalid -> invalid_params, no run', async () => {+ await run_skillopt.handler(ctxOf({ remote: true }), { skill_name: 'test-skill' });+ expect((runSkillOptCalls[0] as { reflectMaxTokens?: number }).reflectMaxTokens).toBeUndefined();+ for (const bad of [-5, 1.5, 'lots']) {+ await expectCode(run_skillopt.handler(ctxOf({ remote: true }), { skill_name: 'test-skill', reflect_max_tokens: bad }), 'invalid_params');+ }+ expect(runSkillOptCalls.length).toBe(1);+ });+});diff --git a/test/skillopt/validate-gate-abort.test.ts b/test/skillopt/validate-gate-abort.test.tsindex d019a4852e..3f40cbb1ce 100644--- a/test/skillopt/validate-gate-abort.test.ts+++ b/test/skillopt/validate-gate-abort.test.ts@@ -27,6 +27,7 @@ import {import { ClaudeCliProcessError } from '../../src/core/ai/providers/claude-cli-language-model.ts';import type { BenchmarkTask, ScoredRollout, Trajectory } from '../../src/core/skillopt/types.ts';import type { RolloutOpts } from '../../src/core/skillopt/rollout.ts';+import { invokeAI, withAIInvocationGuard } from '../../src/core/ai/invocation-guard.ts';const TASKS: BenchmarkTask[] = [{ task_id: 't1', task: 'do a thing', judge: { kind: 'rule', checks: [{ op: 'contains', arg: 'x' }] } } as never,@@ -62,6 +63,27 @@ describe('runValidationGate — must-abort errors surface', () => {).rejects.toThrow(/no pricing entry/);});+ test('an AI spend-policy refusal on one task is re-thrown, not scored 0 beside a passing task', async () => {+ const denied = new Error('spend policy refused this call');+ await withAIInvocationGuard(async () => { throw denied; }, () =>+ invokeAI({ operation: 'test', kind: 'chat', model: 'test:model' }, async () => 'unreached', () => null)).catch(() => {});+ const mixedRollout = (async (o: RolloutOpts) => {+ if ((o as { task?: BenchmarkTask }).task?.task_id === 't1') throw denied;+ return okTrajectory('y');+ }) as never;+ await expect(+ runValidationGate({+ engine: {} as never,+ candidateSkillText: 'skill',+ selSet: TASKS,+ bestScore: -1,+ targetModel: 'anthropic:claude-haiku-4-5',+ runsPerTask: 1,+ rolloutFn: mixedRollout,+ }),+ ).rejects.toBe(denied);+ });+test('scoreSkillOnTasks propagates the abort too (does not return a vacuous 0)', async () => {const throwingRollout = (async () => {throw budgetExhausted();