Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(enrich): --background asks for consent before queueing paid jobs
garrytan7192e6055e76
diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 709c659402..9cf6ce9738 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -54,6 +54,7 @@ import {} from '../core/op-checkpoint.ts';import { createProgress } from '../core/progress.ts';import { consentGateOrExit, engineConsentEnv, tokenmaxUncappedEnv } from '../core/consent-cli.ts';+import { derivedCapUsd } from '../core/consent.ts';import { getCliOptions, cliOptsToProgressOptions, maybeBackground } from '../core/cli-options.ts';import { loadConfig } from '../core/config.ts';import { runSlidingPool } from '../core/worker-pool.ts';@@ -948,40 +949,8 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<vo// --background: fan out one Minion job per source (D4). With --source, one job.// PGLite has no worker daemon → fall through to inline (note emitted below).- if (args.includes('--background') && engine.kind !== 'pglite') {- const parsed = parseArgs(args);- if (parsed.error) { console.error(parsed.error); process.exit(1); }- const sourceIds = parsed.sourceId- ? [parsed.sourceId]- : (await listSources(engine)).map((s) => s.id);- if (sourceIds.length <= 1) {- // Single source (or only one source exists) → one job via maybeBackground.- const backgrounded = await maybeBackground({- engine,- args: parsed.sourceId ? args : [...args, '--source', sourceIds[0] ?? 'default'],- jobName: 'enrich',- paramBuilder: buildJobParams,- });- if (backgrounded) return;- } else {- // Multi-source fan-out: one job per source.- const { MinionQueue } = await import('../core/minions/queue.ts');- const queue = new MinionQueue(engine);- const ids: number[] = [];- for (const sid of sourceIds) {- const job = await queue.add(- 'enrich',- { ...buildJobParams(args), sourceId: sid },- { idempotency_key: backgroundIdempotencyKey(sid, args) },- );- ids.push(job.id);- }- console.log(`Submitted ${ids.length} enrich job(s) (one per source): ${ids.map((i) => `job_id=${i}`).join(' ')}`);- console.log('Follow with: gbrain jobs follow <id>');- return;- }- } else if (args.includes('--background')) {- // PGLite + --background: no worker daemon; degrade to inline.+ const background = args.includes('--background') && engine.kind !== 'pglite';+ if (args.includes('--background') && !background) {process.stderr.write('[--background] PGLite has no worker daemon; running enrich inline.\n');}@@ -992,10 +961,11 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<voprocess.exit(1);}- // Chat gateway is required for non-dry-run. Recover a cold singleton before- // reporting an availability error (#2590).- if (!parsed.dryRun && !isAvailable('chat')) configureGatewayIfUninitialized();- if (!parsed.dryRun && !isAvailable('chat')) {+ // Chat gateway is required for non-dry-run inline work (the worker needs it+ // for background jobs). Recover a cold singleton before reporting an+ // availability error (#2590).+ if (!background && !parsed.dryRun && !isAvailable('chat')) configureGatewayIfUninitialized();+ if (!background && !parsed.dryRun && !isAvailable('chat')) {console.error('Chat gateway unavailable. Set a provider key (OPENAI_API_KEY or ANTHROPIC_API_KEY — ' +'chat routes to whichever is present), or configure a model explicitly ' +@@ -1004,34 +974,64 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<voprocess.exit(1);}- const sourceIds: string[] = parsed.sourceId+ const listed: string[] = parsed.sourceId? [parsed.sourceId]: (await listSources(engine)).map((s) => s.id);-- // A4 consent before spending. `--max-usd <usd>`, `--yes` (derived cap: the- // estimate x1.5), a per-run preapproval or spend.posture=tokenmax authorize- // it; `--max-usd off` is the explicit uncapped choice. tokenmax keeps its- // documented meaning here (D15A: the ceiling is removed, spend is still- // ledgered), so unattended tokenmax runs do not flip to a derived-cap stop.- // Without authorization: a TTY prompt, else exit 3 with the consent payload.+ const sourceIds = background && listed.length === 0 ? ['default'] : listed;++ // A4 consent before spending, and before queueing paid jobs. `--max-usd+ // <usd>`, `--yes` (derived cap: the estimate x1.5), a per-run preapproval or+ // spend.posture=tokenmax authorize it; `--max-usd off` is the explicit+ // uncapped choice. tokenmax keeps its documented meaning here (D15A: the+ // ceiling is removed, spend is still ledgered), so unattended tokenmax runs+ // do not flip to a derived-cap stop. Without authorization: a TTY prompt,+ // else exit 3 with the consent payload and nothing queued.const explicitOff = parsed.maxCostUsd === Infinity;let maxCostUsd = parsed.maxCostUsd;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)`,+ what: `Enrich up to ${limit} page(s) per source across ${sourceIds.length} source(s)${background ? ' as background jobs' : ''}`,why: 'Fills thin person and company pages with model-written summaries from the brain\'s own evidence.',risk: `Spends about $${estUsd.toFixed(2)} with the chat model provider; pages gain model-written text (each write is attributed and can be reviewed).`,user_message: `Enrich up to ${limit} thin page(s) per source across ${sourceIds.length} source(s) for about $${estUsd.toFixed(2)}?`,- argv: ['gbrain', 'enrich', ...args.filter(a => a !== '--yes')],- preview_argv: ['gbrain', 'enrich', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run'],+ argv: ['gbrain', 'enrich', ...base, ...(background && parsed.maxCostUsd === undefined ? ['--max-usd', derivedCapUsd(estUsd).toFixed(2)] : [])],+ preview_argv: ['gbrain', 'enrich', ...base.filter(a => a !== '--json' && a !== '--background' && a !== '--follow'), '--dry-run'],est_usd: estUsd,args,}, { 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) {+ if (sourceIds.length === 1) {+ await maybeBackground({+ engine,+ args: parsed.sourceId ? args : [...args, '--source', sourceIds[0]],+ jobName: 'enrich',+ paramBuilder: buildJobParams,+ });+ return;+ }+ const { MinionQueue } = await import('../core/minions/queue.ts');+ const queue = new MinionQueue(engine);+ const ids: number[] = [];+ for (const sid of sourceIds) {+ const job = await queue.add(+ 'enrich',+ { ...buildJobParams(args), sourceId: sid },+ { idempotency_key: backgroundIdempotencyKey(sid, args) },+ );+ ids.push(job.id);+ }+ console.log(`Submitted ${ids.length} enrich job(s) (one per source): ${ids.map((i) => `job_id=${i}`).join(' ')}`);+ console.log('Follow with: gbrain jobs follow <id>');+ return;+ }+const uncapped = !parsed.dryRun && maxCostUsd === Infinity;if (uncapped) {console.error(`${explicitOff ? '--max-usd off' : 'spend.posture=tokenmax'}: running uncapped, spend ledgered. docs: docs/operations/spend-controls.md`);diff --git a/test/enrich-background-consent.test.ts b/test/enrich-background-consent.test.tsnew file mode 100644index 0000000000..1298511ed1--- /dev/null+++ b/test/enrich-background-consent.test.ts@@ -0,0 +1,94 @@+/**+ * `enrich --background` asks for consent before it queues paid jobs.+ *+ * Protects: a non-TTY agent cannot queue paid `enrich` Minion jobs without an+ * authorization (`--yes`, `--max-usd`, a preapproval or tokenmax). Regression+ * that fails it: the background branch queueing before the consent gate runs.+ * Existing coverage gates only the inline path.+ */+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+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';++class Exit extends Error { constructor(readonly code: number) { super(`exit ${code}`); } }++function fakePostgres(sourceIds: string[]) {+ return {+ kind: 'postgres',+ getConfig: async () => null,+ executeRaw: async (sql: string) => sql.includes('FROM sources')+ ? sourceIds.map(id => ({ id, name: id, local_path: null, last_sync_at: null, config: {} }))+ : [{ n: 0 }],+ } as never;+}++let home: string;+let added: Array<{ name: string; data: Record<string, unknown>; opts: Record<string, unknown> | undefined }>;+let out: string[];+let spies: Array<{ mockRestore(): void }>;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-enrich-bg-consent-'));+ added = [];+ 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++ };+ }) 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),+ spyOn(process.stderr, 'write').mockImplementation((() => true) as never),+ spyOn(console, 'log').mockImplementation(((...a: unknown[]) => { out.push(a.join(' ')); }) as never),+ ];+});++afterEach(() => {+ for (const s of spies) s.mockRestore();+ rmSync(home, { recursive: true, force: true });+});++async function run(sources: string[], args: string[]): Promise<number | null> {+ return withEnv({ GBRAIN_HOME: home, GBRAIN_INTERACTIVE: undefined }, async () => {+ try {+ await runEnrich(fakePostgres(sources), args);+ return null;+ } catch (e) {+ if (e instanceof Exit) return e.code;+ throw e;+ }+ });+}++describe('enrich --background consent', () => {+ test('single source without --yes exits 3 and queues nothing', async () => {+ expect(await run(['default'], ['--background', '--json'])).toBe(3);+ expect(added).toEqual([]);+ const payload = JSON.parse(out.join(''));+ expect(payload.code).toBe('confirmation_required');+ expect(payload.est_usd).toBe(0.5);+ expect(payload.fix.argv).toEqual(['gbrain', 'enrich', '--background', '--json', '--max-usd', '0.75', '--yes']);+ expect(payload.preview.argv).toEqual(['gbrain', 'enrich', '--dry-run']);+ });++ test('several sources without --yes exit 3 and queue nothing', async () => {+ expect(await run(['default', 'wiki'], ['--background', '--json'])).toBe(3);+ expect(added).toEqual([]);+ expect(JSON.parse(out.join('')).est_usd).toBe(1);+ });++ test('--yes queues one job per source', async () => {+ expect(await run(['default', 'wiki'], ['--background', '--yes'])).toBeNull();+ expect(added.map(a => [a.name, a.data.sourceId])).toEqual([['enrich', 'default'], ['enrich', 'wiki']]);+ });++ test('--dry-run queues without consent', async () => {+ expect(await run(['default'], ['--background', '--dry-run'])).toBeNull();+ expect(added.map(a => a.data.dryRun)).toEqual([true]);+ });+});