Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(eval): takes-quality prices every canonical model; unpriced models run or point at gbrain pricing set
garrytanc299776740da
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex a98ea987a8..fcbc01eff8 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/eval/ranked-docs.ts` — dependency-free page-level ranking primitive shared by the retrieval eval harness, NamedThingBench, and the qrels correctness gate. `dedupeRankedKeys()` preserves the first/best occurrence of each `${source_id}::${slug}` or slug key before any cutoff, so repeated chunks neither inflate relevance gain nor consume document ranks. Precision retains its fixed-`k` denominator; Recall and nDCG are structurally bounded to `[0,1]`. Pinned across `test/eval.test.ts`, `test/retrieval-quality-harness.test.ts`, `test/bench/qrels-file.test.ts`, and `test/bench/correctness-gate.test.ts`.-- `src/core/takes-quality-eval/pricing.ts` — fail-closed budget pricing for `eval takes-quality run --budget-usd N`. `MODEL_PRICING` is a curated `provider:model` allowlist (default panel + likely overrides) whose VALUES are derived from `model-pricing.ts` via `canonicalLookup`; an allowlisted id missing from canonical throws at module load. Schema is `{input_per_1m, output_per_1m}`. A model NOT on the allowlist aborts the run with an actionable error rather than guessing (distinct from `cross-modal-eval/runner.ts`, which silently estimates zero on unknown models — both now source numbers from canonical).+- `src/core/takes-quality-eval/pricing.ts` — budget pricing for `eval takes-quality run`. `getPricing(model, overrides?)` returns the operator rate registered with `gbrain pricing set` (`pricing.overrides`), else the canonical rate (`canonicalLookup`), else null; schema `{input_per_1m, output_per_1m}`. Every canonically priced model is gateable. Miss policy (new models must run): with no `--budget-usd` an unpriced model runs with a warning naming the registration command and its spend is not counted; under a user cap the runner refuses before any call with `no_pricing` (`unpricedUnderCapError`), whose fix is `gbrain pricing set <model> --input … --output … --source …` (no-pricing.ts). Rates are never copied here; `test/model-pricing.test.ts` pins equality with canonical for every canonical key.- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.slow.test.ts`. System One arm: `--decide*` flags (`src/eval/decide-eval-flags.ts`) configure the benchmark brain; the claude-code adapter captures the turn-context `decide.recall_needed` meta onto `turn_rows[].decide`, the result gains a `decide` block, and `--update-baseline` is refused for an arm (`test/eval-brainbench-decide.serial.test.ts`).diff --git a/docs/eval-takes-quality.md b/docs/eval-takes-quality.mdindex 1511402d1b..1725c1ee18 100644--- a/docs/eval-takes-quality.md+++ b/docs/eval-takes-quality.md@@ -87,9 +87,11 @@ receipt file from disk and re-renders it. The other modes need the brain.- `verdict` — `pass` if every dim mean >= 7 AND every dim min acrosscontributing models >= 5; `fail` otherwise; `inconclusive` if fewer than2/3 models contributed complete scores.-- `cost_usd` — sum of per-call cost via `pricing.ts`. Unknown models when- `--budget-usd` is set produce a `PricingNotFoundError` before any call- fires.+- `cost_usd` — sum of per-call cost via `pricing.ts` (a rate registered with+ `gbrain pricing set`, else the canonical table). An unpriced model with+ `--budget-usd` set refuses with `no_pricing` before any call fires; its fix+ is `gbrain pricing set <model> --input <usd/1M> --output <usd/1M> --source+ <url>`. Without a cap it runs with a warning and its spend is not counted.## Receipt persistencediff --git a/src/commands/eval-takes-quality.ts b/src/commands/eval-takes-quality.tsindex aec87b5e1d..dc85cdd01a 100644--- a/src/commands/eval-takes-quality.ts+++ b/src/commands/eval-takes-quality.ts@@ -12,9 +12,11 @@* require a brain. The cli.ts no-DB bypass routes `replay` here directly;* run/trend/regress go through connectEngine in cli.ts.*- * Codex review #4 fail-closed budget: `--budget-usd N` aborts before the- * next call's projected cost would exceed the cap. Models without a- * pricing entry produce an actionable error, not silent zero.+ * Budget: `--budget-usd N` aborts before the next call's projected cost+ * would exceed the cap. Every canonically priced (or `gbrain pricing set`)+ * model is gateable; an unpriced model refuses under the cap with a+ * `no_pricing` envelope whose fix registers the rate, and runs with a+ * warning when no cap is set.** Codex review #3 receipt naming: every run binds (corpus, prompt, models,* rubric) shas; rubric_version field segregates trend rows by rubric epoch.@@ -29,6 +31,8 @@ import { writeReceipt } from '../core/takes-quality-eval/receipt-write.ts';import { loadReceiptFromDisk } from '../core/takes-quality-eval/replay.ts';import { compareReceipts } from '../core/takes-quality-eval/regress.ts';import { loadTrend, renderTrendTable, type TrendRow } from '../core/takes-quality-eval/trend.ts';+import { OperationError } from '../core/ops/contract.ts';+import { writeCliError } from '../cli/cli-error.ts';const HELP = `gbrain eval takes-quality — reproducible cross-modal quality eval@@ -37,8 +41,9 @@ Subcommands:[--slug-prefix P] [--cycles N] [--models a,b,c] [--json]Sample N takes from the brain, score with 3 models in parallel,aggregate to PASS/FAIL/INCONCLUSIVE. Default: --limit 100, --cycles 3- (1 in non-TTY), --source db, --budget-usd null (no cap; pass 0 to- explicitly disable budget enforcement). Default models:+ (1 in non-TTY), --source db, no --budget-usd cap. Under a cap, a model+ gbrain has no price for refuses (no_pricing; register its rate with+ gbrain pricing set); without one it runs uncounted. Default models:${DEFAULT_MODEL_PANEL.join(', ')}Exit codes: 0 PASS, 1 FAIL, 2 INCONCLUSIVE.@@ -169,6 +174,7 @@ export async function runEvalTakesQuality(engine: BrainEngine, args: string[]):try {result = await runEval(engine, { limit, cycles, models, budgetUsd, slugPrefix, source });} catch (e) {+ if (e instanceof OperationError) process.exit(writeCliError(e, 'eval', { json }));process.stderr.write(`run failed: ${e instanceof Error ? e.message : String(e)}\n`);process.exit(1);}diff --git a/src/core/takes-quality-eval/pricing.ts b/src/core/takes-quality-eval/pricing.tsindex bc2a7783d4..ccb68b647e 100644--- a/src/core/takes-quality-eval/pricing.ts+++ b/src/core/takes-quality-eval/pricing.ts@@ -1,23 +1,20 @@/**- * takes-quality-eval/pricing — fail-closed model pricing for budget- * enforcement.+ * takes-quality-eval/pricing — model pricing for `eval takes-quality run`.*- * The KEY SET here is an intentional allowlist — only the default panel and a- * handful of likely overrides. Passing a model NOT in this list to- * `eval takes-quality run --budget-usd N` aborts with an actionable error- * rather than guessing (codex review #4 fail-closed posture vs- * cross-modal-eval/runner.ts which silently estimates zero on unknown models).+ * Every model the canonical table prices (`src/core/model-pricing.ts`) is+ * budget-gateable; an operator rate registered with `gbrain pricing set`+ * (`pricing.overrides`) wins over the table. Rates are never hand-copied here.*- * The VALUES come from the canonical table (`src/core/model-pricing.ts`) — do- * NOT hand-edit rates here; update canonical and they flow through. This keeps- * the allowlist's fail-closed curation while removing the duplicated numbers- * that let Opus 4.7 drift to a stale $15/$75 here.- *- * Schema is `{model_id: {input_per_1m, output_per_1m}}` so callers can compute- * (in_tokens * input_per_1m + out_tokens * output_per_1m) / 1_000_000.+ * Miss policy (new models must run): an unpriced model runs with a warning when+ * no `--budget-usd` cap is set, and its spend is not counted. Under a user-set+ * cap it refuses with `no_pricing`, whose fix is the `gbrain pricing set`+ * registration, because the cap could not be enforced.*/import { canonicalLookup } from '../model-pricing.ts';+import { overrideFor, type PricingOverrides } from '../budget/reservation-cost.ts';+import { noPricingFix, noPricingGuidance, noPricingMessage, noPricingSteps, pricingSetCommand } from '../budget/no-pricing.ts';+import { opError, type OperationError } from '../ops/contract.ts';export interface ModelPricing {/** USD per 1M input tokens. */@@ -26,74 +23,29 @@ export interface ModelPricing {output_per_1m: number;}-/**- * The curated allowlist of models takes-quality will budget-gate. Each must- * exist in CANONICAL_PRICING; the map below fails fast at module load if one- * is missing (a programmer error caught immediately, not at run time).- */-const SUPPORTED_MODELS = [- 'openai:gpt-4o',- 'openai:gpt-5',- 'openai:gpt-5.2',- 'openai:gpt-5.5',- 'anthropic:claude-opus-5-5',- 'anthropic:claude-opus-5',- 'anthropic:claude-opus-4-8',- 'anthropic:claude-opus-4-7',- 'anthropic:claude-sonnet-5-5',- 'anthropic:claude-sonnet-5',- 'anthropic:claude-sonnet-4-6',- 'anthropic:claude-haiku-4-5',- // gemini-2.5-flash holds the DEFAULT_MODEL_PANEL slot; gemini-1.5-pro- // (#3510) and the gemini-2.0 family before it were retired by Google. The- // retired ids stay listed so a `--models` run over historical results still- // budget-gates, but they are no longer reachable defaults.- 'google:gemini-2.5-flash',- 'google:gemini-2.0-flash',- 'google:gemini-2-flash',-] as const;--export const MODEL_PRICING: Record<string, ModelPricing> = Object.fromEntries(- SUPPORTED_MODELS.map((id) => {- const p = canonicalLookup(id);- if (!p) {- throw new Error(- `takes-quality allowlist model "${id}" is missing from CANONICAL_PRICING ` +- `(src/core/model-pricing.ts). Add it there.`,- );- }- return [id, { input_per_1m: p.input, output_per_1m: p.output }];- }),-);+/** The model's rate: registered override first, then the canonical table; null when unpriced. */+export function getPricing(modelId: string, overrides?: PricingOverrides): ModelPricing | null {+ const p = overrideFor(modelId, overrides) ?? canonicalLookup(modelId);+ return p ? { input_per_1m: p.input, output_per_1m: p.output } : null;+}-export class PricingNotFoundError extends Error {- constructor(public readonly modelId: string) {- super(- `Model "${modelId}" has no pricing entry. Add it to CANONICAL_PRICING in ` +- `src/core/model-pricing.ts AND to the SUPPORTED_MODELS allowlist in ` +- `src/core/takes-quality-eval/pricing.ts, OR pass --budget-usd 0 to disable ` +- `budget enforcement (you'll still see the cost printed to stderr but the ` +- `runner won't abort).`,- );- this.name = 'PricingNotFoundError';- }+/** USD for a call's token usage; null when the model is unpriced. */+export function estimateCost(modelId: string, inTokens: number, outTokens: number, overrides?: PricingOverrides): number | null {+ const p = getPricing(modelId, overrides);+ return p ? (inTokens * p.input_per_1m + outTokens * p.output_per_1m) / 1_000_000 : null;}-/**- * Look up pricing for a model. Throws PricingNotFoundError when the model- * isn't in the table — caller catches and surfaces the actionable message.- */-export function getPricing(modelId: string): ModelPricing {- const p = MODEL_PRICING[modelId];- if (!p) throw new PricingNotFoundError(modelId);- return p;+/** The refusal for an unpriced model under a user-set `--budget-usd` cap. */+export function unpricedUnderCapError(modelId: string, capUsd: number): OperationError {+ const g = noPricingGuidance(modelId, 'chat');+ return opError('no_pricing', noPricingMessage(g, { label: 'eval takes-quality', capUsd }), noPricingSteps(g), {+ fix: noPricingFix(g),+ docs: g.docs,+ });}-/**- * Estimate cost in USD for a given model + token usage. Uses fail-closed- * lookup; throws on unknown model.- */-export function estimateCost(modelId: string, inTokens: number, outTokens: number): number {- const p = getPricing(modelId);- return (inTokens * p.input_per_1m + outTokens * p.output_per_1m) / 1_000_000;+/** The warning for an unpriced model with no cap: it runs, its spend is not counted. */+export function unpricedWarning(modelId: string): string {+ return `[eval takes-quality] warning: gbrain has no price for ${modelId}; it runs, but its spend is not counted in cost_usd. ` ++ `Look up its rate and register it: ${pricingSetCommand(modelId, 'chat')}`;}diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.tsindex c1ce3960ee..c02fa8a6fa 100644--- a/src/core/takes-quality-eval/runner.ts+++ b/src/core/takes-quality-eval/runner.ts@@ -7,10 +7,11 @@* incomplete dim scores (codex review #5), aggregates, and stops early on* PASS or INCONCLUSIVE.*- * Budget enforcement (codex review #4 fail-closed): if --budget-usd is set,- * the runner aborts BEFORE the next call's projected cost would exceed the- * cap. Pricing comes from pricing.ts; unknown model → loud abort, never- * silent zero.+ * Budget enforcement: if --budget-usd is set, the runner aborts BEFORE the+ * next call's projected cost would exceed the cap. Pricing comes from+ * pricing.ts (registered overrides, then the canonical table). An unpriced+ * model refuses up front under a cap (`no_pricing`, fix: register the rate)+ * and runs with a warning without one.** NB: this module is engine-aware (samples takes from DB) but the runner* itself doesn't write the receipt — that's `runEval()`'s caller's job@@ -30,13 +31,14 @@ import {modelSetSha8,} from './receipt-name.ts';import type { TakesQualityReceipt } from './receipt.ts';-import { estimateCost, getPricing, PricingNotFoundError } from './pricing.ts';+import { estimateCost, getPricing, unpricedUnderCapError, unpricedWarning } from './pricing.ts';+import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';/*** Three distinct providers (uncorrelated judge blind spots). Every entry MUST- * be listed in its recipe's chat touchpoint AND in the SUPPORTED_MODELS- * pricing allowlist — pinned by test/default-model-panels.test.ts.+ * be listed in its recipe's chat touchpoint AND priced for takes-quality+ * (pricing.ts) — pinned by test/default-model-panels.test.ts.* google:gemini-1.5-pro (retired by Google) and openai:gpt-4o (dropped from* the OpenAI recipe's chat list) sat here dead until #3510; gemini-2.0-flash* replaced the former and was itself retired before it was ever swept.@@ -166,16 +168,12 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<throw new Error('fs source not yet wired in v0.32; use --source db');}- // Pre-flight pricing check (codex review #4 fail-closed): every requested- // model must be in the pricing table when --budget-usd is set, otherwise- // budget enforcement is meaningless.- if (budgetUsd !== null) {- for (const m of models) {- try { getPricing(m); } catch (e) {- if (e instanceof PricingNotFoundError) throw e;- throw e;- }- }+ // Pre-flight pricing: a cap is enforceable only when every model is priced.+ const overrides = await loadPricingOverrides(engine);+ for (const m of models) {+ if (getPricing(m, overrides)) continue;+ if (budgetUsd !== null) throw unpricedUnderCapError(m, budgetUsd);+ process.stderr.write(`${unpricedWarning(m)}\n`);}// Sample the corpus.@@ -208,7 +206,7 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<if (budgetUsd !== null) {let projected = 0;for (const m of models) {- try { projected += estimateCost(m, 5000, 2000); } catch { /* unreachable: pre-flight checked */ }+ projected += estimateCost(m, 5000, 2000, overrides) ?? 0;}if (cumulativeCost + projected > budgetUsd) {process.stderr.write(@@ -230,8 +228,7 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<if (s.status === 'fulfilled') {const r = s.value as SlotResult & { _usage?: { input_tokens: number; output_tokens: number } };if (r._usage) {- try { cumulativeCost += estimateCost(m, r._usage.input_tokens, r._usage.output_tokens); }- catch { /* unknown model + no budget cap → skip cost addition */ }+ cumulativeCost += estimateCost(m, r._usage.input_tokens, r._usage.output_tokens, overrides) ?? 0;}slots.push(r);} else {diff --git a/test/default-model-panels.test.ts b/test/default-model-panels.test.tsindex 7a32bc6ac3..7cc3723cb3 100644--- a/test/default-model-panels.test.ts+++ b/test/default-model-panels.test.ts@@ -31,13 +31,12 @@ describe('takes-quality DEFAULT_MODEL_PANEL ↔ recipe consistency', () => {}});- test('every default panel model prices via canonical AND the takes-quality allowlist', () => {+ test('every default panel model prices via canonical AND takes-quality pricing', () => {for (const id of DEFAULT_MODEL_PANEL) {expect(canonicalLookup(id), `"${id}" missing from CANONICAL_PRICING`).toBeDefined();- // getPricing throws PricingNotFoundError if the model is missing from- // SUPPORTED_MODELS — a default that can't be budget-gated aborts every- // `--budget-usd` run before the first call.- expect(getPricing(id)).toBeDefined();+ // An unpriced default refuses every `--budget-usd` run with no_pricing+ // before the first call.+ expect(getPricing(id), `"${id}" unpriced for takes-quality`).not.toBeNull();}});diff --git a/test/eval-takes-quality-boundaries.test.ts b/test/eval-takes-quality-boundaries.test.tsindex 4790400453..cfb7a8d882 100644--- a/test/eval-takes-quality-boundaries.test.ts+++ b/test/eval-takes-quality-boundaries.test.ts@@ -30,7 +30,7 @@ describe('runner boundaries — pre-LLM (no API calls fire)', () => {await expect(runEval(engine, { source: 'fs', limit: 10 })).rejects.toThrow(/fs source not yet wired/);});- test('--budget-usd with unknown model → PricingNotFoundError BEFORE any HTTP call (codex review #4)', async () => {+ test('--budget-usd with unknown model → no_pricing refusal BEFORE any HTTP call (codex review #4)', async () => {// Seed 1 take so the corpus isn't empty (otherwise we'd fail on that check first).await engine.putPage('test/budget-bound', {type: 'note', title: 't', compiled_truth: 'b', frontmatter: {},@@ -43,15 +43,15 @@ describe('runner boundaries — pre-LLM (no API calls fire)', () => {]);// Unknown model + budget cap set → must abort fail-closed before any- // network call. The error message names the offending model and points- // at pricing.ts.+ // network call. The refusal names the offending model; its fix registers+ // the rate (gbrain pricing set).await expect(runEval(engine, {models: ['unknown:gpt-99'],budgetUsd: 1.0,limit: 1,}),- ).rejects.toThrow(/has no pricing entry/);+ ).rejects.toMatchObject({ code: 'no_pricing', message: expect.stringContaining('no pricing for chat model "unknown:gpt-99"') });});test('--budget-usd null with unknown model → does NOT pre-flight pricing (allowed; cost may be unknown)', async () => {@@ -63,8 +63,8 @@ describe('runner boundaries — pre-LLM (no API calls fire)', () => {// so we test the negative: pre-flight does NOT fire when budgetUsd is null.// The actual call would error at gateway level, separate from pricing.//- // Verify by checking that the error (if any) is NOT the- // PricingNotFoundError shape — it should be a provider-resolve error.+ // Verify by checking that the error (if any) is NOT the no_pricing+ // refusal — it should be a provider-resolve error.try {await runEval(engine, {models: ['unknown:gpt-99'],@@ -75,7 +75,7 @@ describe('runner boundaries — pre-LLM (no API calls fire)', () => {// If the call reached the gateway, the error message should be// about provider/recipe, NOT pricing.const msg = (e as Error).message;- expect(msg).not.toContain('has no pricing entry');+ expect(msg).not.toContain('no pricing for chat model');}});});diff --git a/test/eval-takes-quality-pricing.test.ts b/test/eval-takes-quality-pricing.test.tsindex c6df343442..5ecefa53d3 100644--- a/test/eval-takes-quality-pricing.test.ts+++ b/test/eval-takes-quality-pricing.test.ts@@ -1,57 +1,75 @@/**- * takes-quality-eval/pricing — fail-closed lookup tests (codex review #4).+ * takes-quality-eval/pricing — canonical-table lookup, operator overrides,+ * and the unpriced-model refusal under a user cap (new models must run).*/import { describe, test, expect } from 'bun:test';import {getPricing,estimateCost,- PricingNotFoundError,- MODEL_PRICING,+ unpricedUnderCapError,+ unpricedWarning,} from '../src/core/takes-quality-eval/pricing.ts';+import { CANONICAL_PRICING } from '../src/core/model-pricing.ts';-describe('getPricing — fail-closed contract', () => {+describe('getPricing — canonical table', () => {test('returns pricing for the default 3-model panel', () => {- expect(getPricing('openai:gpt-5.2')).toBeDefined();- expect(getPricing('anthropic:claude-opus-4-7')).toBeDefined();- expect(getPricing('google:gemini-2.5-flash')).toBeDefined();+ expect(getPricing('openai:gpt-5.2')).not.toBeNull();+ expect(getPricing('anthropic:claude-opus-4-7')).not.toBeNull();+ expect(getPricing('google:gemini-2.5-flash')).not.toBeNull();});- test('retired google:gemini-1.5-pro is no longer in the allowlist (#3510)', () => {- expect(() => getPricing('google:gemini-1.5-pro')).toThrow(PricingNotFoundError);+ test('every canonically priced model is budget-gateable, including new ones', () => {+ for (const id of ['anthropic:claude-fable-5', 'anthropic:claude-fable-5-1', 'openai:gpt-5.6-sol', 'openai:gpt-5.6-luna']) {+ expect(getPricing(id)).toEqual({ input_per_1m: CANONICAL_PRICING[id]!.input, output_per_1m: CANONICAL_PRICING[id]!.output });+ }+ });++ test('returns null for an unpriced model', () => {+ expect(getPricing('unknown:gpt-99')).toBeNull();});- test('throws PricingNotFoundError on unknown model', () => {- expect(() => getPricing('unknown:gpt-99')).toThrow(PricingNotFoundError);+ test('a registered override wins over the table and prices an unpriced model', () => {+ const overrides = { 'unknown:gpt-99': { input: 1, output: 2 }, 'openai:gpt-4o': { input: 0.5, output: 0.5 } };+ expect(getPricing('unknown:gpt-99', overrides)).toEqual({ input_per_1m: 1, output_per_1m: 2 });+ expect(getPricing('openai:gpt-4o', overrides)).toEqual({ input_per_1m: 0.5, output_per_1m: 0.5 });});test('opus 4.7 priced at $5/$25 (regression: was a stale $15/$75) — gbrain#1819', () => {- const p = getPricing('anthropic:claude-opus-4-7');+ const p = getPricing('anthropic:claude-opus-4-7')!;expect(p.input_per_1m).toBeCloseTo(5.0, 5);expect(p.output_per_1m).toBeCloseTo(25.0, 5);});test('opus 4.8 is supported and priced $5/$25 — gbrain#1819', () => {- const p = getPricing('anthropic:claude-opus-4-8');+ const p = getPricing('anthropic:claude-opus-4-8')!;expect(p.input_per_1m).toBeCloseTo(5.0, 5);expect(p.output_per_1m).toBeCloseTo(25.0, 5);});test('opus 5 is supported and priced $5/$25', () => {- const p = getPricing('anthropic:claude-opus-5');+ const p = getPricing('anthropic:claude-opus-5')!;expect(p.input_per_1m).toBeCloseTo(5.0, 5);expect(p.output_per_1m).toBeCloseTo(25.0, 5);});+});- test('error message names the model AND points to the file', () => {- try {- getPricing('foo:bar');- throw new Error('expected throw');- } catch (e) {- expect(e).toBeInstanceOf(PricingNotFoundError);- expect((e as Error).message).toContain('foo:bar');- expect((e as Error).message).toContain('src/core/takes-quality-eval/pricing.ts');- expect((e as Error).message).toContain('--budget-usd 0');- }+describe('unpriced models', () => {+ test('under a user cap: no_pricing refusal whose fix registers the rate with gbrain pricing set', () => {+ const e = unpricedUnderCapError('foo:bar', 2);+ expect(e.code).toBe('no_pricing');+ expect(e.message).toContain('foo:bar');+ expect(e.message).toContain('$2.00 cost cap');+ expect(e.fix!.argv).toEqual([+ 'gbrain', 'pricing', 'set', 'foo:bar',+ '--input', '<usd-per-1M-input-tokens>', '--output', '<usd-per-1M-output-tokens>',+ '--source', '<pricing-page-url>',+ ]);+ expect(e.fix!.inputs!.map(i => i.name)).toEqual(['usd-per-1M-input-tokens', 'usd-per-1M-output-tokens', 'pricing-page-url']);+ expect(e.fix!.verify).toEqual({ argv: ['gbrain', 'pricing', 'list'] });+ });++ test('without a cap: the warning names the registration command', () => {+ expect(unpricedWarning('foo:bar')).toContain('gbrain pricing set foo:bar --input');});});@@ -59,30 +77,14 @@ describe('estimateCost', () => {test('returns USD cost for known model', () => {// openai:gpt-4o = $2.50/1M in + $10.00/1M out// 1M in + 1M out = $12.50- const c = estimateCost('openai:gpt-4o', 1_000_000, 1_000_000);- expect(c).toBeCloseTo(12.5, 5);+ expect(estimateCost('openai:gpt-4o', 1_000_000, 1_000_000)).toBeCloseTo(12.5, 5);});test('zero tokens → zero cost', () => {expect(estimateCost('openai:gpt-4o', 0, 0)).toBe(0);});- test('throws on unknown model (matches getPricing)', () => {- expect(() => estimateCost('unknown:foo', 100, 100)).toThrow(PricingNotFoundError);- });-});--describe('MODEL_PRICING table', () => {- test('every entry has finite positive rates', () => {- for (const [model, p] of Object.entries(MODEL_PRICING)) {- expect(Number.isFinite(p.input_per_1m)).toBe(true);- expect(Number.isFinite(p.output_per_1m)).toBe(true);- expect(p.input_per_1m).toBeGreaterThan(0);- expect(p.output_per_1m).toBeGreaterThan(0);- // Output is typically more expensive than input; canary on weird drift.- expect(p.output_per_1m).toBeGreaterThanOrEqual(p.input_per_1m);- // Sanity guard against an accidental integer column (model id has the colon).- expect(model).toContain(':');- }+ test('unpriced model → null, never a silent zero', () => {+ expect(estimateCost('unknown:foo', 100, 100)).toBeNull();});});diff --git a/test/eval-takes-quality-runner.serial.test.ts b/test/eval-takes-quality-runner.serial.test.tsindex 2846e38eb5..f356ca8337 100644--- a/test/eval-takes-quality-runner.serial.test.ts+++ b/test/eval-takes-quality-runner.serial.test.ts@@ -7,8 +7,11 @@* - happy path: 3 model successes → PASS receipt with all dim scores* - mixed: 1 success, 2 errors → INCONCLUSIVE* - budget cap fires mid-run → budgetAborted=true; receipt still produced+ * - pricing gate: canonically priced models pass under a cap; an unpriced+ * model refuses under a cap (no_pricing, fix registers the rate), runs+ * with a warning without one, and passes once its rate is registered*/-import { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, mock, spyOn } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';// Stub gateway.chat BEFORE importing the runner so the runner picks up@@ -176,8 +179,6 @@ describe('runner — budget cap (codex review #4)', () => {const r = await runEval(engine, {limit: 5,cycles: 3,- // gemini-2.5-flash (not the retired 1.5-pro or 2.0 family) — the- // budget path pre-flights getPricing, which is allowlist-gated (#3510).models: ['openai:gpt-4o', 'anthropic:claude-opus-4-7', 'google:gemini-2.5-flash'],budgetUsd: 0.05, // tighter than projected per-cycle cost (~$0.109)});@@ -211,3 +212,65 @@ describe('runner — budget cap (codex review #4)', () => {expect(r.receipt.cycles_run).toBe(1);});});++describe('runner — pricing gate (new models must run)', () => {+ const scored = async () => ({+ text: fullScoreJson(8),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'stub',+ providerId: 'stub',+ });++ test('canonically priced models outside the old allowlist pass the gate under a cap', async () => {+ chatHandler = scored;+ const r = await runEval(engine, {+ limit: 5, cycles: 1, models: ['anthropic:claude-fable-5', 'openai:gpt-5.6-sol'], budgetUsd: 100,+ });+ expect(r.receipt.cycles_run).toBe(1);+ expect(r.receipt.cost_usd).toBeGreaterThan(0);+ });++ test('an unpriced model under a user cap refuses with no_pricing before any call', async () => {+ chatHandler = async () => { throw new Error('chat must not run when the cap cannot be enforced'); };+ let err: unknown;+ try {+ await runEval(engine, { limit: 5, cycles: 1, models: ['openai:gpt-4o', 'vendor:brand-new-model'], budgetUsd: 1 });+ } catch (e) { err = e; }+ expect(err).toMatchObject({ code: 'no_pricing' });+ const fix = (err as { fix: { argv: string[]; actor: string } }).fix;+ expect(fix.argv.slice(0, 4)).toEqual(['gbrain', 'pricing', 'set', 'vendor:brand-new-model']);+ expect(fix.argv).toContain('--input');+ expect(fix.argv).toContain('--output');+ expect(fix.actor).toBe('agent');+ expect((err as Error).message).toContain('$1.00 cost cap');+ });++ test('an unpriced model without a cap warns and runs; its spend is not counted', async () => {+ chatHandler = scored;+ const lines: string[] = [];+ const spy = spyOn(process.stderr, 'write').mockImplementation((c: string | Uint8Array) => { lines.push(String(c)); return true; });+ let r;+ try {+ r = await runEval(engine, { limit: 5, cycles: 1, models: ['vendor:brand-new-model'], budgetUsd: null });+ } finally {+ spy.mockRestore();+ }+ expect(r.receipt.cycles_run).toBe(1);+ expect(r.receipt.cost_usd).toBe(0);+ expect(lines.join('')).toContain('gbrain pricing set vendor:brand-new-model');+ });++ test('a rate registered in pricing.overrides prices the model under a cap', async () => {+ chatHandler = scored;+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'vendor:brand-new-model': { input: 1, output: 2 } }));+ try {+ const r = await runEval(engine, { limit: 5, cycles: 1, models: ['vendor:brand-new-model'], budgetUsd: 100 });+ expect(r.receipt.cycles_run).toBe(1);+ expect(r.receipt.cost_usd).toBeCloseTo((100 * 1 + 50 * 2) / 1_000_000, 10);+ } finally {+ await engine.setConfig('pricing.overrides', '');+ }+ });+});diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.tsindex f716dfc09a..72b095e611 100644--- a/test/model-pricing.test.ts+++ b/test/model-pricing.test.ts@@ -21,7 +21,7 @@ import {ANTHROPIC_CACHE_WRITE_5M_MULT,} from '../src/core/model-pricing.ts';import { ANTHROPIC_PRICING } from '../src/core/anthropic-pricing.ts';-import { MODEL_PRICING } from '../src/core/takes-quality-eval/pricing.ts';+import { getPricing as takesQualityPricing } from '../src/core/takes-quality-eval/pricing.ts';import { estimateAnthropicCost } from '../src/core/brain-score-recommendations.ts';describe('CANONICAL_PRICING — table integrity', () => {@@ -188,12 +188,9 @@ describe('DRIFT GUARD — derived views stay equal to canonical (re-hardcode tri}});- test('takes-quality MODEL_PRICING equals canonical for every allowlisted key', () => {- for (const [key, p] of Object.entries(MODEL_PRICING)) {- const c = canonicalLookup(key);- expect(c).toBeDefined();- expect(p.input_per_1m).toBe(c!.input);- expect(p.output_per_1m).toBe(c!.output);+ test('takes-quality pricing equals canonical for every canonical key', () => {+ for (const [key, c] of Object.entries(CANONICAL_PRICING)) {+ expect({ key, p: takesQualityPricing(key) }).toEqual({ key, p: { input_per_1m: c.input, output_per_1m: c.output } });}});