Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(spend): consent-gated producers store the authorization on queued jobs
garrytan6ad7e6abf479
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 9114720d3d..700a31c4b6 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -1,5 +1,4 @@# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>count-src/commands/book-mirror.ts 1src/commands/capture.ts 4src/commands/embed-facts-delegate.ts 5src/commands/extract-stale-delegate.ts 4diff --git a/src/commands/book-mirror.ts b/src/commands/book-mirror.tsindex 3dc7bade9d..b92d3063c8 100644--- a/src/commands/book-mirror.ts+++ b/src/commands/book-mirror.ts@@ -41,13 +41,14 @@import * as fs from 'node:fs';import { randomUUID } from 'node:crypto';-import { OperationError } from '../core/ops/contract.ts';+import { OperationError, opError } from '../core/ops/contract.ts';import { isWriteReceipt } from '../core/persistence/types.ts';import * as path from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { MinionQueue } from '../core/minions/queue.ts';import { waitForCompletion, TimeoutError } from '../core/minions/wait-for-completion.ts';-import type { MinionJobInput, SubagentHandlerData } from '../core/minions/types.ts';+import type { MinionJob, MinionJobInput, SubagentHandlerData } from '../core/minions/types.ts';+import { jobSpendAuthorization, spendSubmitSummary } from '../core/minions/spend-authorization.ts';import { operations } from '../core/operations.ts';import { loadConfig } from '../core/config.ts';import { getCliOptions } from '../core/cli-options.ts';@@ -349,7 +350,13 @@ export async function prepareBookMirrorPublication(engine: BrainEngine, slug: stcliOpts: getCliOptions(), sourceId: 'default' }, {slug, content, request_id: requestId, ...(snapshot ? { expected_revision: snapshot.revision } : {}),});- if (!isWriteReceipt(receipt)) throw new OperationError('storage_error', 'Book publication returned no durable write receipt.');+ if (!isWriteReceipt(receipt)) {+ throw opError('storage_error', `Publishing ${slug} returned no durable write receipt, so whether the page was written is unknown.`,+ `Read the page to see whether it was written; if it is missing or stale, run the same book-mirror command again (completed chapters are reused).`,+ { why: 'A publication is confirmed only by its write receipt; without one the page may or may not hold the new mirror.',+ fix: { argv: ['gbrain', 'get', '--source', 'default', '--', slug], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the page as stored now, so you can tell whether the publication landed.' } });+ }if (receipt.state !== 'committed') {const code = ['queued', 'running', 'recovering'].includes(receipt.state) ? 'write_pending' : 'storage_error';const error = new OperationError(code, `Book publication is ${receipt.state}.`,@@ -417,17 +424,20 @@ export async function runBookMirrorCmd(engine: BrainEngine, args: string[]): Pro// tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt// (interaction.readLine: EOF/timeout = decline, never a hang) or exit 3// with the consent payload. Nothing is submitted before consent.- await consentGateOrExit({+ const consentArgv = ['gbrain', 'book-mirror', ...args.filter(a => a !== '--yes' && a !== '--no-confirm')];+ const auth = await consentGateOrExit({command: 'book-mirror', effects: ['paid'], actor: 'agent',what: `Run ${chapters.length} chapter subagent(s) for ${targetSlug}`,why: `Writes a personalized two-column mirror of "${bookTitle}" from the brain's context, one ${flags.model} subagent per chapter.`,risk: `Spends about $${estimateUsd.toFixed(2)} (~$${(estimateUsd / chapters.length).toFixed(2)} per chapter) with the model provider. Subagents are read-only; the result is one new page.`,user_message: `Spend about $${estimateUsd.toFixed(2)} to mirror ${chapters.length} chapter(s) of "${bookTitle}" against your brain?`,- argv: ['gbrain', 'book-mirror', ...args.filter(a => a !== '--yes' && a !== '--no-confirm')],- preview_argv: ['gbrain', 'book-mirror', ...args.filter(a => a !== '--yes' && a !== '--no-confirm'), '--dry-run'],+ argv: consentArgv,+ preview_argv: [...consentArgv, '--dry-run'],est_usd: estimateUsd,args: flags.noConfirm ? [...args, '--yes'] : args,}, { json: false, env: engineConsentEnv(engine) });+ // One approved total for every chapter subagent (the worker enforces it across the group).+ const spend = jobSpendAuthorization(auth, { command: 'book-mirror', est_usd: estimateUsd, of: chapters.length, argv: consentArgv });const publish = await prepareBookMirrorPublication(engine, targetSlug);@@ -436,6 +446,7 @@ export async function runBookMirrorCmd(engine: BrainEngine, args: string[]): Pro// tool-allowlist layer rather than at allowedSlugPrefixes scope.const queue = new MinionQueue(engine);const childIds: number[] = [];+ const children: MinionJob[] = [];for (const ch of chapters) {const data: SubagentHandlerData = {prompt: buildChapterPrompt(ch, chapters.length, bookTitle, flags.author, contextPack),@@ -456,14 +467,16 @@ export async function runBookMirrorCmd(engine: BrainEngine, args: string[]): Pro'subagent',data as unknown as Record<string, unknown>,submitOpts,- { allowProtectedSubmit: true },+ { allowProtectedSubmit: true, spendAuthorization: spend },);childIds.push(job.id);+ children.push(job);}process.stderr.write(`submitted: ${childIds.length} subagent jobs (${childIds[0]}..${childIds[childIds.length - 1]})\n`);+ for (const line of spendSubmitSummary(spend, children, consentArgv).lines) process.stderr.write(`${line}\n`);if (!flags.follow) {process.stdout.write(JSON.stringify({ child_ids: childIds, slug: targetSlug }) + '\n');diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 9cf6ce9738..9cf0f41b44 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -55,9 +55,10 @@ import {import { createProgress } from '../core/progress.ts';import { consentGateOrExit, engineConsentEnv, tokenmaxUncappedEnv } from '../core/consent-cli.ts';import { derivedCapUsd } from '../core/consent.ts';+import { jobSpendAuthorization, spendSubmitSummary, type SpendAuthorization } from '../core/minions/spend-authorization.ts';import { getCliOptions, cliOptsToProgressOptions, maybeBackground } from '../core/cli-options.ts';import { loadConfig } from '../core/config.ts';-import { runSlidingPool } from '../core/worker-pool.ts';+import { isMustAbortError, runSlidingPool } from '../core/worker-pool.ts';import { parseWorkers, resolveWorkersWithClamp } from '../core/sync-concurrency.ts';import { withRefreshingLock, LockUnavailableError } from '../core/db-lock.ts';import {@@ -603,7 +604,7 @@ export async function runEnrichCore(// pages completed since the last 25-item flush BEFORE it bubbles to// runEnrichCore's catch, else resume re-charges them (and SKIP pages stay// thin). `done` is in scope here; it isn't in the outer catch.- if (err instanceof BudgetExhausted && !dryRun) {+ if ((err instanceof BudgetExhausted || isMustAbortError(err)) && !dryRun) {await recordCompleted(engine, cpKey, [...done]);}throw err;@@ -988,10 +989,14 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<vo// else exit 3 with the consent payload and nothing queued.const explicitOff = parsed.maxCostUsd === Infinity;let maxCostUsd = parsed.maxCostUsd;+ const base = args.filter(a => a !== '--yes');+ let spend: SpendAuthorization | undefined;+ if (background && !parsed.dryRun && explicitOff) {+ spend = jobSpendAuthorization({ uncapped: true, via: 'max_usd' }, { command: 'enrich', of: sourceIds.length, argv: ['gbrain', 'enrich', ...base] });+ }if (!parsed.dryRun && !explicitOff) {const limit = parsed.limit ?? DEFAULT_LIMIT;const estUsd = Math.ceil(limit * sourceIds.length * COST_ESTIMATE_PER_PAGE_USD * 100) / 100;- const base = args.filter(a => a !== '--yes');const auth = await consentGateOrExit({command: 'enrich', effects: ['paid'], actor: 'agent',what: `Enrich up to ${limit} page(s) per source across ${sourceIds.length} source(s)${background ? ' as background jobs' : ''}`,@@ -1004,6 +1009,7 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<voargs,}, { json: parsed.json === true, env: engineConsentEnv(engine, await tokenmaxUncappedEnv(engine, parsed.maxCostUsd !== undefined)) });if (maxCostUsd === undefined && auth.cap_usd !== null) maxCostUsd = auth.cap_usd;+ if (background) spend = jobSpendAuthorization(auth, { command: 'enrich', est_usd: estUsd, of: sourceIds.length, argv: ['gbrain', 'enrich', ...base] });}if (background) {@@ -1013,22 +1019,24 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<voargs: parsed.sourceId ? args : [...args, '--source', sourceIds[0]],jobName: 'enrich',paramBuilder: buildJobParams,+ spendAuthorization: spend,});return;}const { MinionQueue } = await import('../core/minions/queue.ts');const queue = new MinionQueue(engine);- const ids: number[] = [];+ const jobs = [];for (const sid of sourceIds) {- const job = await queue.add(+ jobs.push(await queue.add('enrich',{ ...buildJobParams(args), sourceId: sid },{ idempotency_key: backgroundIdempotencyKey(sid, args) },- );- ids.push(job.id);+ spend ? { spendAuthorization: spend } : undefined,+ ));}- console.log(`Submitted ${ids.length} enrich job(s) (one per source): ${ids.map((i) => `job_id=${i}`).join(' ')}`);+ console.log(`Submitted ${jobs.length} enrich job(s) (one per source): ${jobs.map((j) => `job_id=${j.id}`).join(' ')}`);console.log('Follow with: gbrain jobs follow <id>');+ if (spend) for (const line of spendSubmitSummary(spend, jobs, spend.argv!).lines) console.error(line);return;}diff --git a/src/commands/jobs/submit.ts b/src/commands/jobs/submit.tsindex 55cff738ff..6ca3c83494 100644--- a/src/commands/jobs/submit.ts+++ b/src/commands/jobs/submit.ts@@ -6,6 +6,7 @@ import { clampLockDurationMs } from '../../core/minions/handler-timeouts.ts';import { MinionWorker } from '../../core/minions/worker.ts';import { reportInlineWorkerConfiguration } from '../jobs-readiness.ts';import { intFlagValue, numberFlagValue } from '../../cli/flag-values.ts';+import { spendSubmitSummary, type SpendAuthorization } from '../../core/minions/spend-authorization.ts';export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext): Promise<void> {// Lazy: jobs.ts imports this module statically, so a static import back would be a cycle.@@ -111,6 +112,14 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)}}+ // A4 + T8: queued paid enrich/subagent work needs the user's authorization; it is stored on the row and the worker enforces its cap.+ let spendAuthorization: SpendAuthorization | undefined;+ if (PAID_SUBMIT_NAMES.has(name)) {+ const authorized = await authorizePaidSubmit(engine, name, data, args);+ if (!authorized) return;+ spendAuthorization = authorized;+ }+try { await queue.ensureSchema(); }catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }@@ -148,7 +157,10 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)lock_duration_ms: lockDurationMs,idempotency_key: idempotencyKey,queue: queueName,- }, trusted);+ }, { ...trusted, ...(spendAuthorization ? { spendAuthorization } : {}) });+ if (spendAuthorization) {+ for (const line of spendSubmitSummary(spendAuthorization, [job], spendAuthorization.argv ?? []).lines) process.stderr.write(`${line}\n`);+ }// Submission audit log (operational trace, not forensic insurance).try {@@ -239,6 +251,44 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)}}+/** Paid job names a CLI submit must authorize (the consent-gated producers' job types). */+const PAID_SUBMIT_NAMES = new Set(['enrich', 'subagent']);++/**+ * The same consent gate the producing commands run: `--yes` (derived or+ * default cap), `--max-usd <usd>`, a preapproval or tokenmax authorize it,+ * `--max-usd off` is the explicit uncapped choice; otherwise exit 3 with the+ * consent payload and nothing queued. Returns the record to store, or null.+ */+async function authorizePaidSubmit(engine: JobsCommandContext['engine'], name: string, data: Record<string, unknown>, args: string[]): Promise<SpendAuthorization | null> {+ const { consentGate, engineConsentEnv } = await import('../../core/consent-cli.ts');+ const { jobSpendAuthorization } = await import('../../core/minions/spend-authorization.ts');+ const argv = ['gbrain', 'jobs', ...args.filter(a => a !== '--yes')];+ const maxUsd = parseFlag(args, '--max-usd');+ if (maxUsd !== undefined && ['off', 'unlimited', 'none'].includes(maxUsd.trim().toLowerCase())) {+ return jobSpendAuthorization({ uncapped: true, via: 'max_usd' }, { command: `jobs submit ${name}`, of: 1, argv });+ }+ const { DEFAULT_LIMIT } = await import('../enrich.ts');+ const estUsd = name === 'enrich'+ ? Math.ceil((typeof data.limit === 'number' && data.limit > 0 ? data.limit : DEFAULT_LIMIT) * 0.01 * 100) / 100+ : null;+ const auth = await consentGate({+ command: `jobs submit ${name}`, effects: ['paid'], actor: 'agent',+ what: `Queue a paid ${name} job`,+ why: name === 'enrich'+ ? 'An enrich job writes model-generated summaries into thin pages and pays the chat model provider per page.'+ : 'A subagent job runs a model tool loop and pays the model provider for every turn.',+ risk: estUsd !== null+ ? `Spends about $${estUsd.toFixed(2)} with the chat model provider once a worker runs it.`+ : 'Spends with the model provider once a worker runs it; with no estimate the default $5 cap applies unless --max-usd sets one.',+ user_message: estUsd !== null+ ? `Queue an enrich job that spends about $${estUsd.toFixed(2)}?`+ : `Queue a subagent job that spends up to $5 unless you set another cap?`,+ argv, preview_argv: [...argv, '--dry-run'], est_usd: estUsd, args,+ }, { json: hasFlag(args, '--json'), env: engineConsentEnv(engine) });+ return auth ? jobSpendAuthorization(auth, { command: `jobs submit ${name}`, of: 1, argv, ...(estUsd !== null ? { est_usd: estUsd } : {}) }) : null;+}+/*** Queue honesty (agent-first operator wave E5): PGLite has no background* worker, so a plain submit would leave the job waiting with no error. Refusediff --git a/src/core/cli-options.ts b/src/core/cli-options.tsindex adc1c7c36d..cea90870c7 100644--- a/src/core/cli-options.ts+++ b/src/core/cli-options.ts@@ -423,6 +423,7 @@ export function childGlobalFlags(cliOpts?: CliOptions): string {// ============================================================import type { BrainEngine } from './engine.ts';+import type { SpendAuthorization } from './minions/spend-record.ts';import { createHash } from 'crypto';export interface MaybeBackgroundOpts {@@ -432,6 +433,8 @@ export interface MaybeBackgroundOpts {paramBuilder: (args: string[]) => Record<string, unknown>;/** Source id for the idempotency key namespace. Default 'cli'. */source?: string;+ /** The user's spend authorization for a consent-gated paid job (stored on the row, never in data). */+ spendAuthorization?: SpendAuthorization;}let lastBackgroundJobId: number | null = null;@@ -477,8 +480,12 @@ export async function maybeBackground(opts: MaybeBackgroundOpts): Promise<booleaqueue: 'default',idempotency_key,max_attempts: 2,- });+ }, opts.spendAuthorization ? { spendAuthorization: opts.spendAuthorization } : undefined);process.stdout.write(`job_id=${job.id}\n`);+ if (opts.spendAuthorization) {+ const { spendSubmitSummary } = await import('./minions/spend-authorization.ts');+ for (const line of spendSubmitSummary(opts.spendAuthorization, [job], opts.spendAuthorization.argv ?? []).lines) process.stderr.write(`${line}\n`);+ }lastBackgroundJobId = job.id;if (follow) {diff --git a/src/core/minions/handlers/enrich.ts b/src/core/minions/handlers/enrich.tsindex 30322155a7..d63fddc175 100644--- a/src/core/minions/handlers/enrich.ts+++ b/src/core/minions/handlers/enrich.ts@@ -6,9 +6,11 @@ import type { MinionHandler } from '../types.ts';/*** v0.41.39 (#1700) — enrich. NOT in PROTECTED_JOB_NAMES: per-call cost is- * bounded by data.maxCostUsd (default DEFAULT_MAX_COST_USD) and the handler- * re-creates the BudgetTracker in its own process. BudgetExhausted is caught- * at the core level and returned as result.budget_exhausted (NOT a failure).+ * bounded by data.maxCostUsd (default DEFAULT_MAX_COST_USD, or the job's+ * spend authorization cap) and the handler re-creates the BudgetTracker in+ * its own process. BudgetExhausted is caught at the core level and returned+ * as result.budget_exhausted; under a spend authorization (`ctx.spend`) it is+ * terminal instead: the job dies with the group's exhaustion envelope.* Strict per-source: the CLI fans out one job per source when --source is* omitted, so a job ALWAYS carries data.sourceId.*/@@ -30,13 +32,20 @@ export function makeEnrichHandler(engine: BrainEngine): MinionHandler {limit: typeof job.data.limit === 'number' ? job.data.limit : undefined,workers: typeof job.data.workers === 'number' ? job.data.workers : undefined,model: typeof job.data.model === 'string' ? job.data.model : undefined,- maxCostUsd: typeof job.data.maxCostUsd === 'number' ? job.data.maxCostUsd : undefined,+ maxCostUsd: typeof job.data.maxCostUsd === 'number' ? job.data.maxCostUsd+ : job.spend ? (job.spend.record.cap_usd ?? Infinity) : undefined,minContextChars: typeof job.data.minContextChars === 'number' ? job.data.minContextChars : undefined,thinThreshold: typeof job.data.thinThreshold === 'number' ? job.data.thinThreshold : undefined,reenrichAfterMs: typeof job.data.reenrichAfterMs === 'number' ? job.data.reenrichAfterMs : undefined,dryRun: !!job.data.dryRun,force: !!job.data.force,});+ if (job.spend && result.budget_exhausted) {+ const { spendRefusal } = await import('../spend-authorization.ts');+ throw await spendRefusal(engine, job, job.spend.record, result.budget_exhausted_reason === 'no_pricing' && result.budget_exhausted_model+ ? { kind: 'no_pricing', model: result.budget_exhausted_model }+ : { kind: 'cost' });+ }return result;};}diff --git a/test/book-mirror-spend-authorization.test.ts b/test/book-mirror-spend-authorization.test.tsnew file mode 100644index 0000000000..1431557748--- /dev/null+++ b/test/book-mirror-spend-authorization.test.ts@@ -0,0 +1,70 @@+/**+ * book-mirror stores the user's approval on every chapter subagent it queues.+ *+ * Protects: the approved total reaches the worker (one group shared by all+ * children, `of` = chapters), and a rerun reports the kept authorization of+ * still-queued children with the cancel-and-resubmit commands. Regression+ * that fails it: the consent Authorization discarded before submission.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runBookMirrorCmd } from '../src/commands/book-mirror.ts';+import { parseSpendAuthorization } from '../src/core/minions/spend-authorization.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ dir = mkdtempSync(join(tmpdir(), 'gbrain-book-mirror-spend-'));+ writeFileSync(join(dir, '01-one.txt'), 'Chapter one text about patience and long games.');+ writeFileSync(join(dir, '02-two.txt'), 'Chapter two text about compounding small advantages.');+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++async function run(args: string[]): Promise<string> {+ const err: string[] = [];+ const spies = [+ spyOn(process.stderr, 'write').mockImplementation(((c: string) => { err.push(String(c)); return true; }) as never),+ spyOn(process.stdout, 'write').mockImplementation((() => true) as never),+ ];+ try {+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_INTERACTIVE: undefined }, () => runBookMirrorCmd(engine, args));+ } finally { for (const s of spies) s.mockRestore(); }+ return err.join('');+}++describe('book-mirror spend authorization', () => {+ test('every child row carries the authorization and the same group', async () => {+ const stderr = await run(['--chapters-dir', dir, '--slug', 'a-book', '--model', 'anthropic:claude-opus-4-7', '--yes']);+ const rows = await engine.executeRaw<{ spend_authorization: unknown; data: unknown }>(+ `SELECT spend_authorization, data FROM minion_jobs WHERE name = 'subagent' ORDER BY id`);+ expect(rows).toHaveLength(2);+ const records = rows.map(r => parseSpendAuthorization(r.spend_authorization)!);+ expect(new Set(records.map(r => r.group_id)).size).toBe(1);+ expect(records[0]).toMatchObject({ kind: 'authorized', of: 2, command: 'book-mirror', cap_source: 'derived', via: 'yes' });+ expect(records[0]!.argv).toEqual(['gbrain', 'book-mirror', '--chapters-dir', dir, '--slug', 'a-book', '--model', 'anthropic:claude-opus-4-7']);+ expect(JSON.stringify(rows[0]!.data)).not.toContain('spend_authorization');+ expect(stderr).toContain(`under group ${records[0]!.group_id}`);+ });++ test('a rerun keeps queued children on their authorization and names the cancel-and-resubmit commands', async () => {+ const [{ group_id }] = await engine.executeRaw<{ group_id: string }>(+ `SELECT spend_authorization->>'group_id' AS group_id FROM minion_jobs WHERE name = 'subagent' LIMIT 1`);+ const stderr = await run(['--chapters-dir', dir, '--slug', 'a-book', '--model', 'anthropic:claude-opus-4-7', '--max-usd', '20']);+ expect(stderr).toContain(`keep their earlier authorization: group ${group_id}`);+ expect(stderr).toContain(`gbrain jobs cancel --group ${group_id}`);+ const groups = await engine.executeRaw<{ g: string }>(`SELECT DISTINCT spend_authorization->>'group_id' AS g FROM minion_jobs`);+ expect(groups).toEqual([{ g: group_id }]);+ });+});diff --git a/test/cli-jobs-submit-consent.test.ts b/test/cli-jobs-submit-consent.test.tsnew file mode 100644index 0000000000..4e5f27717c--- /dev/null+++ b/test/cli-jobs-submit-consent.test.ts@@ -0,0 +1,74 @@+/**+ * `gbrain jobs submit enrich|subagent` asks for consent like the producing+ * commands, so the consent payload of `enrich --background` has no+ * unconsented alternative.+ *+ * Protects: without authorization a non-TTY submit exits 3 with the consent+ * payload and queues nothing; with `--yes` the row carries an `authorized`+ * record (never in job data); `--dry-run` needs no consent.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCli } from './helpers/cli-spawn.ts';++let home: string;+let brainPath: string;++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-jobs-submit-consent-'));+ brainPath = join(home, '.gbrain', 'brain.pglite');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: brainPath, embedding_disabled: true }));+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: brainPath });+ await engine.initSchema();+ await engine.disconnect();+}, 120_000);++afterAll(() => rmSync(home, { recursive: true, force: true }));++async function queued(): Promise<Array<{ name: string; spend_authorization: Record<string, unknown> | null; data: Record<string, unknown> }>> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: brainPath });+ try {+ return await engine.executeRaw(`SELECT name, spend_authorization, data FROM minion_jobs ORDER BY id`);+ } finally { await engine.disconnect(); }+}++const submit = (...args: string[]) => runCli(['jobs', 'submit', ...args], { home, env: { GBRAIN_INTERACTIVE: undefined }, timeoutMs: 90_000 });++describe('jobs submit consent for paid job names', () => {+ test('non-TTY enrich without --yes exits 3 with the consent payload and queues nothing', async () => {+ const r = await submit('enrich', '--params', '{"sourceId":"default"}', '--queue-only', '--json');+ expect(r.exitCode).toBe(3);+ const payload = JSON.parse(r.stdout);+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['paid'], est_usd: 0.5 });+ expect(payload.fix.argv).toContain('--yes');+ expect(await queued()).toEqual([]);+ }, 120_000);++ test('subagent without --yes is refused the same way', async () => {+ const r = await submit('subagent', '--params', '{"prompt":"x","model":"anthropic:claude-sonnet-5"}', '--queue-only', '--json');+ expect(r.exitCode).toBe(3);+ expect(JSON.parse(r.stdout).risk).toContain('$5 cap');+ expect(await queued()).toEqual([]);+ }, 120_000);++ test('--dry-run needs no consent and queues nothing', async () => {+ const r = await submit('enrich', '--params', '{"sourceId":"default"}', '--dry-run');+ expect(r.exitCode).toBe(0);+ expect(await queued()).toEqual([]);+ }, 120_000);++ test('--yes queues the job with an authorized record on the row', async () => {+ const r = await submit('enrich', '--params', '{"sourceId":"default","limit":10}', '--queue-only', '--yes');+ expect(r.exitCode).toBe(0);+ const rows = await queued();+ expect(rows).toHaveLength(1);+ expect(rows[0]!.spend_authorization).toMatchObject({ kind: 'authorized', command: 'jobs submit enrich', cap_usd: 0.25, cap_source: 'derived', est_usd: 0.1, of: 1 });+ expect(rows[0]!.data).not.toHaveProperty('spend_authorization');+ }, 120_000);+});diff --git a/test/enrich-background-consent.test.ts b/test/enrich-background-consent.test.tsindex 1298511ed1..b7e1b8d6c4 100644--- a/test/enrich-background-consent.test.ts+++ b/test/enrich-background-consent.test.ts@@ -13,6 +13,7 @@ import { join } from 'node:path';import { runEnrich } from '../src/commands/enrich.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { withEnv } from './helpers/with-env.ts';+import type { SpendAuthorization } from '../src/core/minions/spend-authorization.ts';class Exit extends Error { constructor(readonly code: number) { super(`exit ${code}`); } }@@ -27,7 +28,7 @@ function fakePostgres(sourceIds: string[]) {}let home: string;-let added: Array<{ name: string; data: Record<string, unknown>; opts: Record<string, unknown> | undefined }>;+let added: Array<{ name: string; data: Record<string, unknown>; opts: Record<string, unknown> | undefined; trusted: { spendAuthorization?: SpendAuthorization } | undefined }>;let out: string[];let spies: Array<{ mockRestore(): void }>;@@ -37,9 +38,9 @@ beforeEach(() => {out = [];let nextId = 1;spies = [- spyOn(MinionQueue.prototype, 'add').mockImplementation((async (name: string, data: Record<string, unknown>, opts?: Record<string, unknown>) => {- added.push({ name, data, opts });- return { id: nextId++ };+ spyOn(MinionQueue.prototype, 'add').mockImplementation((async (name: string, data: Record<string, unknown>, opts?: Record<string, unknown>, trusted?: { spendAuthorization?: SpendAuthorization }) => {+ added.push({ name, data, opts, trusted });+ return { id: nextId++, status: 'waiting', spend_authorization: trusted?.spendAuthorization ?? null };}) as never),spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Exit(code ?? 0); }) as never),spyOn(process.stdout, 'write').mockImplementation(((chunk: string) => { out.push(String(chunk)); return true; }) as never),@@ -82,13 +83,30 @@ describe('enrich --background consent', () => {expect(JSON.parse(out.join('')).est_usd).toBe(1);});- test('--yes queues one job per source', async () => {+ test('--yes queues one job per source, all under one authorized group', async () => {expect(await run(['default', 'wiki'], ['--background', '--yes'])).toBeNull();expect(added.map(a => [a.name, a.data.sourceId])).toEqual([['enrich', 'default'], ['enrich', 'wiki']]);+ const records = added.map(a => a.trusted?.spendAuthorization);+ expect(records[0]).toMatchObject({ kind: 'authorized', of: 2, cap_usd: 1.5, cap_source: 'derived', est_usd: 1, command: 'enrich',+ argv: ['gbrain', 'enrich', '--background'] });+ expect(records[1]!.group_id).toBe(records[0]!.group_id);+ expect(added.every(a => !('spend_authorization' in a.data))).toBe(true);+ });++ test('a single source carries its record through the background submit', async () => {+ expect(await run(['default'], ['--background', '--max-usd', '3'])).toBeNull();+ expect(added[0]!.trusted?.spendAuthorization).toMatchObject({ kind: 'authorized', of: 1, cap_usd: 3, cap_source: 'user', via: 'max_usd' });+ expect(added[0]!.opts?.idempotency_key).toMatch(/^cli:enrich:/);+ });++ test('--max-usd off is itself the authorization and stores an uncapped record', async () => {+ expect(await run(['default', 'wiki'], ['--background', '--max-usd', 'off'])).toBeNull();+ expect(added[0]!.trusted?.spendAuthorization).toMatchObject({ cap_usd: null, uncapped: true, via: 'max_usd' });});test('--dry-run queues without consent', async () => {expect(await run(['default'], ['--background', '--dry-run'])).toBeNull();expect(added.map(a => a.data.dryRun)).toEqual([true]);+ expect(added[0]!.trusted).toBeUndefined();});});diff --git a/test/minions-spend-authorization.serial.test.ts b/test/minions-spend-authorization.serial.test.tsnew file mode 100644index 0000000000..47cb161789--- /dev/null+++ b/test/minions-spend-authorization.serial.test.ts@@ -0,0 +1,164 @@+/**+ * Worker enforcement of queued spend authorizations (in-process worker,+ * PGLite, provider attempts through the invocation guard).+ *+ * Protects: a group's jobs share one approved total (live holds of a sibling+ * delay a job instead of killing it); a job that finds the group spent dies+ * with the exhaustion code, the group amounts and the resume command; an+ * unpriced model runs under a derived cap and stops under a user cap; an+ * enrich job whose in-process budget runs out dies instead of completing,+ * and a rerun with a higher cap inserts a fresh group.+ *+ * Serial: mock.module replaces the enrich core for the enrich-handler case.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';++mock.module('../src/commands/enrich.ts', () => ({+ runEnrichCore: async () => ({+ candidates_considered: 3, pages_enriched: 1, pages_skipped_insufficient: 0, pages_skipped_lock: 0,+ pages_skipped_disappeared: 0, pages_failed: 0, budget_exhausted: true, budget_exhausted_reason: 'cost', spent_usd: 0.75,+ }),+}));++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { invokeAI } from '../src/core/ai/invocation-guard.ts';+import { makeEnrichHandler } from '../src/core/minions/handlers/enrich.ts';+import { readGroupSpend } from '../src/core/minions/budget-meter.ts';+import {+ __setGroupPressureRetryMsForTests, jobSpendAuthorization, type SpendAuthorization,+} from '../src/core/minions/spend-authorization.ts';+import type { Authorization } from '../src/core/consent.ts';+import type { MinionJob } from '../src/core/minions/types.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+ __setGroupPressureRetryMsForTests(100);+});++afterAll(async () => {+ __setGroupPressureRetryMsForTests(null);+ await engine.disconnect();+});++beforeEach(async () => {+ for (const t of ['mcp_spend_reservations', 'mcp_spend_log', 'minion_lease_pressure_log', 'minion_jobs']) await engine.executeRaw(`DELETE FROM ${t}`);+});++const auth = (cap: number, source: Authorization['cap_source']): Authorization => ({ consented_effects: ['paid'], cap_usd: cap, cap_source: source, via: 'yes' });+const group = (cap: number, source: Authorization['cap_source'] = 'derived', of = 2) =>+ jobSpendAuthorization(auth(cap, source), { command: 'book-mirror', of, argv: ['gbrain', 'book-mirror', '--slug', 'a-book'] });++/** One provider attempt: maximum `maxCents`, actual `actualCents` (claude-sonnet-5 input at $2/Mtok). */+const attempt = (maxCents: number, actualCents: number, model = 'anthropic:claude-sonnet-5', gate?: Promise<void>) => invokeAI(+ { operation: 'test', kind: 'chat', model, maxInputTokens: maxCents * 2500, maxOutputTokens: 0 },+ async () => { await gate; return 'ok'; }, () => ({ inputTokens: actualCents * 5000, outputTokens: 0 }));++async function settled(ids: number[], timeoutMs = 20_000): Promise<MinionJob[]> {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const jobs = await Promise.all(ids.map(id => queue.getJob(id)));+ if (jobs.every(j => j && ['completed', 'failed', 'dead', 'cancelled'].includes(j.status))) return jobs as MinionJob[];+ if (Date.now() > deadline) throw new Error(`jobs did not settle: ${jobs.map(j => `${j?.id}:${j?.status}`).join(', ')}`);+ await new Promise(r => setTimeout(r, 50));+ }+}++async function runJobs(name: string, handler: (job: { data: Record<string, unknown> }) => Promise<unknown>, specs: Array<{ data: Record<string, unknown>; spend: SpendAuthorization }>, concurrency = 1) {+ const ids: number[] = [];+ for (const s of specs) ids.push((await queue.add(name, s.data, { max_attempts: 3 }, { allowProtectedSubmit: true, spendAuthorization: s.spend })).id);+ const worker = new MinionWorker(engine, { pollInterval: 30, concurrency, healthCheckInterval: 0 });+ worker.register(name, handler as never);+ const running = worker.start();+ try { return await settled(ids); } finally { worker.stop(); await running; }+}++describe('one approved total per group', () => {+ test('two children reserving $8 each under a $10 cap, $1 actual each, both finish', async () => {+ const spend = group(10);+ let release!: () => void;+ const gate = new Promise<void>(r => { release = r; });+ let pressured = 0;+ const jobs = await runJobs('subagent', async (job) => {+ if (job.data.first) { await attempt(800, 100, undefined, gate); return { ok: 1 }; }+ try { await attempt(800, 100); }+ catch (e) { pressured++; release(); throw e; }+ return { ok: 2 };+ }, [{ data: { first: true }, spend }, { data: { first: false }, spend }], 2);+ expect(jobs.map(j => j.status)).toEqual(['completed', 'completed']);+ expect(pressured).toBe(1);+ expect(jobs[1]!.attempts_made).toBe(0);+ expect((await readGroupSpend(engine, `group:${spend.group_id}`)).committedCents).toBe(200);+ });++ test('a child that finds the group spent dies with the exhaustion code, the amounts and the resume command', async () => {+ const spend = group(10, 'user');+ const [first, second] = await runJobs('subagent', async (job) => {+ await attempt(800, job.data.first ? 1000 : 1);+ return { ok: true };+ }, [{ data: { first: true }, spend }, { data: { first: false }, spend }]);+ expect(first!.status).toBe('completed');+ expect(second!.status).toBe('dead');+ expect(second!.error_text).toStartWith('cost_cap_exceeded:');+ const refusal = (second!.result as { spend_refusal: Record<string, any> }).spend_refusal;+ expect(refusal).toMatchObject({ code: 'cost_cap_exceeded', group: { group_id: spend.group_id, cap_usd: 10, spent_usd: 10, remaining_usd: 0 } });+ expect(refusal.fix.argv).toEqual(['gbrain', 'book-mirror', '--slug', 'a-book', '--max-usd', '20.00', '--yes']);+ expect(refusal.fix.next).toBe('ask_user');+ });++ test('a derived cap exhaustion carries derived_cap_exhausted', async () => {+ const spend = group(1, 'derived', 1);+ const [job] = await runJobs('subagent', async () => { await attempt(80, 100); await attempt(80, 1); }, [{ data: {}, spend }]);+ expect(job!.status).toBe('dead');+ expect(job!.error_text).toStartWith('derived_cap_exhausted:');+ });+});++describe('unpriced models', () => {+ test('run with a warning under a derived cap', async () => {+ const err: string[] = [];+ const spy = spyOn(process.stderr, 'write').mockImplementation(((c: string) => { err.push(String(c)); return true; }) as never);+ try {+ const [job] = await runJobs('subagent', async () => { await attempt(10, 10, 'example:unpriced-model'); return { ok: true }; }, [{ data: {}, spend: group(5, 'derived', 1) }]);+ expect(job!.status).toBe('completed');+ } finally { spy.mockRestore(); }+ expect(err.join('')).toContain('BUDGET_TRACKER_NO_PRICING');+ });++ test('stop with no_pricing under a user cap, before any provider call', async () => {+ let called = false;+ const [job] = await runJobs('subagent', async () => {+ await invokeAI({ operation: 'test', kind: 'chat', model: 'example:unpriced-model', maxInputTokens: 10, maxOutputTokens: 0 },+ async () => { called = true; return 'ok'; }, () => null);+ }, [{ data: {}, spend: group(5, 'user', 1) }]);+ expect(called).toBe(false);+ expect(job!.status).toBe('dead');+ expect(job!.error_text).toStartWith('no_pricing:');+ });+});++describe('enrich under a spend authorization', () => {+ test('an exhausted enrich job dies instead of completing, and a rerun with a higher cap inserts a fresh group', async () => {+ const spend = jobSpendAuthorization(auth(0.75, 'derived'), { command: 'enrich', of: 1, argv: ['gbrain', 'enrich', '--background', '--source', 'default'] });+ const key = 'cli:enrich:feedbeef';+ const added = await queue.add('enrich', { sourceId: 'default' }, { idempotency_key: key }, { spendAuthorization: spend });+ const worker = new MinionWorker(engine, { pollInterval: 30, healthCheckInterval: 0 });+ worker.register('enrich', makeEnrichHandler(engine));+ const running = worker.start();+ let job: MinionJob;+ try { [job] = await settled([added.id]) as [MinionJob]; } finally { worker.stop(); await running; }+ expect(job.status).toBe('dead');+ expect(job.error_text).toStartWith('derived_cap_exhausted:');+ const higher = jobSpendAuthorization(auth(3, 'user'), { command: 'enrich', of: 1 });+ const rerun = await queue.add('enrich', { sourceId: 'default' }, { idempotency_key: key }, { spendAuthorization: higher });+ expect(rerun.id).not.toBe(added.id);+ expect(rerun.spend_authorization?.group_id).toBe(higher.group_id);+ });+});