Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(jobs): preview-bound authorize-legacy --select with coded refusals (#5157 T3, DX-O2, DX-O3)

garrytan47204c2558e3
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index 7a6f4bcd66..8df1222eeb 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -66,6 +66,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError`, `RateLeaseUnavailableError`, and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.
+- `src/core/minions/legacy-selection.ts` — the `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"` grammar shared by `gbrain jobs authorize-legacy --select` and `gbrain jobs cancel --select` (`parseLegacyJobSelection` refuses with `legacy_job_selection_invalid`), the filled preview/apply commands (`selectCommand`), the recovery hint every legacy refusal names (`legacyRecoveryHint`), the `legacy_jobs_active` precondition listing up to 10 `gbrain jobs cancel <id>` commands, and the DX-O3(d) summary. Both commands are CLI-only (no operation). Tests: `test/jobs-authorize-legacy-select.test.ts`.
+
- `src/core/minions/lock-renewal-tick.ts` — Pure function behind `MinionWorker.launchJob`'s setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. Exports `runLockRenewalTick(deps, state) → Promise<TickResult>` + `resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs` + `RenewalCallTimeoutError` + `LockRenewalTelemetryCtx`. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (`lease - safetyMargin`, cadence-aware: `sinceLastSuccess + intervalMs >= deadline`), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (audit `success_after_failure` with `via: 'verify'`); fenced-false → CERTAIN loss → `lock_lost` (the only certain signal); verify unreachable → defer + reconnect-once (audit `failure` with `deadline_deferred: true`), aborting only past `hardEvictMs` — a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps): `GBRAIN_LOCK_RENEWAL_MAX_FAILURES` (default 3, audit-labeling only), `GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS` (default `min(lease/3, 15s)`), `GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS` (default `min(lease/6, 30s)`), `GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS` (default `2×lease`, floored to the soft deadline; setting it TO the deadline approximates abort-at-deadline). Telemetry: tick lateness (`now - lastTickFiredAt - intervalMs`, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation), `overlapSkips` (tickInFlight re-entrancy skips only), failure-cause classification via the named `RenewalCallTimeoutError` (`call-timeout` | `refused` | `fenced-lost`), optional `deps.loadSnapshot` (try/caught — telemetry must never throw into control flow) and `deps.onRenewalSuccess` (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected `deps.now`, which production binds to `performance.now()` (monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded to `renewLock` (best-effort — the fence is the correctness authority). The tick checks `state.cancelled()` at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: `should_abort` carries `{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}` and `lock_lost` carries `{cause: 'fenced-lost', via: 'renewal'|'verify'}`; the worker stashes the result as per-launch `abortMeta` so the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned by `test/worker-lock-renewal.test.ts` (hermetic state-machine suite incl. a fake-time starvation replay, the cadence-quantization pin, hard-backstop timelines, relational-clamp cases) + `test/e2e/worker-lock-renewal-starvation.test.ts` (real-PG foundations). `LockRenewalDeps.renewLock` carries an optional per-call `{signal}`; the timeout race aborts it so the losing UPDATE releases its slot.
- `src/core/minions/niceness.ts` — OS scheduling-priority (niceness) primitives for the `--nice` flag. `parseNiceValue(raw)` whole-string parses + range-validates to POSIX `[-20, 19]` (rejects `"3.5"`/`"10abc"` that `parseInt` would silently truncate). `applyNiceness(nice, setPriority?, getPriority?)` calls `os.setPriority(0, n)` and ALWAYS re-reads `os.getPriority(0)` afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an `RLIMIT_NICE` clamp records the real effective value (e.g. `0`), not null; returns `{applied, requested, effective, error?}`. `getEffectiveNiceness(pid, getPriority?)` reads an arbitrary pid's niceness (null on dead/unreadable). `formatNice(n)` → `+10`/`0`/`-5`. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned by `test/niceness.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index fd810e6ef2..8c3ba51c78 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).
-- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_SQL` is the claim gate's query, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.
+- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_SQL` is the claim gate's query, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under its snapshot hash with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 88f8e6d678..09fa913cd5 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -71,7 +71,6 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },
{ path: 'src/core/chronicle/backstop.ts', reason: 'held: the put_page chronicle backstop was dropped in v0.51.0.0, so the documented auto_chronicle setting does nothing; restore-or-retract is a product decision' },
{ path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },
- { path: 'src/core/persistence/preview-approval.ts', reason: 'held: fix wave 5 shared commit (ENG-O1); its callers (jobs authorize-legacy/cancel --select, repair stale-atoms/extractor-facts) land in the wave 5 lanes, which remove this entry' },
{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },
{ path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
{ path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index dee1654df5..82414215a7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -9,7 +9,7 @@ src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); cei
src/commands/embed.ts 2187 ratchet 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
src/commands/extract-conversation-facts.ts 2146 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)
src/commands/extract.ts 2621 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
-src/commands/jobs.ts 635 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
+src/commands/jobs.ts 642 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; +7 help lines: authorize-legacy --select (#5157 T3)
src/commands/serve-http.ts 915 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
src/core/ai/gateway.ts 4358 ratchet +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)
src/commands/sync.ts 472 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)
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 0ffe65604b..d36520a1c6 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -99,7 +99,7 @@ export async function refreshGatewayForJob(engine: BrainEngine): Promise<void> {
// pins this set against the registerBuiltinJob call sites — a gateway-using
// handler registered via bare worker.register() runs with a stale gateway
// (the #3387 chronicle_extract silent-no_events class).
-const GATEWAY_REFRESH_JOB_NAMES = new Set([
+export const GATEWAY_REFRESH_JOB_NAMES = new Set([
'embed',
'extract-conversation-facts',
'enrich',
@@ -154,6 +154,7 @@ const JOBS_HELP = `gbrain jobs — Minions job queue
USAGE
gbrain jobs authorize-legacy --ids 12,34 [--expect <snapshot_digest> --yes] [--json]
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]
gbrain jobs submit <name> [--params JSON] [--follow] [--priority N]
[--delay Nms] [--max-attempts N] [--max-stalled N]
[--max-waiting N]
@@ -376,10 +377,16 @@ OPTIONS
USAGE
gbrain jobs authorize-legacy --ids 12,34 --json
gbrain jobs authorize-legacy --ids 12,34 --expect <snapshot_digest> --yes --json
-
-Stop producers and workers and drain active jobs first. The first command only
-previews; apply requires the exact reviewed snapshot digest and --yes. Dependencies
-are shown but never implicitly authorized. IDs, data, schedule and retries persist.
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture" [--json]
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture" --expect <hash> --yes
+
+Stop producers (gbrain serve, gbrain autopilot) and workers and cancel active jobs
+first. A command without --yes only previews; apply requires the exact reviewed hash
+and --yes. --select keys: status (waiting, delayed, waiting-children, paused,
+completed, failed) and name, each taking | alternatives. The --select preview lists
+counts by job name and status, the first 20 ids and the preview hash, and the apply
+authorizes exactly the previewed set. Dependencies are shown but never implicitly
+authorized. IDs, data, schedule and retries persist.
`,
prune: `gbrain jobs prune — delete old terminal jobs
diff --git a/src/commands/jobs/authorize-legacy.ts b/src/commands/jobs/authorize-legacy.ts
index 3bb548855b..9219b53821 100644
--- a/src/commands/jobs/authorize-legacy.ts
+++ b/src/commands/jobs/authorize-legacy.ts
@@ -1,10 +1,48 @@
/** `gbrain jobs authorize-legacy` (dispatched by runJobs in src/commands/jobs.ts). */
-import { parseFlag, type JobsCommandContext } from './shared.ts';
-import { authorizeLegacyJobs, parseLegacyJobIds } from '../../core/minions/authorize-legacy.ts';
+import { paidJobNames, parseFlag, reportJobsError, selectionSummaryLines, type JobsCommandContext } from './shared.ts';
+import { applyLegacySelection, authorizeLegacyJobs, parseLegacyJobIds, previewLegacySelection } from '../../core/minions/authorize-legacy.ts';
+import { parseLegacyJobSelection } from '../../core/minions/legacy-selection.ts';
+import { catalogueError } from '../../core/error-catalogue.ts';
+import { OperationError } from '../../core/ops/contract.ts';
export async function runJobsAuthorizeLegacy({ args, engine }: JobsCommandContext): Promise<void> {
- const ids = parseLegacyJobIds(parseFlag(args, '--ids'));
- const preview = args.includes('--dry-run');
- const result = await authorizeLegacyJobs(engine, ids, preview ? undefined : parseFlag(args, '--expect'), !preview && args.includes('--yes'));
- console.log(JSON.stringify(result, null, 2));
+ const json = args.includes('--json');
+ try {
+ const select = parseFlag(args, '--select');
+ if (select === undefined && !args.includes('--select')) {
+ const ids = parseLegacyJobIds(parseFlag(args, '--ids'));
+ const preview = args.includes('--dry-run');
+ const result = await authorizeLegacyJobs(engine, ids, preview ? undefined : parseFlag(args, '--expect'), !preview && args.includes('--yes'));
+ console.log(JSON.stringify(result, null, 2));
+ return;
+ }
+ if (args.includes('--ids')) {
+ throw catalogueError('legacy_job_selection_invalid', 'Pass either --ids or --select, not both.', 'gbrain jobs authorize-legacy --select "status=waiting"');
+ }
+ const selection = parseLegacyJobSelection(select, 'authorize-legacy');
+ const expected = parseFlag(args, '--expect');
+ const yes = args.includes('--yes');
+ if (expected !== undefined || yes) {
+ const result = await applyLegacySelection(engine, selection, expected, yes);
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ console.log(`Authorized ${result.authorized} legacy job(s) matching ${result.selection}. Restart producers and workers now.`);
+ return;
+ }
+ const preview = await previewLegacySelection(engine, selection);
+ const paid = await paidJobNames(Object.keys(preview.summary.by_name));
+ if (json) { console.log(JSON.stringify({ ...preview, paid_job_names: paid }, null, 2)); return; }
+ console.log(`Legacy jobs matching ${preview.selection} (SQL NULL authority, authorizable): ${preview.summary.total}`);
+ for (const line of selectionSummaryLines(preview.summary, paid)) console.log(line);
+ if (preview.unsupported_ids.length) {
+ console.log(`Unsupported non-NULL authority (not authorizable; cancel locally): ${preview.unsupported_ids.slice(0, 20).join(', ')}${preview.unsupported_ids.length > 20 ? ' …' : ''}`);
+ }
+ if (!preview.snapshot_digest) { console.log('Nothing to authorize.'); return; }
+ console.log(`Startup-blocking dependencies outside the selection: ${preview.startup_blocking_dependency_count}`);
+ console.log(`Preview hash: ${preview.snapshot_digest}`);
+ console.log(`Apply exactly this set: ${preview.apply_command}`);
+ console.log('Full rows: re-run with --json. Nothing was changed.');
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ reportJobsError(error, json);
+ }
}
diff --git a/src/commands/jobs/shared.ts b/src/commands/jobs/shared.ts
index f5e9e5d236..be6af2b927 100644
--- a/src/commands/jobs/shared.ts
+++ b/src/commands/jobs/shared.ts
@@ -6,6 +6,9 @@
import type { BrainEngine } from '../../core/engine.ts';
import type { MinionQueue } from '../../core/minions/queue.ts';
import type { MinionJob } from '../../core/minions/types.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';
import { parseNiceValue } from '../../core/minions/niceness.ts';
import { defaultTimeoutMsFor, defaultLockDurationMsFor } from '../../core/minions/handler-timeouts.ts';
@@ -227,3 +230,26 @@ export function formatJobDetail(job: MinionJob): string {
lines.push(` Data: ${JSON.stringify(job.data)}`);
return lines.join('\n');
}
+
+/** Renders a coded jobs refusal: the `toJSON()` envelope on stdout with --json, the human lines on stderr, exit 1. */
+export function reportJobsError(error: OperationError, json: boolean): void {
+ if (json) console.log(JSON.stringify(error.toJSON(), null, 2));
+ console.error(`Error [${error.code}]: ${error.message}`);
+ if (error.suggestion) console.error(`Fix: ${error.suggestion}`);
+ if (error.docs) console.error(`Docs: ${error.docs}`);
+ setCliExitVerdict(1);
+}
+
+/** Job names whose handlers call a paid model provider (the gateway-refresh set plus the subagent loop). */
+export async function paidJobNames(names: Iterable<string>): Promise<string[]> {
+ const { GATEWAY_REFRESH_JOB_NAMES } = await import('../jobs.ts');
+ return [...new Set(names)].filter(name => GATEWAY_REFRESH_JOB_NAMES.has(name) || name === 'subagent').sort();
+}
+
+/** DX-O3(d) human preview lines: counts by job name and status, the first 20 ids, paid markers. */
+export function selectionSummaryLines(summary: SelectionSummary, paid: readonly string[]): string[] {
+ const lines = Object.entries(summary.by_name).sort(([a], [b]) => a.localeCompare(b)).map(([name, counts]) =>
+ ` ${name}: ${Object.entries(counts).map(([status, n]) => `${status} ${n}`).join(', ')}${paid.includes(name) ? ' [paid provider calls]' : ''}`);
+ if (summary.total) lines.push(` First ${summary.first_ids.length} ids: ${summary.first_ids.join(', ')}${summary.total > summary.first_ids.length ? ' …' : ''}`);
+ return lines;
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index bf2878ab6d..45c909e486 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -69,7 +69,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--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-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--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', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--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-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--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', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--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-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'],
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--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'],
@@ -116,7 +116,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--images', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--images', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
diff --git a/src/core/minions/authorize-legacy.ts b/src/core/minions/authorize-legacy.ts
index 184fe0653d..cb6617f22a 100644
--- a/src/core/minions/authorize-legacy.ts
+++ b/src/core/minions/authorize-legacy.ts
@@ -1,15 +1,34 @@
/** Local-only, explicit preview/CAS authorization of pre-cutover job rows. */
import type { BrainEngine } from '../engine.ts';
-import { APPLICATION_AUTHORITY, authorityDigest, parseSubmissionAuthority } from './submission-authority.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { APPLICATION_AUTHORITY, parseSubmissionAuthority } from './submission-authority.ts';
+import {
+ assertNoActiveJobs, formatSelection, selectCommand, selectedStatuses, summarizeSelection,
+ type LegacyJobSelection, type SelectionSummary,
+} from './legacy-selection.ts';
+
+const IDS_EXAMPLE = 'gbrain jobs authorize-legacy --ids 12,34';
+
+function idsPreviewCommand(ids: number[]): string {
+ return `gbrain jobs authorize-legacy --ids ${ids.join(',')}`;
+}
+
+function selectionInvalid(message: string, hint: string) {
+ return catalogueError('legacy_job_selection_invalid', message, hint);
+}
export function parseLegacyJobIds(raw: string | undefined): number[] {
- if (!raw || !/^\d+(,\d+)*$/.test(raw)) throw new Error('authorize-legacy requires --ids <id,id,...>; implicit/all-job approval is unavailable');
+ if (!raw || !/^\d+(,\d+)*$/.test(raw)) {
+ throw selectionInvalid('authorize-legacy requires --ids <id,id,...> or --select <filter>; implicit/all-job approval is unavailable.',
+ `${IDS_EXAMPLE}, or gbrain jobs authorize-legacy --select "status=waiting"`);
+ }
const ids = [...new Set(raw.split(',').map(Number))].sort((a, b) => a - b);
- if (ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('job ids must be positive safe integers');
+ if (ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw selectionInvalid('Job ids must be positive safe integers.', IDS_EXAMPLE);
return ids;
}
-async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
+async function snapshot(engine: BrainEngine, ids: number[], lock: boolean, previewCommand: string) {
// The controlled cutover normally has no producers. Lock the graph table on
// apply as well so a descendant insertion/reparent cannot race the CAS.
if (lock) {
@@ -19,16 +38,20 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
const jobs = await engine.executeRaw<Record<string, unknown>>(
`SELECT *, submission_authority IS NULL AS legacy_authority_is_null
FROM minion_jobs WHERE id = ANY($1::int[]) ORDER BY id${lock ? ' FOR UPDATE' : ''}`, [ids]);
- if (jobs.length !== ids.length) throw new Error('One or more selected jobs no longer exist');
+ if (jobs.length !== ids.length) {
+ const found = new Set(jobs.map(job => Number(job.id)));
+ throw selectionInvalid(`Selected jobs no longer exist: ${ids.filter(id => !found.has(id)).slice(0, 10).join(', ')}.`, `Re-run the preview: ${previewCommand}`);
+ }
// JSONB null also decodes to JS null. Only the SQL NULL left by the cutover
// represents historical provenance; never downgrade unknown/versioned authority.
- if (jobs.some(job => job.legacy_authority_is_null !== true)) {
- throw new Error('Every selected job must have SQL NULL submission authority. For unsupported non-NULL authority, use matching application/database versions or explicitly cancel the job locally.');
+ const unsupported = jobs.filter(job => job.legacy_authority_is_null !== true).map(job => Number(job.id));
+ if (unsupported.length) {
+ throw selectionInvalid(`Every selected job must have SQL NULL submission authority; jobs ${unsupported.slice(0, 10).join(', ')} carry unsupported non-NULL authority.`,
+ `Run matching application and database versions, or cancel them locally: ${unsupported.slice(0, 10).map(id => `gbrain jobs cancel ${id}`).join('; ')}.`);
}
- const [active] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM minion_jobs WHERE status = 'active'");
// The controlled upgrade drains before review. Recovery decisions belong to
// the local operator, never an implicit status/retry rewrite in this command.
- if (Number(active?.count ?? 0)) throw new Error('Drain or cancel all active jobs and stop producers/workers before authorizing legacy jobs');
+ await assertNoActiveJobs(engine, previewCommand);
const graph = await engine.executeRaw<Record<string, unknown>>(
`WITH RECURSIVE connected(id) AS (
SELECT id FROM minion_jobs WHERE id = ANY($1::int[])
@@ -42,12 +65,12 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
// fields prove authority. The operator is approving the actual historical work.
const sources = await engine.executeRaw<Record<string, unknown>>('SELECT id, local_path, config, archived, created_at FROM sources ORDER BY id');
const version = await engine.getConfig('version');
- const digest = authorityDigest({ preview_version: 1, authority_version: 1, version, jobs, dependencies, sources });
+ const digest = previewHash({ preview_version: 1, authority_version: 1, version, jobs, dependencies, sources });
return {
preview_version: 1 as const, authority_version: 1 as const, snapshot_digest: digest,
jobs: jobs.map(job => ({
id: job.id, name: job.name, status: job.status, data: job.data, previous_authority: job.submission_authority,
- data_digest: authorityDigest(job.data), parent_job_id: job.parent_job_id,
+ data_digest: previewHash(job.data), parent_job_id: job.parent_job_id,
delay_until: job.delay_until, attempts_made: job.attempts_made,
})),
// Full recursive graph, including payload and failure policy, makes downstream
@@ -64,17 +87,81 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
};
}
-export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], expected?: string, yes = false) {
- if (ids.length === 0 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('Explicit positive job ids required');
- if (!yes && expected === undefined) return { ...(await snapshot(engine, ids, false)), applied: false, authorized: 0 };
- if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) throw new Error('Apply requires BOTH --expect <preview snapshot_digest> and --yes');
+export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], expected?: string, yes = false, previewCommand = idsPreviewCommand(ids)) {
+ if (ids.length === 0 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw selectionInvalid('Explicit positive job ids are required.', IDS_EXAMPLE);
+ if (!yes && expected === undefined) return { ...(await snapshot(engine, ids, false, previewCommand)), applied: false, authorized: 0 };
+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {
+ throw selectionInvalid('Apply requires BOTH --expect <preview snapshot_digest> and --yes.',
+ expected && /^[a-f0-9]{64}$/.test(expected) ? `${previewCommand} --expect ${expected} --yes` : `Preview first: ${previewCommand}`);
+ }
return engine.transaction(async tx => {
- const preview = await snapshot(tx, ids, true);
- if (preview.snapshot_digest !== expected) throw new Error('Legacy authorization snapshot changed; preview and review again');
+ const preview = await snapshot(tx, ids, true, previewCommand);
+ if (preview.snapshot_digest !== expected) {
+ throw catalogueError('preview_changed', `Legacy authorization snapshot changed since ${expected}; re-run ${previewCommand} and use the new hash.`,
+ `Re-run the preview: ${previewCommand}`);
+ }
const changed = await tx.executeRaw<{ id: number }>(
`UPDATE minion_jobs SET submission_authority = $2::jsonb
WHERE id = ANY($1::int[]) AND submission_authority IS NULL RETURNING id`, [ids, APPLICATION_AUTHORITY]);
- if (changed.length !== ids.length) throw new Error('Legacy authorization CAS failed; no jobs authorized');
+ if (changed.length !== ids.length) throw previewChangedError(expected, previewCommand);
return { ...preview, applied: true, authorized: changed.length };
});
}
+
+interface ApprovedLegacySelection { selection: string; ids: number[] }
+
+export interface LegacySelectionPreview {
+ selection: string;
+ preview_command: string;
+ /** Selected rows with SQL NULL authority: the set an apply authorizes. */
+ summary: SelectionSummary;
+ /** Matching live rows whose non-NULL authority is unsupported; never authorizable. */
+ unsupported_ids: number[];
+ snapshot_digest: string | null;
+ apply_command: string | null;
+ startup_blocking_dependency_count: number;
+ snapshot: Awaited<ReturnType<typeof snapshot>> | null;
+ applied: false;
+}
+
+/**
+ * `gbrain jobs authorize-legacy --select <filter>`: lists every matching SQL
+ * NULL row, hashes the same snapshot `--ids` reviews and saves the exact id
+ * set under that hash, so `--expect <hash> --yes` approves exactly it.
+ */
+export async function previewLegacySelection(engine: BrainEngine, selection: LegacyJobSelection): Promise<LegacySelectionPreview> {
+ const previewCommand = selectCommand('authorize-legacy', selection);
+ const rows = await engine.executeRaw<{ id: number; name: string; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(
+ `SELECT id, name, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null
+ FROM minion_jobs
+ WHERE status = ANY($1::text[]) AND (cardinality($2::text[]) = 0 OR name = ANY($2::text[]))
+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb
+ ORDER BY id`, [selectedStatuses('authorize-legacy', selection), selection.names]);
+ const legacy = rows.filter(row => row.legacy_authority_is_null === true);
+ const unsupported_ids = rows.filter(row => row.legacy_authority_is_null !== true && !parseSubmissionAuthority(row.submission_authority)).map(row => Number(row.id));
+ const base = { selection: formatSelection(selection), preview_command: previewCommand, summary: summarizeSelection(legacy), unsupported_ids, applied: false as const };
+ if (!legacy.length) return { ...base, snapshot_digest: null, apply_command: null, startup_blocking_dependency_count: 0, snapshot: null };
+ const ids = legacy.map(row => Number(row.id));
+ const preview = await snapshot(engine, ids, false, previewCommand);
+ await saveApprovedSet<ApprovedLegacySelection>(engine, { command: 'authorize-legacy', hash: preview.snapshot_digest }, [{ selection: base.selection, ids }]);
+ return {
+ ...base, snapshot_digest: preview.snapshot_digest, apply_command: selectCommand('authorize-legacy', selection, preview.snapshot_digest),
+ startup_blocking_dependency_count: preview.effects.startup_blocking_dependency_ids.length, snapshot: preview,
+ };
+}
+
+/** `--select <filter> --expect <hash> --yes`: authorizes exactly the set the preview saved under `hash`, or refuses whole. */
+export async function applyLegacySelection(engine: BrainEngine, selection: LegacyJobSelection, expected: string | undefined, yes: boolean) {
+ const previewCommand = selectCommand('authorize-legacy', selection);
+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {
+ throw selectionInvalid('Apply requires BOTH --expect <preview hash> and --yes.',
+ expected && /^[a-f0-9]{64}$/.test(expected) ? selectCommand('authorize-legacy', selection, expected) : `Preview first: ${previewCommand}`);
+ }
+ const approved = await loadApprovedSet<ApprovedLegacySelection>(engine, { command: 'authorize-legacy', hash: expected, previewCommand });
+ const [item] = approved.items;
+ if (!item || item.selection !== formatSelection(selection) || !item.ids.length) throw previewChangedError(expected, previewCommand);
+ const result = await authorizeLegacyJobs(engine, item.ids, expected, true, previewCommand);
+ await clearApprovedSet(engine, { command: 'authorize-legacy', hash: expected });
+ return { selection: item.selection, authorized_ids: item.ids, ...result };
+}
+
diff --git a/src/core/minions/legacy-selection.ts b/src/core/minions/legacy-selection.ts
new file mode 100644
index 0000000000..ef947ba709
--- /dev/null
+++ b/src/core/minions/legacy-selection.ts
@@ -0,0 +1,121 @@
+/**
+ * Preview-bound bulk selection of legacy job rows (#5157 T3, DX-T2): the
+ * `--select` grammar, the active-job precondition and the preview summary
+ * shared by `gbrain jobs authorize-legacy --select` and `gbrain jobs cancel
+ * --select`. Both are CLI-only: neither is an operation, so MCP and
+ * remediation can never run them.
+ *
+ * Grammar: `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"`, keys
+ * `status` and `name`, at least one key. A missing `status` key means every
+ * status the command handles.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { catalogueError } from '../error-catalogue.ts';
+
+export type LegacySelectCommand = 'authorize-legacy' | 'cancel';
+
+export interface LegacyJobSelection {
+ /** Statuses as given (deduplicated); empty means every status the command handles. */
+ statuses: string[];
+ names: string[];
+}
+
+/** Statuses each command handles. Active rows are never selected: they refuse with `legacy_jobs_active`. */
+export const SELECT_STATUSES: Record<LegacySelectCommand, readonly string[]> = {
+ 'authorize-legacy': ['waiting', 'delayed', 'waiting-children', 'paused', 'completed', 'failed'],
+ cancel: ['waiting', 'delayed', 'waiting-children', 'paused'],
+};
+
+export const SELECT_EXAMPLE: Record<LegacySelectCommand, string> = {
+ 'authorize-legacy': 'status=waiting|paused,name=synthesize|ingest_capture',
+ cancel: 'status=waiting|paused,name=synthesize',
+};
+
+export function formatSelection(selection: LegacyJobSelection): string {
+ return [
+ selection.statuses.length ? `status=${selection.statuses.join('|')}` : '',
+ selection.names.length ? `name=${selection.names.join('|')}` : '',
+ ].filter(Boolean).join(',');
+}
+
+/** The filled preview command, or the apply command when `hash` is given. */
+export function selectCommand(command: LegacySelectCommand, selection: LegacyJobSelection, hash?: string): string {
+ const preview = `gbrain jobs ${command} --select "${formatSelection(selection)}"`;
+ return hash ? `${preview} --expect ${hash} --yes` : preview;
+}
+
+/** The statuses a selection covers. */
+export function selectedStatuses(command: LegacySelectCommand, selection: LegacyJobSelection): string[] {
+ return selection.statuses.length ? selection.statuses : [...SELECT_STATUSES[command]];
+}
+
+export function parseLegacyJobSelection(raw: string | undefined, command: LegacySelectCommand): LegacyJobSelection {
+ const invalid = (what: string) => catalogueError('legacy_job_selection_invalid',
+ `${what}; --select takes the keys status and name, with statuses ${SELECT_STATUSES[command].join('|')}.`,
+ `gbrain jobs ${command} --select "${SELECT_EXAMPLE[command]}"`);
+ if (!raw?.trim()) throw invalid('--select needs a filter');
+ const selection: LegacyJobSelection = { statuses: [], names: [] };
+ const seen = new Set<string>();
+ for (const part of raw.split(',')) {
+ const eq = part.indexOf('=');
+ const key = (eq < 0 ? part : part.slice(0, eq)).trim();
+ if (key !== 'status' && key !== 'name') throw invalid(`Unknown --select key "${key}"`);
+ if (seen.has(key)) throw invalid(`--select names the key "${key}" twice`);
+ seen.add(key);
+ const values = eq < 0 ? [''] : part.slice(eq + 1).split('|').map(value => value.trim());
+ if (values.some(value => !value)) throw invalid(`--select key "${key}" needs a value for every | alternative`);
+ if (key === 'status') {
+ const unknown = values.find(value => !SELECT_STATUSES[command].includes(value));
+ if (unknown) throw invalid(`Unknown --select status "${unknown}"`);
+ selection.statuses = [...new Set(values)];
+ } else {
+ selection.names = [...new Set(values)];
+ }
+ }
+ return selection;
+}
+
+/** Shared stop instruction for every legacy-job refusal (ENG-O4: active jobs are cancelled, never finished). */
+export const STOP_PRODUCERS = 'Stop producers (gbrain serve, gbrain autopilot) and workers';
+
+/**
+ * The recovery order every legacy refusal names (DX-O3(b)): stop producers
+ * and workers, cancel active jobs, preview with the filled `--select`, apply
+ * with the printed hash, restart.
+ */
+export function legacyRecoveryHint(statuses: Iterable<string>, names: string[] = []): string {
+ const reviewable = [...new Set(statuses)].filter(status => SELECT_STATUSES['authorize-legacy'].includes(status));
+ const preview = selectCommand('authorize-legacy', { statuses: reviewable.length ? reviewable : ['waiting'], names });
+ return `${STOP_PRODUCERS}, cancel active jobs (gbrain jobs cancel <id>), preview with ${preview}, apply with the printed --expect <hash> --yes, then restart them.`;
+}
+
+/** `legacy_jobs_active`: legacy rows are reviewed only with nothing active. Lists up to 10 ids to cancel. */
+export async function assertNoActiveJobs(engine: BrainEngine, previewCommand: string): Promise<void> {
+ const active = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 11");
+ if (!active.length) return;
+ const [total] = active.length > 10
+ ? await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM minion_jobs WHERE status = 'active'")
+ : [{ count: String(active.length) }];
+ const cancels = active.slice(0, 10).map(row => `gbrain jobs cancel ${row.id}`).join('; ');
+ const more = active.length > 10 ? `; list the rest with gbrain jobs list --status active` : '';
+ throw catalogueError('legacy_jobs_active',
+ `${total!.count} job(s) are active, so legacy jobs cannot be reviewed until producers and workers are stopped and active jobs are cancelled.`,
+ `${STOP_PRODUCERS}, cancel the active jobs (${cancels}${more}), then re-run ${previewCommand}.`);
+}
+
+export interface SelectionSummary {
+ total: number;
+ /** Counts by job name, then status. */
+ by_name: Record<string, Record<string, number>>;
+ first_ids: number[];
+}
+
+/** DX-O3(d): counts by job name and status plus the first 20 ids; the full rows stay in `--json`. */
+export function summarizeSelection(rows: ReadonlyArray<{ id: unknown; name: unknown; status: unknown }>): SelectionSummary {
+ const by_name: Record<string, Record<string, number>> = {};
+ for (const row of rows) {
+ const counts = by_name[String(row.name)] ??= {};
+ counts[String(row.status)] = (counts[String(row.status)] ?? 0) + 1;
+ }
+ return { total: rows.length, by_name, first_ids: rows.slice(0, 20).map(row => Number(row.id)) };
+}
diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.ts
index a112195a28..9208fe3e18 100644
--- a/src/core/minions/submission-authority.ts
+++ b/src/core/minions/submission-authority.ts
@@ -6,6 +6,7 @@ import type { BrainEngine } from '../engine.ts';
import type { AuthInfo, OperationContext } from '../ops/contract.ts';
import { OperationError } from '../ops/contract.ts';
import { catalogueError } from '../error-catalogue.ts';
+import { STOP_PRODUCERS, legacyRecoveryHint, selectCommand } from './legacy-selection.ts';
import { normalizeSlugPrefix } from '../ops/context.ts';
import { hasScope } from '../scope.ts';
import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';
@@ -285,25 +286,18 @@ export const UNREVIEWED_LIVE_JOBS_SQL = `SELECT id, name, status, submission_aut
/** Select-list column every coalesce read adds so SQL NULL stays distinguishable from JSONB null. */
export const LEGACY_AUTHORITY_COLUMN = 'submission_authority IS NULL AS legacy_authority_is_null';
-/** The filled `--select` preview that reviews one legacy row's name and status. */
-export function legacyAuthorizeCommand(name: string, status: string): string {
- return `gbrain jobs authorize-legacy --select "status=${status},name=${name}"`;
-}
-
/** `permission_denied` for a job row whose SQL NULL authority predates the v0.50 cutover. */
export function legacyJobAuthorityError(row: Record<string, unknown>): OperationError {
const id = String(row.id), name = String(row.name), status = String(row.status);
const what = `Queued job authorization: job ${id} (${name}, ${status}) has no submission authority because it predates the upgrade, so it cannot be reused until it is reviewed.`;
if (status === 'completed' || status === 'failed') {
return catalogueError('legacy_job_authority', what,
- `Resubmit with a new idempotency key; a local operator can review the old row with ${legacyAuthorizeCommand(name, status)}.`);
+ `Resubmit with a new idempotency key; a local operator can review the old row with ${selectCommand('authorize-legacy', { statuses: [status], names: [name] })}.`);
}
if (status === 'active') {
- return catalogueError('legacy_job_authority', what,
- `Stop producers (gbrain serve, gbrain autopilot) and workers, then cancel it: gbrain jobs cancel ${id}; run gbrain doctor to review the rest.`);
+ return catalogueError('legacy_job_authority', what, `${STOP_PRODUCERS}, then cancel it: gbrain jobs cancel ${id}; run gbrain doctor to review the rest.`);
}
- return catalogueError('legacy_job_authority', what,
- `Stop producers (gbrain serve, gbrain autopilot) and workers, cancel active jobs (gbrain jobs cancel <id>), preview with ${legacyAuthorizeCommand(name, status)}, apply with the printed --expect <hash> --yes, then restart them.`);
+ return catalogueError('legacy_job_authority', what, legacyRecoveryHint([status], [name]));
}
const RELEASABLE = new Set(['dead', 'cancelled']);
@@ -333,7 +327,12 @@ export function coalesceDecision(row: Record<string, unknown>, authority: Submis
/** Startup and claim gate: do not let sweeps silently destroy unresolved legacy dependency graphs. */
export async function assertNoUnreviewedJobs(engine: BrainEngine): Promise<void> {
- const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(UNREVIEWED_LIVE_JOBS_SQL);
+ const rows = await engine.executeRaw<{ id: number; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(UNREVIEWED_LIVE_JOBS_SQL);
const invalid = rows.filter(row => !parseSubmissionAuthority(row.submission_authority));
- if (invalid.length) deny(`${invalid.length} legacy jobs have missing or unsupported authority; stop producers/workers. Review SQL NULL rows with jobs authorize-legacy --ids ...; unsupported non-NULL authority requires matching application/database versions or explicit local cancellation before workers start`);
+ if (!invalid.length) return;
+ const unsupported = invalid.filter(row => row.legacy_authority_is_null !== true).length;
+ throw catalogueError('legacy_job_authority',
+ `Queued job authorization: ${invalid.length} legacy jobs have missing or unsupported authority, so workers cannot start until they are reviewed.`,
+ `${legacyRecoveryHint(invalid.filter(row => row.legacy_authority_is_null === true).map(row => row.status))}${unsupported
+ ? ` ${unsupported} job(s) carry unsupported non-NULL authority: run matching application and database versions, or cancel them with gbrain jobs cancel <id> (gbrain doctor lists them).` : ''}`);
}
diff --git a/test/jobs-authorize-legacy-select.test.ts b/test/jobs-authorize-legacy-select.test.ts
new file mode 100644
index 0000000000..2115d6bdc5
--- /dev/null
+++ b/test/jobs-authorize-legacy-select.test.ts
@@ -0,0 +1,218 @@
+/**
+ * #5157 Taste T3: `gbrain jobs authorize-legacy --select <filter>` previews
+ * every matching SQL NULL row with a hash, and `--expect <hash> --yes`
+ * authorizes exactly that set through the shared preview-approval helper.
+ * Also pins the coded refusals that replaced the module's plain Errors
+ * (DX-O2) and that the command is CLI-only (ENG-O13).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { applyLegacySelection, authorizeLegacyJobs, parseLegacyJobIds, previewLegacySelection } from '../src/core/minions/authorize-legacy.ts';
+import { parseLegacyJobSelection } from '../src/core/minions/legacy-selection.ts';
+import { assertNoUnreviewedJobs } from '../src/core/minions/submission-authority.ts';
+import { PREVIEW_APPROVAL_OP } from '../src/core/persistence/preview-approval.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { operations } from '../src/core/operations.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [PREVIEW_APPROVAL_OP]);
+});
+afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });
+
+async function legacy(name: string, status = 'waiting', authority: string | null = null): Promise<number> {
+ const job = await queue.add(name, { n: Math.random() }, {}, { allowProtectedSubmit: true });
+ if (status !== 'waiting') await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [job.id, status]);
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [job.id, authority]);
+ return job.id;
+}
+async function authorities(): Promise<Record<number, unknown>> {
+ const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>('SELECT id, submission_authority FROM minion_jobs ORDER BY id');
+ return Object.fromEntries(rows.map(r => [r.id, r.submission_authority]));
+}
+async function refusal(fn: () => unknown): Promise<OperationError> {
+ try { await fn(); } catch (error) { expect(error).toBeInstanceOf(OperationError); return error as OperationError; }
+ throw new Error('expected a refusal');
+}
+async function cli(args: string[]): Promise<{ out: string; err: string; exit: number }> {
+ const out: string[] = [], err: string[] = [];
+ const log = console.log, error = console.error;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.join(' ')); };
+ try { await runJobs(engine, args); } finally { console.log = log; console.error = error; }
+ return { out: out.join('\n'), err: err.join('\n'), exit: currentExitCode() };
+}
+
+describe('--select grammar', () => {
+ test('status and name keys with | alternatives', () => {
+ expect(parseLegacyJobSelection('status=waiting|paused,name=synthesize|ingest_capture', 'authorize-legacy'))
+ .toEqual({ statuses: ['waiting', 'paused'], names: ['synthesize', 'ingest_capture'] });
+ expect(parseLegacyJobSelection('name=synthesize', 'authorize-legacy')).toEqual({ statuses: [], names: ['synthesize'] });
+ });
+
+ test('an unknown key or value refuses with legacy_job_selection_invalid listing the valid ones', async () => {
+ for (const raw of ['state=waiting', 'status=active', 'status=bogus', 'status=waiting,status=paused', 'status=', 'status=waiting|', '', undefined]) {
+ const error = await refusal(() => parseLegacyJobSelection(raw, 'authorize-legacy'));
+ expect(error.code, String(raw)).toBe('legacy_job_selection_invalid');
+ expect(error.message).toContain('status and name');
+ expect(error.message).toContain('waiting|delayed|waiting-children|paused|completed|failed');
+ expect(error.suggestion).toBe('gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture"');
+ expect(error.docs).toBe('docs/guides/repair.md#legacy-job-selection-invalid');
+ }
+ });
+});
+
+describe('authorize-legacy --select preview and apply', () => {
+ test('preview lists every matching SQL NULL id with a hash and changes nothing', async () => {
+ const a = await legacy('synthesize');
+ const b = await legacy('synthesize', 'paused');
+ const c = await legacy('ingest_capture');
+ const unsupported = await legacy('synthesize', 'waiting', '{"version":2,"kind":"application"}');
+ await queue.add('synthesize', { fresh: true }, {}, { allowProtectedSubmit: true });
+ const before = await authorities();
+ const preview = await previewLegacySelection(engine, parseLegacyJobSelection('status=waiting|paused,name=synthesize', 'authorize-legacy'));
+ expect(preview.summary).toEqual({ total: 2, by_name: { synthesize: { waiting: 1, paused: 1 } }, first_ids: [a, b] });
+ expect(preview.unsupported_ids).toEqual([unsupported]);
+ expect(preview.snapshot_digest).toMatch(/^[a-f0-9]{64}$/);
+ expect(preview.apply_command).toBe(`gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" --expect ${preview.snapshot_digest} --yes`);
+ expect(await authorities()).toEqual(before);
+ expect(c).toBeGreaterThan(0);
+ });
+
+ test('apply authorizes exactly the previewed set, not rows that match later', async () => {
+ const a = await legacy('synthesize');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ const late = await legacy('synthesize');
+ const result = await applyLegacySelection(engine, selection, preview.snapshot_digest!, true);
+ expect(result.authorized_ids).toEqual([a]);
+ const now = await authorities();
+ expect(now[a]).toEqual({ version: 1, kind: 'application' });
+ expect(now[late]).toBeNull();
+ // The approved set is consumed: replaying the same hash refuses.
+ expect((await refusal(() => applyLegacySelection(engine, selection, preview.snapshot_digest!, true))).code).toBe('preview_changed');
+ });
+
+ test('a stale or unknown hash refuses with preview_changed and authorizes nothing', async () => {
+ const a = await legacy('synthesize');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ await engine.executeRaw('UPDATE minion_jobs SET priority = priority + 1 WHERE id = $1', [a]);
+ const stale = await refusal(() => applyLegacySelection(engine, selection, preview.snapshot_digest!, true));
+ expect(stale.code).toBe('preview_changed');
+ expect(stale.message).toContain(preview.snapshot_digest!);
+ expect(stale.suggestion).toBe('Re-run the preview: gbrain jobs authorize-legacy --select "status=waiting"');
+ expect(stale.docs).toBe('docs/guides/repair.md#preview-changed');
+ const unknown = await refusal(() => applyLegacySelection(engine, selection, 'b'.repeat(64), true));
+ expect(unknown.message).toBe(`The preview changed since ${'b'.repeat(64)}; re-run gbrain jobs authorize-legacy --select "status=waiting" and use the new hash.`);
+ // A hash previewed for another filter does not apply under this one.
+ const other = parseLegacyJobSelection('status=waiting,name=synthesize', 'authorize-legacy');
+ const otherPreview = await previewLegacySelection(engine, other);
+ expect((await refusal(() => applyLegacySelection(engine, selection, otherPreview.snapshot_digest!, true))).code).toBe('preview_changed');
+ expect((await authorities())[a]).toBeNull();
+ });
+
+ test('active jobs refuse with legacy_jobs_active listing up to 10 cancel commands', async () => {
+ await legacy('synthesize');
+ const active: number[] = [];
+ for (let i = 0; i < 11; i++) {
+ const job = await queue.add('busy', { i });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [job.id]);
+ active.push(job.id);
+ }
+ const error = await refusal(() => previewLegacySelection(engine, parseLegacyJobSelection('status=waiting', 'authorize-legacy')));
+ expect(error.code).toBe('legacy_jobs_active');
+ expect(error.message).toContain('11 job(s) are active');
+ expect(error.suggestion).toContain('Stop producers (gbrain serve, gbrain autopilot) and workers');
+ for (const id of active.slice(0, 10)) expect(error.suggestion).toMatch(new RegExp(`gbrain jobs cancel ${id}\\b`));
+ expect(error.suggestion).not.toMatch(new RegExp(`gbrain jobs cancel ${active[10]}\\b`));
+ expect(error.suggestion).toContain('gbrain jobs list --status active');
+ expect(error.docs).toBe('docs/guides/repair.md#legacy-jobs-active');
+ });
+
+ test('17.8k-scale selection previews with a summary and applies in one transaction', async () => {
+ await engine.executeRaw(`INSERT INTO minion_jobs (name, status, data, submission_authority)
+ SELECT CASE WHEN g % 10 = 0 THEN 'ingest_capture' ELSE 'synthesize' END, 'waiting', jsonb_build_object('g', g), '{"version":1,"kind":"application"}'::jsonb
+ FROM generate_series(1, 17800) g`);
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ expect(preview.summary.total).toBe(17800);
+ expect(preview.summary.by_name).toEqual({ synthesize: { waiting: 16020 }, ingest_capture: { waiting: 1780 } });
+ expect(preview.summary.first_ids).toHaveLength(20);
+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');
+ const result = await applyLegacySelection(engine, selection, preview.snapshot_digest!, true);
+ expect(result.authorized).toBe(17800);
+ await assertNoUnreviewedJobs(engine);
+ }, 120_000);
+});
+
+describe('coded refusals on the --ids path (DX-O2)', () => {
+ test('missing ids, non-SQL-NULL rows and a stale digest carry codes, hints and anchors', async () => {
+ const missing = await refusal(() => parseLegacyJobIds(undefined));
+ expect(missing.code).toBe('legacy_job_selection_invalid');
+ expect(missing.suggestion).toContain('gbrain jobs authorize-legacy --ids 12,34');
+ const future = await legacy('synthesize', 'waiting', '{"version":2,"kind":"application"}');
+ const unsupported = await refusal(() => authorizeLegacyJobs(engine, [future]));
+ expect(unsupported.message).toContain('SQL NULL');
+ expect(unsupported.suggestion).toContain(`gbrain jobs cancel ${future}`);
+ const id = await legacy('synthesize');
+ const stale = await refusal(() => authorizeLegacyJobs(engine, [id], 'a'.repeat(64), true));
+ expect(stale.code).toBe('preview_changed');
+ expect(stale.message).toContain('snapshot changed');
+ expect(stale.suggestion).toBe(`Re-run the preview: gbrain jobs authorize-legacy --ids ${id}`);
+ const flags = await refusal(() => authorizeLegacyJobs(engine, [id], 'a'.repeat(64), false));
+ expect(flags.suggestion).toBe(`gbrain jobs authorize-legacy --ids ${id} --expect ${'a'.repeat(64)} --yes`);
+ });
+});
+
+describe('CLI transport (ENG-O12) and CLI-only pin (ENG-O13)', () => {
+ test('human preview summarizes and marks paid job names; --json carries the full rows', async () => {
+ const a = await legacy('synthesize');
+ await legacy('ingest_capture', 'paused');
+ const human = await cli(['authorize-legacy', '--select', 'status=waiting|paused']);
+ expect(human.exit).toBe(0);
+ expect(human.out).toContain('Legacy jobs matching status=waiting|paused (SQL NULL authority, authorizable): 2');
+ expect(human.out).toContain(' synthesize: waiting 1 [paid provider calls]');
+ expect(human.out).toContain(' ingest_capture: paused 1');
+ expect(human.out).not.toContain('ingest_capture: paused 1 [paid');
+ expect(human.out).toMatch(/Apply exactly this set: gbrain jobs authorize-legacy --select "status=waiting\|paused" --expect [a-f0-9]{64} --yes/);
+ const json = JSON.parse((await cli(['authorize-legacy', '--select', 'status=waiting|paused', '--json'])).out);
+ expect(json.snapshot.jobs.map((job: { id: number }) => job.id)).toContain(a);
+ expect(json.paid_job_names).toEqual(['synthesize']);
+ const applied = await cli(['authorize-legacy', '--select', 'status=waiting|paused', '--expect', json.snapshot_digest, '--yes']);
+ expect(applied.out).toContain('Authorized 2 legacy job(s) matching status=waiting|paused.');
+ });
+
+ test('a refusal prints the toJSON envelope with --json and exits 1', async () => {
+ const result = await cli(['authorize-legacy', '--select', 'state=waiting', '--json']);
+ expect(result.exit).toBe(1);
+ expect(JSON.parse(result.out)).toMatchObject({
+ error: 'legacy_job_selection_invalid',
+ suggestion: 'gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture"',
+ docs: 'docs/guides/repair.md#legacy-job-selection-invalid',
+ });
+ expect(result.err).toContain('Error [legacy_job_selection_invalid]: Unknown --select key "state"');
+ expect(result.err).toContain('Docs: docs/guides/repair.md#legacy-job-selection-invalid');
+ });
+
+ test('no operation exposes legacy authorization or bulk cancel to MCP or remediation', () => {
+ const names = operations.map(op => op.name);
+ expect(names.filter(name => /legacy|authorize_job|cancel_jobs/.test(name))).toEqual([]);
+ const cancel = operations.find(op => op.name === 'cancel_job')!;
+ expect(Object.keys(cancel.params)).toEqual(['id']);
+ });
+});