Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-133 2a.4: key-files entries, live-sync guide and behavior notes for the autopilot lane

garrytan85707b8ca1e2
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 0d8706ca75..23e4622acb 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -19,10 +19,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/autopilot-retry-global.ts` — `gbrain autopilot --retry-global [--phase <name>] [--json]` (GBRA-130 A-10): clears `retry_at` on the backed-off phase streaks in `autopilot.global_maintenance.progress` (one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a running `autopilot-global-maintenance` job, whose next progress save can restore the back-off. Test: `test/pathological/a10-global-maintenance-stamp.test.ts`.
- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.
-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value from `automaticSyncPull` (`src/core/persistence/automatic-sync-policy.ts`): a parsed `remote_url` on an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; it also adds `global_maintenance`, the daemon's latest stall verdict (`readGlobalMaintenanceVerdict` in `src/core/minions/global-maintenance-stall.ts`, null when absent or older than a day), and a non-ok verdict turns exit 0 into 1 (`autopilotStatusExitCode(state, stalled)`); see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. `--install` without `--repo` uses `sync.repo_path`, else the default source's `local_path` (`src/commands/autopilot/install-repo.ts`), and refuses when neither is set; pinned by `test/autopilot-install-repo-fallback-6755.test.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value from `automaticSyncPull` (`src/core/persistence/automatic-sync-policy.ts`): a parsed `remote_url` on an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; it also adds `global_maintenance`, the daemon's latest stall verdict (`readGlobalMaintenanceVerdict` in `src/core/minions/global-maintenance-stall.ts`, null when absent or older than a day), and a non-ok verdict turns exit 0 into 1 (`autopilotStatusExitCode(state, stalled)`); see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. `--install` without `--repo` uses `sync.repo_path`, else the default source's `local_path` (`src/commands/autopilot/install-repo.ts`), and refuses when neither is set; pinned by `test/autopilot-install-repo-fallback-6755.test.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`. #7003: `--status` passes the daemon's sidecar verdict (`readDaemonStaleAfter`, `src/core/autopilot-heartbeat.ts`) to `classifyAutopilotStatus` as `daemon`; without a matching sidecar it keeps 6 x `--interval`. `--status --json` adds `stale_after_source` and `next_tick_at`. Tests: `test/pathological/s-7003-autopilot-heartbeat.test.ts` + its Postgres twin.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume, --retry-global; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through `autopilotTargetedSteps` in `autopilot-remediation-policy.ts`, which drops manual-only steps) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
-- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`.
+- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (`recordGlobalMaintenanceStallStatus`, GBRA-130 C-6) that `autopilot --status` reads; a failed write is logged (`global_maintenance_verdict_failed` under `--json`) and leaves the previous verdict to expire. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`. GBRA-133 2a.4: freshness is HEAD-driven. `freshnessTrigger` returns `head` when the checkout's HEAD (`src/core/checkout-head.ts`) differs from `sources.last_commit` and from the HEAD this daemon last decided (`freshnessHeads`), `interval` for the wall-clock backstop, nothing mid-rebase or merge. HEAD jobs use the key `autopilot-sync:<id>:head:<sha>`. `dispatchFreshnessSyncs` returns a `FreshnessDecision` per source. `sleepWatchingHeads`: with `sync.on_commit` on, the Minions-mode sleep probes HEADs every `GBRAIN_AUTOPILOT_HEAD_PROBE_MS` (3 s, 1-30 s; no DB read) and dispatches for moved sources. Tests: `test/pathological/s-autopilot-head-dispatch.test.ts` + its Postgres twin.
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`. `backup create|restore` failures render the agent-operator contract (`storage_error`, fix `gbrain doctor --json`) with the legacy `ok`/`reason`/`message`/`retryable` JSON keys; a message-less thrown value is described only by its bounded name/code/errno (`backupFailureMessage`), never `String(object)`.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index f2d30de8b0..58a3adf7eb 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains. Help (`--help`/`-h`/`help` after any subcommand) prints usage without running it, and `auto` / `reset-progress` take strict arguments (`src/cli/strict-args.ts`). A segmented page is scanned block by block (`bodyLines`, fence state and line numbers carried) with inline-identical hits; an unreadable page goes to `skipped`.
-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke` (`jobs/smoke.ts`) tracks every job it adds to the private `smoke` queue and discards exactly those (cancel if live, then delete) in one `finally` on pass, failure, timeout and throw (`test/jobs-smoke-cleanup.test.ts`); its `--sigkill-rescue`/`--wedge-rescue` cases (W4.9) add a probe under its own job name (`smoke-sigkill-probe`, `smoke-wedge-probe`), move it to `active` through `queue.claim` (the queue protocol trigger refuses a forged transition) and then age only `lock_until`/`started_at` (`timeout_at=NULL` for wedge), so each reaches its rescue verdict. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite). `jobs submit enrich|subagent` runs the paid consent gate and stores an `authorized` spend record on the row; `jobs get --json` adds `spend_basis`, `spend_why` and `spend_group`; `jobs list --group <id>` and `jobs cancel --group <id>` act on one spend group.
+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke` (`jobs/smoke.ts`) tracks every job it adds to the private `smoke` queue and discards exactly those (cancel if live, then delete) in one `finally` on pass, failure, timeout and throw (`test/jobs-smoke-cleanup.test.ts`); its `--sigkill-rescue`/`--wedge-rescue` cases (W4.9) add a probe under its own job name (`smoke-sigkill-probe`, `smoke-wedge-probe`), move it to `active` through `queue.claim` (the queue protocol trigger refuses a forged transition) and then age only `lock_until`/`started_at` (`timeout_at=NULL` for wedge), so each reaches its rescue verdict. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite). `jobs submit enrich|subagent` runs the paid consent gate and stores an `authorized` spend record on the row; `jobs get --json` adds `spend_basis`, `spend_why` and `spend_group`; `jobs list --group <id>` and `jobs cancel --group <id>` act on one spend group. GBRA-133 2a.4 / #7002: on Postgres, `jobs work` starts `startSyncQueueWake` (`src/core/minions/sync-queue-wake.ts`, given `worker.idleWaiter`) before `worker.start()` and stops it in the finally, and calls `startWorkerPersistenceConsumer` (exported from `jobs/work.ts`): `startPersistenceConsumer` at boot through the existing election (service.ts unchanged), so an idle worker runs the persistence consumer, or with `persistence.single_consumer` on waits beside a live owner and promotes when it stops; `engine.disconnect()` stops it. Tests: `test/pathological/s-7002-worker-consumer.test.ts` + its Postgres twin (real `jobs work` processes).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `runJobs` resolves help and the thin-client refusal, builds the queue, then dispatches through `JOBS_SUBCOMMANDS` (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in `src/commands/jobs/<sub>.ts` (`runJobs<Sub>(ctx)`; parsers, formatters and `JobsCommandContext` in `jobs/shared.ts`; `maybeRunWorkerStartupRecovery` in `jobs/work.ts`), all re-exported from `jobs.ts`. Subcommands that register handlers import `registerBuiltinHandlers` lazily from `jobs.ts`. `registerBuiltinHandlers` is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in `src/core/minions/handlers/` (see core-minions-1). Registration names and order are pinned by `test/jobs-handler-registry-golden.test.ts`, which also drives the supervisor's `deriveHandlerNames` probe.
- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker defers it (`JobDeferredError`, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 88a4718ddb..1eb037f64a 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -21,6 +21,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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` in `supervisor-pid.ts`, which also stamps audit rows through `processStartStamp`; 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/idle-wait.ts` — GBRA-133 2a.4: `IdleWaiter`, the worker claim loop's idle poll wait. `wake(reason)` ends a wait in progress; a wake while the loop is claiming makes the next `wait()` a no-op (`skipped`) instead of being lost, and `claimStarted()` clears it. `idle` says whether a wait is in progress; `history` keeps the last 100 waits and how each ended (`timer`, `wake` with its reason, `skipped`, `stop`), the decisions `test/pathological/s-sync-queue-wake.test.ts` asserts on.
+- `src/core/autopilot-heartbeat.ts` — #7003: the autopilot daemon's heartbeat sidecar `autopilot.heartbeat.json` beside the lock (`autopilotHeartbeatPath()` in `src/core/autopilot-paths.ts`), written by `autopilot-daemon.ts` at the top of every tick (phase `cycle`) and before every sleep (phase `sleep`, `next_tick_at`). `daemonStaleAfterSeconds` grades it against the lock: stale once the lock is older than the next tick plus max(base interval, 120 s), or 6 x the daemon's base interval mid-cycle; null (the caller's flag rule) for a missing sidecar, one from another pid than the lock, or one older than the lock. `readDaemonStaleAfter` reads the lock's mtime and pid and applies it for `gbrain autopilot --status`. Tests: `test/pathological/s-7003-autopilot-heartbeat.test.ts` + its Postgres twin.
+- `src/core/checkout-head.ts` — GBRA-133 2a.4: `readCheckoutHead(root)` for the autopilot HEAD probe: the git directory from the checkout's own `.git` entry (`enclosingGitMetadata`, `src/core/persistence/root-registry.ts`), one bounded `git rev-parse HEAD` (`execFileBounded`, 5 s, `GIT_OPTIONAL_LOCKS=0`), and which `GIT_OPERATION_MARKERS` entry (rebase, merge, cherry-pick, revert) is present. Null when git cannot read HEAD.
+- `src/core/minions/sync-queue-wake.ts` — GBRA-133 2a.4: wakes an idle `gbrain jobs work` claim loop when a `sync` job turns `waiting` in its queue. `chooseSyncQueueWake(engine, env)` picks `listen` only on a detected direct session (the engine's dual-pool direct route, or a pool whose `prepare` is not off, read through `consumerConnectionRoute` in persistence/consumer-lane.ts), `poll` behind a transaction pooler or an unknown pooler mode, `off` on PGLite or with `GBRAIN_WORKER_SYNC_WAKE=0`. `startSyncQueueWake` LISTENs on the `minion_jobs` channel (the schema's `notify_minion_job_change` trigger) and requires a probe NOTIFY to arrive within 3 s, else it polls; the poll reads one `minion_jobs` row every `GBRAIN_WORKER_SYNC_WAKE_POLL_MS` (default 1 s, 250 ms-5 s) only while the worker is idle. It logs one line naming the mode and never throws; the worker's own poll stays the backstop. Tests: `test/pathological/s-sync-queue-wake.test.ts` + `test/e2e/s-sync-queue-wake-postgres.test.ts` (listed in `scripts/e2e-backend-matrix.txt`, so it also runs through PgBouncer).
- `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`.
- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent `get_page` with `include_content: true` is forced to `content_only: true`, so the body arrives once (as `content`) instead of also as parsed `compiled_truth`/`timeline`. `BuildBrainToolsOpts.readBudgetBytes` (from trusted `SubagentHandlerData.read_budget_bytes`) routes `get_page` results through `read-budget.ts`. #6779: a subagent `put_page` refused `revision_required` names the page's current revision (`rethrowWithCurrentRevision` in `put-page-result.ts`); MCP and CLI callers keep the bare refusal.
@@ -37,6 +41,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.
- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.
-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired). Each `inFlight` entry carries `shared` (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to `settleWatchdogAbort` (back to `waiting` uncharged, marked to run alone), so only a job that ran alone is charged `aborted: watchdog`, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job.
+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired). Each `inFlight` entry carries `shared` (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to `settleWatchdogAbort` (back to `waiting` uncharged, marked to run alone), so only a job that ran alone is charged `aborted: watchdog`, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job. GBRA-133 2a.4: the idle poll wait (nothing claimed, nothing in flight) goes through `idleWaiter` (`src/core/minions/idle-wait.ts`), which the sync-queue wake ends early; `claimStarted()` runs right before each claim, and `stop()` and `requestShutdown()` end the wait at once.
- `src/core/minions/watchdog-attribution.ts` — RSS watchdog attribution (GBRA-130 A-30). The watchdog measures the whole worker process, so a drain with several jobs in flight cannot name the job that grew: `settleWatchdogAbort` requeues each such job token-fenced with no attempt burned (`error_text` `WATCHDOG_DRAIN_RELEASE`) and appends `WATCHDOG_SUSPECT_MARK` once to its `stacktrace`, the job's durable history; a job that ran alone is marked and its caller charges it. An isolated child whose stop is unconfirmed, or any error during the release, leaves the claim to the stall sweep. `unmarkedJobSql` is the claim filter. `requeueCoRunnerStalls` requeues, marked and with no stall counted, the stalled claims of a worker that held other expired claims (lock tokens share the `<worker id>:` prefix, or a co-runner was already requeued with `worker_stalled_with_co_runners: <worker id>`); a marked or lone job's stall counts as before, so a kernel OOM kill gets the same attribution. Doctor's watchdog-kill counts (`error_text = 'aborted: watchdog'` on dead/failed rows) therefore count only jobs charged for a solo trip. Pinned by `test/pathological/a30-watchdog-attribution.test.ts` (both engines) and `test/worker-shutdown-error-matrix.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index bea0fc2ed6..df1f54ee01 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -167,6 +167,11 @@ therefore prefers one full consumer per host:
`sources`, `cli`) keep their own consumer for the life of their write, because
the owner's wake is in-process only and a waiter-only `gbrain put` would often
return `writer_pending`.
+- An idle `gbrain jobs work` on Postgres starts its consumer at boot (#7002),
+ not on its first job, so it takes over queued writes and effects when the
+ `serve` on the host stops. With `persistence.single_consumer` off, a worker
+ beside a `serve` runs its own full consumer, as every resident process does,
+ and doctor lists the pair as `two_consumers_on_host`.
- This is a preference, not a fenced role. Two processes that start within one
heartbeat of each other can both start full, and a sync CLI that took its
consumer before the `serve` started keeps it for that run; doctor reports the
@@ -292,6 +297,30 @@ on repeated failures.
gbrain sync --watch --repo /data/brain
```
+### Autopilot and the jobs worker
+
+The autopilot daemon reads every checkout's HEAD at each tick and queues a
+sync when it differs from the commit the source last synced, once per HEAD,
+never in the middle of a rebase or merge; a source whose last sync is older
+than `--interval` is still synced as a backstop. With `sync.on_commit` on, the
+daemon also reads HEADs between ticks (every 3 s, git only;
+`GBRAIN_AUTOPILOT_HEAD_PROBE_MS`, 1 to 30 s), so a commit is queued within
+seconds instead of at the next tick (150 to 600 s).
+
+A `gbrain jobs work` worker picks up a queued sync job at once: it LISTENs for
+queued sync jobs when its database URL is a direct session, and reads the sync
+queue every second (`GBRAIN_WORKER_SYNC_WAKE_POLL_MS`, 250 ms to 5 s) behind a
+transaction pooler (port 6543 or `?prepare=false`), where LISTEN does not
+work. Its startup line names the mode (`sync-queue wake: listen (direct_session)`
+or `sync-queue wake: poll every 1000 ms (transaction_pooler)`);
+`GBRAIN_WORKER_SYNC_WAKE=0` turns the wake off and leaves the 5 s idle poll.
+
+`gbrain autopilot --status` grades the daemon from its own next tick, written
+to `autopilot.heartbeat.json` beside the lock (#7003); `--status --json`
+names the source of the threshold in `stale_after_source` (`daemon`, or `flag`
+when the sidecar is missing or from an older daemon, which falls back to
+6 x `--interval`).
+
### Approach 3: Git Hook / Webhook
Triggers sync on push events for instant sync (<5s).
diff --git a/llms-full.txt b/llms-full.txt
index 97f0273a8a..9e2cc2e23a 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6927,6 +6927,11 @@ therefore prefers one full consumer per host:
`sources`, `cli`) keep their own consumer for the life of their write, because
the owner's wake is in-process only and a waiter-only `gbrain put` would often
return `writer_pending`.
+- An idle `gbrain jobs work` on Postgres starts its consumer at boot (#7002),
+ not on its first job, so it takes over queued writes and effects when the
+ `serve` on the host stops. With `persistence.single_consumer` off, a worker
+ beside a `serve` runs its own full consumer, as every resident process does,
+ and doctor lists the pair as `two_consumers_on_host`.
- This is a preference, not a fenced role. Two processes that start within one
heartbeat of each other can both start full, and a sync CLI that took its
consumer before the `serve` started keeps it for that run; doctor reports the
@@ -7052,6 +7057,30 @@ on repeated failures.
gbrain sync --watch --repo /data/brain
```
+### Autopilot and the jobs worker
+
+The autopilot daemon reads every checkout's HEAD at each tick and queues a
+sync when it differs from the commit the source last synced, once per HEAD,
+never in the middle of a rebase or merge; a source whose last sync is older
+than `--interval` is still synced as a backstop. With `sync.on_commit` on, the
+daemon also reads HEADs between ticks (every 3 s, git only;
+`GBRAIN_AUTOPILOT_HEAD_PROBE_MS`, 1 to 30 s), so a commit is queued within
+seconds instead of at the next tick (150 to 600 s).
+
+A `gbrain jobs work` worker picks up a queued sync job at once: it LISTENs for
+queued sync jobs when its database URL is a direct session, and reads the sync
+queue every second (`GBRAIN_WORKER_SYNC_WAKE_POLL_MS`, 250 ms to 5 s) behind a
+transaction pooler (port 6543 or `?prepare=false`), where LISTEN does not
+work. Its startup line names the mode (`sync-queue wake: listen (direct_session)`
+or `sync-queue wake: poll every 1000 ms (transaction_pooler)`);
+`GBRAIN_WORKER_SYNC_WAKE=0` turns the wake off and leaves the 5 s idle poll.
+
+`gbrain autopilot --status` grades the daemon from its own next tick, written
+to `autopilot.heartbeat.json` beside the lock (#7003); `--status --json`
+names the source of the threshold in `stale_after_source` (`daemon`, or `flag`
+when the sidecar is missing or from an older daemon, which falls back to
+6 x `--interval`).
+
### Approach 3: Git Hook / Webhook
Triggers sync on push events for instant sync (<5s).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9347a38d1b..ee1d24cdc4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -912,6 +912,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.309.0', text: 'A brain without an embedding provider no longer queues embed-backfill jobs; one already queued ends once with the notice `embed_backfill_skipped`. A managed sync job submitted without pull options imports the checkout HEAD instead of failing permanently. A mention whose link target is not a valid slug is skipped instead of failing the links effect (#7008).' },
{ since: '0.60.309.0', text: '`gbrain backup check` reads a dirty tree as dirty however long its status listing is (a listing over 1 MiB used to read `probe_failed`), the remote probe timeout is configurable with `backup.remote_timeout_ms` (or GBRAIN_BACKUP_REMOTE_TIMEOUT_MS, 0.5 to 30 s, default 2 s), and a timed-out probe is counted in `totals.remote_timeouts` and named as a timeout, not as a missing backup (#6907).' },
{ since: '0.60.309.0', text: 'Managed dream synthesis counts a transcript a pre-managed run already synthesised as done while a dream-generated page naming that transcript still exists in the same source, so upgrading to managed mode no longer re-synthesises old transcripts (#6924).' },
+ { since: '0.60.309.0', text: 'The autopilot daemon dispatches a freshness sync when a checkout\'s HEAD differs from the commit its source last synced, at the next tick instead of after the 5-minute wall-clock interval (which stays as the backstop), once per HEAD and never in the middle of a rebase or merge; classic and managed sources alike. With `sync.on_commit` on, the daemon also reads every checkout\'s HEAD between ticks (every 3 s, git only; `GBRAIN_AUTOPILOT_HEAD_PROBE_MS`) and queues the sync within seconds.' },
+ { since: '0.60.309.0', text: 'On Postgres, `gbrain jobs work` starts a persistence consumer at boot (#7002), so queued persistence effects drain after a `serve` stops even while the worker is idle. It joins the existing election: with `persistence.single_consumer` on it waits beside a live owner and takes over when that owner stops; with the switch off (the default) a worker beside a `serve` runs its own full consumer, as every resident process already does, and doctor `two_consumers_on_host` lists it. A queued sync job now wakes an idle worker at once: LISTEN on a direct session (one extra connection), a 1 s sync-queue read behind a transaction pooler; `GBRAIN_WORKER_SYNC_WAKE=0` turns it off.' },
+ { since: '0.60.309.0', text: '`gbrain autopilot --status` grades a running daemon from its own schedule (#7003): the daemon writes `autopilot.heartbeat.json` beside its lock with its next tick, so a healthy daemon on a long adaptive sleep no longer reads `stale` (exit 1); a missing or outdated sidecar falls back to the interval-flag rule. `--status --json` adds `stale_after_source` (`daemon` or `flag`) and `next_tick_at`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */