Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(jobs): supervisor stop verifies the run's own rows and process identity (W9F item 7)
time-attackf22b03f62797
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 7e20cfc192..13879624ff 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`.-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`. #5062: registers as the CLI signal owner; `shutdown()` is one shared promise (repeated signals join it) that keeps refreshing the queue lock while the worker drains (SIGTERM, 35s, SIGKILL by liveness, 5s confirmation), then releases the lock and emits `stopped` with `drained` / `worker_forced` / `worker_exit_code` / `lock_released`. `gbrain jobs supervisor stop` (`src/commands/jobs/supervisor.ts`) reports `drained` only when the pid is gone, the supervisor's own `stopped` row follows its `shutting_down` with `drained: true`, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (`no_stopped_event`, `worker_still_running`, `lock_unverified`, `lock_still_held`, `forced`) and exits 1.+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`. #5062: registers as the CLI signal owner; `shutdown()` is one shared promise (repeated signals join it) that keeps refreshing the queue lock while the worker drains (SIGTERM, 35s, SIGKILL by liveness, 5s confirmation), then releases the lock and emits `stopped` with `drained` / `worker_forced` / `worker_exit_code` / `lock_released`. `gbrain jobs supervisor stop` (`src/commands/jobs/supervisor.ts`) reports `drained` only when the pid is gone, the supervisor's own `stopped` row follows its `shutting_down` with `drained: true`, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (`no_stopped_event`, `worker_still_running`, `lock_unverified`, `lock_still_held`, `forced`) and exits 1. W9F item 7: the rows it reads are the run's own (`readSupervisorRun` in `supervisor-audit.ts`: from the supervisor pid's last `started` row, searching back up to `SUPERVISOR_RUN_LOOKBACK_WEEKS` weekly files, so a run started before the ISO-week boundary keeps its spawns); `worker_exited` rows carry the child's `pid` (null when no process was created) and `worker_spawned` rows its kernel start time (`pid_start`), so the live set is spawns with no later exit whose pid is still alive with the recorded start time (a recycled pid is not a live worker; pre-upgrade exit rows without a `pid` key pair with spawns by order and add `warnings: ['legacy_exit_pairing']`); a run with no `started` row on record reports `unverified` (exit 1, `audit_files` listed), never `drained`. The PID file now holds the pid and, on Linux, its start time on a second line (`pidFileContents`; every reader takes the first line), and `started` records `supervisor_start`: when the pid is alive with a different start time, stop reports `stale_pid_file` (exit 0, `stopped: false`) and signals nothing. Process start times come from `processStartTime` in `src/core/pglite-lock.ts` (moved from `graduation-custody.ts`, which re-exports it). Pinned by `test/jobs-supervisor-stop-identity.test.ts`.- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.diff --git a/src/commands/jobs/supervisor.ts b/src/commands/jobs/supervisor.tsindex b63d303a5a..6cdbafc54f 100644--- a/src/commands/jobs/supervisor.ts+++ b/src/commands/jobs/supervisor.ts@@ -301,14 +301,20 @@ const STOP_WAIT_MS = 45_000;* is gone" is not enough. Success also needs the supervisor's own `stopped`* audit row (after its `shutting_down`) saying the worker drained, every* worker it spawned gone, and its queue lock row released. Anything less is- * reported with the failing check and exits 1.+ * reported with the failing check and exits 1. W9F item 7: the audit rows are+ * the run's own (from its `started` row, searched back across weekly files);+ * a worker is live only when its pid is alive with the start time recorded at+ * spawn; a run with no `started` row on record is `unverified`, never+ * `drained`; and a PID file whose pid now belongs to a different process+ * (start time mismatch) is reported `stale_pid_file` without signaling it.*/async function stopSupervisor(engine: BrainEngine, args: string[], pidFile: string, jsonMode: boolean): Promise<void> {const { existsSync, readFileSync } = await import('fs');const { hostname } = await import('os');- const { readSupervisorEvents } = await import('../../core/minions/handlers/supervisor-audit.ts');+ const { readSupervisorRun } = await import('../../core/minions/handlers/supervisor-audit.ts');const { supervisorLockId } = await import('../../core/minions/supervisor.ts');const { inspectLock } = await import('../../core/db-lock.ts');+ const { processStartTime } = await import('../../core/pglite-lock.ts');const report = (payload: Record<string, unknown>, human: string, ok: boolean): never => {if (jsonMode) console.log(JSON.stringify(payload));else if (ok) console.log(human);@@ -318,21 +324,35 @@ async function stopSupervisor(engine: BrainEngine, args: string[], pidFile: striconst isAlive = (pid: number): boolean => {try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }};+ // W9F item 7: a live pid whose kernel start time differs from the recorded+ // one is a different (recycled) process. Unknown start times compare equal.+ const sameProcess = (pid: number, recordedStart: unknown): boolean => {+ if (!isAlive(pid)) return false;+ const current = processStartTime(pid);+ return typeof recordedStart !== 'string' || current === null || current === recordedStart;+ };if (!existsSync(pidFile)) {report({ stopped: false, reason: 'pid_file_missing', pid_file: pidFile }, `No PID file at ${pidFile}; supervisor not running.`, false);}let supervisorPid: number;+ let recordedStart: string | null;try {- supervisorPid = parseInt(readFileSync(pidFile, 'utf8').trim().split('\n')[0], 10);+ const [pidLine, startLine] = readFileSync(pidFile, 'utf8').trim().split('\n');+ supervisorPid = parseInt(pidLine, 10);if (isNaN(supervisorPid) || supervisorPid <= 0) throw new Error('invalid pid');+ recordedStart = /^\d+$/.test(startLine?.trim() ?? '') ? startLine!.trim() : null;} catch (err) {return report({ stopped: false, reason: 'pid_file_corrupt', error: String(err) }, `PID file corrupt: ${err}`, false);}- const ownEvents = () => readSupervisorEvents().filter(e => e.supervisor_pid === supervisorPid);- const startedEvt = ownEvents().filter(e => e.event === 'started').pop();- const queue = (typeof startedEvt?.queue === 'string' ? startedEvt.queue : undefined) ?? parseFlag(args, '--queue') ?? 'default';+ const before = readSupervisorRun(supervisorPid, { supervisorStart: recordedStart });+ const supervisorStart = recordedStart ?? before.started?.supervisor_start;+ if (isAlive(supervisorPid) && !sameProcess(supervisorPid, supervisorStart)) {+ report({ stopped: false, reason: 'stale_pid_file', supervisor_pid: supervisorPid, pid_file: pidFile },+ `PID file ${pidFile} names pid ${supervisorPid}, which now belongs to a different process; the supervisor is not running and nothing was signaled.`, true);+ }+ const queue = (typeof before.started?.queue === 'string' ? before.started.queue : undefined) ?? parseFlag(args, '--queue') ?? 'default';try { process.kill(supervisorPid, 'SIGTERM'); }catch (err: unknown) {@@ -356,13 +376,28 @@ async function stopSupervisor(engine: BrainEngine, args: string[], pidFile: stri`Supervisor ${supervisorPid} did not exit within ${STOP_WAIT_MS / 1000}s.`, false);}- const events = ownEvents();+ const run = readSupervisorRun(supervisorPid, { supervisorStart: typeof supervisorStart === 'string' ? supervisorStart : null });+ if (!run.started) {+ report({ stopped: true, supervisor_pid: supervisorPid, queue, reason: 'unverified', drained: false, audit_files: run.files },+ `Supervisor ${supervisorPid} exited, but its audit trail has no record of the run (missing, pruned or corrupt; searched ${run.files.length ? run.files.join(', ') : 'no existing audit files'}), so the drain cannot be verified. ` ++ 'Inspect in-flight jobs with `gbrain jobs list --status active`.', false);+ }+ const events = run.events;const shuttingIdx = events.map(e => e.event).lastIndexOf('shutting_down');const stoppedEvt = shuttingIdx >= 0 ? events.slice(shuttingIdx + 1).find(e => e.event === 'stopped') : undefined;- const spawned = events- .filter(e => e.event === 'worker_spawned' && typeof e.pid === 'number')- .map(e => e.pid as number);- const liveWorkers = spawned.filter(isAlive);+ // The live set: spawns with no later exit. An exit row carries the child's+ // pid (null: no process was created); a row written before exits carried+ // one (no `pid` key) pairs with the oldest open spawn.+ const open: Array<{ pid: number; start: unknown }> = [];+ let legacyPairing = false;+ for (const e of events) {+ if (e.event === 'worker_spawned' && typeof e.pid === 'number') open.push({ pid: e.pid, start: e.pid_start });+ if (e.event !== 'worker_exited' || e.pid === null) continue;+ if (!('pid' in e)) legacyPairing = true;+ const idx = typeof e.pid === 'number' ? open.findIndex(w => w.pid === e.pid) : 0;+ if (idx >= 0) open.splice(idx, 1);+ }+ const liveWorkers = open.filter(w => sameProcess(w.pid, w.start)).map(w => w.pid);let lockReleased: boolean | null;try {const snap = await inspectLock(engine, supervisorLockId(queue));@@ -389,6 +424,8 @@ async function stopSupervisor(engine: BrainEngine, args: string[], pidFile: stri: `Supervisor ${supervisorPid} exited but the stop is not verified as drained (${reason}): ` +`${JSON.stringify(checks)}${liveWorkers.length > 0 ? `; live worker pid(s): ${liveWorkers.join(', ')}` : ''}. ` +'Inspect in-flight jobs with `gbrain jobs list --status active`.';+ if (legacyPairing) console.error('Warning: audit rows written before worker exits carried a pid were paired with spawns by order.');report({ stopped: true, supervisor_pid: supervisorPid, queue, reason, drained, checks,- ...(liveWorkers.length > 0 ? { live_worker_pids: liveWorkers } : {}) }, human, drained);+ ...(liveWorkers.length > 0 ? { live_worker_pids: liveWorkers } : {}),+ ...(legacyPairing ? { warnings: ['legacy_exit_pairing'] } : {}) }, human, drained);}diff --git a/src/core/minions/child-worker-supervisor.ts b/src/core/minions/child-worker-supervisor.tsindex 10989941cc..64dd98c918 100644--- a/src/core/minions/child-worker-supervisor.ts+++ b/src/core/minions/child-worker-supervisor.ts@@ -54,6 +54,8 @@ export type ChildSupervisorEvent =| { kind: 'worker_spawn_failed'; error: string; phase: 'sync' | 'async'; errnoCode?: string }| {kind: 'worker_exited';+ /** The exited child's pid (absent when the spawn never produced a process). */+ pid?: number;code: number | null;signal: NodeJS.Signals | null;runDurationMs: number;@@ -555,6 +557,7 @@ export class ChildWorkerSupervisor {this.opts.onEvent({kind: 'worker_exited',+ pid: child.pid,code: null,signal: null,runDurationMs: runDuration,@@ -598,7 +601,7 @@ export class ChildWorkerSupervisor {this.opts.processingState?.workerExited();this._lastExitCode = code;this.markConfigurationBlocked();- this.opts.onEvent({ kind: 'worker_exited', code, signal: signal ?? null,+ this.opts.onEvent({ kind: 'worker_exited', pid: child.pid, code, signal: signal ?? null,runDurationMs: this.now() - this._lastStartTime, likelyCause: 'configuration_blocked', crashCount: this._crashCount });resolve();return;@@ -692,6 +695,7 @@ export class ChildWorkerSupervisor {this.opts.onEvent({kind: 'worker_exited',+ pid: child.pid,code: code ?? null,signal: signal ?? null,runDurationMs: runDuration,diff --git a/src/core/minions/handlers/supervisor-audit.ts b/src/core/minions/handlers/supervisor-audit.tsindex fa089b11a7..2e610408b8 100644--- a/src/core/minions/handlers/supervisor-audit.ts+++ b/src/core/minions/handlers/supervisor-audit.ts@@ -117,6 +117,56 @@ export function readSupervisorEvents(opts: { sinceMs?: number } = {}): Supervisoreturn events;}+/** Weekly audit files `readSupervisorRun` searches back for a run's `started` row. */+export const SUPERVISOR_RUN_LOOKBACK_WEEKS = 26;++export interface SupervisorRun {+ /** The run's `started` row, or null when no file in the bound holds it (missing, pruned or corrupt audit). */+ started: SupervisorEmission | null;+ /** The run's rows from its `started` row on, oldest first (empty when `started` is null). */+ events: SupervisorEmission[];+ /** The audit files that exist among those searched, newest first. */+ files: string[];+}++/**+ * The rows of one supervisor run (W9F item 7): from the last `started` row of+ * `supervisorPid` on, searching back across weekly files (at most+ * `maxWeeks`) so a supervisor started before an ISO-week boundary keeps its+ * `worker_spawned` rows. With `supervisorStart` (the process start time the+ * PID file recorded), a `started` row stamped with a different start belongs+ * to an earlier process that had the same pid and is skipped; legacy rows+ * without a stamp match on pid alone.+ */+export function readSupervisorRun(supervisorPid: number,+ opts: { supervisorStart?: string | null; now?: Date; maxWeeks?: number } = {}): SupervisorRun {+ const fs = require('node:fs') as typeof import('node:fs');+ const path = require('node:path') as typeof import('node:path');+ const dir = writer.resolveDir();+ const now = opts.now ?? new Date();+ const files: string[] = [];+ let rows: SupervisorEmission[] = [];+ for (let week = 0; week < (opts.maxWeeks ?? SUPERVISOR_RUN_LOOKBACK_WEEKS); week++) {+ const file = path.join(dir, computeSupervisorAuditFilename(new Date(now.getTime() - week * 7 * 86_400_000)));+ let raw: string;+ try { raw = fs.readFileSync(file, 'utf8'); } catch { continue; }+ files.push(file);+ const own: SupervisorEmission[] = [];+ for (const line of raw.split('\n')) {+ if (!line.trim()) continue;+ try {+ const obj = JSON.parse(line) as SupervisorEmission;+ if (obj.event && obj.ts && obj.supervisor_pid === supervisorPid) own.push(obj);+ } catch { /* truncated or corrupt line */ }+ }+ rows = [...own, ...rows];+ const startedIdx = rows.findLastIndex(e => e.event === 'started'+ && (!opts.supervisorStart || e.supervisor_start === undefined || e.supervisor_start === opts.supervisorStart));+ if (startedIdx >= 0) return { started: rows[startedIdx]!, events: rows.slice(startedIdx), files };+ }+ return { started: null, events: [], files };+}+/*** Cross-week supervisor read for windows that can straddle a Monday boundary* (issue #1685, CODEX #7). The single-file `readSupervisorEvents` above can losediff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex ee6a556d4d..22d1741dab 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -51,6 +51,17 @@ import { currentBrainId, readWorkers } from './worker-registry.ts';import { autopilotOperatorPauseMarkerPath, autopilotPaused } from '../autopilot-paths.ts';import { registerSignalOwner, triggerCleanupAndExit } from '../process-cleanup.ts';import { resolveEnvNumber } from '../env-number.ts';+import { processStartTime } from '../pglite-lock.ts';++/**+ * PID file body: the supervisor pid, then (Linux) its kernel start time, so+ * `supervisor stop` can tell a stale PID file whose pid was recycled from+ * this supervisor (W9F item 7). Readers take the first line.+ */+export function pidFileContents(pid: number = process.pid): string {+ const start = processStartTime(pid);+ return start ? `${pid}\n${start}\n` : String(pid);+}export type SupervisorEvent =| 'started'@@ -831,8 +842,11 @@ export class MinionSupervisor {}// 5. Announce start.+ const supervisorStart = processStartTime(process.pid);this.emit('started', {supervisor_pid: process.pid,+ // W9F item 7: the identity `supervisor stop` validates before SIGTERM.+ ...(supervisorStart ? { supervisor_start: supervisorStart } : {}),// Resolved to absolute at emit time (relative to THIS process's cwd,// the only context in which a relative --pid-file was meaningful) so a// later reader (e.g. `gbrain doctor`, possibly running from a@@ -1091,7 +1105,7 @@ export class MinionSupervisor {// O_CREAT | O_EXCL | O_WRONLY — fails with EEXIST if the file exists.const fd = openSync(this.opts.pidFile, 'wx');try {- writeSync(fd, String(process.pid));+ writeSync(fd, pidFileContents());} finally {closeSync(fd);}@@ -1117,7 +1131,7 @@ export class MinionSupervisor {try {const fd = openSync(this.opts.pidFile, 'wx');try {- writeSync(fd, String(process.pid));+ writeSync(fd, pidFileContents());} finally {closeSync(fd);}@@ -1223,8 +1237,12 @@ export class MinionSupervisor {// (possibly wedged) one's stale DB state.this.childStartedAt = Date.now();this.consecutiveWedgedChecks = 0;+ const pidStart = event.pid >= 0 ? processStartTime(event.pid) : null;this.emit('worker_spawned', {pid: event.pid >= 0 ? event.pid : undefined,+ // W9F item 7: process identity, so `supervisor stop` never mistakes+ // a recycled pid for this worker.+ ...(pidStart ? { pid_start: pidStart } : {}),cli_path: this.opts.cliPath,...(event.tini ? { tini: true } : {}),...(this.opts.nice_requested !== undefined ? { nice: this.opts.nice_requested } : {}),@@ -1245,6 +1263,7 @@ export class MinionSupervisor {? `signal ${event.signal}`: `code ${event.code ?? 'null'}`;this.emit('worker_exited', {+ pid: event.pid ?? null,code: event.code,signal: event.signal,reason: exitReason,diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.tsindex 58cdec07eb..14936f50d1 100644--- a/src/core/persistence/graduation-custody.ts+++ b/src/core/persistence/graduation-custody.ts@@ -14,7 +14,7 @@ import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFimport { basename, dirname, join, resolve } from 'node:path';import type { OperationError } from '../ops/contract.ts';import { engineGraduatedError, inProgressError, interruptedError, splitBrainError } from './graduation-errors.ts';-import { inspectLockHolder, isProcessAlive, readBootId, readPidNs, type LockHandle } from '../pglite-lock.ts';+import { inspectLockHolder, isProcessAlive, processStartTime, readBootId, readPidNs, type LockHandle } from '../pglite-lock.ts';import { moveHeldPglite } from './maintenance.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { flushDirectory } from '../fs-durable.ts';@@ -89,14 +89,7 @@ export function allowGraduationInspection(dataDir: string): () => void {// ── process identity (marker liveness) ─────────────────────────────────────-/** Kernel start time of `pid` (Linux /proc clock ticks), or null when unknowable. */-export function processStartTime(pid: number): string | null {- try {- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');- const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');- return fields[19] ?? null;- } catch { return null; }-}+export { processStartTime };export function currentProcessIdentity(): Pick<IntentMarker, 'pid' | 'bootId' | 'pidNs' | 'processStart'> {return { pid: process.pid, bootId: readBootId(), pidNs: readPidNs(), processStart: processStartTime(process.pid) };diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.tsindex c25b5ea279..e3341da8b7 100644--- a/src/core/pglite-lock.ts+++ b/src/core/pglite-lock.ts@@ -75,6 +75,14 @@ export function readPidNs(): string | null {export function readBootId(): string | null {try { return readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() || null; } catch { return null; }}+/** Kernel start time of `pid` (Linux /proc clock ticks), or null when unknowable. */+export function processStartTime(pid: number): string | null {+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');+ return fields[19] ?? null;+ } catch { return null; }+}/** Resolve existing ancestors without creating the datastore during inspection. */function canonicalPath(path: string): string {diff --git a/test/jobs-supervisor-stop-identity.test.ts b/test/jobs-supervisor-stop-identity.test.tsnew file mode 100644index 0000000000..8feb5ac749--- /dev/null+++ b/test/jobs-supervisor-stop-identity.test.ts@@ -0,0 +1,146 @@+/**+ * W9F item 7: `gbrain jobs supervisor stop` verifies the drain against the+ * run's own audit rows and real process identity.+ *+ * Protects: a worker pid recycled by an unrelated process (start time differs+ * from the one recorded at spawn) is not "still running"; a supervisor started+ * before the ISO-week boundary keeps its earlier `worker_spawned` rows, so a+ * live worker spawned last week is reported `worker_still_running`, never+ * `drained`; a run with no `started` row on record is `unverified`; a PID file+ * whose pid now belongs to another process is never signaled; audit rows from+ * before exits carried a pid pair with spawns by order, with a warning.+ * Fails when: stop checks every spawn pid of the supervisor pid in the+ * current week's file only (the pre-fix behavior: false `worker_still_running`+ * on a recycled pid, false `drained` across a week boundary or with a pruned+ * audit) or SIGTERMs whatever process holds a stale PID file's pid.+ *+ * The "supervisor" is a `sleep` that exits on SIGTERM; its audit rows are+ * written by the test into a temp GBRAIN_AUDIT_DIR.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { computeSupervisorAuditFilename } from '../src/core/minions/handlers/supervisor-audit.ts';+import { processStartTime } from '../src/core/pglite-lock.ts';++const linuxOnly = process.platform === 'linux' ? describe : describe.skip;+let home: string;+const spawned: Array<ReturnType<typeof Bun.spawn>> = [];++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'sup-stop-identity-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') }));+});+afterAll(() => {+ for (const p of spawned) { try { p.kill('SIGKILL'); } catch { /* gone */ } }+ rmSync(home, { recursive: true, force: true });+});++function sleeper(): number {+ const proc = Bun.spawn({ cmd: ['sleep', '300'], stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' });+ spawned.push(proc);+ return proc.pid;+}+function alive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch { return false; }+}+const WEEK_MS = 7 * 86_400_000;+let caseNo = 0;++/** Writes `weeks[i]` (oldest first, the last entry is this week) to the audit dir and runs stop. */+async function runStop(supervisorPid: number, weeks: Array<Array<Record<string, unknown>>>, pidFileBody = String(supervisorPid)) {+ const auditDir = join(home, `audit-${++caseNo}`);+ mkdirSync(auditDir, { recursive: true });+ const now = Date.now();+ weeks.forEach((rows, i) => {+ if (!rows.length) return;+ const at = new Date(now - (weeks.length - 1 - i) * WEEK_MS);+ writeFileSync(join(auditDir, computeSupervisorAuditFilename(at)),+ rows.map(r => JSON.stringify({ ts: at.toISOString(), supervisor_pid: supervisorPid, ...r })).join('\n') + '\n');+ });+ const pidFile = join(home, `sup-${caseNo}.pid`);+ writeFileSync(pidFile, pidFileBody);+ const result = await runCli(['jobs', 'supervisor', 'stop', '--json', '--pid-file', pidFile],+ { home, timeoutMs: 60_000, env: { GBRAIN_AUDIT_DIR: auditDir } });+ const line = result.stdout.split('\n').find(l => l.startsWith('{'));+ return { exitCode: result.exitCode, payload: line ? JSON.parse(line) : null, stderr: result.stderr };+}++const tail = [{ event: 'shutting_down' }, { event: 'stopped', drained: true }];++linuxOnly('jobs supervisor stop identity and run scope (W9F item 7)', () => {+ test('a recycled worker pid (different start time) does not count as a live worker', async () => {+ const recycled = sleeper();+ const sup = sleeper();+ const out = await runStop(sup, [[+ { event: 'started', queue: 'default' },+ { event: 'worker_spawned', pid: recycled, pid_start: '1' },+ ...tail,+ ]]);+ expect(out.payload?.reason, out.stderr).toBe('drained');+ expect(out.exitCode).toBe(0);+ }, 90_000);++ test('a live worker spawned before the week boundary is still running, not drained', async () => {+ const worker = sleeper();+ const sup = sleeper();+ const out = await runStop(sup, [+ [{ event: 'started', queue: 'default' }, { event: 'worker_spawned', pid: worker, pid_start: processStartTime(worker) }],+ tail,+ ]);+ expect(out.payload?.reason, out.stderr).toBe('worker_still_running');+ expect(out.payload?.live_worker_pids).toEqual([worker]);+ expect(out.exitCode).toBe(1);+ }, 90_000);++ test('weeks of uptime: rows from the run started weeks ago pair across files and drain', async () => {+ const reused = sleeper();+ const sup = sleeper();+ const out = await runStop(sup, [+ [{ event: 'started', queue: 'default' }],+ [{ event: 'worker_spawned', pid: reused, pid_start: '1' }],+ [{ event: 'worker_exited', pid: reused }, { event: 'worker_spawned', pid: 999_999_901 }],+ [{ event: 'worker_exited', pid: 999_999_901 }, ...tail],+ ]);+ expect(out.payload?.reason, out.stderr).toBe('drained');+ expect(out.exitCode).toBe(0);+ }, 90_000);++ test('a run whose started row was pruned is unverified, never drained', async () => {+ const sup = sleeper();+ const out = await runStop(sup, [tail]);+ expect(out.payload?.reason, out.stderr).toBe('unverified');+ expect(out.payload?.drained).toBe(false);+ expect(out.payload?.audit_files).toHaveLength(1);+ expect(out.exitCode).toBe(1);+ }, 90_000);++ test('a stale PID file whose pid belongs to another process is never signaled', async () => {+ const unrelated = sleeper();+ const out = await runStop(unrelated, [], `${unrelated}\n1\n`);+ expect(out.payload?.reason, out.stderr).toBe('stale_pid_file');+ expect(out.payload?.stopped).toBe(false);+ expect(alive(unrelated)).toBe(true);++ const legacyFile = await runStop(unrelated, [[{ event: 'started', queue: 'default', supervisor_start: '1' }]]);+ expect(legacyFile.payload?.reason, legacyFile.stderr).toBe('stale_pid_file');+ expect(alive(unrelated)).toBe(true);+ }, 90_000);++ test('legacy exit rows without a pid pair with spawns by order and warn', async () => {+ const recycled = sleeper();+ const sup = sleeper();+ const out = await runStop(sup, [[+ { event: 'started', queue: 'default' },+ { event: 'worker_spawned', pid: recycled },+ { event: 'worker_exited', code: 0 },+ ...tail,+ ]]);+ expect(out.payload?.reason, out.stderr).toBe('drained');+ expect(out.payload?.warnings).toEqual(['legacy_exit_pairing']);+ expect(out.exitCode).toBe(0);+ }, 90_000);+});