Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(jobs): approval hash binds the --select filter; mark every job that may spend (Codex review)
garrytan7bcdbb10c074
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 9a0b587872..1c4df7a9a5 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_WHERE` is the claim gate's predicate, 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/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_WHERE` is the claim gate's predicate, 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 a hash of the filter and the snapshot digest 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/src/commands/jobs/authorize-legacy.ts b/src/commands/jobs/authorize-legacy.tsindex 66ce55b4f5..62cd086b75 100644--- a/src/commands/jobs/authorize-legacy.ts+++ b/src/commands/jobs/authorize-legacy.ts@@ -37,9 +37,9 @@ export async function runJobsAuthorizeLegacy({ args, engine }: JobsCommandContexif (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; }+ if (!preview.preview_hash) { 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(`Preview hash: ${preview.preview_hash}`);console.log(`Apply exactly this set: ${preview.apply_command}`);console.log('Full rows: re-run with --json. Nothing was changed.');} catch (error) {diff --git a/src/commands/jobs/shared.ts b/src/commands/jobs/shared.tsindex be6af2b927..46d367759b 100644--- a/src/commands/jobs/shared.ts+++ b/src/commands/jobs/shared.ts@@ -240,16 +240,19 @@ export function reportJobsError(error: OperationError, json: boolean): void {setCliExitVerdict(1);}-/** Job names whose handlers call a paid model provider (the gateway-refresh set plus the subagent loop). */+/** Handlers outside the gateway-refresh set that can still spend: embedding by default, or the subagent and optimizer loops. */+const OTHER_PAID_JOB_NAMES = new Set(['subagent', 'skillopt', 'import', 'reindex', 'sync']);++/** Job names whose handlers can make paid model-provider calls (DX-O3(d) marks them in a legacy preview). */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();+ return [...new Set(names)].filter(name => GATEWAY_REFRESH_JOB_NAMES.has(name) || OTHER_PAID_JOB_NAMES.has(name)).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]' : ''}`);+ ` ${name}: ${Object.entries(counts).map(([status, n]) => `${status} ${n}`).join(', ')}${paid.includes(name) ? ' [may make 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/minions/authorize-legacy.ts b/src/core/minions/authorize-legacy.tsindex cb6617f22a..b984732a88 100644--- a/src/core/minions/authorize-legacy.ts+++ b/src/core/minions/authorize-legacy.ts@@ -1,6 +1,7 @@/** Local-only, explicit preview/CAS authorization of pre-cutover job rows. */import type { BrainEngine } from '../engine.ts';import { catalogueError } from '../error-catalogue.ts';+import { OperationError } from '../ops/contract.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { APPLICATION_AUTHORITY, parseSubmissionAuthority } from './submission-authority.ts';import {@@ -108,7 +109,7 @@ export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], ex});}-interface ApprovedLegacySelection { selection: string; ids: number[] }+interface ApprovedLegacySelection { selection: string; ids: number[]; snapshot_digest: string }export interface LegacySelectionPreview {selection: string;@@ -117,7 +118,8 @@ export interface LegacySelectionPreview {summary: SelectionSummary;/** Matching live rows whose non-NULL authority is unsupported; never authorizable. */unsupported_ids: number[];- snapshot_digest: string | null;+ /** The hash `--expect` takes: the filter plus the snapshot digest the apply re-checks. */+ preview_hash: string | null;apply_command: string | null;startup_blocking_dependency_count: number;snapshot: Awaited<ReturnType<typeof snapshot>> | null;@@ -140,12 +142,15 @@ export async function previewLegacySelection(engine: BrainEngine, selection: Legconst 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 };+ if (!legacy.length) return { ...base, preview_hash: 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 }]);+ // The approval hash binds the filter as well as the snapshot, so two filters+ // that happen to select the same rows never overwrite each other's set.+ const hash = previewHash({ selection: base.selection, snapshot_digest: preview.snapshot_digest });+ await saveApprovedSet<ApprovedLegacySelection>(engine, { command: 'authorize-legacy', hash }, [{ selection: base.selection, ids, snapshot_digest: preview.snapshot_digest }]);return {- ...base, snapshot_digest: preview.snapshot_digest, apply_command: selectCommand('authorize-legacy', selection, preview.snapshot_digest),+ ...base, preview_hash: hash, apply_command: selectCommand('authorize-legacy', selection, hash),startup_blocking_dependency_count: preview.effects.startup_blocking_dependency_ids.length, snapshot: preview,};}@@ -159,8 +164,14 @@ export async function applyLegacySelection(engine: BrainEngine, selection: Legac}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);+ if (!item || item.selection !== formatSelection(selection) || !item.ids.length || !item.snapshot_digest) throw previewChangedError(expected, previewCommand);+ let result;+ try {+ result = await authorizeLegacyJobs(engine, item.ids, item.snapshot_digest, true, previewCommand);+ } catch (error) {+ if (error instanceof OperationError && error.code === 'preview_changed') throw previewChangedError(expected, previewCommand);+ throw error;+ }await clearApprovedSet(engine, { command: 'authorize-legacy', hash: expected });return { selection: item.selection, authorized_ids: item.ids, ...result };}diff --git a/test/jobs-authorize-legacy-select.test.ts b/test/jobs-authorize-legacy-select.test.tsindex 240cc1a397..e2f6d19781 100644--- a/test/jobs-authorize-legacy-select.test.ts+++ b/test/jobs-authorize-legacy-select.test.ts@@ -87,8 +87,8 @@ describe('authorize-legacy --select preview and apply', () => {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(preview.preview_hash).toMatch(/^[a-f0-9]{64}$/);+ expect(preview.apply_command).toBe(`gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" --expect ${preview.preview_hash} --yes`);expect(await authorities()).toEqual(before);expect(c).toBeGreaterThan(0);});@@ -98,13 +98,13 @@ describe('authorize-legacy --select preview and apply', () => {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);+ const result = await applyLegacySelection(engine, selection, preview.preview_hash!, 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');+ expect((await refusal(() => applyLegacySelection(engine, selection, preview.preview_hash!, true))).code).toBe('preview_changed');});test('a stale or unknown hash refuses with preview_changed and authorizes nothing', async () => {@@ -112,9 +112,9 @@ describe('authorize-legacy --select preview and apply', () => {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));+ const stale = await refusal(() => applyLegacySelection(engine, selection, preview.preview_hash!, true));expect(stale.code).toBe('preview_changed');- expect(stale.message).toContain(preview.snapshot_digest!);+ expect(stale.message).toContain(preview.preview_hash!);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));@@ -122,10 +122,21 @@ describe('authorize-legacy --select preview and apply', () => {// 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 refusal(() => applyLegacySelection(engine, selection, otherPreview.preview_hash!, true))).code).toBe('preview_changed');expect((await authorities())[a]).toBeNull();});+ test('two filters that select the same rows keep separate approvals (Codex review)', async () => {+ const a = await legacy('example-job');+ const broad = parseLegacyJobSelection('status=waiting', 'authorize-legacy');+ const narrow = parseLegacyJobSelection('status=waiting,name=example-job', 'authorize-legacy');+ const first = await previewLegacySelection(engine, broad);+ const second = await previewLegacySelection(engine, narrow);+ expect(first.snapshot!.snapshot_digest).toBe(second.snapshot!.snapshot_digest);+ expect(first.preview_hash).not.toBe(second.preview_hash);+ expect((await applyLegacySelection(engine, broad, first.preview_hash!, true)).authorized_ids).toEqual([a]);+ });+test('active jobs refuse with legacy_jobs_active listing up to 10 cancel commands', async () => {await legacy('synthesize');const active: number[] = [];@@ -155,7 +166,7 @@ describe('authorize-legacy --select preview and apply', () => {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);+ const result = await applyLegacySelection(engine, selection, preview.preview_hash!, true);expect(result.authorized).toBe(17800);await assertNoUnreviewedJobs(engine);}, 120_000);@@ -187,21 +198,21 @@ describe('CLI transport (ENG-O12) and CLI-only pin (ENG-O13)', () => {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(' synthesize: waiting 1 [may make paid provider calls]');expect(human.out).toContain(' ingest_capture: paused 1');- expect(human.out).not.toContain('ingest_capture: paused 1 [paid');+ expect(human.out).not.toContain('ingest_capture: paused 1 [may');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']);+ const applied = await cli(['authorize-legacy', '--select', 'status=waiting|paused', '--expect', json.preview_hash, '--yes']);expect(applied.out).toContain('Authorized 2 legacy job(s) matching status=waiting|paused.');});test('--dry-run next to --expect/--yes previews and authorizes nothing (Codex review)', async () => {const a = await legacy('synthesize');const json = JSON.parse((await cli(['authorize-legacy', '--select', 'status=waiting', '--json'])).out);- const dry = await cli(['authorize-legacy', '--select', 'status=waiting', '--expect', json.snapshot_digest, '--yes', '--dry-run']);+ const dry = await cli(['authorize-legacy', '--select', 'status=waiting', '--expect', json.preview_hash, '--yes', '--dry-run']);expect(dry.out).toContain('Nothing was changed.');expect((await authorities())[a]).toBeNull();});