Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(minions): every long-running process reports its build; doctor runtime_build_skew; job children record or refuse a skewed build (#7245)
garrytane8924f426de2
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex c85b5a5c63..fa89180284 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -11,6 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. `serve_build_drift` (#6696 C6, its own `serveBuildDriftEntry`, one `listHostConsumers` read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's `VERSION` through `compareWriterVersions` (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with `details { count, this_version, owner, older, newer }` and a `fix` (actor `user`, `doctorVerify`) whose argv is the installed serve service's restart (`systemctl --user restart gbrain-serve.service` when `systemdUnitPath` exists on Linux, `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when `launchdPlistPath` exists on macOS; `serveBuildDriftCheck`'s `ServiceHost` argument injects platform, home and uid) or else `kill <pid>`; a newer row is reported in an ok message; no rows names `consumers_without_heartbeat` for a pre-heartbeat serve. Registered in `DOCTOR_CHECK_REGISTRY` (the consumer entry, then `serveBuildDriftEntry`) before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`. Tests: `test/doctor-serve-build-drift.test.ts`.+- `src/commands/doctor/checks/runtime-build-skew.ts` — #7245: doctor `runtime_build_skew` (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), worker parents from the worker registry (`version`, `install_root`), the supervisor from its PID file (`readSupervisorBuild`), and job-child builds from `job_build_skew:` history entries on the newest 500 jobs updated in the last 24 h, counted only while their worker pid is live. Warns when the running builds differ or a process's install now holds another version; the fix restarts serve (`restartArgv`, exported from persistence-consumers.ts), else the supervisor (`gbrain jobs supervisor stop`), else a worker pid. Output carries pids and versions only. Pinned by `test/doctor-runtime-build-skew.test.ts`.- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex eb8681ccd6..169696eca7 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/refusal.ts` — #7239: `jobRefusal(err)` decides whether a handler error is a deterministic refusal from its error-registry code: a site `retryable` wins, else a caller/consent/host_only code the registry does not mark retryable, except the concurrency codes (`revision_conflict`, `page_identity_changed`, `concurrent_write`); classes retryable/server/unavailable, unregistered codes and code-less errors are not (a code-less error is looked through to its `cause`; other `UnrecoverableError`s keep their own path). The worker's executeJob catch and the dream inline drain end such a job `dead` after one attempt with `refusedJobResult` (`job_outcome: 'refused'`, `refusal: {code, reason, message, fix, docs_cmd}`); the suggestion prose is never stored (job rows are served remotely). Across the per-job child boundary it travels as errorKind `refused` and is rebuilt as `JobRefusedError` (errors.ts). Tests: `test/minions-refusal-7239.test.ts`.- `src/core/minions/rss-default.ts` — cgroup-aware auto-sized default for the worker RSS watchdog cap. `resolveDefaultMaxRssMb(opts?)` / `describeDefaultMaxRss(opts?)` (provenance for the startup log) / `readCgroupMemLimitBytes(readFile?)`. Used at every spawn site (`jobs work`, `jobs supervisor`, autopilot, `MinionSupervisor`). Formula `clamp(round(0.5 × basisMB), 4096, 16384)` where `basis = min(cgroupLimit, totalmem)`. LOAD-BEARING NUANCE: plain `os.totalmem()` reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 `/sys/fs/cgroup/memory.max` (literal `max` = unlimited) then v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Explicit `--max-rss` (including `0` to disable) always wins. Pinned by `test/rss-default.test.ts`.-- `src/core/minions/run-child.ts` — `runChildJobEntry(engine, opts, injectables)`: the `jobs run-child` core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler under `runWithJobSpend` (the job's spend authorization), writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling `process.kill(parentPid, 0)` (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by `test/run-child-entry.test.ts`.+- `src/core/minions/run-child.ts` — `runChildJobEntry(engine, opts, injectables)`: the `jobs run-child` core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler under `runWithJobSpend` (the job's spend authorization), writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling `process.kill(parentPid, 0)` (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by `test/run-child-entry.test.ts`. #7245: before the handler it compares its build with the worker's (`parentBuild`, the `GBRAIN_JOB_PARENT_BUILD` env `runJobInChild` sets from `parentBuildEnvValue`) through `jobChildBuildVerdict` (`child-readiness.ts`): a differing version runs, with one `job_build_skew:` history entry and one stderr line; a readiness-protocol mismatch or a required feature the child lacks writes the entry and a `child_protocol_incompatible` configuration outcome (exit 16) without running the handler, so the worker blocks for configuration as the startup handshake does. A worker that sends no build (older) gets no comparison. Pinned by `test/runtime-build-skew-7245.test.ts`.- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/subagent-stop-reason.ts` — the one home of the subagent handler's stop-reason mapping (#6448 items 2/3): `isEmptyFinalText` (empty or whitespace-only text); `directStopReason` for the Messages path (`max_tokens` → `max_tokens`, `refusal` → `refusal`, a clean stop whose final text is empty → `error`); `gatewayStopReason` for `toolLoop` (`length` → `max_tokens`, `refusal`/`content_filter` → `refusal`, `empty_response`/`aborted`/`unrecoverable` → `error`, `end` → `end_turn`); `replayTerminalStopReason` for a persisted terminal turn (`tokens_out >= cap` → `max_tokens`, empty text → `error`, else `end_turn`). On both replay paths in `handlers/subagent.ts` ANY trailing assistant turn without tool calls is terminal, text or not, so a thinking-only or empty tail is answered from the transcript instead of being re-sent as an assistant prefill; the gateway's `empty_response` stop reason is additive (`gateway.ts` `ToolLoopStopReason`). Pinned by `test/subagent-stop-reason-6448.test.ts` and `test/subagent-stop-reason-helper.test.ts`.- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_WHERE` is the claim gate's predicate, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under a hash of the filter and the snapshot digest with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.-- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running, host?}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. `pidFileContents(pid, host = hostname())` writes three lines: the pid, the kernel start time (empty when unknown; `jobs supervisor stop` reads it as the recycled-pid fence) and, since PR #6463, the hostname the supervisor puts in its DB lock, which `readSupervisorPid` returns as `host` (absent on an older two-line file). Pinned by `test/supervisor-pid.test.ts`, `test/supervisor-singleton-host-6463.test.ts`.+- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running, host?}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. `pidFileContents(pid, host = hostname())` writes three lines: the pid, the kernel start time (empty when unknown; `jobs supervisor stop` reads it as the recycled-pid fence) and, since PR #6463, the hostname the supervisor puts in its DB lock, which `readSupervisorPid` returns as `host` (absent on an older two-line file). Pinned by `test/supervisor-pid.test.ts`, `test/supervisor-singleton-host-6463.test.ts`. #7245: lines 4 and 5 are the supervisor's gbrain VERSION and the package root it loaded from (empty in a compiled binary); `readSupervisorBuild` reads them (null for an older file) and `readSupervisorPid` stays unchanged.- `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`.@@ -39,7 +39,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12` and `WORKER_EXIT_CONFIGURATION = 16`; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).-- `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. Only a missing directory (ENOENT) reads as no workers; any other listing failure throws `WorkerRegistryUnreadableError` (errno + path, read with `workerRegistryReadFailure`), and every liveness consumer reports unknown instead of zero: doctor `queue_health` (`worker_alive: null`, no start-a-worker fix) and `wedged_queue`, `legacy_job_authority` (`live_workers: null`), `jobs supervisor status` (`workers: null`), the submit-time `probeQueueState` (`worker_alive` omitted, liveness-unknown warning), the `migrate-embeddings` writer census (`workers: null`) and the readiness worker probe (`probe_failed`); each carries `worker_registry_unreadable`, `worker_registry_errno` and `worker_registry_path`. Pinned by `test/worker-registry.serial.test.ts`.+- `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. Only a missing directory (ENOENT) reads as no workers; any other listing failure throws `WorkerRegistryUnreadableError` (errno + path, read with `workerRegistryReadFailure`), and every liveness consumer reports unknown instead of zero: doctor `queue_health` (`worker_alive: null`, no start-a-worker fix) and `wedged_queue`, `legacy_job_authority` (`live_workers: null`), `jobs supervisor status` (`workers: null`), the submit-time `probeQueueState` (`worker_alive` omitted, liveness-unknown warning), the `migrate-embeddings` writer census (`workers: null`) and the readiness worker probe (`probe_failed`); each carries `worker_registry_unreadable`, `worker_registry_errno` and `worker_registry_path`. Pinned by `test/worker-registry.serial.test.ts`. #7245: each entry also carries `version` (VERSION in memory) and `install_root` (`runtimeInstallRoot()`, a local path that no remote output carries); doctor `runtime_build_skew` reads both.+- `src/core/runtime-build.ts` — #7245: `runtimeInstallRoot()` (the package root this process loaded from; null without a readable package.json, as in a compiled binary), `installedVersion(root)` (the `gbrain` package.json version on disk now) and `serveBuild()` (`{version, installed_version, restart_pending}` for `/health`, disk read cached 10 s, never a path).- `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. 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.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex aa08e90a46..395cecfe2d 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3499,6 +3499,16 @@ More: [docs/guides/windowed-reads.md#revision_changed](../../docs/guides/windowe|---|---|---|---|---|---|---|| The exact authorized revision is unavailable. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### runtime_build_skew++<a id="runtime_build_skew"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Long-running gbrain processes on this host run different builds, or one runs an older build than its install holds on disk: serve, the jobs supervisor, worker parents (in memory) and the job children they spawn from the install (on disk). | A process keeps the code it loaded at start, and `gbrain jobs run-child` spawns a fresh process from the install on disk for every job, so after a checkout reset or an upgrade on disk newer job code runs under an older worker and next to an older serve until each process restarts. | Restart the process the check names (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid so its supervisor respawns it), then each other listed process on an older build; nothing restarts automatically. Run: gbrain doctor --only runtime_build_skew --json | agent | `gbrain doctor --only runtime_build_skew --json` | 1 | no |++More: [docs/guides/troubleshooting.md#runtime-build-skew](../../docs/guides/troubleshooting.md#runtime-build-skew)+### schema_lock_blocked<a id="schema_lock_blocked"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex f2155e7851..a053720d26 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -51,6 +51,7 @@| [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` || [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` || [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |+| [Doctor warns `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | restart the process the check names with the command it prints (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid), then each other process listed on an older build | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok || [Doctor warns `host_identity_mismatch`, or maintenance jobs report `owner_unavailable` / `host_mismatch` for weeks](#host-identity-mismatch) | set `GBRAIN_HOME` on that process's supervisor to the value the check prints (the owner's home; config appends `.gbrain` itself) and restart it; never edit or delete a `host.json` | brain host, after the user agrees | `persistent_install` when it rewrites a service definition | `gbrain doctor --only host_identity_mismatch --json` || [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner || [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |@@ -173,6 +174,8 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.+<a id="runtime-build-skew"></a>**Doctor warns `runtime_build_skew` (several gbrain builds are running on this host)?** Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It warns when the running builds differ, or when a process's install now holds another build than the one it runs, and lists every process with its pid and version (never a path). The fix names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.+<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.diff --git a/llms-full.txt b/llms-full.txtindex 085c0d3850..0ef8b16291 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10461,6 +10461,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` || [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` || [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |+| [Doctor warns `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | restart the process the check names with the command it prints (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid), then each other process listed on an older build | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok || [Doctor warns `host_identity_mismatch`, or maintenance jobs report `owner_unavailable` / `host_mismatch` for weeks](#host-identity-mismatch) | set `GBRAIN_HOME` on that process's supervisor to the value the check prints (the owner's home; config appends `.gbrain` itself) and restart it; never edit or delete a `host.json` | brain host, after the user agrees | `persistent_install` when it rewrites a service definition | `gbrain doctor --only host_identity_mismatch --json` || [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner || [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |@@ -10583,6 +10584,8 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.+<a id="runtime-build-skew"></a>**Doctor warns `runtime_build_skew` (several gbrain builds are running on this host)?** Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It warns when the running builds differ, or when a process's install now holds another build than the one it runs, and lists every process with its pid and version (never a path). The fix names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.+<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.tsindex a9cbdbee3c..c7c96c8f62 100644--- a/src/commands/doctor/checks/persistence-consumers.ts+++ b/src/commands/doctor/checks/persistence-consumers.ts@@ -109,7 +109,7 @@ export async function hostIdentityMismatchCheck(engine: BrainEngine): Promise<Chexport interface ServiceHost { platform: string; home: string; uid: number }/** The restart for one consumer: the installed serve service's own command, else stopping that pid for its supervisor or operator to start again. */-function restartArgv(row: ListedConsumer, service: ServiceHost): string[] {+export function restartArgv(row: Pick<ListedConsumer, 'kind' | 'pid'>, service: ServiceHost): string[] {if (row.kind === 'serve' && service.platform === 'darwin' && existsSync(launchdPlistPath(service.home))) return ['launchctl', 'kickstart', '-k', `gui/${service.uid}/${SERVE_LAUNCHD_LABEL}`];if (row.kind === 'serve' && service.platform === 'linux' && existsSync(systemdUnitPath(service.home))) return ['systemctl', '--user', 'restart', SERVE_SYSTEMD_UNIT];return ['kill', String(row.pid)];diff --git a/src/commands/doctor/checks/runtime-build-skew.ts b/src/commands/doctor/checks/runtime-build-skew.tsnew file mode 100644index 0000000000..26c5203292--- /dev/null+++ b/src/commands/doctor/checks/runtime-build-skew.ts@@ -0,0 +1,147 @@+/**+ * #7245: doctor `runtime_build_skew`. Each long-running gbrain process keeps+ * the code it loaded at start, while `gbrain jobs run-child` spawns a fresh+ * process from the install on disk for every job, so after a checkout reset or+ * an upgrade on disk one host can run several builds at once: serve on one, the+ * supervisor and worker parents on another (in memory), job children on a third+ * (from disk). `serve_build_drift` compares the consumer heartbeat rows with+ * this binary only; this check compares the running processes with each other+ * and with the build each one's install holds on disk now:+ *+ * - serve and the other resident consumers: their `persistence_consumers`+ * heartbeat `version` (Postgres; PGLite keeps none);+ * - the jobs supervisor: lines 4-5 of its PID file (`readSupervisorBuild`);+ * - worker parents (`gbrain jobs work`, autopilot-spawned ones included): the+ * `version` and `install_root` of their worker-registry entries;+ * - job children: the `job_build_skew:` history entry a child writes when its+ * build differs from its worker's (`jobChildBuildVerdict`), on the newest 500+ * jobs of the last 24 h, counted while that worker is still alive.+ *+ * Read-only. It warns with the processes and versions involved and names one+ * restart (serve first, then the supervisor, then a worker); nothing restarts+ * automatically. Output carries pids and versions only, never a path.+ */+import { homedir } from 'node:os';+import type { Check } from '../../doctor.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import { listHostConsumers, RESIDENT_CONSUMER_KINDS } from '../../../core/persistence/consumer-heartbeat.ts';+import { localHostIdentity } from '../../../core/persistence/identity.ts';+import { compareWriterVersions } from '../../../core/persistence/writer-versions.ts';+import { installedVersion } from '../../../core/runtime-build.ts';+import { JOB_BUILD_SKEW_PREFIX } from '../../../core/minions/child-readiness.ts';+import { readWorkers, type WorkerRegistryEntry } from '../../../core/minions/worker-registry.ts';+import { readSupervisorBuild, readSupervisorPid } from '../../../core/minions/supervisor-pid.ts';+import { checkError, doctorVerify } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { restartArgv, type ServiceHost } from './persistence-consumers.ts';++const DOCS = 'docs/guides/troubleshooting.md#runtime-build-skew';+const CHILD_WINDOW_HOURS = 24;+const CHILD_SCAN_JOBS = 500;+const ROLE_ORDER = ['serve', 'supervisor', 'worker'];++export interface RunningBuild { role: string; pid: number; version: string | null; installed_version: string | null }+export interface ChildBuild { job_id: number; child_version: string; worker_pid: number; worker_version: string; refused: boolean }++export interface RuntimeBuildSources {+ workers: () => Array<Pick<WorkerRegistryEntry, 'pid' | 'version' | 'install_root'>>;+ supervisor: () => Promise<{ pid: number; version: string | null; install_root: string | null } | null>;+ installedVersion: (root: string | null | undefined) => string | null;+}++const CHILD_LINE = new RegExp(`^${JOB_BUILD_SKEW_PREFIX} job child v(\\S+) (ran|refused to run) under worker pid (\\d+) v([0-9.]+)`);++const defaultSources: RuntimeBuildSources = {+ workers: () => readWorkers(() => null),+ supervisor: async () => {+ const { DEFAULT_PID_FILE } = await import('../../../core/minions/supervisor.ts');+ const status = readSupervisorPid(DEFAULT_PID_FILE);+ if (!status.running || status.pid === null) return null;+ const build = readSupervisorBuild(DEFAULT_PID_FILE);+ return { pid: status.pid, version: build?.version ?? null, install_root: build?.install_root ?? null };+ },+ installedVersion,+};++async function recentChildBuilds(engine: BrainEngine): Promise<ChildBuild[]> {+ const rows = await engine.executeRaw<{ id: number; line: string }>(+ `SELECT j.id, e.line FROM (+ SELECT id, stacktrace FROM minion_jobs+ WHERE jsonb_typeof(stacktrace) = 'array' AND updated_at > now() - interval '${CHILD_WINDOW_HOURS} hours'+ ORDER BY id DESC LIMIT ${CHILD_SCAN_JOBS}) j+ CROSS JOIN LATERAL jsonb_array_elements_text(j.stacktrace) AS e(line)+ WHERE e.line LIKE $1`, [`${JOB_BUILD_SKEW_PREFIX}%`]);+ return rows.flatMap(row => {+ const match = CHILD_LINE.exec(row.line);+ return match ? [{ job_id: Number(row.id), child_version: match[1]!, worker_pid: Number(match[3]), worker_version: match[4]!, refused: match[2] === 'refused to run' }] : [];+ });+}++const label = (p: RunningBuild) => `${p.role} pid ${p.pid} v${p.version}${p.installed_version && p.installed_version !== p.version ? ` (its install now holds v${p.installed_version})` : ''}`;++function restartFor(target: RunningBuild, service: ServiceHost): string[] {+ if (target.role === 'supervisor') return ['gbrain', 'jobs', 'supervisor', 'stop'];+ return restartArgv({ kind: target.role, pid: target.pid }, service);+}++export async function runtimeBuildSkewCheck(engine: BrainEngine, hostId: string, sources: RuntimeBuildSources = defaultSources,+ service: ServiceHost = { platform: process.platform, home: homedir(), uid: process.getuid?.() ?? 501 }): Promise<Check> {+ try {+ const byPid = new Map<number, RunningBuild>();+ for (const row of await listHostConsumers(engine, hostId)) {+ if (row.liveness !== 'live' || row.self || !RESIDENT_CONSUMER_KINDS.includes(row.kind)) continue;+ byPid.set(row.pid, { role: row.kind, pid: row.pid, version: row.version || null, installed_version: null });+ }+ for (const entry of sources.workers()) {+ byPid.set(entry.pid, { role: 'worker', pid: entry.pid, version: entry.version ?? byPid.get(entry.pid)?.version ?? null, installed_version: sources.installedVersion(entry.install_root) });+ }+ const supervisor = await sources.supervisor();+ if (supervisor) byPid.set(supervisor.pid, { role: 'supervisor', pid: supervisor.pid, version: supervisor.version, installed_version: sources.installedVersion(supervisor.install_root) });+ const processes = [...byPid.values()].sort((a, b) => (ROLE_ORDER.indexOf(a.role) + 1 || 99) - (ROLE_ORDER.indexOf(b.role) + 1 || 99) || a.pid - b.pid);+ const children = await recentChildBuilds(engine);+ const liveChildren = children.filter(child => byPid.has(child.worker_pid));+ const versions = new Set<string>([...processes.flatMap(p => p.version ? [p.version] : []), ...liveChildren.map(child => child.child_version)]);+ const newest = [...versions].sort((a, b) => compareWriterVersions(b, a) ?? 0)[0] ?? null;+ const stale = processes.filter(p => p.version && ((newest && (compareWriterVersions(p.version, newest) ?? 0) < 0) || (p.installed_version && p.installed_version !== p.version)));+ const unknown = processes.filter(p => !p.version);+ const details = { count: stale.length, newest, builds: [...versions],+ processes: processes.map(p => ({ role: p.role, pid: p.pid, version: p.version, installed_version: p.installed_version })),+ stale: stale.map(p => ({ role: p.role, pid: p.pid, version: p.version, installed_version: p.installed_version })),+ job_children: liveChildren, earlier_job_children: children.length - liveChildren.length, unknown_builds: unknown.map(p => ({ role: p.role, pid: p.pid })), docs: DOCS };+ const unknownNote = unknown.length ? ` ${unknown.map(p => `${p.role} pid ${p.pid}`).join('; ')} started before builds were recorded; restart it to report one.` : '';+ if (!stale.length) {+ return { name: 'runtime_build_skew', status: 'ok', details,+ message: (processes.length ? `Every long-running gbrain process on this host that records its build runs ${newest ? `v${newest}` : 'an unrecorded build'} (${processes.map(p => `${p.role} pid ${p.pid}`).join('; ')}).`+ : 'No long-running gbrain process (serve, jobs supervisor, worker) is running on this host.') + unknownNote };+ }+ const target = stale[0]!;+ const argv = restartFor(target, service);+ const childLines = [...new Map(liveChildren.map(c => [`${c.worker_pid}|${c.child_version}|${c.refused}`, c])).values()].map(c => {+ const jobs = liveChildren.filter(o => o.worker_pid === c.worker_pid && o.child_version === c.child_version && o.refused === c.refused).map(o => `#${o.job_id}`);+ return `job children of worker pid ${c.worker_pid} ${c.refused ? 'refused to run' : 'ran'} v${c.child_version} (jobs ${jobs.slice(0, 5).join(', ')}${jobs.length > 5 ? `, +${jobs.length - 5} more` : ''})`;+ });+ const restartHow = target.role === 'supervisor' ? ' and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk)'+ : argv[0] === 'kill' ? ' (SIGTERM: it drains its jobs; a supervisor respawns a worker from the install on disk) and start it again the way it was launched if nothing supervises it' : '';+ return { name: 'runtime_build_skew', status: 'warn', details,+ message: `runtime_build_skew: ${versions.size > 1 ? `${versions.size} gbrain builds are running on this host` : 'a gbrain process runs an older build than its install'} (newest v${newest}): `+ + `${processes.filter(p => p.version).map(label).join('; ')}${childLines.length ? `; ${childLines.join('; ')}` : ''}. `+ + 'A process keeps the build it started with, and every job child it spawns runs the build its install holds on disk now. '+ + `Restart with \`${argv.join(' ')}\`${restartHow}, then restart each other process listed on an older build; nothing restarts automatically.${unknownNote}`,+ fix: { argv, consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('runtime_build_skew'), docs: DOCS,+ why: `Restarts ${label(target)} on the build its install holds (v${target.installed_version ?? newest}); restart every other listed process the same way.` } };+ } catch (error) {+ return checkError('runtime_build_skew', 'read the builds of this host\'s gbrain processes', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } });+ }+}++async function runRuntimeBuildSkew(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push(await runtimeBuildSkewCheck(connectedEngine(ctx), localHostIdentity().id));+ return checks;+}++export const runtimeBuildSkewEntry: DoctorEntry = {+ name: 'runtime_build_skew',+ emits: ['runtime_build_skew'],+ run: runRuntimeBuildSkew,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 567a6a7615..3abbac43b3 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -93,6 +93,7 @@ import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { grantNewOpsEntry } from './checks/grant-new-ops.ts';import { linksExtractionLagEntry, syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';+import { runtimeBuildSkewEntry } from './checks/runtime-build-skew.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';@@ -258,6 +259,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [trustSourcesUnclaimedEntry,coreMemoryEntry,persistenceConsumersEntry,+ runtimeBuildSkewEntry,atomHeldFailedEntry,extractionInputTruncatedEntry,ghostPagesEntry,diff --git a/src/commands/jobs/run-child.ts b/src/commands/jobs/run-child.tsindex 0df1ea25aa..371b7974d4 100644--- a/src/commands/jobs/run-child.ts+++ b/src/commands/jobs/run-child.ts@@ -5,6 +5,7 @@ import { JOB_CHILD_EXIT_USAGE } from '../../core/minions/worker-exit-codes.ts';import { CHILD_ENV } from '../../core/minions/job-isolation.ts';import { MinionWorker } from '../../core/minions/worker.ts';import { runChildJobEntry, writeChildBootstrapError } from '../../core/minions/run-child.ts';+import { CHILD_PARENT_BUILD_ENV } from '../../core/minions/child-readiness.ts';export async function runJobsRunChild({ args, engine }: JobsCommandContext): Promise<void> {// Lazy: jobs.ts imports this module statically, so a static import back would be a cycle.@@ -52,6 +53,7 @@ export async function runJobsRunChild({ args, engine }: JobsCommandContext): ProlockToken,resultPath,parentPid: Number.isInteger(parentPidRaw) && parentPidRaw > 0 ? parentPidRaw : 0,+ parentBuild: process.env[CHILD_PARENT_BUILD_ENV],},{ resolveHandler: (name) => throwaway.getHandler(name) },);diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.tsindex 2f83812b14..c44b542e5e 100644--- a/src/commands/serve-http-metrics.ts+++ b/src/commands/serve-http-metrics.ts@@ -28,6 +28,7 @@ import { persistenceConsumerStatus } from '../core/persistence/service.ts';import { readCheckpointBlockerMap, readTerminalFailureSummary, type TerminalSourceSummary, type TerminalSummary } from '../core/persistence/terminal-failures.ts';import { consumerRestartRequired, selfExitSuppressed, serveTransport, type ServeTransport } from './serve-health.ts';import { VERSION } from '../version.ts';+import { serveBuild } from '../core/runtime-build.ts';import type { ServeHttpContext } from './serve-http.ts';export interface MetricsCounters {@@ -368,7 +369,11 @@ export async function probeDeepHealth(return { ok: true, status: 200, body: { status: 'ok', deep: true, version, engine: engineName, probe_ms: Date.now() - started, pool: pool(), transport } };}-/** GET /health: liveness only (full stats are the admin-only /admin/api/full-stats); `?deep=1` probes through the ordinary pool. */+/**+ * GET /health: liveness only (full stats are the admin-only /admin/api/full-stats); `?deep=1` probes through the ordinary pool.+ * #7245: a 200 carries `build` (this serve's version and the version its install holds on disk now, never a path), so a+ * serve that kept running an old build after an upgrade on disk says `restart_pending: true` while it stays healthy.+ */export function mountHealth(app: Express, ctx: ServeHttpContext): void {const { engine, config } = ctx;// ---------------------------------------------------------------------------@@ -380,7 +385,7 @@ export function mountHealth(app: Express, ctx: ServeHttpContext): void {const result = deep === '1' || deep === 'true'? await probeDeepHealth(engine, config.engine || 'pglite', VERSION): await probeLiveness(engine, config.engine || 'pglite', VERSION);- res.status(result.status).json(result.body);+ res.status(result.status).json(result.ok ? { ...result.body, build: serveBuild() } : result.body);});}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 559a963f70..b4d34c4379 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1055,6 +1055,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },// GBRA-158 minions wave (#7239).{ since: 'TBD', text: 'A background job that fails with a deterministic refusal (an error whose code is a caller, consent or host-only refusal the error registry does not mark retryable, or one its site marks `retryable: false`, such as `writer_coordinator_required`, `connector_account_changed`, `not_connected` or an `owner_unavailable` on a host that does not own the checkout) now ends at once as `dead` after one attempt instead of retrying until its attempts run out. Its result carries `job_outcome: "refused"` and `refusal` with the code, reason, message, fix and `gbrain errors <code>`; failures that can pass on retry (rate limits, timeouts, server and unavailable errors, write conflicts, a write still pending) retry as before. Autopilot\'s freshness dispatch then holds that source\'s automatic sync for the failure cooldown of its refusal count (10 minutes doubling to 2 hours, `autopilot.failure_cooldown_min` / `autopilot.failure_cooldown_cap_min`, 0 disables) instead of queueing a sync that is refused again every slot and every commit; it says so once per refused job (`freshness_sync_refused`), a completed sync job clears the hold, and `gbrain sync --source <id>` is never held.' },+ // #7245 (several gbrain builds run at once on one host and nothing reported it).+ { since: 'TBD', text: 'New doctor check `runtime_build_skew`: it warns when serve, the jobs supervisor, worker parents (`gbrain jobs work`, autopilot-spawned ones included) and the job children they spawn run different gbrain builds on this host, or when a process\'s install now holds another build than the one it runs, and names the restart for each (serve first, then the supervisor, then a worker); nothing restarts automatically. The supervisor PID file gains two lines (its version and install root), worker-registry entries carry `version` and `install_root`, and `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. A job child whose build differs from its worker\'s now writes one `job_build_skew:` line into the job\'s history (`gbrain jobs get`) and stderr and still runs; a child missing a readiness protocol or feature its worker needs refuses the job instead, which releases it without counting an attempt and puts the worker on a configuration block until it restarts on one build.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 5150b8d182..709ed8efeb 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -327,6 +327,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['host_identity_mismatch',// #6696 C6: a live serve or worker on an older build than this checkout (doctor/checks/persistence-consumers.ts).'serve_build_drift',+ // #7245: serve, the jobs supervisor, worker parents and job children on different builds (doctor/checks/runtime-build-skew.ts).+ 'runtime_build_skew','stale_embedding_effects','vector_plan','keyword_plan',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2196438189..693f7b7219 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -601,6 +601,7 @@ export const CODES = {search_offset_over_cap: { class: 'caller', summary: "A search offset was over the 10,000 limit.", suggestion: 'Page with match: "keyword" and the next object each response returns; a cursor has no depth limit.' },segmented_mirror_writer_gate: { class: 'host_only', actor: 'host_admin', summary: "A withdrawal mirror of a page stored in segments waits because a gbrain that cannot read its recovery record, and that doctor segmented_storage still warns about, wrote to this brain in the last 7 days; the withdrawal is committed and the canonical file keeps the withdrawn row until the mirror runs.", why: "The mirror's version 2 recovery record names a streamed staging file; a gbrain below the segmented writer floor (v0.60.290.0) misreads it and wedges the worktree, so no record is written while the segmented-storage writer gate sees such a live writer (this host's own pre-upgrade writes, superseded by the upgraded build, do not count). The mirror retries, parks, and runs again by itself once the gate clears.", docs: 'docs/guides/write-refusals.md#segmented_mirror_writer_gate' },serve_build_drift: { class: 'host_only', summary: "A live `serve` or resident worker on this host runs an older gbrain build than this checkout: its `persistence_consumers` heartbeat `version` is below this binary's VERSION.", why: "Upgrading or pulling the checkout does not restart the processes already running from it, so one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts`) run newer code against the older consumer until serve and its workers restart. A serve older than the heartbeat table writes no row; `consumers_without_heartbeat` names it.", docs: 'docs/guides/troubleshooting.md#serve-build-drift', suggestion: 'Restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker; nothing restarts automatically.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with each heartbeat row\'s kind, pid and gbrain version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'serve_build_drift', '--json'] } } },+ runtime_build_skew: { class: 'host_only', summary: "Long-running gbrain processes on this host run different builds, or one runs an older build than its install holds on disk: serve, the jobs supervisor, worker parents (in memory) and the job children they spawn from the install (on disk).", why: "A process keeps the code it loaded at start, and `gbrain jobs run-child` spawns a fresh process from the install on disk for every job, so after a checkout reset or an upgrade on disk newer job code runs under an older worker and next to an older serve until each process restarts.", docs: 'docs/guides/troubleshooting.md#runtime-build-skew', suggestion: 'Restart the process the check names (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid so its supervisor respawns it), then each other listed process on an older build; nothing restarts automatically.', fix: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the serve, supervisor, worker and recent job-child builds on this host with each pid and version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },settle_mismatch: { class: 'server', retryable: false, actor: 'agent',diff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.tsindex 0ae4da6d0a..1cf703d483 100644--- a/src/core/minions/child-job-runner.ts+++ b/src/core/minions/child-job-runner.ts@@ -38,6 +38,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { buildSpawnInvocation } from './spawn-helpers.ts';import { SpendEnforcementUnavailableError, childSpendEnforcementReady } from './spend-authorization.ts';+import { CHILD_PARENT_BUILD_ENV, parentBuildEnvValue } from './child-readiness.ts';import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';import {UnrecoverableError,@@ -208,6 +209,7 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {[CHILD_ENV.resultPath]: resultPath,[CHILD_ENV.isChild]: '1',[CHILD_ENV.parentPid]: String(process.pid),+ [CHILD_PARENT_BUILD_ENV]: parentBuildEnvValue(opts.spendAuthorized === true),GBRAIN_POOL_SIZE: String(childPoolSize),GBRAIN_DIRECT_POOL_SIZE: '1',};diff --git a/src/core/minions/child-readiness.ts b/src/core/minions/child-readiness.tsindex f7c82840e0..ce28f9eb85 100644--- a/src/core/minions/child-readiness.ts+++ b/src/core/minions/child-readiness.ts@@ -18,6 +18,59 @@ export const CHILD_READINESS_FEATURES = ['local-configuration-outcome-v1', 'post/** Every child must advertise these; `spend-enforcement-v1` only gates spend-authorized rows (child-job-runner.ts). */const REQUIRED_CHILD_FEATURES = ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] as const;+/**+ * #7245: the readiness handshake runs once, when the worker starts, but every+ * job spawns a fresh `jobs run-child` from the install on disk, so a checkout+ * that moves under a running worker hands later jobs to another build. The+ * worker passes its build and the features this job needs in this env var+ * (JSON), and the child compares them before it runs the handler.+ */+export const CHILD_PARENT_BUILD_ENV = 'GBRAIN_JOB_PARENT_BUILD';++/** The worker's build for one job child: every job needs the required features, a spend-authorized row also `spend-enforcement-v1`. */+export function parentBuildEnvValue(spendAuthorized: boolean): string {+ const features: string[] = [...REQUIRED_CHILD_FEATURES];+ if (spendAuthorized) features.push('spend-enforcement-v1');+ return JSON.stringify({ version: VERSION, protocol_version: CHILD_READINESS_PROTOCOL_VERSION, features });+}++/** The history entry prefix a job child writes when its build differs from its worker's (doctor `runtime_build_skew` reads it). */+export const JOB_BUILD_SKEW_PREFIX = 'job_build_skew:';++export interface JobChildBuildVerdict {+ worker_version: string;+ /** The worker needs a protocol or feature this child lacks: the child runs nothing. */+ refused: boolean;+ /** The one-line history entry and warning naming both builds and the decision. */+ note: string;+}++/**+ * Compares this job child's build with the spawning worker's. Null when the+ * builds match, or the worker sent none (a worker older than #7245) or an+ * unreadable value: nothing to report. A differing version alone runs the job+ * (the compatible protocol is what both sides read); a protocol mismatch or a+ * missing required feature refuses it, like the startup handshake does.+ */+export function jobChildBuildVerdict(raw: string | undefined, workerPid: number): JobChildBuildVerdict | null {+ if (!raw) return null;+ let parent: { version?: unknown; protocol_version?: unknown; features?: unknown };+ try { parent = JSON.parse(raw); } catch { return null; }+ if (!parent || typeof parent.version !== 'string' || !/^\d+(?:\.\d+){2,3}$/.test(parent.version)) return null;+ const features = Array.isArray(parent.features) ? parent.features.filter((f): f is string => typeof f === 'string') : [];+ const missing = features.filter(feature => !(CHILD_READINESS_FEATURES as readonly string[]).includes(feature));+ const protocolMismatch = parent.protocol_version !== CHILD_READINESS_PROTOCOL_VERSION;+ if (parent.version === VERSION && !protocolMismatch && !missing.length) return null;+ const builds = `job child v${VERSION} ${protocolMismatch || missing.length ? 'refused to run' : 'ran'} under worker pid ${workerPid} v${parent.version}`;+ if (!protocolMismatch && !missing.length) {+ return { worker_version: parent.version, refused: false,+ note: `${JOB_BUILD_SKEW_PREFIX} ${builds}; the readiness protocol and every feature the worker needs match, so the job ran on the child's build. Restart the worker to run one build (gbrain doctor --only runtime_build_skew).` };+ }+ const why = protocolMismatch ? `the worker speaks readiness protocol ${String(parent.protocol_version)} and this child ${CHILD_READINESS_PROTOCOL_VERSION}` : `this child lacks ${missing.join(', ')}`;+ return { worker_version: parent.version, refused: true,+ note: `${JOB_BUILD_SKEW_PREFIX} ${builds}: ${why}. The job is released without counting an attempt and the worker stops on a configuration block until it restarts on one build (gbrain doctor --only runtime_build_skew).` };+}+export interface ChildReadinessOptions {invocation: ChildCliInvocation;tiniPath: string;diff --git a/src/core/minions/run-child.ts b/src/core/minions/run-child.tsindex 38dc7bcb65..1bf33b2b95 100644--- a/src/core/minions/run-child.ts+++ b/src/core/minions/run-child.ts@@ -41,8 +41,9 @@ import {JOB_CHILD_EXIT_RESULT_WRITE_FAILED,WORKER_EXIT_CONFIGURATION,} from './worker-exit-codes.ts';-import { encodeHandlerError, unrefTimer, writeChildOutcomeFile } from './job-isolation.ts';+import { childConfigurationError, encodeHandlerError, unrefTimer, writeChildOutcomeFile } from './job-isolation.ts';import { isLocalConfigurationError } from './configuration-error.ts';+import { jobChildBuildVerdict } from './child-readiness.ts';export function writeChildBootstrapError(resultPath: string, error: unknown): number {if (!isLocalConfigurationError(error)) return 1;@@ -57,6 +58,8 @@ export interface RunChildOpts {resultPath: string;/** Worker pid for the liveness watchdog; 0/absent disables the watchdog. */parentPid: number;+ /** #7245: the worker's build (`CHILD_PARENT_BUILD_ENV`); absent from a worker older than #7245. */+ parentBuild?: string;}export interface RunChildInjectables {@@ -159,6 +162,15 @@ export async function runChildJobEntry(abort.signal,shutdown.signal,);+ // #7245: a build that differs from the worker's is recorded in the job's+ // history and warned once; a missing protocol or feature refuses the job.+ const verdict = jobChildBuildVerdict(opts.parentBuild, opts.parentPid);+ if (verdict) {+ process.stderr.write(`[run-child] ${verdict.note}\n`);+ try { await context.log(verdict.note); }+ catch (error) { process.stderr.write(`[run-child] could not record the build skew on job ${job.id}: ${error instanceof Error ? error.message : String(error)}\n`); }+ if (verdict.refused) return writeChildBootstrapError(opts.resultPath, childConfigurationError('child_protocol_incompatible'));+ }let outcome;try {// #4218: same phase attribution as the in-process worker path — thediff --git a/src/core/minions/supervisor-pid.ts b/src/core/minions/supervisor-pid.tsindex 48609ab301..ef13e57477 100644--- a/src/core/minions/supervisor-pid.ts+++ b/src/core/minions/supervisor-pid.ts@@ -10,6 +10,8 @@import { existsSync, readFileSync } from 'fs';import { hostname } from 'os';import { processStartTime } from '../pglite-lock.ts';+import { VERSION } from '../../version.ts';+import { runtimeInstallRoot } from '../runtime-build.ts';export interface SupervisorPidStatus {/** Parsed pid from the PID file, or null if missing/corrupt. */@@ -54,10 +56,24 @@ export function readSupervisorPid(pidFile: string): SupervisorPidStatus {* hostname label change from a second supervisor. Every reader takes the first* line; `jobs supervisor stop` reads line 2 (non-numeric = unknown); doctor* reads line 3 (missing = an older supervisor). An unknown start time leaves- * line 2 empty so the hostname stays on line 3.+ * line 2 empty so the hostname stays on line 3. #7245: line 4 is the gbrain+ * version the supervisor runs and line 5 the package root it loaded from+ * (empty in a compiled binary); `readSupervisorBuild` reads them.*/export function pidFileContents(pid: number = process.pid, host: string = hostname()): string {- return `${pid}\n${processStartTime(pid) ?? ''}\n${host}\n`;+ return `${pid}\n${processStartTime(pid) ?? ''}\n${host}\n${VERSION}\n${runtimeInstallRoot() ?? ''}\n`;+}++/** #7245: the build a supervisor recorded in its PID file (lines 4 and 5); null for a file an older supervisor wrote, or none. */+export function readSupervisorBuild(pidFile: string): { version: string; install_root: string | null } | null {+ try {+ const lines = readFileSync(pidFile, 'utf8').split('\n');+ const version = lines[3]?.trim();+ if (!version || !/^\d+(?:\.\d+){2,3}$/.test(version)) return null;+ return { version, install_root: lines[4]?.trim() || null };+ } catch {+ return null;+ }}/** `{ [key]: <kernel start time of pid> }` for an audit row, or nothing when it is unknowable. */diff --git a/src/core/minions/worker-registry.ts b/src/core/minions/worker-registry.tsindex cd14402112..2b78b43cee 100644--- a/src/core/minions/worker-registry.ts+++ b/src/core/minions/worker-registry.ts@@ -30,6 +30,8 @@ import { join } from 'path';import { execFileSync } from '../spawn.ts';import { gbrainPath, loadConfig } from '../config.ts';import { getEffectiveNiceness } from './niceness.ts';+import { VERSION } from '../../version.ts';+import { runtimeInstallRoot } from '../runtime-build.ts';/** On-disk shape of a `worker-<pid>.json` entry. */export interface WorkerRegistryEntry {@@ -43,6 +45,10 @@ export interface WorkerRegistryEntry {nice_requested: number | null;/** Niceness actually in effect when the worker registered. */nice_effective: number | null;+ /** #7245: the gbrain version the worker runs (in memory); absent on an entry an older worker wrote. */+ version?: string;+ /** #7245: the package root the worker loaded its code from (local path, never in remote output); null in a compiled binary. */+ install_root?: string | null;}/** A live worker as returned by readWorkers(): on-disk entry + fresh re-measure. */@@ -123,6 +129,8 @@ export function registerWorker(info: {started_at: info.started_at,nice_requested: info.nice_requested,nice_effective: info.nice_effective,+ version: VERSION,+ install_root: runtimeInstallRoot(),};const path = entryPath(info.pid);try {diff --git a/src/core/runtime-build.ts b/src/core/runtime-build.tsnew file mode 100644index 0000000000..f32846a619--- /dev/null+++ b/src/core/runtime-build.ts@@ -0,0 +1,56 @@+/**+ * #7245: the build a long-running gbrain process runs, next to the build its+ * install holds on disk now. A process keeps the code it loaded at start, so+ * after a checkout reset or an upgrade on disk its `VERSION` (in memory) and+ * the `package.json` beside the code it loaded (on disk) differ until it+ * restarts, and every `jobs run-child` it spawns from that install runs the+ * newer code. `install_root` is local-only evidence: it names a filesystem+ * path, so no remote-facing output carries it.+ */+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { VERSION } from '../version.ts';++const VERSION_PATTERN = /^\d+(?:\.\d+){2,3}$/;++/** The package root this process loaded its code from; null when it has no readable package.json there (a compiled binary). */+export function runtimeInstallRoot(): string | null {+ try {+ const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');+ return existsSync(join(root, 'package.json')) ? root : null;+ } catch {+ return null;+ }+}++/** The gbrain version installed at `root` now, read from disk; null when unknown or unreadable. */+export function installedVersion(root: string | null | undefined): string | null {+ if (!root) return null;+ try {+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: unknown; version?: unknown };+ return pkg.name === 'gbrain' && typeof pkg.version === 'string' && VERSION_PATTERN.test(pkg.version) ? pkg.version : null;+ } catch {+ return null;+ }+}++export interface ServeBuild {+ version: string;+ /** The version the install this process loaded from holds on disk now; null when unknown. */+ installed_version: string | null;+ /** The install on disk moved to another build since this process started. */+ restart_pending: boolean;+}++const BUILD_CACHE_MS = 10_000;+let cached: { at: number; build: ServeBuild } | null = null;++/** This process's build for `/health`: versions only, never a path. The disk read is cached for 10 s. */+export function serveBuild(now: number = Date.now()): ServeBuild {+ if (cached && now - cached.at < BUILD_CACHE_MS) return cached.build;+ const installed = installedVersion(runtimeInstallRoot());+ const build = { version: VERSION, installed_version: installed, restart_pending: installed !== null && installed !== VERSION };+ cached = { at: now, build };+ return build;+}diff --git a/test/doctor-runtime-build-skew.test.ts b/test/doctor-runtime-build-skew.test.tsnew file mode 100644index 0000000000..2e0075f5ab--- /dev/null+++ b/test/doctor-runtime-build-skew.test.ts@@ -0,0 +1,132 @@+/**+ * #7245: doctor `runtime_build_skew` compares the builds of this host's+ * long-running gbrain processes with each other and with the build each one's+ * install holds on disk: serve (heartbeat row), the jobs supervisor (PID file),+ * worker parents (worker registry) and the job children they spawned (the+ * `job_build_skew:` history entry a child writes). Stub sources for the+ * processes; real PGLite for the job-history read.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import { runtimeBuildSkewCheck, type RuntimeBuildSources } from '../src/commands/doctor/checks/runtime-build-skew.ts';+import { jobChildBuildVerdict, CHILD_READINESS_PROTOCOL_VERSION } from '../src/core/minions/child-readiness.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { VERSION } from '../src/version.ts';++const OLD = '0.60.1.0';+const OLDER = '0.60.0.9';+const INSTALL = '/srv/install-example';+const HOST = '00000000-0000-4000-8000-000000000001';+const home = mkdtempSync(join(tmpdir(), 'gbrain-runtime-skew-'));+const service = { platform: 'linux', home, uid: 501 };+afterAll(() => rmSync(home, { recursive: true, force: true }));++const heartbeat = (over: { kind?: string; pid?: number; version?: string } = {}) => ({+ host_id: HOST, pid: over.pid ?? 4242, nonce: `n-${over.pid ?? 4242}`, pid_ns: null, kind: over.kind ?? 'serve', mode: 'full',+ started_at: '2026-10-14 05:00:00+00', renewed_at: '2026-10-14 12:00:00+00', restart_required: false, root_barrier_age_ms: null, pool: null,+ host_json_path: `${INSTALL}/host.json`, persistence_home: INSTALL, minted_under: null, version: over.version ?? VERSION, boot_id: null, process_start: null,+ renewed_age_ms: '2000', age_ms: '25200000' });+const childLine = (workerPid: number, workerVersion: string) => jobChildBuildVerdict(JSON.stringify({ version: workerVersion, protocol_version: CHILD_READINESS_PROTOCOL_VERSION,+ features: ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] }), workerPid)!.note;++function stub(heartbeats: unknown[], children: Array<{ id: number; line: string }> = []) {+ const sql: string[] = [];+ const engine = { kind: 'postgres', executeRaw: async (statement: string) => {+ sql.push(statement);+ return statement.includes('persistence_consumers') ? heartbeats : statement.includes('minion_jobs') ? children : [];+ } } as unknown as BrainEngine;+ return { engine, sql };+}+function sources(over: Partial<{ workers: Array<{ pid: number; version?: string; install_root?: string | null }>; supervisor: { pid: number; version: string | null; install_root: string | null } | null; installed: string | null }> = {}): RuntimeBuildSources {+ return {+ workers: () => over.workers ?? [],+ supervisor: async () => over.supervisor ?? null,+ installedVersion: root => (root ? (over.installed === undefined ? VERSION : over.installed) : null),+ };+}++describe('doctor runtime_build_skew', () => {+ test('the incident shape: serve, supervisor and worker on old builds while job children run the install build', async () => {+ const { engine } = stub([heartbeat({ version: OLDER }), heartbeat({ kind: 'jobs', pid: 5151, version: OLD })],+ [{ id: 11, line: childLine(5151, OLD) }, { id: 12, line: childLine(5151, OLD) }]);+ const check = await runtimeBuildSkewCheck(engine, HOST, sources({+ workers: [{ pid: 5151, version: OLD, install_root: INSTALL }],+ supervisor: { pid: 6161, version: OLD, install_root: INSTALL },+ }), service);+ expect(check.status).toBe('warn');+ expect(check.message).toStartWith(`runtime_build_skew: 3 gbrain builds are running on this host (newest v${VERSION})`);+ expect(check.message).toContain(`serve pid 4242 v${OLDER}`);+ expect(check.message).toContain(`supervisor pid 6161 v${OLD} (its install now holds v${VERSION})`);+ expect(check.message).toContain(`worker pid 5151 v${OLD} (its install now holds v${VERSION})`);+ expect(check.message).toContain(`job children of worker pid 5151 ran v${VERSION} (jobs #11, #12)`);+ const fix = check.fix as { argv: string[]; actor: string; verify: { argv: string[] } };+ expect(fix.argv).toEqual(['kill', '4242']);+ expect(fix.actor).toBe('user');+ expect(fix.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json']);+ expect(check.details).toMatchObject({ count: 3, newest: VERSION, earlier_job_children: 0 });+ expect(JSON.stringify(check)).not.toContain(INSTALL);+ });++ test('one build everywhere reads ok, and so does an idle host', async () => {+ const same = await runtimeBuildSkewCheck(stub([heartbeat()]).engine, HOST, sources({+ workers: [{ pid: 5151, version: VERSION, install_root: INSTALL }], supervisor: { pid: 6161, version: VERSION, install_root: INSTALL } }), service);+ expect(same.status).toBe('ok');+ expect(same.message).toContain(`runs v${VERSION}`);+ const idle = await runtimeBuildSkewCheck(stub([]).engine, HOST, sources(), service);+ expect(idle.status).toBe('ok');+ expect(idle.message).toContain('No long-running gbrain process');+ });++ test('a worker whose install moved under it warns even when it is the only process', async () => {+ const check = await runtimeBuildSkewCheck(stub([]).engine, HOST, sources({ workers: [{ pid: 5151, version: OLD, install_root: INSTALL }] }), service);+ expect(check.status).toBe('warn');+ expect(check.message).toStartWith(`runtime_build_skew: a gbrain process runs an older build than its install (newest v${OLD})`);+ expect((check.fix as { argv: string[] }).argv).toEqual(['kill', '5151']);+ });++ test('a stale supervisor is restarted before its worker', async () => {+ const check = await runtimeBuildSkewCheck(stub([heartbeat()]).engine, HOST, sources({+ workers: [{ pid: 5151, version: OLD, install_root: INSTALL }], supervisor: { pid: 6161, version: OLD, install_root: INSTALL } }), service);+ expect(check.status).toBe('warn');+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'jobs', 'supervisor', 'stop']);+ expect(check.message).toContain('gbrain jobs supervisor start --detach');+ });++ test('job children of a worker that is gone are history, not a warning; an unrecorded build is named', async () => {+ const check = await runtimeBuildSkewCheck(stub([heartbeat()], [{ id: 9, line: childLine(9999, OLD) }]).engine, HOST, sources({+ supervisor: { pid: 6161, version: null, install_root: null } }), service);+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ earlier_job_children: 1, job_children: [], unknown_builds: [{ role: 'supervisor', pid: 6161 }] });+ expect(check.message).toContain('supervisor pid 6161 started before builds were recorded');+ });++ test('registered as its own entry', () => {+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.emits.includes('runtime_build_skew'));+ expect(entry?.name).toBe('runtime_build_skew');+ });+});++describe('doctor runtime_build_skew on PGLite', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ });+ afterAll(async () => { await engine.disconnect(); });++ test('reads job-child builds from the job history of a live worker', async () => {+ const queue = new MinionQueue(engine);+ const job = await queue.add('sync', {});+ await engine.executeRaw(`UPDATE minion_jobs SET stacktrace = jsonb_build_array('earlier failure', $1::text) WHERE id = $2`, [childLine(process.pid, OLD), job.id]);+ const check = await runtimeBuildSkewCheck(engine as unknown as BrainEngine, HOST, sources({ workers: [{ pid: process.pid, version: OLD, install_root: INSTALL }] }), service);+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ job_children: [{ job_id: job.id, child_version: VERSION, worker_pid: process.pid, worker_version: OLD, refused: false }] });+ expect(check.message).toContain(`job children of worker pid ${process.pid} ran v${VERSION} (jobs #${job.id})`);+ });+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 3b78bfcb21..a9525cadc2 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2834,6 +2834,24 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "builds": [],+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#runtime-build-skew",+ "earlier_job_children": 0,+ "job_children": [],+ "newest": null,+ "processes": [],+ "stale": [],+ "unknown_builds": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No long-running gbrain process (serve, jobs supervisor, worker) is running on this host.",+ "name": "runtime_build_skew",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex c5f18ef387..4db51150c8 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2878,6 +2878,24 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "builds": [],+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#runtime-build-skew",+ "earlier_job_children": 0,+ "job_children": [],+ "newest": null,+ "processes": [],+ "stale": [],+ "unknown_builds": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No long-running gbrain process (serve, jobs supervisor, worker) is running on this host.",+ "name": "runtime_build_skew",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 1234c1970d..939acd429a 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -2881,6 +2881,24 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "builds": [],+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#runtime-build-skew",+ "earlier_job_children": 0,+ "job_children": [],+ "newest": null,+ "processes": [],+ "stale": [],+ "unknown_builds": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No long-running gbrain process (serve, jobs supervisor, worker) is running on this host.",+ "name": "runtime_build_skew",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e4b55a8201..40c53b24d4 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -881,6 +881,10 @@"category": "ops","name": "host_identity_mismatch"},+ {+ "category": "ops",+ "name": "runtime_build_skew"+ },{"category": "brain","name": "extract_atoms_held_failed"diff --git a/test/runtime-build-skew-7245.test.ts b/test/runtime-build-skew-7245.test.tsnew file mode 100644index 0000000000..8ce8b5c575--- /dev/null+++ b/test/runtime-build-skew-7245.test.ts@@ -0,0 +1,213 @@+/**+ * #7245: several gbrain builds run at once on one host and nothing reported it.+ * After a checkout reset or an upgrade on disk, serve, the jobs supervisor and+ * the worker parents keep the build they loaded (in memory) while every+ * `jobs run-child` runs the build on disk. Pins the records each long-running+ * process now writes (worker registry, supervisor PID file, serve /health) and+ * the job child's per-job comparison with its worker's build: a differing+ * version runs and is recorded in the job's history; a protocol or feature the+ * worker needs and the child lacks refuses the job.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import express from 'express';+import type { Server } from 'http';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { runChildJobEntry } from '../src/core/minions/run-child.ts';+import { runJobInChild } from '../src/core/minions/child-job-runner.ts';+import { decodeChildOutcomeFile } from '../src/core/minions/job-isolation.ts';+import { WORKER_EXIT_CONFIGURATION } from '../src/core/minions/worker-exit-codes.ts';+import { CHILD_READINESS_FEATURES, CHILD_READINESS_PROTOCOL_VERSION, JOB_BUILD_SKEW_PREFIX, jobChildBuildVerdict, parentBuildEnvValue } from '../src/core/minions/child-readiness.ts';+import { installedVersion, runtimeInstallRoot, serveBuild } from '../src/core/runtime-build.ts';+import { pidFileContents, readSupervisorBuild } from '../src/core/minions/supervisor-pid.ts';+import { registerWorker, workerRegistryDir } from '../src/core/minions/worker-registry.ts';+import { createMetricsCounters, mountHealth } from '../src/commands/serve-http-metrics.ts';+import type { ServeHttpContext } from '../src/commands/serve-http.ts';+import { VERSION } from '../src/version.ts';+import { withEnv } from './helpers/with-env.ts';++const OLD = '0.60.1.0';+let engine: PGLiteEngine;+let queue: MinionQueue;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ queue = new MinionQueue(engine);+ dir = mkdtempSync(join(tmpdir(), 'gbrain-build-skew-7245-'));+});+afterAll(async () => {+ await engine.disconnect();+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* the OS reaps tmpdir */ }+});+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });++const parentBuild = (over: { version?: string; protocol_version?: number; features?: string[] } = {}) => JSON.stringify({+ version: over.version ?? OLD, protocol_version: over.protocol_version ?? CHILD_READINESS_PROTOCOL_VERSION,+ features: over.features ?? ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] });++async function claimed(name: string) {+ await queue.add(name, {});+ const job = await queue.claim('worker-7245:1', 30_000, 'default', [name]);+ if (!job) throw new Error('claim failed in test setup');+ return job;+}++describe('runtime build identity', () => {+ test('the install root this process loaded from holds this VERSION on disk', () => {+ const root = runtimeInstallRoot();+ expect(root).not.toBeNull();+ expect(installedVersion(root)).toBe(VERSION);+ });++ test('installedVersion reads the version on disk now, and nothing it cannot trust', () => {+ const root = join(dir, 'install');+ mkdirSync(root, { recursive: true });+ expect(installedVersion(root)).toBeNull();+ writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'gbrain', version: '0.60.9.0' }));+ expect(installedVersion(root)).toBe('0.60.9.0');+ writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'other-package', version: '0.60.9.0' }));+ expect(installedVersion(root)).toBeNull();+ expect(installedVersion(null)).toBeNull();+ });++ test('serve reports its build with no path in it', () => {+ const build = serveBuild(Date.now() + 3_600_000);+ expect(build).toEqual({ version: VERSION, installed_version: VERSION, restart_pending: false });+ });++ test('/health carries the build on a 200', async () => {+ const app = express();+ mountHealth(app, { engine, config: { engine: 'pglite' }, requireAdmin: () => undefined, metricsCounters: createMetricsCounters() } as unknown as ServeHttpContext);+ const server: Server = app.listen(0);+ await new Promise<void>(resolve => server.once('listening', () => resolve()));+ try {+ const addr = server.address();+ const res = await fetch(`http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}/health`);+ expect(res.status).toBe(200);+ const body = await res.json() as Record<string, unknown>;+ expect(body.status).toBe('ok');+ expect(body.build).toEqual({ version: VERSION, installed_version: VERSION, restart_pending: false });+ expect(JSON.stringify(body)).not.toContain(runtimeInstallRoot()!);+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()));+ }+ });++ test('a worker registry entry records the worker build and install', () => {+ const home = join(dir, 'home-registry');+ withEnv({ GBRAIN_HOME: home }, () => {+ const cleanup = registerWorker({ pid: process.pid, queue: 'default', nice_requested: null, nice_effective: null, started_at: Date.now() });+ try {+ const entry = JSON.parse(readFileSync(join(workerRegistryDir(), `worker-${process.pid}.json`), 'utf8'));+ expect(entry.version).toBe(VERSION);+ expect(entry.install_root).toBe(runtimeInstallRoot());+ } finally { cleanup(); }+ });+ });++ test('the supervisor PID file records its build on lines 4 and 5; an older three-line file reads as unrecorded', () => {+ const lines = pidFileContents(process.pid, 'host-a').split('\n');+ expect(lines[2]).toBe('host-a');+ expect(lines[3]).toBe(VERSION);+ expect(lines[4]).toBe(runtimeInstallRoot() ?? '');+ const file = join(dir, 'supervisor.pid');+ writeFileSync(file, pidFileContents(process.pid, 'host-a'));+ expect(readSupervisorBuild(file)).toEqual({ version: VERSION, install_root: runtimeInstallRoot() });+ writeFileSync(file, `${process.pid}\n\nhost-a\n`);+ expect(readSupervisorBuild(file)).toBeNull();+ expect(readSupervisorBuild(join(dir, 'missing.pid'))).toBeNull();+ });+});++describe('job child build verdict', () => {+ test('the worker build names the features the job needs', () => {+ expect(JSON.parse(parentBuildEnvValue(false))).toEqual({ version: VERSION, protocol_version: CHILD_READINESS_PROTOCOL_VERSION,+ features: ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] });+ expect(JSON.parse(parentBuildEnvValue(true)).features).toContain('spend-enforcement-v1');+ });++ test('the same build, an older worker that sends none and an unreadable value report nothing', () => {+ expect(jobChildBuildVerdict(parentBuildEnvValue(true), 42)).toBeNull();+ expect(jobChildBuildVerdict(undefined, 42)).toBeNull();+ expect(jobChildBuildVerdict('not json', 42)).toBeNull();+ expect(jobChildBuildVerdict(JSON.stringify({ version: 'v-latest' }), 42)).toBeNull();+ });++ test('a differing version with a compatible protocol runs and names both builds', () => {+ const verdict = jobChildBuildVerdict(parentBuild(), 42)!;+ expect(verdict.refused).toBe(false);+ expect(verdict.worker_version).toBe(OLD);+ expect(verdict.note).toStartWith(`${JOB_BUILD_SKEW_PREFIX} job child v${VERSION} ran under worker pid 42 v${OLD}`);+ });++ test('a protocol mismatch or a feature the child lacks refuses the job', () => {+ const protocol = jobChildBuildVerdict(parentBuild({ protocol_version: CHILD_READINESS_PROTOCOL_VERSION + 1 }), 42)!;+ expect(protocol.refused).toBe(true);+ expect(protocol.note).toStartWith(`${JOB_BUILD_SKEW_PREFIX} job child v${VERSION} refused to run under worker pid 42 v${OLD}`);+ const feature = jobChildBuildVerdict(parentBuild({ version: VERSION, features: [...CHILD_READINESS_FEATURES, 'future-feature-v9'] }), 42)!;+ expect(feature.refused).toBe(true);+ expect(feature.note).toContain('this child lacks future-feature-v9');+ });+});++describe('runChildJobEntry records the build decision on the job', () => {+ test('a skewed child runs the handler and leaves one history entry naming both builds', async () => {+ const job = await claimed('sync');+ const resultPath = join(dir, `skew-${job.id}.json`);+ let ran = false;+ const code = await runChildJobEntry(engine, { jobId: job.id, lockToken: 'worker-7245:1', resultPath, parentPid: 4242, parentBuild: parentBuild() },+ { resolveHandler: () => async () => { ran = true; return { ok: true }; } });+ expect(code).toBe(0);+ expect(ran).toBe(true);+ expect(decodeChildOutcomeFile(resultPath).outcome).toBe('success');+ const after = await queue.getJob(job.id);+ const notes = after!.stacktrace.filter(line => line.startsWith(JOB_BUILD_SKEW_PREFIX));+ expect(notes).toEqual([jobChildBuildVerdict(parentBuild(), 4242)!.note]);+ });++ test('a child missing what the worker needs runs nothing and reports a configuration outcome', async () => {+ const job = await claimed('sync');+ const resultPath = join(dir, `refuse-${job.id}.json`);+ let ran = false;+ const build = parentBuild({ features: ['local-configuration-outcome-v1', 'future-feature-v9'] });+ const code = await runChildJobEntry(engine, { jobId: job.id, lockToken: 'worker-7245:1', resultPath, parentPid: 4242, parentBuild: build },+ { resolveHandler: () => async () => { ran = true; } });+ expect(code).toBe(WORKER_EXIT_CONFIGURATION);+ expect(ran).toBe(false);+ const outcome = decodeChildOutcomeFile(resultPath);+ if (outcome.outcome !== 'error') throw new Error('expected an error outcome');+ expect(outcome.errorKind).toBe('local_configuration');+ expect(JSON.stringify(outcome)).toContain('child_protocol_incompatible');+ const after = await queue.getJob(job.id);+ expect(after!.stacktrace.some(line => line.startsWith(`${JOB_BUILD_SKEW_PREFIX} job child v${VERSION} refused to run under worker pid 4242 v${OLD}`))).toBe(true);+ });++ test('a child on its worker build writes no history entry', async () => {+ const job = await claimed('sync');+ const resultPath = join(dir, `same-${job.id}.json`);+ const code = await runChildJobEntry(engine, { jobId: job.id, lockToken: 'worker-7245:1', resultPath, parentPid: 4242, parentBuild: parentBuildEnvValue(false) },+ { resolveHandler: () => async () => ({ ok: true }) });+ expect(code).toBe(0);+ expect((await queue.getJob(job.id))!.stacktrace).toEqual([]);+ });+});++describe('runJobInChild hands the worker build to every job child', () => {+ test('the child env carries this worker build and the features the job needs', async () => {+ const harness = join(dir, 'echo-build.mjs');+ writeFileSync(harness, `import { writeFileSync, renameSync } from 'node:fs';+const RESULT = process.env.GBRAIN_JOB_RESULT_PATH;+writeFileSync(RESULT + '.tmp', JSON.stringify({ outcome: 'success', result: { build: process.env.GBRAIN_JOB_PARENT_BUILD } }));+renameSync(RESULT + '.tmp', RESULT);+`);+ const result = await runJobInChild({ jobId: 7245, jobName: 'sync', lockToken: 'tok-7245', abortSignal: new AbortController().signal,+ shutdownSignal: new AbortController().signal, invocation: { cmd: process.execPath, argsPrefix: [harness] }, tiniPath: '' }) as { build: string };+ expect(JSON.parse(result.build)).toEqual(JSON.parse(parentBuildEnvValue(false)));+ }, 30_000);+});