Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(jobs): preview-bound jobs cancel --select for legacy rows (DX-T2, ENG-O5)
garrytan0902f229c8d9
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 8df1222eeb..e9d8051dc6 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-cancel.ts` — `gbrain jobs cancel --select` (DX-T2, ENG-O5): selects live rows with SQL NULL or unsupported authority, hashes the full `cancelJobs` closure (selected rows plus parents that return from waiting-children to waiting), refuses a selection that would cascade to a descendant outside it (`legacy_job_selection_invalid`, E-T4), and applies under a table lock through `cancelJobs` in one transaction after re-hashing (`preview_changed` on drift). Tests: `test/jobs-cancel-select.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.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 82414215a7..2dcd8820d3 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); ceisrc/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 pagessrc/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 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/jobs.ts 658 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)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.tssrc/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.tsindex d36520a1c6..cf1d06d0c4 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -167,6 +167,7 @@ USAGEgbrain jobs list [--status S] [--queue Q] [--limit N] [--json]gbrain jobs get <id> [--json]gbrain jobs cancel <id>+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]gbrain jobs retry <id>gbrain jobs prune [--older-than 30d] [--dry-run]gbrain jobs delete <id>@@ -387,6 +388,21 @@ completed, failed) and name, each taking | alternatives. The --select preview licounts by job name and status, the first 20 ids and the preview hash, and the applyauthorizes exactly the previewed set. Dependencies are shown but never implicitlyauthorized. IDs, data, schedule and retries persist.+`,+ cancel: `gbrain jobs cancel — cancel a job, or preview-bound bulk cancel of legacy jobs++USAGE+ gbrain jobs cancel <id>+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--json]+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" --expect <hash> --yes++--select picks live jobs whose submission authority is missing or unsupported+(the rows that block workers after an upgrade across v0.50). Keys: status+(waiting, delayed, waiting-children, paused) and name, each taking | alternatives.+Without --yes it only previews: counts by job name and status, the first 20 ids,+parents that return to waiting, and the preview hash. The apply cancels exactly+the previewed set; a selection that would cascade to a job outside it refuses.+Stop producers and workers and cancel active jobs (gbrain jobs cancel <id>) first.`,prune: `gbrain jobs prune — delete old terminal jobsdiff --git a/src/commands/jobs/cancel.ts b/src/commands/jobs/cancel.tsindex 3c9206fd84..250857325a 100644--- a/src/commands/jobs/cancel.ts+++ b/src/commands/jobs/cancel.ts@@ -1,7 +1,44 @@/** `gbrain jobs cancel` (dispatched by runJobs in src/commands/jobs.ts). */-import type { JobsCommandContext } from './shared.ts';+import { paidJobNames, parseFlag, reportJobsError, selectionSummaryLines, type JobsCommandContext } from './shared.ts';+import { applyLegacyCancel, previewLegacyCancel } from '../../core/minions/legacy-cancel.ts';+import { parseLegacyJobSelection } from '../../core/minions/legacy-selection.ts';+import { OperationError } from '../../core/ops/contract.ts';-export async function runJobsCancel({ args, queue }: JobsCommandContext): Promise<void> {+/** `--select <filter> [--expect <hash> --yes]`: preview-bound bulk cancel of legacy rows (DX-T2). */+async function runLegacyCancel({ args, engine }: JobsCommandContext): Promise<void> {+ const json = args.includes('--json');+ try {+ const selection = parseLegacyJobSelection(parseFlag(args, '--select'), 'cancel');+ const expected = parseFlag(args, '--expect');+ const yes = args.includes('--yes');+ if (expected !== undefined || yes) {+ const result = await applyLegacyCancel(engine, selection, expected, yes);+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }+ console.log(`Cancelled ${result.cancelled_ids.length} legacy job(s) matching ${result.selection}.`);+ return;+ }+ const preview = await previewLegacyCancel(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} to cancel (missing or unsupported authority): ${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 among them: ${preview.unsupported_ids.slice(0, 20).join(', ')}`);+ if (!preview.preview_hash) { console.log('Nothing to cancel.'); return; }+ if (preview.parent_transitions.length) {+ console.log(`Parents that return to waiting: ${preview.parent_transitions.map(p => p.id).join(', ')}`);+ }+ console.log(`Preview hash: ${preview.preview_hash}`);+ console.log(`Cancel 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);+ }+}++export async function runJobsCancel(ctx: JobsCommandContext): Promise<void> {+ const { args, queue } = ctx;+ if (args.includes('--select')) return runLegacyCancel(ctx);const id = parseInt(args[1], 10);if (isNaN(id)) { console.error('Error: job ID required.'); process.exit(1); }diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 45c909e486..43859aa463 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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'],- 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--select', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],@@ -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', '--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', '--select', '--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/legacy-cancel.ts b/src/core/minions/legacy-cancel.tsnew file mode 100644index 0000000000..ca3882d83d--- /dev/null+++ b/src/core/minions/legacy-cancel.ts@@ -0,0 +1,115 @@+/**+ * `gbrain jobs cancel --select <filter>` (DX-T2, ENG-O5): bulk cancellation+ * of the live rows the claim gate blocks on (SQL NULL or unsupported+ * authority), preview-bound like `authorize-legacy --select`.+ *+ * The preview hashes the complete cancellation closure `cancelJobs` would+ * produce: the selected rows, and the parents that return from+ * waiting-children to waiting once their last open child is cancelled. A+ * selection whose closure would also cancel a descendant outside the+ * selected set refuses (E-T4), naming those ids. The apply recomputes the+ * closure under a table lock, refuses with `preview_changed` if its hash+ * moved, and cancels through `cancelJobs` in the same transaction.+ */+import type { BrainEngine } from '../engine.ts';+import { catalogueError } from '../error-catalogue.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { MinionQueue } from './queue.ts';+import { LIVE_JOB_STATUSES, parseSubmissionAuthority } from './submission-authority.ts';+import type { MinionJobStatus } from './types.ts';+import {+ assertNoActiveJobs, formatSelection, selectCommand, selectedStatuses, summarizeSelection,+ type LegacyJobSelection, type SelectionSummary,+} from './legacy-selection.ts';++export const LEGACY_CANCEL_REASON = 'legacy_review: cancelled by gbrain jobs cancel --select';++interface ClosureRow { id: number; name: string; status: string; parent_job_id: number | null; updated_at: unknown; submission_authority: unknown; legacy_authority_is_null: boolean }++async function cancelClosure(engine: BrainEngine, selection: LegacyJobSelection) {+ const previewCommand = selectCommand('cancel', selection);+ await assertNoActiveJobs(engine, previewCommand);+ const candidates = await engine.executeRaw<ClosureRow>(+ `SELECT id, name, status, parent_job_id, updated_at, 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('cancel', selection), selection.names]);+ const rows = candidates.filter(row => !parseSubmissionAuthority(row.submission_authority));+ const ids = rows.map(row => Number(row.id));+ // The same recursion cancelJobs runs: every live descendant of a selected root.+ const outside = ids.length ? await engine.executeRaw<{ id: number }>(+ `WITH RECURSIVE descendants AS (+ SELECT id, 0 AS d FROM minion_jobs WHERE id = ANY($1::int[])+ UNION ALL+ SELECT m.id, descendants.d + 1 FROM minion_jobs m JOIN descendants ON m.parent_job_id = descendants.id WHERE descendants.d < 100+ ) SELECT DISTINCT j.id FROM minion_jobs j+ WHERE j.id IN (SELECT id FROM descendants) AND NOT (j.id = ANY($1::int[]))+ AND j.status = ANY($2::text[])+ ORDER BY j.id`, [ids, [...LIVE_JOB_STATUSES]]) : [];+ if (outside.length) {+ const named = outside.slice(0, 10).map(row => Number(row.id));+ throw catalogueError('legacy_job_selection_invalid',+ `Cancelling the selection would also cancel ${outside.length} descendant job(s) outside it: ${named.join(', ')}${outside.length > 10 ? ' …' : ''}.`,+ `Cancel them on purpose first (${named.map(id => `gbrain jobs cancel ${id}`).join('; ')}) or widen the filter to select them, then re-run ${previewCommand}.`);+ }+ const parents = [...new Set(rows.map(row => row.parent_job_id).filter((id): id is number => id != null && !ids.includes(Number(id))))];+ const transitions = parents.length ? await engine.executeRaw<{ id: number }>(+ `SELECT p.id FROM minion_jobs p+ WHERE p.id = ANY($1::int[]) AND p.status = 'waiting-children'+ AND NOT EXISTS (SELECT 1 FROM minion_jobs c WHERE c.parent_job_id = p.id+ AND c.status NOT IN ('completed','failed','dead','cancelled') AND NOT (c.id = ANY($2::int[])))+ ORDER BY p.id`, [parents, ids]) : [];+ const parent_transitions = transitions.map(row => ({ id: Number(row.id), from: 'waiting-children', to: 'waiting' }));+ const hash = previewHash({ preview_version: 1, command: 'jobs-cancel', selection: formatSelection(selection), rows, parent_transitions });+ return { previewCommand, rows, ids, parent_transitions, hash };+}++export interface LegacyCancelPreview {+ selection: string;+ preview_command: string;+ summary: SelectionSummary;+ /** Selected rows whose non-NULL authority is unsupported (also cancelled). */+ unsupported_ids: number[];+ parent_transitions: Array<{ id: number; from: string; to: string }>;+ preview_hash: string | null;+ apply_command: string | null;+ rows: ClosureRow[];+ applied: false;+}++interface ApprovedCancel { selection: string; ids: number[] }++/** Preview: lists and hashes the closure, saves the exact id set under that hash. Changes no job. */+export async function previewLegacyCancel(engine: BrainEngine, selection: LegacyJobSelection): Promise<LegacyCancelPreview> {+ const closure = await cancelClosure(engine, selection);+ const base = {+ selection: formatSelection(selection), preview_command: closure.previewCommand, summary: summarizeSelection(closure.rows),+ unsupported_ids: closure.rows.filter(row => row.legacy_authority_is_null !== true).map(row => Number(row.id)),+ parent_transitions: closure.parent_transitions, rows: closure.rows, applied: false as const,+ };+ if (!closure.ids.length) return { ...base, preview_hash: null, apply_command: null };+ await saveApprovedSet<ApprovedCancel>(engine, { command: 'jobs-cancel', hash: closure.hash }, [{ selection: base.selection, ids: closure.ids }]);+ return { ...base, preview_hash: closure.hash, apply_command: selectCommand('cancel', selection, closure.hash) };+}++/** Apply: cancels exactly the previewed closure through cancelJobs in one transaction, or refuses whole. */+export async function applyLegacyCancel(engine: BrainEngine, selection: LegacyJobSelection, expected: string | undefined, yes: boolean) {+ const previewCommand = selectCommand('cancel', selection);+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {+ throw catalogueError('legacy_job_selection_invalid', 'Apply requires BOTH --expect <preview hash> and --yes.',+ expected && /^[a-f0-9]{64}$/.test(expected) ? selectCommand('cancel', selection, expected) : `Preview first: ${previewCommand}`);+ }+ const approved = await loadApprovedSet<ApprovedCancel>(engine, { command: 'jobs-cancel', hash: expected, previewCommand });+ const [item] = approved.items;+ if (!item || item.selection !== formatSelection(selection) || !item.ids.length) throw previewChangedError(expected, previewCommand);+ return engine.transaction(async tx => {+ await tx.executeRaw('LOCK TABLE minion_jobs IN SHARE ROW EXCLUSIVE MODE');+ const closure = await cancelClosure(tx, selection);+ if (closure.hash !== expected || previewHash(closure.ids) !== previewHash(item.ids)) throw previewChangedError(expected, previewCommand);+ const cancelled = await new MinionQueue(tx).cancelJobs(closure.ids, { reason: LEGACY_CANCEL_REASON, rootStatuses: selectedStatuses('cancel', selection) as MinionJobStatus[] });+ if (cancelled.length !== closure.ids.length) throw previewChangedError(expected, previewCommand);+ await clearApprovedSet(tx, { command: 'jobs-cancel', hash: expected });+ return { selection: item.selection, cancelled_ids: closure.ids, parent_transitions: closure.parent_transitions, applied: true as const };+ });+}diff --git a/test/jobs-cancel-select.test.ts b/test/jobs-cancel-select.test.tsnew file mode 100644index 0000000000..c14c1fbb75--- /dev/null+++ b/test/jobs-cancel-select.test.ts@@ -0,0 +1,155 @@+/**+ * DX-T2 / ENG-O5: `gbrain jobs cancel --select <filter>` previews and hashes+ * the complete cancellation closure (selected rows plus parent transitions),+ * cancels exactly that set through cancelJobs with `--expect <hash> --yes`,+ * and refuses a selection that would cascade to a descendant outside it.+ */+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 { applyLegacyCancel, previewLegacyCancel } from '../src/core/minions/legacy-cancel.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 { 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; });++const sel = (raw: string) => parseLegacyJobSelection(raw, 'cancel');+async function job(name: string, opts: { parent?: number; authority?: string | null; status?: string } = {}): Promise<number> {+ const added = await queue.add(name, { n: Math.random() }, opts.parent ? { parent_job_id: opts.parent } : {});+ if (opts.status) await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [added.id, opts.status]);+ if (opts.authority !== undefined) await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [added.id, opts.authority]);+ return added.id;+}+async function statuses(): Promise<Record<number, string>> {+ const rows = await engine.executeRaw<{ id: number; status: string }>('SELECT id, status FROM minion_jobs ORDER BY id');+ return Object.fromEntries(rows.map(r => [r.id, r.status]));+}+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');+}++describe('jobs cancel --select', () => {+ test('preview lists and hashes the closure, including parent transitions, and changes nothing', async () => {+ const parent = await job('fanout');+ const child = await job('legacy-child', { parent, authority: null });+ const loner = await job('legacy-loner', { authority: 'null' });+ const keep = await job('legacy-child', { authority: null, status: 'completed' });+ const before = await statuses();+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));+ expect(preview.summary.first_ids).toEqual([child, loner]);+ expect(preview.unsupported_ids).toEqual([loner]);+ expect(preview.parent_transitions).toEqual([{ id: parent, from: 'waiting-children', to: 'waiting' }]);+ expect(preview.apply_command).toBe(`gbrain jobs cancel --select "status=waiting" --expect ${preview.preview_hash} --yes`);+ expect(await statuses()).toEqual(before);+ expect(before[keep]).toBe('completed');+ });++ test('apply cancels exactly the previewed set, applies the parent transition and unblocks workers', async () => {+ const parent = await job('fanout');+ const child = await job('legacy-child', { parent, authority: null });+ const loner = await job('legacy-loner', { authority: 'null' });+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));+ const late = await job('legacy-late', { authority: null, status: 'paused' });+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');+ const result = await applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true);+ expect(result.cancelled_ids).toEqual([child, loner]);+ const now = await statuses();+ expect(now[child]).toBe('cancelled');+ expect(now[loner]).toBe('cancelled');+ expect(now[parent]).toBe('waiting');+ expect(now[late]).toBe('paused');+ expect((await refusal(() => applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true))).code).toBe('preview_changed');+ await engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [late]);+ await assertNoUnreviewedJobs(engine);+ });++ test('a stale hash refuses with preview_changed and cancels nothing', async () => {+ const a = await job('legacy', { authority: null });+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));+ await engine.executeRaw('UPDATE minion_jobs SET priority = priority + 1, updated_at = now() + interval \'1 second\' WHERE id = $1', [a]);+ const error = await refusal(() => applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true));+ expect(error.code).toBe('preview_changed');+ expect(error.message).toBe(`The preview changed since ${preview.preview_hash}; re-run gbrain jobs cancel --select "status=waiting" and use the new hash.`);+ expect((await statuses())[a]).toBe('waiting');+ });++ test('a mixed-authority tree refuses: the application child is outside the selection', async () => {+ const parent = await job('legacy-parent');+ const appChild = await job('worker-step', { parent });+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [parent]);+ const error = await refusal(() => previewLegacyCancel(engine, sel('status=waiting-children')));+ expect(error.code).toBe('legacy_job_selection_invalid');+ expect(error.message).toBe(`Cancelling the selection would also cancel 1 descendant job(s) outside it: ${appChild}.`);+ expect(error.suggestion).toContain(`gbrain jobs cancel ${appChild}`);+ expect((await statuses())[appChild]).toBe('waiting');+ });++ test('an outside-set legacy descendant refuses until the filter selects it', async () => {+ const parent = await job('legacy-parent');+ const child = await job('legacy-child', { parent });+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = ANY($1::int[])', [[parent, child]]);+ const error = await refusal(() => previewLegacyCancel(engine, sel('name=legacy-parent')));+ expect(error.message).toContain(`outside it: ${child}.`);+ const widened = await previewLegacyCancel(engine, sel('name=legacy-parent|legacy-child'));+ expect(widened.summary.first_ids).toEqual([parent, child]);+ await applyLegacyCancel(engine, sel('name=legacy-parent|legacy-child'), widened.preview_hash!, true);+ expect(await statuses()).toEqual({ [parent]: 'cancelled', [child]: 'cancelled' });+ });++ test('active jobs refuse with legacy_jobs_active', async () => {+ await job('legacy', { authority: null });+ const busy = await job('busy');+ 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`, [busy]);+ const error = await refusal(() => previewLegacyCancel(engine, sel('status=waiting')));+ expect(error.code).toBe('legacy_jobs_active');+ expect(error.suggestion).toContain(`gbrain jobs cancel ${busy}`);+ });++ test('CLI: preview, --json and apply through runJobs; jobs cancel <id> is unchanged', async () => {+ const out: string[] = [];+ const log = console.log, err = console.error;+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };+ console.error = () => {};+ try {+ const a = await job('synthesize-legacy', { authority: null });+ await runJobs(engine, ['cancel', '--select', 'status=waiting']);+ expect(out.join('\n')).toContain('Legacy jobs matching status=waiting to cancel (missing or unsupported authority): 1');+ out.length = 0;+ await runJobs(engine, ['cancel', '--select', 'status=waiting', '--json']);+ const preview = JSON.parse(out.join('\n'));+ expect(preview.rows.map((r: { id: number }) => r.id)).toEqual([a]);+ out.length = 0;+ await runJobs(engine, ['cancel', '--select', 'status=waiting', '--expect', preview.preview_hash, '--yes']);+ expect(out.join('\n')).toBe('Cancelled 1 legacy job(s) matching status=waiting.');+ out.length = 0;+ await runJobs(engine, ['cancel', '--select', 'status=active', '--json']);+ expect(JSON.parse(out.join('\n')).error).toBe('legacy_job_selection_invalid');+ expect(currentExitCode()).toBe(1);+ const plain = await job('plain');+ out.length = 0;+ await runJobs(engine, ['cancel', String(plain)]);+ expect(out.join('\n')).toBe(`Job #${plain} cancelled.`);+ } finally {+ console.log = log; console.error = err;+ }+ });+});