Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(minions): enforce queued spend authorizations in the worker
garrytan9cb5d7922aa4
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c8d143f471..1a3f435246 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -9,7 +9,7 @@ src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consentsrc/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)-src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)+src/commands/jobs.ts 661 ratchet +1 spend authorization: jobs submit --yes/--max-usd help line; refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)src/commands/serve-http.ts 919 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities)src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)@@ -29,7 +29,7 @@ src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; growsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)-src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry+src/core/minions/worker.ts 1765 ratchet +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retrysrc/commands/sources.ts 2031 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured)src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump notesrc/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verifydiff --git a/src/commands/jobs-readiness.ts b/src/commands/jobs-readiness.tsindex 92f2104c38..b06a50294c 100644--- a/src/commands/jobs-readiness.ts+++ b/src/commands/jobs-readiness.ts@@ -2,6 +2,7 @@ import type { BrainEngine } from '../core/engine.ts';import { VERSION } from '../version.ts';import { assertWorkerDbReadiness } from '../core/minions/db-probe.ts';import { checkChildReadiness, CHILD_READINESS_PROTOCOL_VERSION } from '../core/minions/child-readiness.ts';+import { noteChildSpendEnforcement } from '../core/minions/spend-authorization.ts';import { childConfigurationError, resolveChildCliInvocation, type ChildCliInvocation } from '../core/minions/job-isolation.ts';import type { LocalConfigurationError } from '../core/minions/configuration-error.ts';import { writeWorkerProcessingStatus, type ProcessingRuntimeIdentity, type WorkerProcessingUpdate, type WorkerStartupStage } from '../core/minions/processing-state.ts';@@ -26,6 +27,10 @@ export async function checkWorkerStartup(if (!invocation) return undefined;reportWorkerStarting('child_readiness');const child = await checkChildReadiness({ invocation, tiniPath });+ noteChildSpendEnforcement(child.features);+ if (!child.features.includes('spend-enforcement-v1')) {+ console.error(`[gbrain jobs] selected child ${child.version} cannot enforce spend authorizations; spend-authorized jobs are released for an upgraded worker instead of running.`);+ }if (child.versionSkew) {console.error(`[gbrain jobs] selected child version ${child.version} differs from worker ${VERSION}; required protocol and capabilities are compatible.`);}diff --git a/src/core/cycle/inline-drain.ts b/src/core/cycle/inline-drain.tsindex f24d805dd0..d4b53f655b 100644--- a/src/core/cycle/inline-drain.ts+++ b/src/core/cycle/inline-drain.ts@@ -42,6 +42,7 @@ import { makeSubagentHandler } from '../minions/handlers/subagent.ts';import { RateLeaseUnavailableError, leaseFullBackoffMs } from '../minions/rate-leases.ts';import { reconnectAfterConnectionError } from '../minions/reconnect.ts';import { withChatPhase } from '../ai/chat-usage.ts';+import { runWithJobSpend } from '../minions/spend-authorization.ts';import { isRetryableConnError } from '../retry-matcher.ts';import { anySignal, throwIfAborted } from '../abort-check.ts';import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';@@ -364,7 +365,7 @@ async function drainLoop(// work (e.g. dream synthesize) would silently absorb every child's// spend into the phase tag, breaking the one-ledger-per-surface rule// the phase telemetry depends on.- result = await withChatPhase(`job:${job.name}`, () => handler(context));+ result = await withChatPhase(`job:${job.name}`, () => runWithJobSpend(engine, job, context, handler));handlerRan = true;} catch (e) {handlerErr = e;diff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.tsindex 64a6364cbe..bfd45b1708 100644--- a/src/core/minions/child-job-runner.ts+++ b/src/core/minions/child-job-runner.ts@@ -37,6 +37,7 @@ import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { buildSpawnInvocation } from './spawn-helpers.ts';+import { SpendEnforcementUnavailableError, childSpendEnforcementReady } from './spend-authorization.ts';import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';import {UnrecoverableError,@@ -109,6 +110,8 @@ const PER_JOB_ABORT_REASONS = new Set<string>([export interface RunJobInChildOpts {jobId: number;+ /** The row carries a spend authorization: only a child with `spend-enforcement-v1` may run it. */+ spendAuthorized?: boolean;jobName: string;lockToken: string;/** Per-job abort (timeout / cancel / lock-lost / lock-renewal-failed). */@@ -141,6 +144,7 @@ interface ChildExit {* them verbatim).*/export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {+ if (opts.spendAuthorized && !childSpendEnforcementReady()) throw new SpendEnforcementUnavailableError();let executionStopped = false;let configurationError: LocalConfigurationError | undefined;try {diff --git a/src/core/minions/child-readiness.ts b/src/core/minions/child-readiness.tsindex 079842eeb7..c85ba4820f 100644--- a/src/core/minions/child-readiness.ts+++ b/src/core/minions/child-readiness.ts@@ -14,7 +14,9 @@ import { WORKER_EXIT_CONFIGURATION } from './worker-exit-codes.ts';export const CHILD_READINESS_PROTOCOL_VERSION = 1;export const CHILD_READINESS_TIMEOUT_MS = 20_000;export const CHILD_READINESS_MAX_BYTES = 64 * 1024;-export const CHILD_READINESS_FEATURES = ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] as const;+export const CHILD_READINESS_FEATURES = ['local-configuration-outcome-v1', 'postgres-cancellation-v1', 'spend-enforcement-v1'] as const;+/** Every child must advertise these; `spend-enforcement-v1` only gates spend-authorized rows (child-job-runner.ts). */+const REQUIRED_CHILD_FEATURES = ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] as const;export interface ChildReadinessOptions {invocation: ChildCliInvocation;@@ -24,7 +26,7 @@ export interface ChildReadinessOptions {signal?: AbortSignal;}-export function parseChildReadiness(raw: string): { version: string; versionSkew: boolean } {+export function parseChildReadiness(raw: string): { version: string; versionSkew: boolean; features: string[] } {let response: unknown;try { response = JSON.parse(raw); } catch {throw childConfigurationError('child_protocol_incompatible');@@ -34,7 +36,7 @@ export function parseChildReadiness(raw: string): { version: string; versionSkewif (r.protocolVersion !== CHILD_READINESS_PROTOCOL_VERSION ||typeof r.version !== 'string' || !/^\d+(?:\.\d+){2,3}$/.test(r.version) || r.version.length > 80 ||!Array.isArray(r.features) || !r.features.every((feature) => typeof feature === 'string') ||- !CHILD_READINESS_FEATURES.every((feature) => (r.features as unknown[]).includes(feature))) {+ !REQUIRED_CHILD_FEATURES.every((feature) => (r.features as unknown[]).includes(feature))) {throw childConfigurationError('child_protocol_incompatible');}if (r.status === 'configuration_error' && isChildConfigurationReason(r.reasonCode)) {@@ -42,10 +44,10 @@ export function parseChildReadiness(raw: string): { version: string; versionSkew}if (r.status === 'transient_error') throw new Error('Selected job child readiness failed transiently; no jobs were admitted.');if (r.status !== 'ready') throw childConfigurationError('child_protocol_incompatible');- return { version: r.version, versionSkew: r.version !== VERSION };+ return { version: r.version, versionSkew: r.version !== VERSION, features: r.features as string[] };}-export async function checkChildReadiness(options: ChildReadinessOptions): Promise<{ version: string; versionSkew: boolean }> {+export async function checkChildReadiness(options: ChildReadinessOptions): Promise<{ version: string; versionSkew: boolean; features: string[] }> {const timeoutMs = options.timeoutMs ?? CHILD_READINESS_TIMEOUT_MS;if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) throw new Error('Invalid child readiness deadline.');if (options.signal?.aborted) throw new Error('Selected job child readiness was interrupted.');@@ -63,7 +65,7 @@ export async function checkChildReadiness(options: ChildReadinessOptions): Promilet groupObserver: ReturnType<typeof setInterval> | undefined;const processGroups = new Set<number>();let child: ReturnType<typeof spawn>;- const finish = (error?: unknown, result?: { version: string; versionSkew: boolean }): void => {+ const finish = (error?: unknown, result?: { version: string; versionSkew: boolean; features: string[] }): void => {if (settled) return;settled = true;if (timer) clearTimeout(timer);diff --git a/src/core/minions/delegated-spend.ts b/src/core/minions/delegated-spend.tsindex 3f74a43840..fa9fe3d591 100644--- a/src/core/minions/delegated-spend.ts+++ b/src/core/minions/delegated-spend.ts@@ -31,7 +31,7 @@ export function maximumInvocationCents(call: AIInvocation): number | null {return Math.ceil((call.maxInputTokens! * Math.max(p.input * 2, p.read, p.write) + call.maxOutputTokens! * p.output) / 100) / 100;}-function actualCents(call: AIInvocation, usage: AIInvocationUsage | null): number | null {+export function actualCents(call: AIInvocation, usage: AIInvocationUsage | null): number | null {const p = prices(call);if (!p || !usage) return null;const values = [usage.inputTokens, usage.outputTokens, usage.cacheReadTokens ?? 0, usage.cacheWriteTokens ?? 0];@@ -58,5 +58,5 @@ export function withDelegatedSpend<T>(engine: BrainEngine, snapshot: DelegationS[hold.reservationId, usage === null ? 'provider_usage_unknown' : 'pricing_unknown'],);} };- }, run);+ }, run, { inherit: true });}diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 2f1219192b..9561fd1102 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -38,6 +38,7 @@ import { readFile, stat } from 'node:fs/promises';import { spawnSync } from 'node:child_process';import { UnrecoverableError } from './types.ts';import { RateLeaseUnavailableError } from './handlers/subagent.ts';+import { SpendGroupRefusedError, type SpendRefusalEnvelope } from './spend-authorization.ts';import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';import { basename, delimiter, resolve } from 'node:path';@@ -99,7 +100,9 @@ export type ChildOutcome =errorKind: ChildErrorKind;message: string;stack?: string;- lease?: { key: string; active: number; max: number };+ lease?: { key: string; active: number; max: number; retryInMs?: number };+ /** A group spend refusal's envelope (code, fix, group amounts). */+ spend?: SpendRefusalEnvelope;protocolVersion?: number;reasonCode?: typeof CHILD_CONFIGURATION_REASONS[number];};@@ -119,7 +122,7 @@ export function encodeHandlerError(err: unknown): ChildOutcome {outcome: 'error',errorKind: 'rate_lease',message: err.message,- lease: { key: err.key, active: err.active, max: err.max },+ lease: { key: err.key, active: err.active, max: err.max, ...(err.retryInMs !== undefined ? { retryInMs: err.retryInMs } : {}) },};}if (err instanceof UnrecoverableError) {@@ -128,6 +131,7 @@ export function encodeHandlerError(err: unknown): ChildOutcome {errorKind: 'unrecoverable',message: err.message,...(err.stack ? { stack: err.stack } : {}),+ ...(err instanceof SpendGroupRefusedError ? { spend: err.envelope } : {}),};}const message = err instanceof Error ? err.message : String(err);@@ -146,10 +150,10 @@ export function reconstructHandlerError(o: Extract<ChildOutcome, { outcome: 'errreturn childConfigurationError(o.reasonCode);}if (o.errorKind === 'rate_lease' && o.lease) {- return new RateLeaseUnavailableError(o.lease.key, o.lease.active, o.lease.max);+ return new RateLeaseUnavailableError(o.lease.key, o.lease.active, o.lease.max, o.lease.retryInMs);}if (o.errorKind === 'unrecoverable') {- return new UnrecoverableError(o.message);+ return o.spend ? new SpendGroupRefusedError(o.spend) : new UnrecoverableError(o.message);}const err = new Error(o.message);if (o.stack) {@@ -196,8 +200,11 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OUreturn encodeHandlerError(childConfigurationError(o.reasonCode));}const rawLease = (o as { lease?: unknown }).lease as- | { key?: unknown; active?: unknown; max?: unknown }+ | { key?: unknown; active?: unknown; max?: unknown; retryInMs?: unknown }| undefined;+ const rawSpend = (o as { spend?: unknown }).spend as { code?: unknown; message?: unknown; group?: unknown } | undefined;+ const spendValid = rawSpend != null && typeof rawSpend === 'object' && typeof rawSpend.code === 'string'+ && typeof rawSpend.message === 'string' && rawSpend.group != null && typeof rawSpend.group === 'object';const leaseValid =rawLease != null &&typeof rawLease.key === 'string' &&@@ -217,8 +224,10 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OU? { stack: (o as { stack: string }).stack }: {}),...(errorKind === 'rate_lease' && leaseValid- ? { lease: { key: rawLease.key as string, active: rawLease.active as number, max: rawLease.max as number } }+ ? { lease: { key: rawLease.key as string, active: rawLease.active as number, max: rawLease.max as number,+ ...(Number.isFinite(rawLease.retryInMs as number) && (rawLease.retryInMs as number) >= 0 ? { retryInMs: rawLease.retryInMs as number } : {}) } }: {}),+ ...(errorKind === 'unrecoverable' && spendValid ? { spend: rawSpend as SpendRefusalEnvelope } : {}),};}throw new Error(`job child outcome file has an unrecognized shape (${size} bytes)`);diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 302fba3f43..1a3c63444c 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -16,6 +16,7 @@ import type {} from './types.ts';import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';+import { adoptSpendAuthorization, legacyDefaultClaimSetSql, legacyDefaultClaimParams, type SpendAuthorization } from './spend-authorization.ts';import { validateAttachment } from './attachments.ts';import { isProtectedJobName } from './protected-names.ts';import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';@@ -49,6 +50,8 @@ export interface TrustedSubmitOpts {allowPgliteInlineWorker?: boolean;/** Authenticated submit_agent identity, never read from agent job parameters. */delegatedClientId?: string;+ /** Consent-gated CLI producers only: the user's spend authorization (spend-authorization.ts). */+ spendAuthorization?: SpendAuthorization;}const MIGRATION_VERSION = 7;@@ -594,11 +597,11 @@ export class MinionQueue {const baseCols = `name, queue, status, priority, data, max_attempts, backoff_type,backoff_delay, backoff_jitter, delay_until, parent_job_id, on_child_fail,depth, max_children, timeout_ms, lock_duration_ms, remove_on_complete, remove_on_fail, idempotency_key,- quiet_hours, stagger_key, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until, submission_authority`;+ quiet_hours, stagger_key, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until, submission_authority, spend_authorization`;const baseVals = `$1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20::jsonb, $21`;- const baseValsWithOwner = `${baseVals}, $22, $23, $24, $25::jsonb`;+ const baseValsWithOwner = `${baseVals}, $22, $23, $24, $25::jsonb, $26::text::jsonb`;const cols = hasMaxStalled ? `${baseCols}, max_stalled` : baseCols;- const vals = hasMaxStalled ? `${baseValsWithOwner}, $26` : baseValsWithOwner;+ const vals = hasMaxStalled ? `${baseValsWithOwner}, $27` : baseValsWithOwner;const insertSql = opts?.idempotency_key? `INSERT INTO minion_jobs (${cols})@@ -645,6 +648,7 @@ export class MinionQueue {opts?.private_queue_owner_token ?? null,privateQueueLeaseUntil,authority,+ trusted?.spendAuthorization ? JSON.stringify(trusted.spendAuthorization) : null,];if (hasMaxStalled) params.push(clampedMaxStalled);@@ -678,7 +682,7 @@ export class MinionQueue {} catch { /* audit failures never block submission */ }}- return result;+ return trusted?.spendAuthorization && result.coalesced ? adoptSpendAuthorization(this.engine, result, trusted.spendAuthorization) : result;}/** Get a job by ID. Returns null if not found. */@@ -1459,6 +1463,7 @@ export class MinionQueue {`UPDATE minion_jobs SETstatus = 'active',claim_generation = claim_generation + 1,+ ${legacyDefaultClaimSetSql('$7', '$8')},lock_token = $1,lock_until = now() + ((CASE WHEN COALESCE(lock_duration_ms, ($6::jsonb ->> name)::int) IS NULL THEN $2ELSE LEAST(GREATEST(COALESCE(lock_duration_ms, ($6::jsonb ->> name)::int), 5000), 3600000) END)::double precision * interval '1 millisecond'),@@ -1479,7 +1484,7 @@ export class MinionQueue {LIMIT 1)RETURNING *`,- [lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS, HANDLER_DEFAULT_LOCK_DURATION_MS]+ [lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS, HANDLER_DEFAULT_LOCK_DURATION_MS, ...legacyDefaultClaimParams()]);return rows.length > 0 ? rowToMinionJob(rows[0]) : null;}diff --git a/src/core/minions/run-child.ts b/src/core/minions/run-child.tsindex d51bb7daff..38dc7bcb65 100644--- a/src/core/minions/run-child.ts+++ b/src/core/minions/run-child.ts@@ -34,6 +34,7 @@ import type { BrainEngine } from '../engine.ts';import { MinionQueue } from './queue.ts';import type { MinionHandler } from './types.ts';import { buildJobContext } from './job-context.ts';+import { runWithJobSpend } from './spend-authorization.ts';import { withChatPhase } from '../ai/chat-usage.ts';import {JOB_CHILD_EXIT_NOT_CLAIMED,@@ -163,7 +164,7 @@ export async function runChildJobEntry(// #4218: same phase attribution as the in-process worker path — the// isolated child runs its own gateway, so the wrap must live here too.const authority = await authorizeJobExecution(engine, job);- const result = await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => handler(context)), abort.signal);+ const result = await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => runWithJobSpend(engine, job, context, handler)), abort.signal);// completeJob's {value: x} wrap decision must run BEFORE JSON// serialization: a JSON round-trip changes typeof for Date /// toJSON-bearing results (object → string), which would flip the wrapdiff --git a/src/core/minions/spend-authorization.ts b/src/core/minions/spend-authorization.tsnew file mode 100644index 0000000000..13b2f104b1--- /dev/null+++ b/src/core/minions/spend-authorization.ts@@ -0,0 +1,367 @@+/**+ * Submit-time spend authorization on queued paid jobs.+ *+ * A consent-gated CLI producer (`book-mirror`, `enrich --background`,+ * `jobs submit enrich|subagent`) stores the user's authorization on every job+ * it queues through the trusted `MinionQueue.add` option `spendAuthorization`+ * (never through job data). All jobs of one command share one group and one+ * approved total. The worker runs each such job under `runWithJobSpend`, which+ * installs the AI invocation guard (the seam delegated spend uses): every+ * provider attempt reserves its maximum liability against+ * `group:<group_id>` in the durable meter and settles its measured usage.+ *+ * Rows of those producers queued before the record existed (NULL, with the+ * producers' idempotency-key prefixes) are stamped `legacy_default` by the+ * claim UPDATE itself (`LEGACY_DEFAULT_CLAIM_SET_SQL`), one group per row.+ * Every other job is `unrecorded` and runs under its producer's own budget.+ */+import { randomUUIDv7 } from 'bun';+import type { BrainEngine } from '../engine.ts';+import { shellQuote, type Action, type Effect } from '../agent-output.ts';+import { DEFAULT_PAID_CAP_USD, resumeMaxUsd, type Authorization } from '../consent.ts';+import { opError } from '../ops/contract.ts';+import { withAIInvocationGuard } from '../ai/invocation-guard.ts';+import { GroupBudgetRefusal, RESERVATION_TTL_MS, readGroupSpend, reserveGroup, settle, type GroupSpend } from './budget-meter.ts';+import { actualCents, maximumInvocationCents } from './delegated-spend.ts';+import { UnrecoverableError } from './errors.ts';+import { RateLeaseUnavailableError } from './rate-leases.ts';+import type { MinionJob, MinionJobContext } from './types.ts';+import { spendBasis, type JobSpendContext, type SpendAuthorization } from './spend-record.ts';++export * from './spend-record.ts';++/** Pre-upgrade rows of these producers get a `legacy_default` record when a worker claims them. */+export const LEGACY_SPEND_KEY_PREFIXES = { subagent: ['book-mirror:'], enrich: ['enrich:', 'cli:enrich:'] } as const;++/** A queued spend-authorized row waiting longer than this while workers run is flagged by doctor. */+export const FENCED_ROW_WAIT_MS = 10 * 60 * 1000;+/** A job delayed by live holds of its group retries this many times (one reservation TTL) before it dies. */+export const MAX_PRESSURE_RENEWALS = 6;+let pressureRetryMs = Math.floor(RESERVATION_TTL_MS / MAX_PRESSURE_RENEWALS);+export function __setGroupPressureRetryMsForTests(ms: number | null): void {+ pressureRetryMs = ms ?? Math.floor(RESERVATION_TTL_MS / MAX_PRESSURE_RENEWALS);+}++/** The record a consent-gated producer stores on each job it queues. */+export function jobSpendAuthorization(+ auth: Authorization | { uncapped: true; via: 'max_usd' },+ opts: { command: string; est_usd?: number; of?: number; argv?: string[] },+): SpendAuthorization {+ const base = {+ version: 1 as const, kind: 'authorized' as const, group_id: randomUUIDv7(),+ ...(opts.of !== undefined ? { of: opts.of } : {}),+ consented_effects: 'uncapped' in auth ? ['paid' as Effect] : auth.consented_effects,+ command: opts.command,+ ...(opts.est_usd !== undefined ? { est_usd: opts.est_usd } : {}),+ ...(opts.argv ? { argv: opts.argv } : {}),+ authorized_at: new Date().toISOString(),+ };+ if ('uncapped' in auth || auth.cap_usd === null || !Number.isFinite(auth.cap_usd)) {+ return { ...base, cap_usd: null, uncapped: true, cap_source: ('uncapped' in auth ? null : auth.cap_source) ?? 'user', via: auth.via };+ }+ return { ...base, cap_usd: auth.cap_usd, cap_source: auth.cap_source ?? 'default', via: auth.via };+}++/**+ * The claim UPDATE's SET items: the per-acquisition fence token, and the+ * `legacy_default` record for a NULL row of a consent-gated producer+ * (`$groupParam` is a fresh uuid per claim, `$capParam` the default cap).+ */+export function legacyDefaultClaimSetSql(groupParam: string, capParam: string): string {+ 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 ');+ return `spend_claim_token = claim_generation + 1,+ spend_authorization = CASE WHEN spend_authorization IS NULL AND (${legacy}) THEN jsonb_build_object(+ 'version', 1, 'kind', 'legacy_default', 'group_id', ${groupParam}::text,+ 'cap_usd', CASE WHEN name = 'enrich' AND jsonb_typeof(data->'maxCostUsd') = 'number'+ THEN CASE WHEN (data->>'maxCostUsd')::numeric > 0 THEN data->'maxCostUsd' ELSE to_jsonb(${capParam}::numeric) END+ ELSE to_jsonb(${capParam}::numeric) END,+ 'cap_source', 'default', 'command', CASE WHEN name = 'enrich' THEN 'enrich' ELSE 'book-mirror' END,+ 'authorized_at', to_jsonb(to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))) ELSE spend_authorization END`;+}++/** Fresh claim parameters for `legacyDefaultClaimSetSql`. */+export function legacyDefaultClaimParams(): [string, number] {+ return [randomUUIDv7(), DEFAULT_PAID_CAP_USD];+}++/**+ * Coalesce rule: a resubmission that lands on a live row with no record or a+ * `legacy_default` record installs the new authorization (compare-and-set on+ * the old record; an `active` row picks it up at its next claim). An+ * `authorized` row keeps its own record. Returns the row as it now stands.+ */+export async function adoptSpendAuthorization(engine: BrainEngine, job: MinionJob, record: SpendAuthorization): Promise<MinionJob> {+ const current = job.spend_authorization ?? null;+ if (current?.kind === 'authorized' || job.spend_authorization_invalid) return job;+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `UPDATE minion_jobs SET spend_authorization = $2::text::jsonb, updated_at = now()+ WHERE id = $1 AND status IN ('waiting','delayed','paused','waiting-children','active')+ AND ${current ? `spend_authorization->>'group_id' = $3` : 'spend_authorization IS NULL AND $3::text IS NULL'}+ RETURNING id`,+ [job.id, JSON.stringify(record), current?.group_id ?? null],+ );+ return rows.length ? { ...job, spend_authorization: record } : job;+}++const cents = (usd: number) => Math.round(usd * 100);+const usd = (c: number) => Math.round(c) / 100;++/** A group's amounts in USD, for envelopes, `jobs get` and `jobs list --group`. */+export function groupAmounts(record: SpendAuthorization, spend: GroupSpend) {+ const spent = spend.committedCents + spend.overdueCents;+ return {+ group_id: record.group_id,+ cap_usd: record.cap_usd,+ cap_source: record.cap_source,+ spent_usd: usd(spend.committedCents),+ overdue_usd: usd(spend.overdueCents),+ reserved_usd: usd(spend.liveCents + spend.overdueCents),+ remaining_usd: record.cap_usd === null ? null : usd(Math.max(0, cents(record.cap_usd) - spent)),+ };+}++/** A group's amounts (read-only), or null when the meter tables are unavailable. */+export async function jobGroupAmounts(engine: BrainEngine, record: SpendAuthorization): Promise<ReturnType<typeof groupAmounts> | null> {+ try { return groupAmounts(record, await readGroupSpend(engine, `group:${record.group_id}`)); }+ catch { return null; }+}++const GROUP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** Every job of a spend group, oldest first (expression index on the record's group_id). */+export async function groupJobs(engine: BrainEngine, groupId: string): Promise<MinionJob[]> {+ if (!GROUP_ID.test(groupId)) return [];+ const { rowToMinionJob } = await import('./types.ts');+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT * FROM minion_jobs WHERE spend_authorization IS NOT NULL AND spend_authorization->>'group_id' = $1 ORDER BY id`, [groupId]);+ return rows.map(rowToMinionJob);+}++export type SpendRefusalEnvelope = ReturnType<ReturnType<typeof opError>['toJSON']> & {+ group: ReturnType<typeof groupAmounts>;+};++/** Typed, terminal refusal of a group (cap exhausted or a model without a price under a user cap). */+export class SpendGroupRefusedError extends UnrecoverableError {+ readonly tag = 'SPEND_GROUP_REFUSED';+ constructor(readonly envelope: SpendRefusalEnvelope) {+ super(`${envelope.code}: ${envelope.message}`);+ this.name = 'SpendGroupRefusedError';+ }+}++/** Live holds of sibling attempts fill the group: the job is delayed (no attempt burned) and retried. */+export class SpendGroupPressureError extends RateLeaseUnavailableError {+ readonly tag = 'SPEND_GROUP_REFUSED';+ constructor(budgetKey: string, liveCents: number, capCents: number) {+ super(budgetKey, Math.round(liveCents), Math.round(capCents), pressureRetryMs);+ this.name = 'SpendGroupPressureError';+ }+}++/** A worker without the spend-enforcement capability in its job child: the row is released, not failed. */+export class SpendEnforcementUnavailableError extends RateLeaseUnavailableError {+ constructor() {+ super('spend-enforcement-v1', 0, 0, 60_000);+ this.name = 'SpendEnforcementUnavailableError';+ }+}++let childSpendEnforcement = false;+/** Records whether the selected job child advertised `spend-enforcement-v1` at readiness. */+export function noteChildSpendEnforcement(features: readonly string[]): void {+ childSpendEnforcement = features.includes('spend-enforcement-v1');+}+export function childSpendEnforcementReady(): boolean { return childSpendEnforcement; }++/** The resume command: the producer's argv with a doubled `--max-usd`, or null for a legacy row. */+function resumeArgv(record: SpendAuthorization, capUsd: number): string[] | null {+ if (!record.argv) return null;+ const argv: string[] = [];+ for (let i = 0; i < record.argv.length; i++) {+ const a = record.argv[i]!;+ if (a === '--max-usd' || a === '--max-cost' || a === '--max-cost-usd') { i++; continue; }+ if (/^--max-(usd|cost|cost-usd)=/.test(a) || a === '--yes' || a === '-y' || a === '--no-confirm') continue;+ argv.push(a);+ }+ return [...argv, '--max-usd', resumeMaxUsd(capUsd).toFixed(2), '--yes'];+}++/** The terminal envelope for a group that ran out (`kind: 'cost'`) or met an unpriced model under a user cap. */+export async function spendRefusal(+ engine: BrainEngine,+ job: Pick<MinionJob, 'id' | 'name'>,+ record: SpendAuthorization,+ cause: { kind: 'cost'; overdueHolds?: boolean } | { kind: 'no_pricing'; model: string },+): Promise<SpendGroupRefusedError> {+ const group = groupAmounts(record, await readGroupSpend(engine, `group:${record.group_id}`));+ const listArgv = ['gbrain', 'jobs', 'list', '--group', record.group_id, '--json'];+ if (cause.kind === 'no_pricing') {+ const e = opError('no_pricing',+ `Job ${job.id} (${record.command}) stopped: gbrain has no price for ${cause.model}, so the user's $${record.cap_usd!.toFixed(2)} cap cannot be enforced. No provider call was made.`,+ `Look up ${cause.model}'s per-token rate, register it with \`gbrain pricing set\`, then run ${record.command} again.`,+ { why: 'A user-set cap is enforced per provider attempt; an attempt with no known price could spend past it.',+ fix: { argv: ['gbrain', 'pricing', 'set', '--help'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows how to register the model\'s rate so the cap can meter it.', verify: { argv: listArgv } } });+ return new SpendGroupRefusedError({ ...e.toJSON(), group } as SpendRefusalEnvelope);+ }+ const cap = record.cap_usd!;+ const derived = record.cap_source === 'derived';+ const resume = resumeArgv(record, cap);+ const n = resumeMaxUsd(cap);+ const reconcile = cause.overdueHolds && group.overdue_usd > 0+ ? ` $${group.overdue_usd.toFixed(2)} of it is held by attempts that never reported usage; they count as spent until reconciled.`+ : '';+ const message = `Job ${job.id} (${record.command}) stopped: its group ${record.group_id} reached the $${cap.toFixed(2)} ${derived ? 'cost cap derived from the estimate' : `${record.cap_source} cost cap`} `+ + `(spent $${group.spent_usd.toFixed(2)}, reserved $${group.reserved_usd.toFixed(2)}, remaining $${(group.remaining_usd ?? 0).toFixed(2)}).${reconcile}`;+ const e = opError(derived ? 'derived_cap_exhausted' : 'cost_cap_exceeded', message,+ resume+ ? `Ask the user whether to continue with a $${n.toFixed(2)} cap, then run: ${shellQuote(resume)} (completed work is skipped; inspect the group with ${shellQuote(listArgv)}).`+ : `Ask the user whether to continue; if they agree, run ${record.command} again with --max-usd ${n.toFixed(2)} (completed work is skipped). Inspect the group with ${shellQuote(listArgv)}.`,+ { why: 'Every job of a command shares the total the user approved; the job dies instead of spending past it, and a rerun authorizes additional spend as a new group.',+ fix: resume+ ? { argv: resume, consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: `Queues the unfinished work under a new $${n.toFixed(2)} group.`,+ user_message: `${record.command} spent its $${cap.toFixed(2)} budget before finishing. Continue with up to $${n.toFixed(2)} more?`,+ verify: { argv: listArgv } }+ : { argv: listArgv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the group\'s jobs and amounts before the user decides on a rerun.' } as Action });+ return new SpendGroupRefusedError({ ...e.toJSON(), group } as SpendRefusalEnvelope);+}++async function pressureRenewals(engine: BrainEngine, jobId: number, budgetKey: string): Promise<number> {+ try {+ const rows = await engine.executeRaw<{ n: number | string }>(+ 'SELECT count(*)::int AS n FROM minion_lease_pressure_log WHERE job_id = $1 AND lease_key = $2', [jobId, budgetKey]);+ return Number(rows[0]?.n ?? 0);+ } catch { return 0; }+}++async function recordRefusal(engine: BrainEngine, job: MinionJob, error: SpendGroupRefusedError): Promise<void> {+ if (!job.lock_token) return;+ await engine.executeRaw(+ `UPDATE minion_jobs SET result = $3::text::jsonb, updated_at = now() WHERE id = $1 AND lock_token = $2 AND status = 'active'`,+ [job.id, job.lock_token, JSON.stringify({ spend_refusal: error.envelope })],+ ).catch(() => { /* the error text still carries the code and message */ });+}++async function logSpendBasis(engine: BrainEngine, job: MinionJob, record: SpendAuthorization | null): Promise<void> {+ const { basis, why } = spendBasis(job);+ if (!record) {+ const { paidJobNames } = await import('../../commands/jobs/shared.ts');+ if (!(await paidJobNames([job.name])).length) return;+ }+ const amounts = record ? groupAmounts(record, await readGroupSpend(engine, `group:${record.group_id}`).catch(() => ({ committedCents: 0, overdueCents: 0, liveCents: 0 }))) : null;+ console.log(`[minions] job_spend_basis ${JSON.stringify({+ job_id: job.id, name: job.name, basis,+ cap_usd: record?.cap_usd ?? null, cap_source: record?.cap_source ?? null,+ ...(amounts ? { group_id: amounts.group_id, group_spent_usd: amounts.spent_usd, group_remaining_usd: amounts.remaining_usd } : {}),+ why,+ })}`);+}++/**+ * Runs one claimed job's handler under its spend authorization. NULL rows+ * run exactly as before. An uncapped record reserves nothing (spend is still+ * ledgered by the handler's own tracker). A capped record runs under the+ * invocation guard, nested inside any outer guard (both must admit): each+ * attempt reserves its maximum against the group and settles its usage; an+ * attempt with unknown usage keeps its maximum charged. Refusals are typed:+ * settled exhaustion (or a model without a price under a user cap) is+ * terminal and recorded on the row; live-hold pressure delays the job, at+ * most `MAX_PRESSURE_RENEWALS` times.+ */+export async function runWithJobSpend<T>(+ engine: BrainEngine,+ job: MinionJob,+ ctx: MinionJobContext,+ handler: (ctx: MinionJobContext) => Promise<T>,+): Promise<T> {+ if (job.spend_authorization_invalid) {+ throw new UnrecoverableError(`spend_authorization_invalid: job ${job.id} carries a malformed spend authorization, so it will not run. Cancel it (gbrain jobs cancel ${job.id}) and run the producing command again.`);+ }+ const record = job.spend_authorization ?? null;+ await logSpendBasis(engine, job, record).catch(() => {});+ if (!record) return handler(ctx);+ const budgetKey = `group:${record.group_id}`;+ const spendCtx: MinionJobContext = { ...ctx, spend: { record, budget_key: budgetKey } };+ if (record.uncapped) return handler(spendCtx);+ const capCents = cents(record.cap_usd!);+ const seen: { refusal: SpendGroupRefusedError | SpendGroupPressureError | null } = { refusal: null };+ let warned = false;+ const guard = async (call: Parameters<Parameters<typeof withAIInvocationGuard>[0]>[0]) => {+ const max = maximumInvocationCents(call);+ if (max === null) {+ if (record.cap_source === 'user') throw (seen.refusal = await spendRefusal(engine, job, record, { kind: 'no_pricing', model: call.model }));+ if (!warned) {+ warned = true;+ process.stderr.write(`[budget] BUDGET_TRACKER_NO_PRICING: model "${call.model}" has no known price; job ${job.id} runs it unmetered under its ${record.cap_source} $${record.cap_usd!.toFixed(2)} cap. Register its rate with \`gbrain pricing set\` to meter it.\n`);+ }+ }+ let hold;+ try {+ hold = await reserveGroup(engine, { budgetKey, capCents, estimatedCents: max ?? 0, estimateKnown: max !== null,+ model: call.model, provider: call.model.split(':')[0] || 'unknown', jobId: job.id });+ } catch (error) {+ if (!(error instanceof GroupBudgetRefusal)) throw error;+ if (error.kind === 'pressure' && await pressureRenewals(engine, job.id, budgetKey) < MAX_PRESSURE_RENEWALS) {+ throw (seen.refusal = new SpendGroupPressureError(budgetKey, error.spend.liveCents, capCents));+ }+ throw (seen.refusal = await spendRefusal(engine, job, record, { kind: 'cost', overdueHolds: true }));+ }+ return { async settle(usage: Parameters<typeof actualCents>[1]) {+ const c = actualCents(call, usage);+ if (c !== null) await settle(engine, hold.reservationId, c, call.operation);+ else await engine.executeRaw(+ `UPDATE mcp_spend_reservations SET usage_unknown_reason = $2 WHERE reservation_id = $1 AND status IN ('pending','expired')`,+ [hold.reservationId, usage === null ? 'provider_usage_unknown' : 'pricing_unknown'],+ );+ } };+ };+ let result: T;+ try {+ result = await withAIInvocationGuard(guard, () => handler(spendCtx), { inherit: true });+ } catch (error) {+ const typed = seen.refusal ?? (error instanceof SpendGroupRefusedError ? error : null);+ if (typed instanceof SpendGroupRefusedError) await recordRefusal(engine, job, typed);+ throw typed ?? error;+ }+ if (seen.refusal instanceof SpendGroupRefusedError) {+ await recordRefusal(engine, job, seen.refusal);+ throw seen.refusal;+ }+ return result;+}++/**+ * Producer-side summary after queueing under `record`: which jobs carry the+ * new group, which kept an earlier authorization (with the cancel-and-resubmit+ * commands), and which were reused as finished rows.+ */+export function spendSubmitSummary(record: SpendAuthorization, jobs: MinionJob[], rerunArgv: string[]) {+ const fresh: number[] = [];+ const reused: number[] = [];+ const kept = new Map<string, { group_id: string; cap_usd: number | null; job_ids: number[] }>();+ for (const job of jobs) {+ const r = job.spend_authorization;+ if (r?.group_id === record.group_id) fresh.push(job.id);+ else if (r?.kind === 'authorized' && !['completed', 'failed', 'dead', 'cancelled'].includes(job.status)) {+ const entry = kept.get(r.group_id) ?? { group_id: r.group_id, cap_usd: r.cap_usd, job_ids: [] };+ entry.job_ids.push(job.id);+ kept.set(r.group_id, entry);+ } else reused.push(job.id);+ }+ const lines = [`[spend] ${record.command}: ${fresh.length} job(s) queued or re-authorized under group ${record.group_id} `+ + `(${record.uncapped ? 'uncapped, spend ledgered' : `$${record.cap_usd!.toFixed(2)} ${record.cap_source} cap shared by the group`}).`];+ for (const k of kept.values()) {+ lines.push(`[spend] ${k.job_ids.length} job(s) (${k.job_ids.join(', ')}) keep their earlier authorization: group ${k.group_id}, `+ + `${k.cap_usd === null ? 'uncapped' : `$${k.cap_usd.toFixed(2)} cap`}. To run them under the new cap: gbrain jobs cancel --group ${k.group_id}, then ${shellQuote(rerunArgv)}`);+ }+ if (reused.length) lines.push(`[spend] ${reused.length} finished job(s) reused: ${reused.join(', ')}.`);+ if (!record.uncapped && record.cap_source !== 'user') {+ lines.push(`[spend] A model with no known price runs unmetered under this ${record.cap_source} cap (it warns); register its rate with \`gbrain pricing set\` to meter it.`);+ }+ return { summary: { group_id: record.group_id, cap_usd: record.cap_usd, cap_source: record.cap_source, uncapped: record.uncapped === true,+ queued_job_ids: fresh, reused_job_ids: reused, kept: [...kept.values()] }, lines };+}diff --git a/src/core/minions/spend-record.ts b/src/core/minions/spend-record.tsnew file mode 100644index 0000000000..cb9da2d3dd--- /dev/null+++ b/src/core/minions/spend-record.ts@@ -0,0 +1,80 @@+/**+ * The stored shape of `minion_jobs.spend_authorization` and its strict+ * parser. Dependency-free so the row mapper (types.ts) can use it; the+ * runtime (guard, producers, claim SQL) lives in spend-authorization.ts.+ */+import type { Effect } from '../agent-output.ts';+import type { Authorization, CapSource } from '../consent.ts';++export type SpendBasis = 'authorized' | 'legacy_default' | 'unrecorded' | 'invalid';++export interface SpendAuthorization {+ version: 1;+ kind: 'authorized' | 'legacy_default';+ group_id: string;+ /** Jobs the producer queued under this group. */+ of?: number;+ consented_effects?: Effect[];+ /** null only when `uncapped`. */+ cap_usd: number | null;+ uncapped?: true;+ cap_source: CapSource;+ via?: Authorization['via'];+ command: string;+ est_usd?: number;+ /** The producer's command without consent flags: the base of the resume command. */+ argv?: string[];+ authorized_at: string;+}++/** What a job's handler sees of its group (`ctx.spend`). */+export interface JobSpendContext {+ record: SpendAuthorization;+ budget_key: string;+}++const KINDS = new Set(['authorized', 'legacy_default']);+const CAP_SOURCES = new Set(['derived', 'default', 'user']);+const VIAS = new Set(['yes', 'max_usd', 'tokenmax', 'preapproval', 'apply_flag', 'non_interactive_flag', 'tty_prompt']);+const KEYS = new Set(['version', 'kind', 'group_id', 'of', 'consented_effects', 'cap_usd', 'uncapped', 'cap_source', 'via', 'command', 'est_usd', 'argv', 'authorized_at']);+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const strings = (v: unknown) => Array.isArray(v) && v.every(s => typeof s === 'string');++/**+ * Strict parser for the `minion_jobs.spend_authorization` column. Returns+ * null for SQL NULL and throws TypeError on any malformed or unknown shape:+ * a record is written only by trusted producers and the claim UPDATE.+ */+export function parseSpendAuthorization(raw: unknown): SpendAuthorization | null {+ if (raw == null) return null;+ const v = typeof raw === 'string' ? JSON.parse(raw) as unknown : raw;+ if (!v || typeof v !== 'object' || Array.isArray(v)) throw new TypeError('spend_authorization is not an object');+ const r = v as Record<string, unknown>;+ const bad = (field: string) => new TypeError(`spend_authorization.${field} is invalid`);+ for (const k of Object.keys(r)) if (!KEYS.has(k)) throw bad(k);+ if (r.version !== 1) throw bad('version');+ if (typeof r.kind !== 'string' || !KINDS.has(r.kind)) throw bad('kind');+ if (typeof r.group_id !== 'string' || !UUID.test(r.group_id)) throw bad('group_id');+ if (r.of !== undefined && !(Number.isSafeInteger(r.of) && (r.of as number) > 0)) throw bad('of');+ if (r.consented_effects !== undefined && !strings(r.consented_effects)) throw bad('consented_effects');+ if (r.uncapped !== undefined && r.uncapped !== true) throw bad('uncapped');+ if (r.uncapped ? r.cap_usd !== null : !(typeof r.cap_usd === 'number' && Number.isFinite(r.cap_usd) && r.cap_usd > 0)) throw bad('cap_usd');+ if (typeof r.cap_source !== 'string' || !CAP_SOURCES.has(r.cap_source)) throw bad('cap_source');+ if (r.via !== undefined && (typeof r.via !== 'string' || !VIAS.has(r.via))) throw bad('via');+ if (typeof r.command !== 'string' || !r.command || r.command.length > 64) throw bad('command');+ if (r.est_usd !== undefined && !(typeof r.est_usd === 'number' && Number.isFinite(r.est_usd) && r.est_usd >= 0)) throw bad('est_usd');+ if (r.argv !== undefined && !strings(r.argv)) throw bad('argv');+ if (typeof r.authorized_at !== 'string' || Number.isNaN(Date.parse(r.authorized_at))) throw bad('authorized_at');+ return r as unknown as SpendAuthorization;+}++/** How a job's spend is governed, with the sentence `jobs get` and the basis log show. */+export function spendBasis(job: { spend_authorization?: SpendAuthorization | null; spend_authorization_invalid?: true }): { basis: SpendBasis; why: string } {+ const r = job.spend_authorization;+ if (job.spend_authorization_invalid) return { basis: 'invalid', why: 'The stored spend authorization is malformed, so the worker refuses to run this job; cancel it and run the producing command again.' };+ if (!r) return { basis: 'unrecorded', why: 'No submit-time spend authorization exists for this job; it runs under its producer\'s own budget (client daily budget, cycle budget, configured embedding caps or --max-usd), if any.' };+ const unmetered = r.cap_source === 'user' ? '' : ' A model with no known price runs unmetered under this cap (it warns); register its rate with `gbrain pricing set` to meter it.';+ if (r.uncapped) return { basis: r.kind, why: `The user authorized ${r.command} without a cost ceiling (${r.via ?? 'max_usd'}); spend is ledgered against group ${r.group_id}.` };+ if (r.kind === 'legacy_default') return { basis: r.kind, why: `This job was queued before submit-time authorization existed, so it runs under the $${r.cap_usd!.toFixed(2)} default cap. Re-run ${r.command} with --max-usd <usd> to authorize a different amount.${unmetered}` };+ return { basis: r.kind, why: `The user approved $${r.cap_usd!.toFixed(2)} (${r.cap_source}) for ${r.command}; every job of group ${r.group_id} shares that total.${unmetered}` };+}diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex f04320e445..abccb45a22 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -1,4 +1,5 @@import { parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';+import { parseSpendAuthorization, type JobSpendContext, type SpendAuthorization } from './spend-record.ts';/*** Minions — BullMQ-inspired Postgres-native job queue for GBrain.*@@ -42,6 +43,10 @@ export interface MinionJob {data: Record<string, unknown>;/** Internal authority column; never accepted from job data or remote options. */submission_authority?: SubmissionAuthority | null;+ /** Submit-time spend authorization (spend-authorization.ts); never read from job data. */+ spend_authorization?: SpendAuthorization | null;+ /** The column holds a value the strict parser rejects; the worker refuses to run the job. */+ spend_authorization_invalid?: true;// Retrymax_attempts: number;@@ -269,6 +274,8 @@ export interface MinionJobContext {data: Record<string, unknown>;/** Internal authority column; never accepted from job data or remote options. */submission_authority?: SubmissionAuthority | null;+ /** Set by runWithJobSpend for a spend-authorized job: its group record and meter key. */+ spend?: JobSpendContext;attempts_made: number;/** AbortSignal for cooperative cancellation (fires on timeout, cancel, pause, or lock loss). */signal: AbortSignal;@@ -435,6 +442,11 @@ export { UnrecoverableError } from './errors.ts';// --- Row Mapping ---+function spendAuthorizationFields(raw: unknown): Pick<MinionJob, 'spend_authorization' | 'spend_authorization_invalid'> {+ try { return { spend_authorization: parseSpendAuthorization(raw) }; }+ catch { return { spend_authorization: null, spend_authorization_invalid: true }; }+}+export function rowToMinionJob(row: Record<string, unknown>): MinionJob {return {id: row.id as number,@@ -443,6 +455,7 @@ export function rowToMinionJob(row: Record<string, unknown>): MinionJob {status: row.status as MinionJobStatus,priority: row.priority as number,submission_authority: parseSubmissionAuthority(row.submission_authority),+ ...spendAuthorizationFields(row.spend_authorization),data: (typeof row.data === 'string' ? JSON.parse(row.data) : row.data ?? {}) as Record<string, unknown>,max_attempts: row.max_attempts as number,attempts_made: row.attempts_made as number,diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 97295b8e28..3b78c70ec8 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -49,6 +49,7 @@ import {type PoolDiagnostics,} from './db-probe.ts';import { buildJobContext } from './job-context.ts';+import { runWithJobSpend } from './spend-authorization.ts';import {runJobInChild,ChildSpawnInfraError,@@ -1507,7 +1508,7 @@ export class MinionWorker extends EventEmitter {}const result = isolated? await runJobInChild({- jobId: job.id,+ jobId: job.id, spendAuthorized: job.spend_authorization != null,jobName: job.name,lockToken,abortSignal: abort.signal,@@ -1525,7 +1526,7 @@ export class MinionWorker extends EventEmitter {})// #4218: attribute every gateway.chat() the handler makes to this// job so chat_usage_log rows carry `phase = 'job:<name>'`.- : await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => handler(context as MinionJobContext)), abort.signal);+ : await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => runWithJobSpend(this.engine, job, context as MinionJobContext, handler)), abort.signal);// The child spawned and ran — the spawn path is healthy again.this._consecutiveChildSpawnFailures = 0;diff --git a/src/core/worker-pool.ts b/src/core/worker-pool.tsindex 7e74120acb..76c34ac967 100644--- a/src/core/worker-pool.ts+++ b/src/core/worker-pool.ts@@ -80,6 +80,7 @@/** Tagged error classes that bypass `onError` and hard-abort the pool. */export const MUST_ABORT_ERROR_TAGS: ReadonlySet<string> = new Set(['BUDGET_EXHAUSTED', // src/core/budget/budget-tracker.ts BudgetExhausted.tag+ 'SPEND_GROUP_REFUSED', // src/core/minions/spend-authorization.ts group refusals (exhaustion, pressure, no_pricing)]);/**diff --git a/test/child-readiness.test.ts b/test/child-readiness.test.tsindex b9e27f29d3..9c6c9b86b8 100644--- a/test/child-readiness.test.ts+++ b/test/child-readiness.test.ts@@ -28,9 +28,9 @@ describe('selected child readiness protocol', () => {test('defaults are bounded and compatible version skew is diagnostic', () => {expect(CHILD_READINESS_TIMEOUT_MS).toBe(20_000);expect(CHILD_READINESS_MAX_BYTES).toBe(64 * 1024);- expect(parseChildReadiness(JSON.stringify(reply))).toEqual({ version: VERSION, versionSkew: false });+ expect(parseChildReadiness(JSON.stringify(reply))).toEqual({ version: VERSION, versionSkew: false, features: reply.features });expect(parseChildReadiness(JSON.stringify({ ...reply, version: '0.0.1' })))- .toEqual({ version: '0.0.1', versionSkew: true });+ .toEqual({ version: '0.0.1', versionSkew: true, features: reply.features });});test('completed malformed, missing-feature and wrong-major replies are permanent and redacted', () => {@@ -65,7 +65,7 @@ describe('selected child readiness protocol', () => {test('invokes the actual selected path with spaces and hidden command', async () => {await fixture(`if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(['jobs','child-readiness','--json'])) process.exit(3);console.log(${JSON.stringify(JSON.stringify(reply))});`, async (invocation) => {- expect(await checkChildReadiness({ invocation, tiniPath: '' })).toEqual({ version: VERSION, versionSkew: false });+ expect(await checkChildReadiness({ invocation, tiniPath: '' })).toEqual({ version: VERSION, versionSkew: false, features: reply.features });});});@@ -215,7 +215,7 @@ describe('selected child readiness protocol', () => {chmodSync(executable, 0o700);expect(await checkChildReadiness({invocation: { cmd: 'selected-example', argsPrefix: [] }, tiniPath: detectTini(), env: { PATH: dir },- })).toEqual({ version: VERSION, versionSkew: false });+ })).toEqual({ version: VERSION, versionSkew: false, features: reply.features });} finally { rmSync(dir, { recursive: true, force: true }); }});diff --git a/test/minions-spend-authorization.test.ts b/test/minions-spend-authorization.test.tsnew file mode 100644index 0000000000..f270dba905--- /dev/null+++ b/test/minions-spend-authorization.test.ts@@ -0,0 +1,189 @@+/**+ * Submit-time spend authorization on queued paid jobs (PGLite).+ *+ * Protects: the strict record parser, the trusted-only storage path, the+ * claim-time `legacy_default` stamp, the coalesce compare-and-set, the+ * per-acquisition fence trigger, and the worker guard's group metering.+ * Regressions that fail it: a record read from job data, a claim that stamps+ * the wrong rows, an old-protocol claim that runs a spend-authorized row, or+ * a guard that does not reserve against the group.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { invokeAI } from '../src/core/ai/invocation-guard.ts';+import {+ jobSpendAuthorization, parseSpendAuthorization, runWithJobSpend, spendBasis, spendSubmitSummary,+ type SpendAuthorization,+} from '../src/core/minions/spend-authorization.ts';+import type { MinionJob, MinionJobContext } from '../src/core/minions/types.ts';+import type { Authorization } from '../src/core/consent.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM mcp_spend_reservations');+ await engine.executeRaw('DELETE FROM mcp_spend_log');+ await engine.executeRaw('DELETE FROM minion_jobs');+});++const auth = (cap: number, source: Authorization['cap_source'] = 'derived'): Authorization =>+ ({ consented_effects: ['paid'], cap_usd: cap, cap_source: source, via: 'yes' });+const record = (cap = 10, source: Authorization['cap_source'] = 'derived', of = 2) =>+ jobSpendAuthorization(auth(cap, source), { command: 'book-mirror', est_usd: cap / 1.5, of, argv: ['gbrain', 'book-mirror', '--slug', 'a-book'] });+const ctxFor = (job: MinionJob) => ({ id: job.id, name: job.name, data: job.data, attempts_made: 0 }) as unknown as MinionJobContext;++/** A priced provider attempt: maximum `maxCents`, actual `actualCents` (claude-sonnet-5 input at $2/Mtok, reserved at 2x). */+const attempt = (maxCents: number, actualCents: number, model = 'anthropic:claude-sonnet-5') => invokeAI(+ { operation: 'test', kind: 'chat', model, maxInputTokens: maxCents * 2500, maxOutputTokens: 0 },+ async () => 'ok', () => ({ inputTokens: actualCents * 5000, outputTokens: 0 }));++async function claimed(name: string, opts: Record<string, unknown> = {}, spend?: SpendAuthorization): Promise<MinionJob> {+ await queue.add(name, { prompt: 'x' }, opts, { allowProtectedSubmit: true, ...(spend ? { spendAuthorization: spend } : {}) });+ const job = await queue.claim('tok', 60_000, 'default', [name]);+ if (!job) throw new Error('nothing claimed');+ return job;+}++describe('spend authorization record', () => {+ test('the parser accepts each kind and rejects malformed or unknown shapes', () => {+ const capped = record();+ expect(parseSpendAuthorization(capped)).toEqual(capped);+ const uncapped = jobSpendAuthorization({ uncapped: true, via: 'max_usd' }, { command: 'enrich', of: 1 });+ expect(parseSpendAuthorization(JSON.stringify(uncapped))).toMatchObject({ cap_usd: null, uncapped: true, cap_source: 'user' });+ expect(parseSpendAuthorization({ version: 1, kind: 'legacy_default', group_id: capped.group_id, cap_usd: 5, cap_source: 'default', command: 'enrich', authorized_at: '2026-10-05T00:00:00.000Z' }))+ .toMatchObject({ kind: 'legacy_default' });+ expect(parseSpendAuthorization(null)).toBeNull();+ for (const bad of [+ { ...capped, kind: 'granted' },+ { ...capped, extra: true },+ { ...capped, cap_usd: null },+ { ...capped, group_id: 'not-a-uuid' },+ { ...capped, cap_usd: -1 },+ [],+ ]) expect(() => parseSpendAuthorization(bad)).toThrow(TypeError);+ });++ test('a record in job data is never read as authorization', async () => {+ const job = await queue.add('enrich', { sourceId: 'default', spend_authorization: record() });+ expect(job.spend_authorization).toBeNull();+ expect(spendBasis(job).basis).toBe('unrecorded');+ });++ test('a malformed column marks the job invalid and the guard refuses to run it', async () => {+ const job = await claimed('subagent', {}, record());+ await engine.executeRaw(`UPDATE minion_jobs SET spend_authorization = '{"version":2}'::jsonb WHERE id = $1`, [job.id]);+ const reread = (await queue.getJob(job.id))!;+ expect(reread.spend_authorization_invalid).toBe(true);+ expect(spendBasis(reread).basis).toBe('invalid');+ await expect(runWithJobSpend(engine, reread, ctxFor(reread), async () => 'ran')).rejects.toThrow('spend_authorization_invalid');+ });+});++describe('claim-time legacy_default', () => {+ test('stamps only NULL rows of the consent-gated producers, with the job-type cap', async () => {+ const rows = [+ ['subagent', 'book-mirror:a-book:ch-1', {}],+ ['enrich', 'enrich:default:abc', { maxCostUsd: 2 }],+ ['enrich', 'cli:enrich:abcd1234', {}],+ ['enrich', 'other:enrich', {}],+ ['subagent', 'enrich:default:x', {}],+ ] as const;+ for (const [name, key, data] of rows) await queue.add(name, { ...data, sourceId: 'default' }, { idempotency_key: key }, { allowProtectedSubmit: true });+ const seen: Record<string, SpendAuthorization | null> = {};+ for (let i = 0; i < rows.length; i++) {+ const job = await queue.claim(`tok-${i}`, 60_000, 'default', ['subagent', 'enrich']);+ seen[job!.idempotency_key!] = job!.spend_authorization ?? null;+ }+ expect(seen['book-mirror:a-book:ch-1']).toMatchObject({ kind: 'legacy_default', cap_usd: 5, cap_source: 'default', command: 'book-mirror' });+ expect(seen['enrich:default:abc']).toMatchObject({ kind: 'legacy_default', cap_usd: 2, command: 'enrich' });+ expect(seen['cli:enrich:abcd1234']).toMatchObject({ kind: 'legacy_default', cap_usd: 5 });+ expect(seen['other:enrich']).toBeNull();+ expect(seen['enrich:default:x']).toBeNull();+ expect(new Set(Object.values(seen).filter(Boolean).map(r => r!.group_id)).size).toBe(3);+ });++ test('a legacy_default subagent runs under the $5 default cap and logs its basis', async () => {+ const job = await claimed('subagent', { idempotency_key: 'book-mirror:a-book:ch-2' });+ const logs: string[] = [];+ const log = spyOn(console, 'log').mockImplementation(((line: string) => { logs.push(String(line)); }) as never);+ try {+ expect(await runWithJobSpend(engine, job, ctxFor(job), async () => { await attempt(300, 100); return 'done'; })).toBe('done');+ } finally { log.mockRestore(); }+ const basis = JSON.parse(logs.find(l => l.includes('job_spend_basis'))!.split('job_spend_basis ')[1]!);+ expect(basis).toMatchObject({ job_id: job.id, basis: 'legacy_default', cap_usd: 5, cap_source: 'default' });+ const holds = await engine.executeRaw<{ budget_key: string; status: string }>('SELECT budget_key, status FROM mcp_spend_reservations');+ expect(holds).toEqual([{ budget_key: `group:${job.spend_authorization!.group_id}`, status: 'settled' }]);+ });+});++describe('coalesce compare-and-set', () => {+ test('NULL and legacy rows adopt the new authorization; an authorized row keeps its own', async () => {+ const key = 'book-mirror:b-book:ch-1';+ const legacy = await queue.add('subagent', { prompt: 'x' }, { idempotency_key: key }, { allowProtectedSubmit: true });+ expect(legacy.spend_authorization).toBeNull();+ const first = record();+ const adopted = await queue.add('subagent', { prompt: 'x' }, { idempotency_key: key }, { allowProtectedSubmit: true, spendAuthorization: first });+ expect(adopted.id).toBe(legacy.id);+ expect(adopted.spend_authorization?.group_id).toBe(first.group_id);+ const second = record(20);+ const kept = await queue.add('subagent', { prompt: 'x' }, { idempotency_key: key }, { allowProtectedSubmit: true, spendAuthorization: second });+ expect(kept.spend_authorization?.group_id).toBe(first.group_id);+ expect((await queue.getJob(legacy.id))!.spend_authorization?.group_id).toBe(first.group_id);+ const { summary, lines } = spendSubmitSummary(second, [kept], ['gbrain', 'book-mirror', '--slug', 'b-book']);+ expect(summary.kept).toEqual([{ group_id: first.group_id, cap_usd: 10, job_ids: [legacy.id] }]);+ expect(lines.join('\n')).toContain(`gbrain jobs cancel --group ${first.group_id}`);+ });++ test('a stamped legacy_default row is re-authorized by a rerun', async () => {+ const job = await claimed('subagent', { idempotency_key: 'book-mirror:c-book:ch-1' });+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'waiting', lock_token = NULL WHERE id = $1`, [job.id]);+ const next = record();+ const adopted = await queue.add('subagent', { prompt: 'x' }, { idempotency_key: 'book-mirror:c-book:ch-1' }, { allowProtectedSubmit: true, spendAuthorization: next });+ expect(adopted.spend_authorization).toMatchObject({ kind: 'authorized', group_id: next.group_id });+ });+});++describe('per-acquisition fence', () => {+ const oldClaim = (id: number, token: string) => engine.executeRaw(+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = $2, attempts_started = attempts_started + 1 WHERE id = $1`,+ [id, token]);++ test('an old-protocol claim of a spend-authorized row is refused; a NULL row is still claimable', async () => {+ const fenced = await queue.add('subagent', { prompt: 'x' }, {}, { allowProtectedSubmit: true, spendAuthorization: record() });+ const open = await queue.add('subagent', { prompt: 'y' }, {}, { allowProtectedSubmit: true });+ await expect(oldClaim(fenced.id, 'old')).rejects.toThrow('Minion spend protocol 1 required');+ await expect(oldClaim(open.id, 'old')).resolves.toBeDefined();+ });++ test('new-worker claim, stall, then an old-worker reclaim is refused', async () => {+ const job = await claimed('subagent', {}, record());+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'waiting', lock_token = NULL WHERE id = $1`, [job.id]);+ await expect(oldClaim(job.id, 'old')).rejects.toThrow('Minion spend protocol 1 required');+ const again = await queue.claim('tok-new', 60_000, 'default', ['subagent']);+ expect(again?.id).toBe(job.id);+ });+});++describe('uncapped records', () => {+ test('reserve nothing', async () => {+ const spend = jobSpendAuthorization({ uncapped: true, via: 'max_usd' }, { command: 'enrich', of: 1 });+ const job = await claimed('subagent', {}, spend);+ let sawSpend = false;+ await runWithJobSpend(engine, job, ctxFor(job), async (ctx) => { sawSpend = ctx.spend?.record.uncapped === true; await attempt(300, 100); });+ expect(sawSpend).toBe(true);+ expect(await engine.executeRaw('SELECT 1 FROM mcp_spend_reservations')).toEqual([]);+ });+});diff --git a/test/minions-spend-enforcement-child.test.ts b/test/minions-spend-enforcement-child.test.tsnew file mode 100644index 0000000000..34dc1dbcc4--- /dev/null+++ b/test/minions-spend-enforcement-child.test.ts@@ -0,0 +1,79 @@+/**+ * Spend refusals across the process-isolation boundary and the child+ * capability gate.+ *+ * Protects: a group refusal keeps its code, fix and group amounts through the+ * child outcome codec; pressure keeps its retry delay; both abort a worker+ * pool; a parent never hands a spend-authorized row to a child executor that+ * did not advertise `spend-enforcement-v1` (the row is released through the+ * lease path, not failed), while such a child still passes readiness for+ * every other row.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { encodeHandlerError, parseChildOutcome, reconstructHandlerError } from '../src/core/minions/job-isolation.ts';+import { CHILD_READINESS_FEATURES, parseChildReadiness } from '../src/core/minions/child-readiness.ts';+import { runJobInChild } from '../src/core/minions/child-job-runner.ts';+import { RateLeaseUnavailableError } from '../src/core/minions/rate-leases.ts';+import { isMustAbortError } from '../src/core/worker-pool.ts';+import {+ SpendEnforcementUnavailableError, SpendGroupPressureError, SpendGroupRefusedError, noteChildSpendEnforcement,+ type SpendRefusalEnvelope,+} from '../src/core/minions/spend-authorization.ts';+import { VERSION } from '../src/version.ts';++afterEach(() => noteChildSpendEnforcement([...CHILD_READINESS_FEATURES]));++const envelope = {+ error: 'derived_cap_exhausted', code: 'derived_cap_exhausted', message: 'Job 7 (book-mirror) stopped.',+ suggestion: 'Ask the user.', fix: { argv: ['gbrain', 'book-mirror', '--max-usd', '20.00', '--yes'], consent: ['paid'], actor: 'agent', why: 'resume', requires_exclusive: false },+ contract_version: 1,+ group: { group_id: '0192a000-0000-7000-8000-000000000002', cap_usd: 10, cap_source: 'derived', spent_usd: 10, overdue_usd: 0, reserved_usd: 0, remaining_usd: 0 },+} as unknown as SpendRefusalEnvelope;++function roundTrip(err: unknown): Error {+ const raw = JSON.stringify(encodeHandlerError(err));+ const decoded = parseChildOutcome(raw, raw.length);+ if (decoded.outcome !== 'error') throw new Error('expected an error outcome');+ return reconstructHandlerError(decoded);+}++describe('child outcome codec', () => {+ test('a group refusal keeps its code, fix and group amounts', () => {+ const back = roundTrip(new SpendGroupRefusedError(envelope));+ expect(back).toBeInstanceOf(SpendGroupRefusedError);+ expect((back as SpendGroupRefusedError).envelope).toEqual(envelope);+ expect(back.message).toBe('derived_cap_exhausted: Job 7 (book-mirror) stopped.');+ });++ test('pressure keeps its retry delay and still releases through the lease path', () => {+ const back = roundTrip(new SpendGroupPressureError('group:0192a000-0000-7000-8000-000000000002', 800, 1000));+ expect(back).toBeInstanceOf(RateLeaseUnavailableError);+ expect((back as RateLeaseUnavailableError).retryInMs).toBeGreaterThan(0);+ });++ test('group refusals abort a worker pool', () => {+ expect(isMustAbortError(new SpendGroupRefusedError(envelope))).toBe(true);+ expect(isMustAbortError(new SpendGroupPressureError('group:x', 1, 2))).toBe(true);+ });+});++describe('child spend-enforcement capability', () => {+ const oldChild = JSON.stringify({ protocolVersion: 1, version: VERSION, status: 'ready',+ features: ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] });++ test('a child without the feature passes readiness and is recorded as unable to enforce', () => {+ const parsed = parseChildReadiness(oldChild);+ expect(parsed.features).not.toContain('spend-enforcement-v1');+ noteChildSpendEnforcement(parsed.features);+ const run = runJobInChild({+ jobId: 1, spendAuthorized: true, jobName: 'subagent', lockToken: 't',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ invocation: { cmd: '/nonexistent/gbrain', argsPrefix: [] }, tiniPath: '',+ });+ return expect(run).rejects.toBeInstanceOf(SpendEnforcementUnavailableError);+ });++ test('the release error is a lease release, so no attempt is burned', () => {+ expect(new SpendEnforcementUnavailableError()).toBeInstanceOf(RateLeaseUnavailableError);+ });+});