Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(jobs): spend group controls, doctor census and upgrade note
garrytanf7598f68f73f
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 165b4d1ec8..1578441c21 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -274,6 +274,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/minions-shell-pglite.test.ts","test/e2e/worker-abort-recovery.test.ts","test/e2e/connector-sync-handler-pglite.test.ts",+ "test/e2e/budget-meter-group.test.ts",],// v0.46.31.0 chat-connectors wave (mapped at the test-gap-wave merge —// these arrived unclaimed): connector classify/sync core + doctor check.diff --git a/src/commands/doctor/checks/legacy-job-authority.ts b/src/commands/doctor/checks/legacy-job-authority.tsindex 92c3a6821a..6e4c0f9e49 100644--- a/src/commands/doctor/checks/legacy-job-authority.ts+++ b/src/commands/doctor/checks/legacy-job-authority.ts@@ -52,6 +52,34 @@ export async function readLegacyJobAuthority(engine: BrainEngine): Promise<Legacconst sum = (counts: Record<string, number>) => Object.values(counts).reduce((n, c) => n + c, 0);+export interface QueuedSpendState {+ /** Queued paid jobs by spend basis (NULL rows of consent-gated producers count as `legacy_default`: the claim stamps them). */+ by_basis: Record<string, number>;+ /** Spend-authorized rows waiting longer than FENCED_ROW_WAIT_MS (first 10 ids). */+ long_waiting_ids: number[];+ long_waiting: number;+}++/** The informational spend-basis census plus the long-waiting fenced rows, read-only. */+export async function readQueuedSpend(engine: BrainEngine): Promise<QueuedSpendState> {+ const { paidJobNames } = await import('../../jobs/shared.ts');+ const { FENCED_ROW_WAIT_MS, LEGACY_SPEND_KEY_PREFIXES } = await import('../../../core/minions/spend-authorization.ts');+ const legacy = Object.entries(LEGACY_SPEND_KEY_PREFIXES)+ .map(([name, prefixes]) => `(name = '${name}' AND (${prefixes.map(p => `idempotency_key LIKE '${p}%'`).join(' OR ')}))`).join(' OR ');+ const rows = await engine.executeRaw<{ name: string; basis: string; n: number | string }>(+ `SELECT name, CASE WHEN spend_authorization IS NOT NULL THEN spend_authorization->>'kind'+ WHEN ${legacy} THEN 'legacy_default' ELSE 'unrecorded' END AS basis, count(*) AS n+ FROM minion_jobs WHERE status IN ('waiting','delayed','paused','waiting-children')+ GROUP BY 1, 2`);+ const paid = new Set(await paidJobNames(rows.map(r => r.name)));+ const by_basis: Record<string, number> = {};+ for (const r of rows) if (paid.has(r.name)) by_basis[r.basis] = (by_basis[r.basis] ?? 0) + Number(r.n);+ const waiting = await engine.executeRaw<{ id: number }>(+ `SELECT id FROM minion_jobs WHERE status = 'waiting' AND spend_authorization IS NOT NULL+ AND updated_at < now() - ($1::double precision * interval '1 millisecond') ORDER BY id`, [FENCED_ROW_WAIT_MS]);+ return { by_basis, long_waiting_ids: waiting.slice(0, 10).map(r => Number(r.id)), long_waiting: waiting.length };+}+export async function legacyJobAuthorityCheck(engine: BrainEngine): Promise<Check> {const state = await readLegacyJobAuthority(engine);const authorizable = sum(state.authorizable);@@ -78,8 +106,21 @@ export async function legacyJobAuthorityCheck(engine: BrainEngine): Promise<Checasync function runLegacyJobAuthority(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];- const { status, message, details } = await legacyJobAuthorityCheck(connectedEngine(ctx));- checks.push({ name: 'legacy_job_authority', status, message, details });+ const engine = connectedEngine(ctx);+ const { status, message, details } = await legacyJobAuthorityCheck(engine);+ const spend = await readQueuedSpend(engine).catch(() => null);+ const workers = spend?.long_waiting ? (await import('../../../core/minions/worker-registry.ts')).readWorkers().length : 0;+ const census = spend && Object.keys(spend.by_basis).length+ ? ` Queued paid jobs by spend basis: ${Object.entries(spend.by_basis).map(([b, n]) => `${b} ${n}`).join(', ')}.` : '';+ if (status === 'ok' && spend?.long_waiting && workers > 0) {+ checks.push({ name: 'legacy_job_authority', status: 'warn', details: { ...details, queued_spend: spend, live_workers: workers },+ message: `${spend.long_waiting} spend-authorized job(s) (${spend.long_waiting_ids.join(', ')}) have waited over 10 minutes while ${workers} worker(s) run: `+ + `an un-upgraded worker may be fenced off; un-upgraded workers stop claiming at a fenced row. Upgrade gbrain on every worker host and restart the workers (gbrain jobs supervisor stop, then gbrain jobs supervisor start, or your service manager).${census}`,+ fix: { argv: ['gbrain', 'jobs', 'list', '--status', 'waiting', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the waiting rows and their spend records; fenced rows run once every worker runs the upgraded binary.' } });+ return checks;+ }+ checks.push({ name: 'legacy_job_authority', status, message: `${message}${census}`, details: spend ? { ...details, queued_spend: spend } : details });return checks;}@@ -98,3 +139,12 @@ export async function legacyJobAuthorityBannerNote(engine: BrainEngine): Promise+ `Stop producers (gbrain serve, gbrain autopilot) and workers, cancel active jobs, then preview with: ${LIVE_LEGACY_PREVIEW}`+ `${state.unsupported ? `; ${state.unsupported} unsupported row(s) need matching versions or gbrain jobs cancel <id>` : ''}. Recipe: ${ERROR_CATALOGUE.legacy_job_authority.docs}`;}++/** `gbrain post-upgrade` banner line when queued paid jobs will run under the legacy default cap. */+export async function legacyDefaultSpendBannerNote(engine: BrainEngine): Promise<string | null> {+ const n = (await readQueuedSpend(engine)).by_basis.legacy_default ?? 0;+ if (!n) return null;+ return `spend: ${n} queued paid job(s) (book-mirror chapters or enrich runs) were queued before submit-time authorization and run under a $5 default cap each. `+ + 'To authorize a different amount, re-run the command that queued them with --max-usd <usd>; inspect them with: gbrain jobs list --status waiting --json';+}+diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsindex 6b4f623b1f..d2b08e75f0 100644--- a/src/commands/doctor/upgrade-banner.ts+++ b/src/commands/doctor/upgrade-banner.ts@@ -13,7 +13,7 @@ import type { BrainEngine } from '../../core/engine.ts';import { findingSource, runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';-import { legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';+import { legacyDefaultSpendBannerNote, legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';import { frontmatterHoldsBannerNote } from './checks/git-holds.ts';/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */@@ -31,7 +31,7 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>* of connector sources that will re-walk once after a checkpoint migration).* Each returns null when it has nothing to say.*/-export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, frontmatterHoldsBannerNote];+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, legacyDefaultSpendBannerNote, frontmatterHoldsBannerNote];/** One banner line for a non-ok wave finding. */export function bannerFindingLine({ spec, check, state }: WaveFinding): string {diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 7c97053708..2a28b93ad9 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -162,11 +162,12 @@ USAGE[--backoff-jitter 0..1] [--timeout-ms Nms][--lock-duration-ms Nms][--idempotency-key K] [--queue Q] [--dry-run]+ [--yes] [--max-usd USD|off] (enrich, subagent: paid)[--redact-secrets] (shell only; scrubs inheritvalues from stdout/stderr)- gbrain jobs list [--status S] [--queue Q] [--limit N] [--json]+ gbrain jobs list [--status S] [--queue Q] [--limit N] [--group SPEND_GROUP] [--json]gbrain jobs get <id> [--json]- gbrain jobs cancel <id>+ gbrain jobs cancel <id> | --group SPEND_GROUPgbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]gbrain jobs retry <id>gbrain jobs prune [--older-than 30d] [--dry-run]@@ -394,7 +395,7 @@ authorized. IDs, data, schedule and retries persist.cancel: `gbrain jobs cancel — cancel a job, or preview-bound bulk cancel of legacy jobsUSAGE- gbrain jobs cancel <id>+ gbrain jobs cancel <id> | --group SPEND_GROUP (--group: every unfinished job of one paid command's approval)gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--json]gbrain jobs cancel --select "status=waiting|paused,name=synthesize" --expect <hash> --yesdiff --git a/src/commands/jobs/cancel.ts b/src/commands/jobs/cancel.tsindex cef37e7949..627ea5871f 100644--- a/src/commands/jobs/cancel.ts+++ b/src/commands/jobs/cancel.ts@@ -40,6 +40,8 @@ async function runLegacyCancel({ args, engine }: JobsCommandContext): Promise<voexport async function runJobsCancel(ctx: JobsCommandContext): Promise<void> {const { args, queue } = ctx;if (args.includes('--select')) return runLegacyCancel(ctx);+ const groupId = parseFlag(args, '--group');+ if (groupId !== undefined) return cancelSpendGroup(ctx, groupId);const id = parseInt(args[1], 10);if (isNaN(id)) { console.error('Error: job ID required.'); process.exit(1); }@@ -54,3 +56,17 @@ export async function runJobsCancel(ctx: JobsCommandContext): Promise<void> {process.exit(1);}}++/** `jobs cancel --group <id>`: cancels every unfinished job of a spend group (finished rows are left as they are). */+async function cancelSpendGroup({ args, engine, queue }: JobsCommandContext, groupId: string): Promise<void> {+ const { groupJobs } = await import('../../core/minions/spend-authorization.ts');+ const jobs = await groupJobs(engine, groupId);+ const cancelled: number[] = [];+ for (const job of jobs) {+ if (['completed', 'failed', 'dead', 'cancelled'].includes(job.status)) continue;+ if (await queue.cancelJob(job.id)) cancelled.push(job.id);+ }+ if (args.includes('--json')) { console.log(JSON.stringify({ group_id: groupId, cancelled_ids: cancelled, jobs: jobs.length }, null, 2)); return; }+ if (!jobs.length) { console.error(`No jobs in spend group ${groupId}; check the id with: gbrain jobs list --group ${groupId} --json`); process.exit(1); }+ console.log(`Cancelled ${cancelled.length} unfinished job(s) of spend group ${groupId}${cancelled.length ? `: ${cancelled.join(', ')}` : ''}.`);+}diff --git a/src/commands/jobs/get.ts b/src/commands/jobs/get.tsindex caa803687e..68a6d5655a 100644--- a/src/commands/jobs/get.ts+++ b/src/commands/jobs/get.ts@@ -3,8 +3,10 @@ import { formatJobDetail, hasFlag, rehydrateJobDates, type JobsCommandContext }import { isThinClient, loadConfig } from '../../core/config.ts';import type { MinionJob } from '../../core/minions/types.ts';import { callRemoteTool, unpackToolResult } from '../../core/mcp-client.ts';+import { spendBasis } from '../../core/minions/spend-record.ts';+import { jobGroupAmounts } from '../../core/minions/spend-authorization.ts';-export async function runJobsGet({ args, queue }: JobsCommandContext): Promise<void> {+export async function runJobsGet({ args, queue, engine }: JobsCommandContext): Promise<void> {const id = parseInt(args[1], 10);if (isNaN(id)) { console.error('Error: job ID required. Usage: gbrain jobs get <id>'); process.exit(1); }@@ -33,7 +35,9 @@ export async function runJobsGet({ args, queue }: JobsCommandContext): Promise<vif (!job) { console.error(`Job #${id} not found.`); process.exit(1); }// #3685: same machine-readable contract as `list --json` above.if (hasFlag(args, '--json')) {- console.log(JSON.stringify(job, null, 2));+ const { basis, why } = spendBasis(job);+ const group = job.spend_authorization && !isThinClient(cfg) ? await jobGroupAmounts(engine, job.spend_authorization) : undefined;+ console.log(JSON.stringify({ ...job, spend_basis: basis, spend_why: why, ...(group ? { spend_group: group } : {}) }, null, 2));return;}console.log(formatJobDetail(job));diff --git a/src/commands/jobs/list.ts b/src/commands/jobs/list.tsindex 53a784a76d..9ddb294812 100644--- a/src/commands/jobs/list.ts+++ b/src/commands/jobs/list.ts@@ -4,7 +4,9 @@ import type { MinionJob, MinionJobStatus } from '../../core/minions/types.ts';import { isThinClient, loadConfig } from '../../core/config.ts';import { callRemoteTool, unpackToolResult } from '../../core/mcp-client.ts';-export async function runJobsList({ args, queue }: JobsCommandContext): Promise<void> {+export async function runJobsList({ args, queue, engine }: JobsCommandContext): Promise<void> {+ const groupId = parseFlag(args, '--group');+ if (groupId !== undefined) return listSpendGroup(engine, groupId, hasFlag(args, '--json'));const status = parseFlag(args, '--status') as MinionJobStatus | undefined;const queueName = parseFlag(args, '--queue');const limit = parseInt(parseFlag(args, '--limit') ?? '20', 10);@@ -46,3 +48,24 @@ export async function runJobsList({ args, queue }: JobsCommandContext): Promise<for (const job of jobs) console.log(formatJob(job));console.log(`\n ${jobs.length} jobs shown`);}++/** `jobs list --group <id>`: one spend group's record, amounts and member jobs. */+async function listSpendGroup(engine: JobsCommandContext['engine'], groupId: string, json: boolean): Promise<void> {+ const { groupJobs, jobGroupAmounts } = await import('../../core/minions/spend-authorization.ts');+ const jobs = await groupJobs(engine, groupId);+ const record = jobs[0]?.spend_authorization ?? null;+ const amounts = record ? await jobGroupAmounts(engine, record) : null;+ const doc = {+ group_id: groupId,+ ...(record ? { command: record.command, kind: record.kind, cap_usd: record.cap_usd, cap_source: record.cap_source, uncapped: record.uncapped === true } : {}),+ ...(amounts ? { spent_usd: amounts.spent_usd, reserved_usd: amounts.reserved_usd, overdue_usd: amounts.overdue_usd, remaining_usd: amounts.remaining_usd } : {}),+ jobs: jobs.map(j => ({ id: j.id, name: j.name, status: j.status, error_text: j.error_text })),+ cancel_argv: ['gbrain', 'jobs', 'cancel', '--group', groupId],+ };+ if (json) { console.log(JSON.stringify(doc, null, 2)); return; }+ if (!jobs.length) { console.log(`No jobs in spend group ${groupId}.`); return; }+ console.log(`Spend group ${groupId}: ${record!.command}, ${record!.uncapped ? 'uncapped' : `$${record!.cap_usd!.toFixed(2)} ${record!.cap_source} cap`}`+ + (amounts ? `; spent $${amounts.spent_usd.toFixed(2)}, reserved $${amounts.reserved_usd.toFixed(2)}${amounts.remaining_usd === null ? '' : `, remaining $${amounts.remaining_usd.toFixed(2)}`}` : ''));+ for (const job of jobs) console.log(formatJob(job));+ console.log(`\n ${jobs.length} jobs. Cancel the unfinished ones with: gbrain jobs cancel --group ${groupId}`);+}diff --git a/src/commands/jobs/shared.ts b/src/commands/jobs/shared.tsindex d0609f298e..1164b9bd7b 100644--- a/src/commands/jobs/shared.ts+++ b/src/commands/jobs/shared.ts@@ -6,6 +6,7 @@import type { BrainEngine } from '../../core/engine.ts';import type { MinionQueue } from '../../core/minions/queue.ts';import type { MinionJob } from '../../core/minions/types.ts';+import { spendBasis } from '../../core/minions/spend-record.ts';import type { OperationError } from '../../core/ops/contract.ts';import type { SelectionSummary } from '../../core/minions/legacy-selection.ts';import { setCliExitVerdict } from '../../core/cli-force-exit.ts';@@ -221,6 +222,10 @@ export function formatJobDetail(job: MinionJob): string {if (job.delay_until) lines.push(` Delayed until: ${job.delay_until.toISOString()}`);if (job.parent_job_id) lines.push(` Parent: job #${job.parent_job_id} (on_child_fail: ${job.on_child_fail})`);if (job.error_text) lines.push(` Error: ${job.error_text}`);+ if (job.spend_authorization || job.spend_authorization_invalid) {+ const { basis, why } = spendBasis(job);+ lines.push(` Spend: ${basis} — ${why}`);+ }if (job.stacktrace.length > 0) {lines.push(` History:`);for (const entry of job.stacktrace) lines.push(` - ${entry}`);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..9eff9ca66a 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -23,7 +23,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],'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', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-turns', '--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'],+ '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', '--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', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--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'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],@@ -46,13 +46,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],- 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],+ 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],- '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', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--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-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', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ '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', '--force-retry', '--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', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--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', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'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'],diff --git a/test/doctor-queued-spend.test.ts b/test/doctor-queued-spend.test.tsnew file mode 100644index 0000000000..9509443d7d--- /dev/null+++ b/test/doctor-queued-spend.test.ts@@ -0,0 +1,65 @@+/**+ * doctor `legacy_job_authority` reports queued paid jobs by spend basis and+ * flags spend-authorized rows that wait while workers run (an un-upgraded+ * worker is fenced off them); the post-upgrade banner names queued rows that+ * run under the legacy default cap.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } 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 { MinionQueue } from '../src/core/minions/queue.ts';+import { jobSpendAuthorization } from '../src/core/minions/spend-authorization.ts';+import { registerWorker } from '../src/core/minions/worker-registry.ts';+import { legacyDefaultSpendBannerNote, legacyJobAuthorityEntry } from '../src/commands/doctor/checks/legacy-job-authority.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+ home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-queued-spend-'));+}, 60_000);+afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });++const spend = () => jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: 3, cap_source: 'user', via: 'max_usd' }, { command: 'enrich', of: 1 });+const run = () => withEnv({ GBRAIN_HOME: home }, () => legacyJobAuthorityEntry.run({ engine } as never)) as Promise<Array<Record<string, any>>>;++describe('queued spend in doctor', () => {+ test('counts queued paid jobs by basis; unpaid jobs are not counted', async () => {+ await queue.add('subagent', { prompt: 'x' }, { idempotency_key: 'book-mirror:a-book:ch-1' }, { allowProtectedSubmit: true });+ await queue.add('enrich', { sourceId: 'default' }, {}, { spendAuthorization: spend() });+ await queue.add('subagent', { prompt: 'y' }, {}, { allowProtectedSubmit: true });+ await queue.add('fixture', {});+ const [check] = await run();+ expect(check).toMatchObject({ status: 'ok', details: { queued_spend: { by_basis: { legacy_default: 1, authorized: 1, unrecorded: 1 }, long_waiting: 0 } } });+ expect(check!.message).toContain('Queued paid jobs by spend basis:');+ expect(await legacyDefaultSpendBannerNote(engine)).toContain('1 queued paid job(s)');+ });++ test('a spend-authorized row waiting over 10 minutes while a worker runs is flagged with a read-only fix', async () => {+ const job = await queue.add('enrich', { sourceId: 'default' }, {}, { spendAuthorization: spend() });+ await engine.executeRaw(`UPDATE minion_jobs SET updated_at = now() - interval '20 minutes' WHERE id = $1`, [job.id]);+ expect((await run())[0]!.status).toBe('ok');+ const unregister = await withEnv({ GBRAIN_HOME: home }, () =>+ registerWorker({ pid: process.pid, queue: 'default', nice_requested: null, nice_effective: null, started_at: Date.now() }));+ try {+ const [check] = await run();+ expect(check).toMatchObject({ status: 'warn', details: { queued_spend: { long_waiting_ids: [job.id] }, live_workers: 1 } });+ expect(check!.message).toContain('un-upgraded worker may be fenced off');+ expect(check!.fix).toMatchObject({ argv: ['gbrain', 'jobs', 'list', '--status', 'waiting', '--json'], consent: [] });+ } finally { await withEnv({ GBRAIN_HOME: home }, () => unregister()); }+ });++ test('no banner line without legacy rows', async () => {+ await queue.add('enrich', { sourceId: 'default' }, {}, { spendAuthorization: spend() });+ expect(await legacyDefaultSpendBannerNote(engine)).toBeNull();+ });+});diff --git a/test/e2e/budget-meter-group.test.ts b/test/e2e/budget-meter-group.test.tsnew file mode 100644index 0000000000..f0a78872ef--- /dev/null+++ b/test/e2e/budget-meter-group.test.ts@@ -0,0 +1,156 @@+/**+ * Real-Postgres proof for group spend budgets and the spend fence.+ *+ * PGLite serializes one connection, so it cannot show that the per-key+ * advisory lock stops concurrent children from jointly passing a group cap,+ * or how the protocol trigger treats an un-upgraded worker's claim SQL.+ *+ * Run:+ * DATABASE_URL=postgresql://... bun test test/e2e/budget-meter-group.test.ts+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUIDv7 } from 'bun';+import { PostgresEngine } from 'gbrain';+import { GroupBudgetRefusal, clientLockKey, readGroupSpend, reserveGroup, settle } from '../../src/core/minions/budget-meter.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { jobSpendAuthorization } from '../../src/core/minions/spend-authorization.ts';+import { queryAgentClientSpend } from '../../src/commands/serve-http-admin-api.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const databaseUrl = process.env.DATABASE_URL;+const describePostgres = databaseUrl ? describe : describe.skip;++describePostgres('group spend budget — Postgres', () => {+ let engine: PostgresEngine;+ let key = '';++ beforeAll(async () => {+ engine = new PostgresEngine();+ assertSafeE2eDatabaseUrl(databaseUrl!);+ await engine.connect({ database_url: databaseUrl!, poolSize: 16 });+ await engine.initSchema();+ });++ beforeEach(() => { key = `group:${randomUUIDv7()}`; });++ afterAll(async () => {+ await engine.executeRaw(`DELETE FROM mcp_spend_reservations WHERE budget_key LIKE 'group:%'`);+ await engine.executeRaw(`DELETE FROM mcp_spend_log WHERE budget_key LIKE 'group:%'`);+ await engine.executeRaw(`DELETE FROM oauth_clients WHERE client_id LIKE 'group-e2e-%'`);+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE data->>'e2e' = 'budget-meter-group'`);+ await engine?.disconnect();+ });++ const hold = (estimatedCents: number, capCents = 100) =>+ reserveGroup(engine, { budgetKey: key, estimatedCents, capCents, model: 'test-provider:test-model', provider: 'test-provider' });++ test('concurrent children cannot jointly reserve past the group cap', async () => {+ const attempts = await Promise.allSettled(Array.from({ length: 20 }, () => hold(10)));+ const admitted = attempts.filter(a => a.status === 'fulfilled');+ expect(admitted).toHaveLength(10);+ for (const a of attempts) if (a.status === 'rejected') expect(a.reason).toBeInstanceOf(GroupBudgetRefusal);+ expect((await readGroupSpend(engine, key)).liveCents).toBe(100);+ });++ for (const order of ['sibling commits its hold first', 'sibling commits nothing'] as const) {+ test(`a reservation waits on the group lock while a sibling holds it (${order})`, async () => {+ let unlock!: () => void;+ const locked = new Promise<void>(r => { unlock = r; });+ let lockHeld!: () => void;+ const held = new Promise<void>(r => { lockHeld = r; });+ const sibling = engine.transaction(async (tx) => {+ await tx.executeRaw('SELECT pg_advisory_xact_lock($1)', [clientLockKey(key)]);+ lockHeld();+ await locked;+ if (order === 'sibling commits its hold first') {+ await tx.executeRaw(+ `INSERT INTO mcp_spend_reservations (reservation_id, budget_key, estimated_cents, model, provider, status, expires_at)+ VALUES ($1, $2, 80, 'm', 'p', 'pending', now() + interval '10 minutes')`, [randomUUIDv7(), key]);+ }+ });+ await held;+ const contender = hold(80).then(r => ({ ok: r }), e => ({ err: e }));+ await new Promise(r => setTimeout(r, 200));+ unlock();+ await sibling;+ const outcome = await contender;+ if (order === 'sibling commits its hold first') {+ expect((outcome as { err: GroupBudgetRefusal }).err.kind).toBe('pressure');+ } else {+ expect((outcome as { ok: unknown }).ok).toBeDefined();+ }+ });+ }++ test('an overdue hold stays charged until reconciled', async () => {+ await hold(100);+ await engine.executeRaw(`UPDATE mcp_spend_reservations SET expires_at = now() - interval '1 second' WHERE budget_key = $1`, [key]);+ const refused = await hold(1).catch(e => e);+ expect((refused as GroupBudgetRefusal).kind).toBe('exhausted');+ });++ test('admin client spend excludes group rows', async () => {+ const clientId = `group-e2e-${randomUUIDv7()}`;+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, client_secret_hash, scope, grant_types, redirect_uris, token_endpoint_auth_method, bound_tools, created_at)+ VALUES ($1, $1, '', 'read', ARRAY['client_credentials'], ARRAY[]::text[], 'client_secret_post', ARRAY['search'], now())`, [clientId]);+ const r = await hold(50);+ await settle(engine, r.reservationId, 50);+ const row = (await queryAgentClientSpend(engine)).find(c => c.client_id === clientId)!;+ expect(row).toMatchObject({ spent_cents_today: 0, pending_cents: 0 });+ });++ test('a reservation or log row with both budget owners is refused', async () => {+ await expect(engine.executeRaw(+ `INSERT INTO mcp_spend_reservations (reservation_id, client_id, budget_key, estimated_cents, model, provider, status, expires_at)+ VALUES ($1, 'group-e2e-x', $2, 1, 'm', 'p', 'pending', now())`, [randomUUIDv7(), key])).rejects.toThrow();+ await expect(engine.executeRaw(+ `INSERT INTO mcp_spend_log (client_id, budget_key, operation, spend_cents) VALUES ('group-e2e-x', $1, 'op', 1)`, [key])).rejects.toThrow();+ });+});++describePostgres('spend fence — Postgres', () => {+ let engine: PostgresEngine;+ let queue: MinionQueue;+ const queueName = `spend-fence-${randomUUIDv7()}`;++ beforeAll(async () => {+ engine = new PostgresEngine();+ assertSafeE2eDatabaseUrl(databaseUrl!);+ await engine.connect({ database_url: databaseUrl!, poolSize: 4 });+ await engine.initSchema();+ queue = new MinionQueue(engine);+ });++ afterAll(async () => {+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE queue = $1`, [queueName]);+ await engine?.disconnect();+ });++ /** The claim SQL of a worker from before the spend fence: no spend_claim_token. */+ const oldWorkerClaim = () => engine.executeRaw<{ id: number }>(+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'old-worker',+ attempts_started = attempts_started + 1, started_at = COALESCE(started_at, now()), updated_at = now()+ WHERE id = (SELECT id FROM minion_jobs WHERE queue = $1 AND status = 'waiting' AND submission_authority IS NOT NULL+ ORDER BY priority ASC, created_at ASC FOR UPDATE SKIP LOCKED LIMIT 1)+ RETURNING id`, [queueName]);++ test('an old worker stalls at a fenced row ahead of a NULL row; an upgraded worker claims both', async () => {+ const spend = jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: 5, cap_source: 'user', via: 'max_usd' }, { command: 'book-mirror', of: 1 });+ const fenced = await queue.add('subagent', { e2e: 'budget-meter-group', prompt: 'a' }, { queue: queueName }, { allowProtectedSubmit: true, spendAuthorization: spend });+ const open = await queue.add('subagent', { e2e: 'budget-meter-group', prompt: 'b' }, { queue: queueName }, { allowProtectedSubmit: true });+ await expect(oldWorkerClaim()).rejects.toThrow('Minion spend protocol 1 required');+ expect((await queue.getJob(open.id))!.status).toBe('waiting');+ const first = await queue.claim('new-worker-1', 60_000, queueName, ['subagent']);+ const second = await queue.claim('new-worker-2', 60_000, queueName, ['subagent']);+ expect([first?.id, second?.id]).toEqual([fenced.id, open.id]);+ });++ test('new-worker claim, stall, then an old-worker reclaim is refused', async () => {+ const spend = jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: 5, cap_source: 'user', via: 'max_usd' }, { command: 'enrich', of: 1 });+ const job = await queue.add('enrich', { e2e: 'budget-meter-group', sourceId: 'default' }, { queue: queueName }, { spendAuthorization: spend });+ expect((await queue.claim('new-worker', 60_000, queueName, ['enrich']))?.id).toBe(job.id);+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'waiting', lock_token = NULL, lock_until = NULL WHERE id = $1`, [job.id]);+ await expect(oldWorkerClaim()).rejects.toThrow('Minion spend protocol 1 required');+ });+});