Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(budget): D19 one shared cost-cap flag parser; enrich, onboard and eval longmemeval use it

time-attack13f476e6b816
diff --git a/src/commands/enrich.ts b/src/commands/enrich.ts
index a340f9fd91..122749606a 100644
--- a/src/commands/enrich.ts
+++ b/src/commands/enrich.ts
@@ -40,6 +40,7 @@ import type { OperationContext } from '../core/operations.ts';
import { configureGatewayIfUninitialized, isAvailable, chat, getChatModel, withBudgetTracker } from '../core/ai/gateway.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';
import { noPricingSteps } from '../core/budget/no-pricing.ts';
+import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
import { ERROR_CATALOGUE } from '../core/error-catalogue.ts';
import { hybridSearch } from '../core/search/hybrid.ts';
import { INTERNAL_BREADTH_SEARCH_OPTS } from '../core/search/internal-breadth.ts';
@@ -729,6 +730,7 @@ function parseDurationDays(raw: string): number | undefined {
export function parseArgs(args: string[]): ParsedArgs {
const out: ParsedArgs = {};
+ let cap: CapFlag | undefined;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--help' || a === '-h') { out.help = true; continue; }
@@ -776,15 +778,18 @@ export function parseArgs(args: string[]): ParsedArgs {
continue;
}
if (a === '--max-usd' || a === '--max-cost-usd') {
- const raw = args[++i] ?? '';
- // v0.42.42.0 (#2139): off/unlimited/none → run uncapped (Infinity sentinel;
- // mapped to "no BudgetTracker ceiling" in runEnrichCore). Spend still ledgered.
- if (['off', 'unlimited', 'none'].includes(raw.trim().toLowerCase())) {
- out.maxCostUsd = Infinity;
- } else {
- const n = parseFloat(raw);
- if (Number.isFinite(n) && n > 0) out.maxCostUsd = n;
+ // D19 shared parser. v0.42.42.0 (#2139): off/unlimited/none → run
+ // uncapped (Infinity sentinel; mapped to "no BudgetTracker ceiling" in
+ // runEnrichCore). Spend still ledgered. A malformed, 0 or conflicting
+ // value is refused before any paid call instead of silently ignored.
+ try {
+ cap = mergeCapFlag(cap, parseCapFlag(a, args[++i]));
+ } catch (e) {
+ if (!(e instanceof CapFlagError)) throw e;
+ out.error = e.message;
+ return out;
}
+ out.maxCostUsd = cap.usd ?? Infinity;
continue;
}
if (a === '--min-context') {
diff --git a/src/commands/onboard.ts b/src/commands/onboard.ts
index a698dad723..32bb36a889 100644
--- a/src/commands/onboard.ts
+++ b/src/commands/onboard.ts
@@ -19,6 +19,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { computeRemediationPlan, runRemediation } from '../core/remediation/index.ts';
import { runAllOnboardChecks } from '../core/onboard/checks.ts';
import { buildOnboardReport, renderHuman } from '../core/onboard/render.ts';
+import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
function parseInt10(args: string[], flag: string): number | null {
const i = args.indexOf(flag);
@@ -27,13 +28,6 @@ function parseInt10(args: string[], flag: string): number | null {
return isNaN(v) ? null : v;
}
-function parseFloat10(args: string[], flag: string): number | null {
- const i = args.indexOf(flag);
- if (i === -1 || i === args.length - 1) return null;
- const v = parseFloat(args[i + 1] ?? '');
- return isNaN(v) ? null : v;
-}
-
export async function runOnboard(engine: BrainEngine, args: string[]): Promise<void> {
const check = args.includes('--check') || (!args.includes('--auto') && !args.includes('--history'));
const auto = args.includes('--auto');
@@ -49,11 +43,20 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<v
// stays undefined, which runRemediation already treats as no ceiling (skips the
// est-cost refusal + BudgetTracker runs uncapped); `maxUsdOff` lifts the
// missing-cap refusal below. Spend is still ledgered.
- const maxUsdIdx = args.indexOf('--max-usd');
- const maxUsdVal = maxUsdIdx >= 0 ? (args[maxUsdIdx + 1] ?? '').trim().toLowerCase() : '';
- const maxUsdOff = ['off', 'unlimited', 'none'].includes(maxUsdVal);
- const maxUsdRaw = parseFloat10(args, '--max-usd');
- const maxUsd = maxUsdRaw === null ? undefined : maxUsdRaw;
+ // D19 shared parser: a malformed, 0 or conflicting --max-usd is refused
+ // before any plan or paid call instead of silently dropping the cap.
+ let cap: CapFlag | undefined;
+ try {
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--max-usd') cap = mergeCapFlag(cap, parseCapFlag('--max-usd', args[i + 1]));
+ }
+ } catch (e) {
+ if (!(e instanceof CapFlagError)) throw e;
+ process.stderr.write(`gbrain onboard: ${e.message}\n`);
+ process.exit(2);
+ }
+ const maxUsdOff = cap?.usd === null;
+ const maxUsd = cap?.usd ?? undefined;
// --history shows the impact log directly; no plan computation.
if (history) {
diff --git a/src/core/budget/cap-flag.ts b/src/core/budget/cap-flag.ts
new file mode 100644
index 0000000000..d8eaff4f2b
--- /dev/null
+++ b/src/core/budget/cap-flag.ts
@@ -0,0 +1,82 @@
+/**
+ * The one USD cost-cap flag parser (D19). Every command that takes a cap
+ * flag (`--max-usd` canonical; legacy `--max-cost`, `--max-cost-usd`,
+ * `--no-max-cost`) parses it here, so the spellings, the off words and the
+ * error text cannot drift between commands.
+ *
+ * Values: a positive USD amount, or `off` / `unlimited` / `none` to run
+ * uncapped (spend is still ledgered; runtime, call and token bounds stay).
+ * A bare `0` is ambiguous (free? uncapped?) and is refused unless the
+ * command declares what it means: skillopt's legacy `--max-cost-usd 0`
+ * means uncapped, and `eval longmemeval --max-usd 0` is a $0 judge cap.
+ * Two cap flags that disagree are refused instead of one silently winning.
+ * All of this happens while parsing argv, before any paid call.
+ */
+
+export const CAP_OFF_WORDS: readonly string[] = ['off', 'unlimited', 'none'];
+
+/** A parsed cap flag: `usd` is the cap, or null for off. `flag` is the spelling the user typed. */
+export interface CapFlag {
+ flag: string;
+ usd: number | null;
+}
+
+export class CapFlagError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'CapFlagError';
+ }
+}
+
+export interface ParseCapOpts {
+ /** What a bare 0 means for this flag. Default `reject`. */
+ zero?: 'reject' | 'off' | 'cap';
+}
+
+/** Parse one cap flag value. Throws CapFlagError with a message naming the flag and the fix. */
+export function parseCapFlag(flag: string, raw: string | undefined, opts: ParseCapOpts = {}): CapFlag {
+ const zero = opts.zero ?? 'reject';
+ const amount = zero === 'reject' ? 'a positive USD amount' : 'a non-negative USD amount';
+ const value = raw?.trim() ?? '';
+ if (value === '' || value.startsWith('--')) {
+ throw new CapFlagError(`${flag} needs ${amount} or "off" (got nothing).`);
+ }
+ if (CAP_OFF_WORDS.includes(value.toLowerCase())) return { flag, usd: null };
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < 0) {
+ throw new CapFlagError(`${flag} must be ${amount} or "off" (got "${value}").`);
+ }
+ if (n === 0) {
+ if (zero === 'off') return { flag, usd: null };
+ if (zero === 'reject') {
+ throw new CapFlagError(`${flag} 0 is ambiguous: pass ${flag} off to run uncapped, or a positive USD amount to cap the run.`);
+ }
+ }
+ return { flag, usd: n };
+}
+
+function show(cap: CapFlag): string {
+ return cap.usd === null ? `${cap.flag} off` : `${cap.flag} ${cap.usd}`;
+}
+
+/** Combine a newly parsed cap flag with an earlier one; the same value twice is fine, two different values are refused. */
+export function mergeCapFlag(prev: CapFlag | undefined, next: CapFlag): CapFlag {
+ if (prev && prev.usd !== next.usd) {
+ throw new CapFlagError(`${show(prev)} conflicts with ${show(next)}; pass one cost cap.`);
+ }
+ return prev ?? next;
+}
+
+/**
+ * The one-line cap notice a run prints once: the cap, where it came from and
+ * how to change or remove it. `usd` null means the user turned the cap off.
+ */
+export function capNotice(cap: { usd: number | null; source: 'user' | 'default'; flag?: string }): string {
+ if (cap.usd === null) {
+ return `cap: off (${cap.flag ?? '--max-usd'} off; spend is still ledgered, runtime bounds still apply)`;
+ }
+ const amount = `$${cap.usd.toFixed(2)}`;
+ return cap.source === 'default'
+ ? `cap: ${amount} (default; change it with --max-usd <usd>, remove it with --max-usd off)`
+ : `cap: ${amount} (${cap.flag ?? '--max-usd'}; remove it with --max-usd off)`;
+}
diff --git a/src/eval/longmemeval/judge-lane.ts b/src/eval/longmemeval/judge-lane.ts
index 7a00f1485d..d9d85b9e4a 100644
--- a/src/eval/longmemeval/judge-lane.ts
+++ b/src/eval/longmemeval/judge-lane.ts
@@ -34,14 +34,12 @@ import {
type JudgePromptInput,
} from './judge.ts';
import type { LongMemEvalQuestion } from './adapter.ts';
+import { parseCapFlag } from '../../core/budget/cap-flag.ts';
/** `--max-usd N|off`: `off` disables the cap (and lets an unpriced judge run). */
export function parseMaxUsd(flag: string, v: string): number | null {
- const s = v.trim().toLowerCase();
- if (s === 'off' || s === 'none' || s === 'unlimited') return null;
- const n = Number(s);
- if (!Number.isFinite(n) || n < 0) throw new Error(`${flag} must be a non-negative number of USD or 'off' (got: ${v})`);
- return n;
+ // D19 shared parser; 0 keeps its meaning here, a $0 judge cap.
+ return parseCapFlag(flag, v, { zero: 'cap' }).usd;
}
/** This run's reader pins (the hash's reader half for live rows). */
diff --git a/test/budget/cap-flag.test.ts b/test/budget/cap-flag.test.ts
new file mode 100644
index 0000000000..96ca7f75ea
--- /dev/null
+++ b/test/budget/cap-flag.test.ts
@@ -0,0 +1,123 @@
+/**
+ * D19: one shared cost-cap flag parser. `--max-usd N|off` is canonical; the
+ * legacy spellings (`--max-cost`, `--max-cost-usd`, `--no-max-cost`) parse
+ * through the same module, so the off words, the 0 rule, conflicts and the
+ * error text are the same in every command. Each command is driven through
+ * its real parser: numeric, each off spelling, missing, invalid, conflicting.
+ * (skillopt's parser is covered in test/skillopt/preflight-pricing-5563.test.ts.)
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { CAP_OFF_WORDS, CapFlagError, capNotice, mergeCapFlag, parseCapFlag } from '../../src/core/budget/cap-flag.ts';
+import { parseBrainstormArgs } from '../../src/commands/brainstorm.ts';
+import { parseArgs as parseEnrichArgs } from '../../src/commands/enrich.ts';
+import { parseMaxUsd } from '../../src/eval/longmemeval/judge-lane.ts';
+import { runOnboard } from '../../src/commands/onboard.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+
+describe('parseCapFlag / mergeCapFlag', () => {
+ test('a positive amount is a cap; every off word is off, case-insensitive', () => {
+ expect(parseCapFlag('--max-usd', '2.5')).toEqual({ flag: '--max-usd', usd: 2.5 });
+ for (const w of [...CAP_OFF_WORDS, 'OFF', ' Unlimited ']) expect(parseCapFlag('--max-usd', w).usd).toBeNull();
+ });
+
+ test('0 is refused by default, means off or a $0 cap only where the command says so', () => {
+ expect(() => parseCapFlag('--max-usd', '0')).toThrow(CapFlagError);
+ expect(parseCapFlag('--max-cost-usd', '0', { zero: 'off' }).usd).toBeNull();
+ expect(parseCapFlag('--max-usd', '0', { zero: 'cap' }).usd).toBe(0);
+ });
+
+ test('missing, flag-shaped, negative and non-numeric values are refused naming the flag', () => {
+ expect(() => parseCapFlag('--max-usd', undefined)).toThrow('--max-usd needs a positive USD amount or "off" (got nothing).');
+ expect(() => parseCapFlag('--max-usd', '--json')).toThrow('--max-usd needs');
+ expect(() => parseCapFlag('--max-usd', '-1')).toThrow('--max-usd must be a positive USD amount or "off" (got "-1").');
+ expect(() => parseCapFlag('--max-usd', '5usd')).toThrow('(got "5usd")');
+ });
+
+ test('a repeated identical cap merges; disagreeing caps are refused', () => {
+ const a = parseCapFlag('--max-usd', '3');
+ expect(mergeCapFlag(a, parseCapFlag('--max-cost', '3'))).toEqual(a);
+ expect(() => mergeCapFlag(a, parseCapFlag('--max-cost', 'off'))).toThrow('--max-usd 3 conflicts with --max-cost off; pass one cost cap.');
+ });
+
+ test('capNotice names the cap, its source and how to remove it', () => {
+ expect(capNotice({ usd: 5, source: 'default' })).toBe('cap: $5.00 (default; change it with --max-usd <usd>, remove it with --max-usd off)');
+ expect(capNotice({ usd: 2, source: 'user', flag: '--max-cost' })).toBe('cap: $2.00 (--max-cost; remove it with --max-usd off)');
+ expect(capNotice({ usd: null, source: 'user' })).toBe('cap: off (--max-usd off; spend is still ledgered, runtime bounds still apply)');
+ });
+});
+
+describe('brainstorm / lsd (parseBrainstormArgs)', () => {
+ test('--max-usd and legacy --max-cost parse numbers and off', () => {
+ expect(parseBrainstormArgs(['q', '--max-usd', '2']).maxCost).toBe(2);
+ expect(parseBrainstormArgs(['q', '--max-cost', '2.5']).maxCost).toBe(2.5);
+ for (const w of CAP_OFF_WORDS) expect(parseBrainstormArgs(['q', '--max-usd', w]).maxCost).toBeNull();
+ expect(parseBrainstormArgs(['q']).maxCost).toBeUndefined();
+ });
+ test('missing, invalid, 0 and conflicting values set an error', () => {
+ expect(parseBrainstormArgs(['q', '--max-usd']).error).toMatch(/--max-usd needs/);
+ expect(parseBrainstormArgs(['q', '--max-usd', 'abc']).error).toMatch(/--max-usd must be a positive USD amount/);
+ expect(parseBrainstormArgs(['q', '--max-cost', '0']).error).toMatch(/--max-cost 0 is ambiguous/);
+ expect(parseBrainstormArgs(['q', '--max-usd', '1', '--max-cost', '2']).error).toMatch(/conflicts/);
+ });
+});
+
+describe('enrich (parseArgs)', () => {
+ test('--max-usd and --max-cost-usd parse numbers; off is the Infinity sentinel', () => {
+ expect(parseEnrichArgs(['--max-usd', '3']).maxCostUsd).toBe(3);
+ expect(parseEnrichArgs(['--max-cost-usd', '1.5']).maxCostUsd).toBe(1.5);
+ for (const w of CAP_OFF_WORDS) expect(parseEnrichArgs(['--max-usd', w]).maxCostUsd).toBe(Infinity);
+ });
+ test('a malformed, 0 or conflicting cap is refused instead of silently ignored', () => {
+ expect(parseEnrichArgs(['--max-usd', 'lots']).error).toMatch(/--max-usd must be a positive USD amount/);
+ expect(parseEnrichArgs(['--max-usd']).error).toMatch(/--max-usd needs/);
+ expect(parseEnrichArgs(['--max-usd', '0']).error).toMatch(/ambiguous/);
+ expect(parseEnrichArgs(['--max-usd', '2', '--max-cost-usd', 'off']).error).toMatch(/conflicts/);
+ });
+});
+
+describe('eval longmemeval (parseMaxUsd)', () => {
+ test('numbers, off words, and 0 as a $0 judge cap', () => {
+ expect(parseMaxUsd('--max-usd', '5')).toBe(5);
+ expect(parseMaxUsd('--max-usd', '0')).toBe(0);
+ for (const w of CAP_OFF_WORDS) expect(parseMaxUsd('--max-usd', w)).toBeNull();
+ expect(() => parseMaxUsd('--max-usd', 'abc')).toThrow(/non-negative/);
+ expect(() => parseMaxUsd('--max-usd', '')).toThrow(/--max-usd needs/);
+ });
+});
+
+describe('onboard (runOnboard)', () => {
+ const origExit = process.exit;
+ const origErr = process.stderr.write.bind(process.stderr);
+ afterEach(() => {
+ process.exit = origExit;
+ process.stderr.write = origErr;
+ });
+ class Exit extends Error { constructor(readonly code: number) { super(`exit ${code}`); } }
+
+ async function exitOf(args: string[]): Promise<{ code: number | null; stderr: string }> {
+ let stderr = '';
+ process.stderr.write = ((c: string | Uint8Array) => { stderr += String(c); return true; }) as typeof process.stderr.write;
+ process.exit = ((code?: number) => { throw new Exit(code ?? 0); }) as typeof process.exit;
+ const engine = new Proxy({}, { get: () => { throw new Error('engine touched before the cap flag was validated'); } }) as BrainEngine;
+ try {
+ await runOnboard(engine, args);
+ return { code: null, stderr };
+ } catch (e) {
+ if (e instanceof Exit) return { code: e.code, stderr };
+ throw e;
+ }
+ }
+
+ test('a malformed, 0 or conflicting --max-usd exits 2 before touching the brain', async () => {
+ for (const [args, msg] of [
+ [['--auto', '--max-usd', 'lots'], /--max-usd must be a positive USD amount/],
+ [['--auto', '--max-usd'], /--max-usd needs/],
+ [['--auto', '--max-usd', '0'], /ambiguous/],
+ [['--auto', '--max-usd', '2', '--max-usd', 'off'], /conflicts/],
+ ] as const) {
+ const r = await exitOf([...args]);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toMatch(msg);
+ }
+ });
+});