Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(brainstorm): #5873 the $5 default is a default cap, overrides reach the run, explicit caps refuse unpriced models with the shared guidance

time-attack88ec4817f726
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.ts
index 54c4ef69f9..c095f3690d 100644
--- a/src/commands/brainstorm.ts
+++ b/src/commands/brainstorm.ts
@@ -29,6 +29,7 @@ import { importFromContent } from '../core/import-file.ts';
import { writePageThrough, type WriteThroughResult } from '../core/write-through.ts';
import { randomBytes } from 'crypto';
import { legacyNestedErrorDocument } from '../core/agent-output.ts';
+import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
export interface BrainstormCliArgs {
question?: string;
@@ -36,8 +37,10 @@ export interface BrainstormCliArgs {
save?: boolean;
yes: boolean;
limit?: number;
- /** Cost ceiling in USD; aborts pre-run if estimate exceeds. Default $5. */
- maxCost?: number;
+ /** Cost ceiling in USD (`--max-usd`, legacy `--max-cost`); null = off; undefined = the $5 default. */
+ maxCost?: number | null;
+ /** The cap flag spelling the user typed. */
+ maxCostFlag?: string;
/** Hard cap on far-set prefix sampling. Default 50. */
maxFarSet?: number;
/** When true, abort mid-run if running spend exceeds 5× estimate. */
@@ -59,6 +62,7 @@ export interface BrainstormCliArgs {
export function parseBrainstormArgs(args: string[]): BrainstormCliArgs {
const out: BrainstormCliArgs = { json: false, yes: false, help: false };
const positional: string[] = [];
+ let cap: CapFlag | undefined;
let i = 0;
while (i < args.length) {
const arg = args[i];
@@ -80,14 +84,16 @@ export function parseBrainstormArgs(args: string[]): BrainstormCliArgs {
return out;
}
out.limit = n;
- } else if (arg === '--max-cost') {
- const v = args[++i];
- const n = v ? parseFloat(v) : NaN;
- if (!Number.isFinite(n) || n <= 0) {
- out.error = `--max-cost requires a positive number in USD (got ${v})`;
+ } else if (arg === '--max-usd' || arg === '--max-cost') {
+ try {
+ cap = mergeCapFlag(cap, parseCapFlag(arg, args[++i]));
+ } catch (err) {
+ if (!(err instanceof CapFlagError)) throw err;
+ out.error = err.message;
return out;
}
- out.maxCost = n;
+ out.maxCost = cap.usd;
+ out.maxCostFlag = cap.flag;
} else if (arg === '--max-far-set') {
const v = args[++i];
const n = v ? parseInt(v, 10) : NaN;
@@ -151,7 +157,11 @@ Options:
--no-save Don't save; print only
--yes, -y Skip the 10s cost-preview wait (TTY only)
--limit N Override the far-bank size (default 6 brainstorm / 12 LSD)
- --max-cost USD Abort if estimated cost exceeds USD (default 5)
+ --max-usd USD|off Abort if estimated cost exceeds USD (default 5;
+ --max-cost is the legacy spelling). off runs
+ uncapped. A model with no price runs under the
+ default with a warning; an explicit cap refuses
+ it until you register its rate (gbrain pricing set)
--max-far-set N Cap domain bank prefix sampling (default 50)
--strict-budget Abort if running cost exceeds 5× the estimate
--judge-model MODEL Override the judge LLM (larger-context for big runs)
@@ -186,7 +196,11 @@ Options:
--save Persist to wiki/ideas/<date>-lsd-<slug>.md (default OFF)
--yes, -y Skip the 10s cost-preview wait (TTY only)
--limit N Override the far-bank size (default 12)
- --max-cost USD Abort if estimated cost exceeds USD (default 5)
+ --max-usd USD|off Abort if estimated cost exceeds USD (default 5;
+ --max-cost is the legacy spelling). off runs
+ uncapped. A model with no price runs under the
+ default with a warning; an explicit cap refuses
+ it until you register its rate (gbrain pricing set)
--max-far-set N Cap domain bank prefix sampling (default 50)
--strict-budget Abort if running cost exceeds 5× the estimate
--judge-model MODEL Override the judge LLM (larger-context for big runs)
@@ -282,6 +296,7 @@ async function runBrainstormCli(
ideaSlug: shouldSave ? freshSlug : undefined,
// v0.39.0.0 T10 cost-cap surface — wired in master, preserved here.
maxCostUsd: parsed.maxCost,
+ maxCostFlag: parsed.maxCostFlag,
maxFarSet: parsed.maxFarSet,
strictBudget: parsed.strictBudget,
judgeModel: parsed.judgeModel,
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 46d80ba52d..3deeb1479e 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -5,6 +5,8 @@
* doctor.ts) and buildChecks / doctorReportRemote consume them.
*/
import { loadConfigFileOnly } from '../../../core/config.ts';
+import { DEFAULT_MAX_COST_USD, findUnpricedBrainstormChatModel } from '../../../core/brainstorm/cost-gate.ts';
+import { pricingSetCommand } from '../../../core/budget/no-pricing.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { checkError } from '../check-fix.ts';
@@ -114,7 +116,7 @@ export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Ch
/**
* v0.37.0 brainstorm_health doctor check.
*
- * Surfaces three readiness signals for `gbrain brainstorm` / `gbrain lsd`:
+ * Surfaces four readiness signals for `gbrain brainstorm` / `gbrain lsd`:
*
* 1. Migration v79 applied — the `pages.last_retrieved_at` column exists.
* If missing, LSD's stale-page signal degrades silently (corpus-sampling
@@ -125,14 +127,22 @@ export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Ch
* is fine; explicit-off is a warning so the user notices the setting.
* Fix: `gbrain config set search.track_retrieval true`.
*
- * 3. Calibration cold-start — the latest calibration profile has empty
+ * 3. Chat model pricing (#5873): a cross or judge chat model nothing
+ * prices runs under the default $5 cap with a warning (its calls go
+ * unmetered), and a run with an explicit --max-usd refuses it. The
+ * warning names the model, its role and the `gbrain pricing set`
+ * command. Skipped when no gateway is configured: the chat model is
+ * then unknown, not unpriced.
+ *
+ * 4. Calibration cold-start — the latest calibration profile has empty
* `active_bias_tags`. brainstorm + LSD judge fall back to no-anti-bias
* mode with a stderr warning at run time; this surfaces it earlier.
* Fix: `gbrain calibration --regenerate` once enough takes are resolved.
*
* Returns the FIRST non-ok signal as the status — column-missing dominates,
- * then disabled-tracking, then cold-start. All three are non-blocking warnings;
- * brainstorm + LSD still work, just with degraded signal.
+ * then disabled-tracking, then unpriced-chat-model, then cold-start. All four
+ * are non-blocking warnings; brainstorm + LSD still work, just with degraded
+ * signal.
*/
export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check> {
// (1) Column probe — fast, single-query.
@@ -177,7 +187,26 @@ export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check>
// Config read miss is benign; default-on applies.
}
- // (3) Calibration cold-start — empty active_bias_tags.
+ // (3) Chat model pricing: the models runBrainstorm's cost gate checks.
+ try {
+ const unpriced = await findUnpricedBrainstormChatModel(engine);
+ if (unpriced) {
+ return {
+ name: 'brainstorm_health',
+ status: 'warn',
+ message: `brainstorm ${unpriced.role} model "${unpriced.model}" has no price: brainstorm/lsd run it under the default $${DEFAULT_MAX_COST_USD} cap with a warning (its calls go unmetered), and a run with an explicit --max-usd refuses it. Fix: look up its rate and register it: ${pricingSetCommand(unpriced.model, 'chat')}`,
+ };
+ }
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'brainstorm_health',
+ status: 'warn',
+ message: `Could not check brainstorm chat model pricing (${msg}); brainstorm/lsd may refuse to start under an explicit --max-usd.`,
+ };
+ }
+
+ // (4) Calibration cold-start — empty active_bias_tags.
try {
const calibRows = await engine.executeRaw<{ active_bias_tags: string[] | null }>(
`SELECT active_bias_tags
diff --git a/src/core/brainstorm/cost-gate.ts b/src/core/brainstorm/cost-gate.ts
new file mode 100644
index 0000000000..6db0347285
--- /dev/null
+++ b/src/core/brainstorm/cost-gate.ts
@@ -0,0 +1,208 @@
+/**
+ * Cost gate for one brainstorm / lsd run (#5873).
+ *
+ * The run wraps every gateway call in a BudgetTracker, and the orchestrator
+ * keeps its own ceiling checks (pre-run estimate, mid-run guard over the
+ * crosses, pre-judge check). The policy is the repo-wide one:
+ * - no flag: the $5 default goes on the tracker as a `default` cap, so an
+ * unpriced chat model warns once and runs while priced calls stay
+ * metered; the orchestrator's checks price an unpriced model at the
+ * Sonnet fallback rate, so an oversized run is still stopped.
+ * - `--max-usd N` (legacy `--max-cost N`): a `user` cap. A run that would
+ * call a model nothing prices is refused before any work, with the shared
+ * no_pricing guidance (look up the rate, `gbrain pricing set`, retry).
+ * - `--max-usd off`: no USD cap on the tracker or the checks; spend is still
+ * ledgered and `--strict-budget` still applies.
+ * Operator `pricing.overrides` reach every price the run computes.
+ *
+ * Builds on @andreineacsu's #5959 (pre-judge check, judge-priced estimate,
+ * gateway chat model precedence, brainstorm_health pricing signal).
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { getChatModel, getEmbeddingModel } from '../ai/gateway.ts';
+import { AIConfigError } from '../ai/errors.ts';
+import { BudgetExhausted, loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { canonicalLookup } from '../model-pricing.ts';
+import { isModelPriceable, usageCostUsd, type BudgetKind, type PricingOverrides } from '../budget/reservation-cost.ts';
+import { noPricingFix, noPricingGuidance, noPricingMessage, pricingSetCommand } from '../budget/no-pricing.ts';
+
+/** Ceiling for a run started without a cap flag. */
+export const DEFAULT_MAX_COST_USD = 5;
+
+/** Rate for a chat model nothing prices: Sonnet tier, the gateway's default chat model, derived from canonical. */
+const FALLBACK_CHAT_PRICING = canonicalLookup('anthropic:claude-sonnet-4-6') ?? { input: 3, output: 15 };
+
+/** Judge prompt and verdict tokens per idea; the pre-run estimate and the pre-judge check share them. */
+const JUDGE_INPUT_TOKENS_PER_IDEA = 350;
+const JUDGE_OUTPUT_TOKENS_PER_IDEA = 200;
+
+export interface BrainstormCostGate {
+ /** Ceiling for the estimate, mid-run and pre-judge checks, and the tracker cap; null when the user turned the cap off. */
+ ceilingUsd: number | null;
+ /** `user` for a cap flag (including off), `default` for the $5 default. */
+ capSource: 'user' | 'default';
+ /** The chat model the judge runs, priced by the estimate and the pre-judge check. */
+ judgeModel: string;
+ pricingOverrides: PricingOverrides | undefined;
+ /** Cross and judge chat models nothing prices, cross first, deduplicated. */
+ unpricedChatModels: Array<{ model: string; role: 'chat' | 'judge' }>;
+}
+
+export function resolveBrainstormCostGate(input: {
+ /** The cap flag: a USD amount, null for off, undefined when absent. */
+ maxCostUsd?: number | null;
+ crossModel: string;
+ judgeModel: string;
+ pricingOverrides?: PricingOverrides;
+}): BrainstormCostGate {
+ const unpricedChatModels: BrainstormCostGate['unpricedChatModels'] = [];
+ for (const [model, role] of [[input.crossModel, 'chat'], [input.judgeModel, 'judge']] as const) {
+ if (unpricedChatModels.some((u) => u.model === model)) continue;
+ if (!isModelPriceable(model, 'chat', input.pricingOverrides)) unpricedChatModels.push({ model, role });
+ }
+ return {
+ ceilingUsd: input.maxCostUsd === undefined ? DEFAULT_MAX_COST_USD : input.maxCostUsd,
+ capSource: input.maxCostUsd === undefined ? 'default' : 'user',
+ judgeModel: input.judgeModel,
+ pricingOverrides: input.pricingOverrides,
+ unpricedChatModels,
+ };
+}
+
+/**
+ * The refusal for a user cap that would meet a model nothing prices, or null.
+ * Checked before the preview, retrieval and checkpoint: the capped tracker
+ * would throw the same no_pricing at that model's first reserve(), and for
+ * the judge only after every cross had been paid for.
+ */
+export function userCapNoPricingRefusal(gate: BrainstormCostGate, embedModel: string | null, label: string): BudgetExhausted | null {
+ if (gate.capSource !== 'user' || gate.ceilingUsd === null) return null;
+ const unpriced: { model: string; kind: BudgetKind; role: string } | undefined =
+ gate.unpricedChatModels[0]
+ ? { model: gate.unpricedChatModels[0].model, kind: 'chat', role: gate.unpricedChatModels[0].role }
+ : embedModel && !isModelPriceable(embedModel, 'embed', gate.pricingOverrides)
+ ? { model: embedModel, kind: 'embed', role: 'embedding' }
+ : undefined;
+ if (!unpriced) return null;
+ const pricing = noPricingGuidance(unpriced.model, unpriced.kind);
+ return new BudgetExhausted(noPricingMessage(pricing, { label: `${label} (${unpriced.role} model)`, capUsd: gate.ceilingUsd }), {
+ reason: 'no_pricing',
+ spent: 0,
+ cap: gate.ceilingUsd,
+ modelId: unpriced.model,
+ pricing,
+ capSource: 'user',
+ fix: noPricingFix(pricing),
+ });
+}
+
+/** The remedy an over-ceiling estimate names. Raising the cap does not help when the estimate rests on a guessed rate. */
+export function ceilingRemedy(gate: BrainstormCostGate): string {
+ const unpriced = gate.unpricedChatModels[0];
+ return unpriced
+ ? `register the real rate of "${unpriced.model}" (the estimate assumes Sonnet rates): ${pricingSetCommand(unpriced.model, 'chat')}`
+ : 'raise --max-usd';
+}
+
+/** USD for chat usage at the run's prices. A model nothing prices counts at the Sonnet fallback rate. */
+export function chatCostUsd(
+ model: string,
+ inputTokens: number,
+ outputTokens: number,
+ pricingOverrides?: PricingOverrides,
+): number {
+ return usageCostUsd(model, inputTokens, outputTokens, 'chat', pricingOverrides)
+ ?? (inputTokens / 1_000_000) * FALLBACK_CHAT_PRICING.input
+ + (outputTokens / 1_000_000) * FALLBACK_CHAT_PRICING.output;
+}
+
+/** Projected USD for judging `ideaCount` ideas on `judgeModel`. */
+export function judgeCostUsd(judgeModel: string, ideaCount: number, pricingOverrides?: PricingOverrides): number {
+ return chatCostUsd(
+ judgeModel,
+ ideaCount * JUDGE_INPUT_TOKENS_PER_IDEA,
+ ideaCount * JUDGE_OUTPUT_TOKENS_PER_IDEA,
+ pricingOverrides,
+ );
+}
+
+/**
+ * Stop before the judge when the crosses already paid plus the projected
+ * judge cost pass the ceiling. The mid-run guard watches only the crosses,
+ * so without this check the judge ran past the ceiling on an unmetered model.
+ */
+export function assertJudgeWithinCeiling(
+ gate: BrainstormCostGate,
+ crossModel: string,
+ crossUsage: { input_tokens: number; output_tokens: number },
+ ideaCount: number,
+ label: string,
+): void {
+ if (gate.ceilingUsd === null) return;
+ const spent = chatCostUsd(crossModel, crossUsage.input_tokens, crossUsage.output_tokens, gate.pricingOverrides);
+ const projected = judgeCostUsd(gate.judgeModel, ideaCount, gate.pricingOverrides);
+ if (spent + projected <= gate.ceilingUsd) return;
+ const usd = (n: number) => `$${n.toFixed(2)}`;
+ throw new BudgetExhausted(
+ `${label}: crosses cost ${usd(spent)} and the projected judge cost is ${usd(projected)}, ` +
+ `over the ${usd(gate.ceilingUsd)} ceiling; skipping the judge. Lower --limit, or ${ceilingRemedy(gate)}`,
+ { reason: 'cost', spent, cap: gate.ceilingUsd, modelId: gate.judgeModel },
+ );
+}
+
+/**
+ * Null when the gateway is not configured (unit runs that inject chatFn) or,
+ * for embeddings, when the brain's embedding identity is unverified: the
+ * embedding call then fails before any reserve(). Both are AIConfigError;
+ * anything else is a real failure and propagates.
+ */
+function unlessUnconfigured(read: () => string): string | null {
+ try {
+ return read();
+ } catch (err) {
+ if (err instanceof AIConfigError) return null;
+ throw err;
+ }
+}
+
+/** The chat model a gateway.chat call without `model` runs. */
+export function configuredChatModel(): string | null {
+ return unlessUnconfigured(getChatModel);
+}
+
+/** The embedding model gateway.embedQuery runs. */
+export function configuredEmbeddingModel(): string | null {
+ return unlessUnconfigured(getEmbeddingModel);
+}
+
+/**
+ * Judge-phase model precedence: --judge-model flag, else the
+ * `models.brainstorm.judge` config key, else undefined (falls back to
+ * `modelOverride` then the gateway default at the runJudge callsite).
+ */
+export async function resolveBrainstormJudgeModel(
+ engine: Pick<BrainEngine, 'getConfig'>,
+ judgeModelFlag?: string,
+): Promise<string | undefined> {
+ if (judgeModelFlag) return judgeModelFlag;
+ const configured = await engine.getConfig('models.brainstorm.judge');
+ return configured ?? undefined;
+}
+
+/**
+ * The first chat model a brainstorm run would call that nothing prices, with
+ * its role, or null. Null too when no gateway is configured: the model is then
+ * unknown, not unpriced. The brainstorm_health doctor check reports it.
+ */
+export async function findUnpricedBrainstormChatModel(
+ engine: Pick<BrainEngine, 'getConfig'>,
+): Promise<{ model: string; role: 'chat' | 'judge' } | null> {
+ const chatModel = configuredChatModel();
+ if (!chatModel) return null;
+ return resolveBrainstormCostGate({
+ crossModel: chatModel,
+ judgeModel: (await resolveBrainstormJudgeModel(engine)) ?? chatModel,
+ pricingOverrides: await loadPricingOverrides(engine),
+ }).unpricedChatModels[0] ?? null;
+}
diff --git a/src/core/brainstorm/orchestrator.ts b/src/core/brainstorm/orchestrator.ts
index fce12c6fc4..5f1640a124 100644
--- a/src/core/brainstorm/orchestrator.ts
+++ b/src/core/brainstorm/orchestrator.ts
@@ -47,7 +47,21 @@ import {
type JudgeConfig,
type ChatFn,
} from './judges.ts';
-import { canonicalLookup } from '../model-pricing.ts';
+import {
+ assertJudgeWithinCeiling,
+ ceilingRemedy,
+ chatCostUsd,
+ configuredChatModel,
+ configuredEmbeddingModel,
+ judgeCostUsd,
+ resolveBrainstormCostGate,
+ resolveBrainstormJudgeModel,
+ userCapNoPricingRefusal,
+ type BrainstormCostGate,
+} from './cost-gate.ts';
+import { capNotice } from '../budget/cap-flag.ts';
+import { pricingSetCommand } from '../budget/no-pricing.ts';
+import type { PricingOverrides } from '../budget/reservation-cost.ts';
import { ensureWellFormed } from '../text-safe.ts';
// ---------------------------------------------------------------------------
@@ -58,7 +72,7 @@ import { ensureWellFormed } from '../text-safe.ts';
// module (the only known caller is the test suite).
// ---------------------------------------------------------------------------
-import { BudgetExhausted, BudgetTracker } from '../budget/budget-tracker.ts';
+import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
import { withBudgetTracker } from '../ai/gateway.ts';
import { isInteractive } from '../interaction.ts';
import { agentBlock } from '../agent-markers.ts';
@@ -157,13 +171,17 @@ export interface BrainstormOptions {
/** Stderr sink — defaults to process.stderr.write. Tests pipe into a buffer. */
stderrWrite?: (s: string) => void;
/**
- * Maximum projected cost in USD before the run aborts. Default $5.
+ * Maximum projected cost in USD before the run aborts (`--max-usd`,
+ * legacy `--max-cost`). Undefined = the $5 default; null = `--max-usd off`.
* The pre-run estimate is compared against this ceiling; if higher, we
* abort with a paste-ready error (unless `skipCostPreview` is set AND
* the caller is non-interactive — then we still abort, the ceiling is
- * a hard limit).
+ * a hard limit). A user cap refuses a run on a model nothing prices; the
+ * default warns and runs it (#5873, see cost-gate.ts).
*/
- maxCostUsd?: number;
+ maxCostUsd?: number | null;
+ /** The cap flag as the user typed it, for the cap notice. */
+ maxCostFlag?: string;
/**
* Hard cap on the domain-bank far set. Default 50. Threaded into
* `fetchFar` to prevent the "2K prefix" explosion on large brains.
@@ -259,6 +277,10 @@ export interface BrainstormResult {
actual_usd: number;
input_tokens: number;
output_tokens: number;
+ /** The USD cap the run held, or null when the user turned it off. */
+ cap_usd: number | null;
+ /** `user` for a cap flag (including off), `default` for the $5 default. */
+ cap_source: 'user' | 'default';
};
}
@@ -270,23 +292,25 @@ export interface BrainstormResult {
* Per-profile cost estimate. At Sonnet pricing ($3/M in, $15/M out — the
* gateway fallback), this formula yields brainstorm ~$0.8 and lsd ~$1.0;
* it scales linearly with the configured chat model's pricing (a Haiku 4.5
- * chat_model at $1/$5 lands exactly 3x lower). The estimate is
- * informational — operators see actuals printed at run-end.
+ * chat_model at $1/$5 lands exactly 3x lower). Operator `pricing.overrides`
+ * win over the shipped tables and the judge share is priced at the judge
+ * model (#5873). The estimate is informational — operators see actuals
+ * printed at run-end.
*/
-export function estimateCost(profile: BrainstormProfile, model: string): number {
+export function estimateCost(
+ profile: BrainstormProfile,
+ model: string,
+ pricingOverrides?: PricingOverrides,
+ judgeModel: string = model,
+): number {
const crosses = profile.k_close * profile.m_far;
const ideas = crosses * profile.ideas_per_cross;
// Rough per-cross budget: ~3K in, ~1.5K out (prompt + ideas).
const inTokens = crosses * 3000;
const outTokens = ideas * 250;
// Judge: one batch ~ all ideas in, ~200 tokens per scored idea out.
- const judgeIn = ideas * 350;
- const judgeOut = ideas * 200;
-
- const pricing = canonicalLookup(model) ?? { input: 3, output: 15 };
- const inCost = ((inTokens + judgeIn) / 1_000_000) * pricing.input;
- const outCost = ((outTokens + judgeOut) / 1_000_000) * pricing.output;
- return inCost + outCost;
+ return chatCostUsd(model, inTokens, outTokens, pricingOverrides)
+ + judgeCostUsd(judgeModel, ideas, pricingOverrides);
}
/** Pretty-print a USD cost with 2 decimals + leading dollar. */
@@ -304,6 +328,9 @@ function fmtUsd(n: number): string {
export async function previewCostAndWait(opts: {
profile: BrainstormProfile;
model: string;
+ pricingOverrides?: PricingOverrides;
+ /** Model the judge share is priced at; defaults to `model`. */
+ judgeModel?: string;
skip: boolean;
stderrWrite: (s: string) => void;
/** Test seam — override the wait so suites don't hang. */
@@ -313,7 +340,7 @@ export async function previewCostAndWait(opts: {
/** Test seam — default isInteractive(). */
interactive?: boolean;
}): Promise<{ aborted: boolean; estimate: number }> {
- const estimate = estimateCost(opts.profile, opts.model);
+ const estimate = estimateCost(opts.profile, opts.model, opts.pricingOverrides, opts.judgeModel);
const interactive = opts.interactive ?? isInteractive();
opts.stderrWrite(
`[${opts.profile.label}] estimated cost: ${fmtUsd(estimate)} (${opts.profile.k_close}×${opts.profile.m_far} = ${opts.profile.k_close * opts.profile.m_far} crosses × ${opts.profile.ideas_per_cross} ideas + judge)\n`
@@ -322,10 +349,10 @@ export async function previewCostAndWait(opts: {
if (!interactive) {
// A4 "no silent flip": unattended runs keep proceeding, under the hard cap, and say so.
opts.stderrWrite(agentBlock({
- why: `${opts.profile.label} runs unattended: about ${fmtUsd(estimate)} of model spend${opts.capUsd !== undefined ? `, hard-capped at ${fmtUsd(opts.capUsd)} (--max-cost)` : ''}.`,
+ why: `${opts.profile.label} runs unattended: about ${fmtUsd(estimate)} of model spend${opts.capUsd !== undefined ? `, hard-capped at ${fmtUsd(opts.capUsd)} (--max-usd)` : ''}.`,
consent: 'paid',
next: 'run',
- if_no: 'Tell the user the spend is happening; lower it with --max-cost <usd>.',
+ if_no: 'Tell the user the spend is happening; lower it with --max-usd <usd>.',
}));
return { aborted: false, estimate };
}
@@ -526,31 +553,32 @@ export interface BrainstormRunConfig {
/**
* Model used for the cost preview + hard cost ceiling. Mirrors what the
* gateway will actually run: explicit --model override, else the configured
- * chat_model (gateway default), else the hardcoded gateway fallback. Before
- * this resolved through config, a non-Sonnet chat_model got its preview
- * priced against the wrong model. (Takeover of PR #1855 by @starm2010.)
+ * gateway's chat model (which carries the DB-plane `models.tier.*` /
+ * `models.default` overrides the file config lacks, #5873), else the file
+ * config's chat_model, else the hardcoded gateway fallback. Before this
+ * resolved through config, a non-Sonnet chat_model got its preview priced
+ * against the wrong model. (Takeover of PR #1855 by @starm2010.)
*/
export function resolveBrainstormChatModel(
config: { chat_model?: string },
modelOverride?: string,
+ gatewayChatModel?: string | null,
): string {
- return modelOverride ?? config.chat_model ?? 'anthropic:claude-sonnet-4-6';
+ return modelOverride ?? gatewayChatModel ?? config.chat_model ?? 'anthropic:claude-sonnet-4-6';
}
-/**
- * Judge-phase model precedence: --judge-model flag, else the
- * `models.brainstorm.judge` config key, else undefined (falls back to
- * `modelOverride` then the gateway default at the runJudge callsite).
- */
-export async function resolveBrainstormJudgeModel(
- engine: BrainEngine,
- judgeModelFlag?: string,
-): Promise<string | undefined> {
- if (judgeModelFlag) return judgeModelFlag;
- const configured = await engine.getConfig('models.brainstorm.judge');
- return configured ?? undefined;
+/** Models and cost gate resolved once per run, before the tracker scope opens. */
+interface BrainstormRunPlan {
+ chatModel: string;
+ /** Judge model from --judge-model, `models.brainstorm.judge` or the --model override; undefined runs the gateway default. */
+ judgeModel: string | undefined;
+ gate: BrainstormCostGate;
}
+// Judge-model precedence lives beside the cost gate that prices it, so the
+// brainstorm_health doctor check reads it without this module's imports.
+export { resolveBrainstormJudgeModel };
+
export async function runBrainstorm(
engine: BrainEngine,
config: BrainstormRunConfig,
@@ -586,17 +614,49 @@ async function runBrainstormImpl(
// estimated call leaks past the ceiling (TX1). BudgetExhausted is NOT
// SQLSTATE 57014, so the outer classifyBrainstormError lets it pass
// through with its original shape (which the CLI formatter renders).
+ //
+ // #5873: the cap carries its source. A user cap refuses a run that would
+ // call a model nothing prices, before any work, with the shared no_pricing
+ // guidance; the $5 default is a `default` cap, so the tracker warns and
+ // runs an unpriced model while still metering priced calls. Every price in
+ // the run reads operator `pricing.overrides`.
+ const label = opts.profile?.label ?? 'brainstorm';
+ const stderr = opts.stderrWrite ?? ((s: string) => { process.stderr.write(s); });
+ const pricingOverrides = await loadPricingOverrides(engine);
+ const chatModel = resolveBrainstormChatModel(config, opts.modelOverride, configuredChatModel());
+ const judgeModel = (await resolveBrainstormJudgeModel(engine, opts.judgeModel)) ?? opts.modelOverride;
+ const gate = resolveBrainstormCostGate({
+ maxCostUsd: opts.maxCostUsd,
+ crossModel: chatModel,
+ judgeModel: judgeModel ?? chatModel,
+ pricingOverrides,
+ });
+ const refusal = userCapNoPricingRefusal(gate, opts.embedQueryFn ? null : configuredEmbeddingModel(), label);
+ if (refusal) throw refusal;
+ stderr(`[${label}] ${capNotice({ usd: gate.ceilingUsd, source: gate.capSource, flag: opts.maxCostFlag })}\n`);
+ if (gate.capSource === 'default') {
+ for (const { model, role } of gate.unpricedChatModels) {
+ stderr(
+ `[${label}] ${role} model "${model}" has no price: the default ${fmtUsd(gate.ceilingUsd!)} cap cannot meter its calls, ` +
+ `so the estimate, mid-run and pre-judge checks count it at Sonnet rates. To meter its real price, register it: ` +
+ `${pricingSetCommand(model, 'chat')}\n`,
+ );
+ }
+ }
const _runTracker = new BudgetTracker({
- label: `brainstorm.${opts.profile?.label ?? 'brainstorm'}`,
- maxCostUsd: opts.maxCostUsd ?? 5,
+ label: `brainstorm.${label}`,
+ ...(gate.ceilingUsd !== null ? { maxCostUsd: gate.ceilingUsd, capSource: gate.capSource } : {}),
+ pricingOverrides,
});
- return withBudgetTracker(_runTracker, () => _runBrainstormInner(engine, config, opts));
+ return withBudgetTracker(_runTracker, () =>
+ _runBrainstormInner(engine, config, opts, { chatModel, judgeModel, gate }));
}
async function _runBrainstormInner(
engine: BrainEngine,
config: BrainstormRunConfig,
opts: BrainstormOptions,
+ plan: BrainstormRunPlan,
): Promise<BrainstormResult> {
const profile = opts.profile ?? BRAINSTORM_PROFILE;
const stderr = opts.stderrWrite ?? ((s: string) => { process.stderr.write(s); });
@@ -604,12 +664,13 @@ async function _runBrainstormInner(
const embedFn = opts.embedQueryFn ?? embedQuery;
// ---- Phase 0: cost preview + TTY grace ----
- const modelStr = resolveBrainstormChatModel(config, opts.modelOverride);
const { aborted, estimate } = await previewCostAndWait({
profile,
- model: modelStr,
+ model: plan.chatModel,
+ pricingOverrides: plan.gate.pricingOverrides,
+ judgeModel: plan.gate.judgeModel,
skip: opts.skipCostPreview === true,
- stderrWrite: stderr, capUsd: opts.maxCostUsd ?? 5,
+ stderrWrite: stderr, capUsd: plan.gate.ceilingUsd ?? undefined,
});
if (aborted) {
throw new Error('brainstorm: aborted before run (Ctrl-C during cost preview window)');
@@ -622,11 +683,11 @@ async function _runBrainstormInner(
// the wild on a 13K-page brain) because `m_far` got blown out by
// un-capped prefix sampling. We refuse to start if the *estimate alone*
// already exceeds the user's ceiling.
- const maxCostUsd = opts.maxCostUsd ?? 5;
- if (estimate > maxCostUsd) {
+ const maxCostUsd = plan.gate.ceilingUsd;
+ if (maxCostUsd !== null && estimate > maxCostUsd) {
throw new BudgetExhausted(
`${profile.label}: estimated cost ${fmtUsd(estimate)} exceeds --max-cost ${fmtUsd(maxCostUsd)}. ` +
- `Lower --limit, raise --max-cost, or pass --max-far-set <n> to cap the domain bank.`,
+ `Lower --limit, ${ceilingRemedy(plan.gate)}, or pass --max-far-set <n> to cap the domain bank.`,
{ reason: 'cost', spent: estimate, cap: maxCostUsd },
);
}
@@ -791,7 +852,7 @@ async function _runBrainstormInner(
};
let totalUsage = { input_tokens: 0, output_tokens: 0 };
- let crossModel = modelStr;
+ let crossModel = plan.chatModel;
// Parallelize chat calls bounded at DEFAULT_PARALLELISM.
const rawIdeasByCross = await mapWithConcurrency(crosses, DEFAULT_PARALLELISM, async (cross) => {
@@ -827,11 +888,9 @@ async function _runBrainstormInner(
crossModel = result.model;
// Mid-run cost guard: if running spend already exceeds the projected
// ceiling or the strict-budget multiplier, abort the remaining crosses.
- const runningPricing = canonicalLookup(result.model) ?? { input: 3, output: 15 };
- const runningUsd =
- (totalUsage.input_tokens / 1_000_000) * runningPricing.input +
- (totalUsage.output_tokens / 1_000_000) * runningPricing.output;
- if (runningUsd > maxCostUsd) {
+ const runningUsd = chatCostUsd(
+ result.model, totalUsage.input_tokens, totalUsage.output_tokens, plan.gate.pricingOverrides);
+ if (maxCostUsd !== null && runningUsd > maxCostUsd) {
throw new BudgetExhausted(
`${profile.label}: running cost ${fmtUsd(runningUsd)} exceeded --max-cost ${fmtUsd(maxCostUsd)} mid-run; aborting remaining crosses`,
{ reason: 'cost', spent: runningUsd, cap: maxCostUsd },
@@ -914,8 +973,9 @@ async function _runBrainstormInner(
close_slug: i.close_slug,
far_slug: i.far_slug,
}));
+ assertJudgeWithinCeiling(plan.gate, crossModel, totalUsage, judgeInput.length, profile.label);
const judgeResult = await runJudge(profile.judge_config, judgeInput, {
- modelOverride: (await resolveBrainstormJudgeModel(engine, opts.judgeModel)) ?? opts.modelOverride,
+ modelOverride: plan.judgeModel,
chatFn: opts.chatFn,
activeBiasTags: activeBiasTags ?? undefined,
abortSignal: opts.abortSignal,
@@ -953,8 +1013,7 @@ async function _runBrainstormInner(
// Cost actuals (codex r2 #10).
const totalIn = totalUsage.input_tokens + judgeUsage.input_tokens;
const totalOut = totalUsage.output_tokens + judgeUsage.output_tokens;
- const pricing = canonicalLookup(crossModel) ?? { input: 3, output: 15 };
- const actual = (totalIn / 1_000_000) * pricing.input + (totalOut / 1_000_000) * pricing.output;
+ const actual = chatCostUsd(crossModel, totalIn, totalOut, plan.gate.pricingOverrides);
stderr(`[${profile.label}] actual cost: ${fmtUsd(actual)} (estimated ${fmtUsd(estimate)}) — in=${totalIn} out=${totalOut} tokens\n`);
// TX4: surface --resume hint when any cross failed during this run.
@@ -1003,6 +1062,8 @@ async function _runBrainstormInner(
actual_usd: actual,
input_tokens: totalIn,
output_tokens: totalOut,
+ cap_usd: plan.gate.ceilingUsd,
+ cap_source: plan.gate.capSource,
},
};
}
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 6e73400304..6d13164142 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -164,6 +164,15 @@ export function parsePricingOverrides(raw: unknown): PricingOverrides | undefine
}
}
}
+ // An override keyed by the alias the operator configured
+ // (`nvidia:nemotron-3-super`) must also price the id the gateway records
+ // for it (`nvidia:nvidia/nemotron-3-super-120b-a12b`): overrideFor
+ // canonicalizes the looked-up id, so the stored key needs its canonical
+ // twin. An explicit row for the canonical id wins. (From #5959.)
+ for (const [key, rate] of Object.entries(out)) {
+ const canonical = canonicalPricingKey(key).toLowerCase();
+ if (!(canonical in out)) out[canonical] = rate;
+ }
return Object.keys(out).length > 0 ? out : undefined;
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 14164c2b1c..1ac69b2116 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -25,7 +25,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--oauth-client-id', '--oauth-client-secret', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
- 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--probe', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
+ 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--regenerate', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--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', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--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', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--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'],
+ 'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
@@ -116,7 +116,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--harness', '--help', '--http', '--json', '--log-full-params', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--tools-json', '--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', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--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', '--max-usd', '--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', '--probe', '--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', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
diff --git a/test/brainstorm/unpriced-chat-model.serial.test.ts b/test/brainstorm/unpriced-chat-model.serial.test.ts
new file mode 100644
index 0000000000..eb24636cd0
--- /dev/null
+++ b/test/brainstorm/unpriced-chat-model.serial.test.ts
@@ -0,0 +1,446 @@
+/**
+ * #5873: brainstorm / lsd on a chat model that has no price.
+ *
+ * Policy (no-pricing.ts): under the default $5 cap an unpriced model warns and
+ * runs, while the run tracker keeps metering priced calls and the
+ * orchestrator's estimate / mid-run / pre-judge checks count the unpriced
+ * model at Sonnet rates; an explicit --max-usd refuses a run that would call
+ * a model nothing prices, before any work, with the shared no_pricing
+ * guidance; --max-usd off removes the USD ceiling. `pricing.overrides`
+ * prices every check in the run.
+ *
+ * Regression: the run tracker was built as `maxCostUsd ?? 5` (a user cap)
+ * without `pricingOverrides`, so every gateway.chat reserve() on an unpriced
+ * model threw no_pricing even with no flag, and the registered rate never
+ * reached the run.
+ *
+ * Every other brainstorm test injects `chatFn`, which bypasses the gateway's
+ * reserve(); these runs go through gateway.chat. Serial: configureGateway and
+ * the transport seams mutate module state.
+ *
+ * Adapted from @andreineacsu's #5959 suite.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { ChunkInput } from '../../src/core/types.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import {
+ runBrainstorm,
+ BRAINSTORM_PROFILE,
+ BudgetExhausted,
+ type BrainstormProfile,
+} from '../../src/core/brainstorm/orchestrator.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __setChatTransportForTests,
+ __setEmbedTransportForTests,
+ type ChatOpts,
+ type ChatResult,
+} from '../../src/core/ai/gateway.ts';
+import { checkBrainstormHealth } from '../../src/commands/doctor/checks/graph-embedding.ts';
+import { resolveBrainstormCostGate } from '../../src/core/brainstorm/cost-gate.ts';
+import { readdirSync, readFileSync } from 'node:fs';
+
+/** Fictional model ids: in no pricing table, so a call to them can never reach a provider. */
+const UNPRICED = 'claude-cli:claude-opus-9-9';
+const UNPRICED_JUDGE = 'claude-cli:claude-judge-9-9';
+const UNPRICED_EMBED = 'litellm:my-embed';
+const PRICED = 'anthropic:claude-sonnet-4-6';
+
+/** k_close x m_far sets the estimate (far above $5 at Sonnet rates); the 4-page far set caps the real crosses. */
+const BIG_ESTIMATE: BrainstormProfile = { ...BRAINSTORM_PROFILE, k_close: 2, m_far: 2000, ideas_per_cross: 1 };
+/** Estimate well under $1 at Sonnet rates; the seeded brain yields 2 x 4 = 8 crosses, one idea each. */
+const TINY: BrainstormProfile = { ...BRAINSTORM_PROFILE, k_close: 2, m_far: 4, ideas_per_cross: 1 };
+const DIMS = 1536;
+
+let engine: PGLiteEngine;
+let home: string;
+let homeBackup: string | undefined;
+const calls = { cross: 0, judge: 0, embed: 0 };
+
+function basisEmbedding(idx: number, dim = DIMS): Float32Array {
+ const v = new Float32Array(dim);
+ v[idx % dim] = 1.0;
+ return v;
+}
+
+async function seedPage(slug: string, body: string, basis: number): Promise<void> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '' });
+ await installFixtureChunks(engine, slug, [
+ { chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth', embedding: basisEmbedding(basis), token_count: 6 },
+ ] satisfies ChunkInput[]);
+}
+
+type Usage = { input: number; output: number };
+
+/**
+ * Answers cross and judge prompts the way the e2e resume stub does. `model`
+ * is reported as the served model; `crossUsage` is the token count each cross
+ * call bills, so a case can drive the mid-run guard and the pre-judge check.
+ */
+function transportFor(model: string, crossUsage: Usage) {
+ return async (opts: ChatOpts): Promise<ChatResult> => {
+ const user = opts.messages.find((m) => m.role === 'user');
+ const content = typeof user?.content === 'string' ? user.content : '';
+ let text: string;
+ let usage: Usage = { input: 100, output: 50 };
+ if (/\(close=.* × far=.*\)/.test(content)) {
+ calls.judge++;
+ const ids = Array.from(content.matchAll(/## Idea (\S+)/g)).map((m) => m[1] as string);
+ const ideas = ids.map((id) => ({
+ id,
+ scores: { originality: 4, resistance: 4, thesis_density: 4, concrete_grounding: 4, cognitive_load: 4 },
+ note: 'stub judge',
+ }));
+ text = '```json\n' + JSON.stringify({ ideas }) + '\n```';
+ } else {
+ calls.cross++;
+ usage = crossUsage;
+ // parseIdeaResponse needs at least two numbered items.
+ text = `1. stub idea ${calls.cross}\n2. backup idea ${calls.cross}`;
+ }
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ model,
+ providerId: 'stub',
+ usage: { input_tokens: usage.input, output_tokens: usage.output, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ };
+ };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedPage('wiki/close-a', 'battery recycling question close anchor a', 10);
+ await seedPage('wiki/close-b', 'battery recycling question close anchor b', 11);
+ await seedPage('concepts/tide-a', 'Far content: tidal energy body a.', 200);
+ await seedPage('concepts/tide-b', 'Far content: tidal energy body b.', 201);
+ await seedPage('people/founder-a', 'Far content: founder notes a.', 202);
+ await seedPage('people/founder-b', 'Far content: founder notes b.', 203);
+}, 60_000);
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-5873-'));
+ homeBackup = process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = home;
+ calls.cross = 0;
+ calls.judge = 0;
+ calls.embed = 0;
+});
+
+afterEach(async () => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.unsetConfig('pricing.overrides');
+ await engine.unsetConfig('models.brainstorm.judge');
+ if (homeBackup === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = homeBackup;
+ rmSync(home, { recursive: true, force: true });
+});
+
+interface RunCase {
+ name: string;
+ /** Chat model the gateway runs (`models.tier.reasoning` lands here in the CLI). */
+ gatewayModel: string;
+ /** The file-config `chat_model` the CLI passes as `config`. */
+ fileModel?: string;
+ /** `models.brainstorm.judge`. */
+ judgeModel?: string;
+ /** Gateway embedding model; when set, the question embeds through gateway.embed instead of an injected fn. */
+ embeddingModel?: string;
+ overrides?: Record<string, number | Usage>;
+ maxCostUsd?: number | null;
+ profile: BrainstormProfile;
+ /** Tokens each cross call bills (default 100 in / 50 out). */
+ crossUsage?: Usage;
+ expect:
+ | { completes: true; judgeFailed?: boolean; crosses?: number; stderr?: RegExp; notStderr?: RegExp }
+ /** `refused`: before the preview, at the estimate, or mid-run after at least one cross. */
+ | { reason: 'cost' | 'no_pricing'; message: RegExp; refused: 'before-preview' | 'at-estimate' | 'mid-run' };
+}
+
+const RUN_CASES: RunCase[] = [
+ {
+ name: 'unpriced chat model, no cap flag: runs under the default cap and names the model with the registration command',
+ gatewayModel: UNPRICED,
+ profile: TINY,
+ expect: { completes: true, judgeFailed: false, stderr: /chat model "claude-cli:claude-opus-9-9" has no price: the default \$5\.00 cap cannot meter its calls.*gbrain pricing set claude-cli:claude-opus-9-9 --input/ },
+ },
+ {
+ name: 'unpriced chat model, no cap flag: the $5 default still stops an oversized run at Sonnet rates',
+ gatewayModel: UNPRICED,
+ profile: BIG_ESTIMATE,
+ expect: { reason: 'cost', message: /estimated cost \$67\.20 exceeds --max-cost \$5\.00\. Lower --limit, register the real rate of "claude-cli:claude-opus-9-9" \(the estimate assumes Sonnet rates\): gbrain pricing set/, refused: 'at-estimate' },
+ },
+ {
+ name: 'unpriced chat model, no cap flag: the mid-run guard stops crosses past $5 at Sonnet rates',
+ gatewayModel: UNPRICED,
+ profile: TINY,
+ crossUsage: { input: 0, output: 400_000 }, // $6.00 per cross at the $15/M Sonnet output rate
+ expect: { reason: 'cost', message: /running cost \$6\.00 exceeded --max-cost \$5\.00 mid-run/, refused: 'mid-run' },
+ },
+ {
+ name: 'unpriced judge model, no cap flag: the run completes and names the judge',
+ gatewayModel: PRICED,
+ judgeModel: UNPRICED_JUDGE,
+ profile: TINY,
+ expect: { completes: true, judgeFailed: false, stderr: /judge model "claude-cli:claude-judge-9-9" has no price/ },
+ },
+ {
+ name: 'the pre-judge check skips a judge whose projected cost passes the ceiling, keeping the ideas',
+ gatewayModel: UNPRICED,
+ judgeModel: UNPRICED_JUDGE,
+ // Estimate: $0.10 crosses + $0.32 judge. Real run: 8 crosses x $0.60 = $4.80, + $0.32 judge > $5.
+ overrides: { [UNPRICED_JUDGE]: { input: 0, output: 200 } },
+ crossUsage: { input: 0, output: 40_000 },
+ profile: TINY,
+ expect: { completes: true, judgeFailed: true, crosses: 8, stderr: /crosses cost \$4\.80 and the projected judge cost is \$0\.32, over the \$5\.00 ceiling; skipping the judge/ },
+ },
+ {
+ name: 'pricing.overrides reaches the run tracker: an explicit cap runs on the registered rate',
+ gatewayModel: UNPRICED,
+ overrides: { [UNPRICED]: 3 },
+ maxCostUsd: 1,
+ profile: TINY,
+ expect: { completes: true, judgeFailed: false, stderr: /cap: \$1\.00 \(--max-usd; remove it with --max-usd off\)/ },
+ },
+ {
+ name: 'pricing.overrides reaches the pre-run estimate: the explicit cap holds against the registered rate',
+ gatewayModel: UNPRICED,
+ overrides: { [UNPRICED]: 0 },
+ maxCostUsd: 1,
+ profile: BIG_ESTIMATE,
+ expect: { completes: true },
+ },
+ {
+ name: 'the estimate prices the chat model the gateway runs, not the file-config chat_model',
+ gatewayModel: UNPRICED,
+ fileModel: PRICED,
+ overrides: { [UNPRICED]: 0 },
+ profile: BIG_ESTIMATE,
+ expect: { completes: true },
+ },
+ {
+ name: 'an unpriced embedding model under the default cap: the question embedding runs (unmetered) instead of failing',
+ gatewayModel: PRICED,
+ embeddingModel: UNPRICED_EMBED,
+ profile: TINY,
+ expect: { completes: true, notStderr: /question embedding failed/ },
+ },
+ {
+ name: 'an unpriced embedding model under an explicit cap: refused before any work with the registration command',
+ gatewayModel: PRICED,
+ embeddingModel: UNPRICED_EMBED,
+ maxCostUsd: 1,
+ profile: TINY,
+ expect: { reason: 'no_pricing', message: /gbrain has no pricing for embedding model "litellm:my-embed".*gbrain pricing set litellm:my-embed --rate/, refused: 'before-preview' },
+ },
+ {
+ name: 'unpriced chat model under an explicit cap: refused before any work with the shared no_pricing guidance',
+ gatewayModel: UNPRICED,
+ maxCostUsd: 1,
+ profile: TINY,
+ expect: { reason: 'no_pricing', message: /brainstorm \(chat model\): gbrain has no pricing for chat model "claude-cli:claude-opus-9-9" \(provider claude-cli\), so the \$1\.00 cost cap can't be enforced\. Look up .*gbrain pricing set claude-cli:claude-opus-9-9 --input/, refused: 'before-preview' },
+ },
+ {
+ name: 'unpriced judge model under an explicit cap: refused before the crosses are paid for',
+ gatewayModel: PRICED,
+ judgeModel: UNPRICED_JUDGE,
+ maxCostUsd: 1,
+ profile: TINY,
+ expect: { reason: 'no_pricing', message: /brainstorm \(judge model\): gbrain has no pricing for chat model "claude-cli:claude-judge-9-9"/, refused: 'before-preview' },
+ },
+ {
+ name: 'priced chat model, no cap flag: the default $5 ceiling still refuses an oversized run',
+ gatewayModel: PRICED,
+ profile: BIG_ESTIMATE,
+ expect: { reason: 'cost', message: /exceeds --max-cost \$5\.00\. Lower --limit, raise --max-usd/, refused: 'at-estimate' },
+ },
+ {
+ name: '--max-usd off: an estimate far past $5 runs, and the notice says the cap is off',
+ gatewayModel: PRICED,
+ maxCostUsd: null,
+ profile: BIG_ESTIMATE,
+ expect: { completes: true, stderr: /cap: off \(--max-usd off; spend is still ledgered/ },
+ },
+ {
+ name: '--max-usd off on an unpriced model: runs without a no_pricing refusal',
+ gatewayModel: UNPRICED,
+ maxCostUsd: null,
+ profile: BIG_ESTIMATE,
+ expect: { completes: true, notStderr: /has no price: the default/ },
+ },
+];
+
+describe('#5873 brainstorm on an unpriced chat model', () => {
+ for (const c of RUN_CASES) {
+ test(c.name, async () => {
+ configureGateway({
+ chat_model: c.gatewayModel,
+ ...(c.embeddingModel ? { embedding_model: c.embeddingModel, embedding_dimensions: DIMS } : {}),
+ env: {},
+ });
+ __setChatTransportForTests(transportFor(c.gatewayModel, c.crossUsage ?? { input: 100, output: 50 }));
+ if (c.embeddingModel) {
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ calls.embed++;
+ return { embeddings: values.map(() => Array.from(basisEmbedding(10))), usage: { tokens: 0 } };
+ }) as never);
+ }
+ if (c.overrides) await engine.setConfig('pricing.overrides', JSON.stringify(c.overrides));
+ if (c.judgeModel) await engine.setConfig('models.brainstorm.judge', c.judgeModel);
+ const stderr: string[] = [];
+ const run = runBrainstorm(engine, c.fileModel ? { chat_model: c.fileModel } : {}, {
+ question: 'battery recycling question',
+ profile: c.profile,
+ skipCostPreview: true,
+ maxCostUsd: c.maxCostUsd,
+ ...(typeof c.maxCostUsd === 'number' || c.maxCostUsd === null ? { maxCostFlag: '--max-usd' } : {}),
+ embedQueryFn: c.embeddingModel ? undefined : async () => basisEmbedding(10),
+ stderrWrite: (s) => { stderr.push(s); },
+ });
+
+ if ('completes' in c.expect) {
+ // Carry the run's stderr into the failure: per-cross errors are only warned there.
+ const result = await run.catch((e: unknown) => {
+ throw new Error(`${e instanceof Error ? e.message : String(e)}\n${stderr.join('')}`);
+ });
+ expect(result.ideas.length).toBeGreaterThan(0);
+ expect(calls.cross).toBeGreaterThan(0);
+ expect(result.cost.cap_usd).toBe(c.maxCostUsd === undefined ? 5 : c.maxCostUsd);
+ expect(result.cost.cap_source).toBe(c.maxCostUsd === undefined ? 'default' : 'user');
+ if (c.expect.crosses !== undefined) expect(calls.cross).toBe(c.expect.crosses);
+ if (c.expect.judgeFailed !== undefined) {
+ expect(result.judge_failed).toBe(c.expect.judgeFailed);
+ expect(calls.judge > 0).toBe(!c.expect.judgeFailed);
+ }
+ if (c.expect.stderr) expect(stderr.join('')).toMatch(c.expect.stderr);
+ if (c.expect.notStderr) expect(stderr.join('')).not.toMatch(c.expect.notStderr);
+ if (c.embeddingModel) expect(calls.embed).toBeGreaterThan(0);
+ return;
+ }
+ let err: unknown = null;
+ try { await run; } catch (e) { err = e; }
+ expect(err).toBeInstanceOf(BudgetExhausted);
+ expect((err as BudgetExhausted).reason).toBe(c.expect.reason);
+ expect((err as Error).message).toMatch(c.expect.message);
+ if (c.expect.reason === 'no_pricing') {
+ expect((err as BudgetExhausted).pricing?.code).toBe('no_pricing');
+ expect((err as BudgetExhausted).fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'pricing', 'set']);
+ expect((err as BudgetExhausted).capSource).toBe('user');
+ }
+ expect(calls.judge).toBe(0);
+ expect(calls.embed).toBe(0);
+ if (c.expect.refused === 'mid-run') {
+ expect(calls.cross).toBeGreaterThan(0);
+ } else {
+ expect(calls.cross).toBe(0);
+ // Refused before the preview means no estimate line and no retrieval.
+ expect(stderr.join('').includes('estimated cost')).toBe(c.expect.refused === 'at-estimate');
+ }
+ });
+ }
+
+ test('a default cap with an unpriced judge keeps metering the priced cross calls', async () => {
+ const auditDir = mkdtempSync(join(tmpdir(), 'gbrain-5873-audit-'));
+ const prev = process.env.GBRAIN_AUDIT_DIR;
+ process.env.GBRAIN_AUDIT_DIR = auditDir;
+ try {
+ configureGateway({ chat_model: PRICED, env: {} });
+ __setChatTransportForTests(transportFor(PRICED, { input: 100, output: 50 }));
+ await engine.setConfig('models.brainstorm.judge', UNPRICED_JUDGE);
+ await runBrainstorm(engine, {}, {
+ question: 'battery recycling question',
+ profile: TINY,
+ skipCostPreview: true,
+ embedQueryFn: async () => basisEmbedding(10),
+ stderrWrite: () => {},
+ });
+ const lines = readdirSync(auditDir)
+ .filter((f) => f.startsWith('budget-'))
+ .flatMap((f) => readFileSync(join(auditDir, f), 'utf8').trim().split('\n'))
+ .map((l) => JSON.parse(l) as { event: string; model?: string; actual_cost_usd?: number; max_cost_usd?: number | null });
+ const priced = lines.filter((l) => l.event === 'record' && l.actual_cost_usd !== undefined);
+ expect(priced.length).toBeGreaterThan(0);
+ expect(priced.every((l) => l.max_cost_usd === 5)).toBe(true);
+ expect(lines.some((l) => l.event === 'reserve_unpriced' && l.model === UNPRICED_JUDGE)).toBe(true);
+ expect(lines.some((l) => l.event === 'reserve_no_pricing')).toBe(false);
+ } finally {
+ if (prev === undefined) delete process.env.GBRAIN_AUDIT_DIR;
+ else process.env.GBRAIN_AUDIT_DIR = prev;
+ rmSync(auditDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('#5873 resolveBrainstormCostGate', () => {
+ test('no flag is the $5 default; a number is a user cap; null is off', () => {
+ const base = { crossModel: PRICED, judgeModel: PRICED };
+ expect(resolveBrainstormCostGate(base)).toMatchObject({ ceilingUsd: 5, capSource: 'default', unpricedChatModels: [] });
+ expect(resolveBrainstormCostGate({ ...base, maxCostUsd: 2 })).toMatchObject({ ceilingUsd: 2, capSource: 'user' });
+ expect(resolveBrainstormCostGate({ ...base, maxCostUsd: null })).toMatchObject({ ceilingUsd: null, capSource: 'user' });
+ });
+
+ test('unpriced cross and judge models are listed once each, cross first; an override prices them', () => {
+ expect(resolveBrainstormCostGate({ crossModel: UNPRICED, judgeModel: UNPRICED }).unpricedChatModels).toEqual([{ model: UNPRICED, role: 'chat' }]);
+ expect(resolveBrainstormCostGate({ crossModel: UNPRICED, judgeModel: UNPRICED_JUDGE }).unpricedChatModels)
+ .toEqual([{ model: UNPRICED, role: 'chat' }, { model: UNPRICED_JUDGE, role: 'judge' }]);
+ expect(resolveBrainstormCostGate({ crossModel: UNPRICED, judgeModel: UNPRICED, pricingOverrides: { [UNPRICED]: { input: 1, output: 1 } } }).unpricedChatModels).toEqual([]);
+ });
+});
+
+describe('#5873 brainstorm_health names an unpriced brainstorm chat model', () => {
+ const DOCTOR_CASES: Array<{
+ name: string;
+ gatewayModel: string;
+ judgeModel?: string;
+ overrides?: Record<string, number>;
+ unpriced: { model: string; role: 'chat' | 'judge' } | null;
+ }> = [
+ { name: 'unpriced gateway chat model -> warn', gatewayModel: UNPRICED, unpriced: { model: UNPRICED, role: 'chat' } },
+ { name: 'unpriced judge model (models.brainstorm.judge) -> warn naming the judge', gatewayModel: PRICED, judgeModel: UNPRICED_JUDGE, unpriced: { model: UNPRICED_JUDGE, role: 'judge' } },
+ { name: 'pricing.overrides prices it -> no pricing warning', gatewayModel: UNPRICED, overrides: { [UNPRICED]: 3 }, unpriced: null },
+ { name: 'priced chat model -> no pricing warning', gatewayModel: PRICED, unpriced: null },
+ ];
+
+ for (const c of DOCTOR_CASES) {
+ test(c.name, async () => {
+ configureGateway({ chat_model: c.gatewayModel, env: {} });
+ if (c.judgeModel) await engine.setConfig('models.brainstorm.judge', c.judgeModel);
+ if (c.overrides) await engine.setConfig('pricing.overrides', JSON.stringify(c.overrides));
+ const check = await checkBrainstormHealth(engine);
+ if (c.unpriced) {
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`brainstorm ${c.unpriced.role} model "${c.unpriced.model}" has no price`);
+ expect(check.message).toContain('under the default $5 cap');
+ expect(check.message).toContain('--max-usd');
+ expect(check.message).toContain(`gbrain pricing set ${c.unpriced.model} --input`);
+ } else {
+ expect(check.message).not.toContain('has no price');
+ }
+ });
+ }
+
+ test('no configured gateway -> the pricing signal is skipped, not guessed', async () => {
+ resetGateway();
+ const check = await checkBrainstormHealth(engine);
+ expect(check.message).not.toContain('has no price');
+ });
+});
diff --git a/test/budget/provider-wildcard-pricing.test.ts b/test/budget/provider-wildcard-pricing.test.ts
index f93e5bec2f..cde94ce6a1 100644
--- a/test/budget/provider-wildcard-pricing.test.ts
+++ b/test/budget/provider-wildcard-pricing.test.ts
@@ -97,3 +97,18 @@ describe('#5847 deepseek:deepseek-flash is priced', () => {
expect(res.estimatedCostUsd).toBeCloseTo(32_000 / 1_000_000 * 1.2, 9);
});
});
+
+describe('#5873 an override keyed by a model alias prices the id the provider serves for it', () => {
+ test('nvidia:nemotron-3-super override prices nvidia:nvidia/nemotron-3-super-120b-a12b', () => {
+ const served = 'nvidia:nvidia/nemotron-3-super-120b-a12b';
+ expect(isModelPriceable(served, 'chat', { 'nvidia:nemotron-3-super': { input: 1, output: 2 } })).toBe(false);
+ const parsed = parsePricingOverrides({ 'nvidia:nemotron-3-super': { input: 1, output: 2 } });
+ expect(priceFor(served, 'chat', parsed)).toEqual({ pricing: { input: 1, output: 2 }, source: 'override' });
+ });
+
+ test('an explicit row for the served id wins over the alias row', () => {
+ const served = 'nvidia:nvidia/nemotron-3-super-120b-a12b';
+ const parsed = parsePricingOverrides({ 'nvidia:nemotron-3-super': 1, [served]: 5 });
+ expect(priceFor(served, 'chat', parsed)?.pricing).toEqual({ input: 5, output: 5 });
+ });
+});