Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): serve_build_drift warns when serve runs an older build than this checkout (#6696 C6)
garrytanc59fa08cfdb9
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex bbd8c861a9..a384cd4bc3 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -5,6 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.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/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`).- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter. Its help names the per-source patterns key `dream:patterns:source:<id>`; doctor `dream_paid_loop` reports that prefix as the key's `key_prefix`.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex f5abd73234..74e4e4d792 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -29,7 +29,6 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce and the pid-namespace inode from `/proc/self/ns/pid` where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.-- `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. Registered in `DOCTOR_CHECK_REGISTRY` before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`.- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark, one probe of the partial index `persistence_requests_sync_watermark`, v223, whose predicate repeats the read's kind test; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the exact `gbrain sources writer status --source <id> --json` beside `data_moving: false`; doctor `managed_sync_not_moving` (warn; counts against the score for `not_moving`, never for `parked`) uses the same rule with that command as its structured fix; `serve` prints one `[gbrain notice]` when a source flips. `/health` stays liveness-only.- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` carries the read failure's own code with `fix.next: report`. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a group follower carries no stamp until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 43b8081975..74994bdaa2 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2705,6 +2705,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A search offset was over the 10,000 limit. | The request itself was wrong or no longer matches the brain; nothing was changed. | Page with match: "keyword" and the next object each response returns; a cursor has no depth limit. | agent | `repeat the read that failed` | 1 | no |+### serve_build_drift++<a id="serve_build_drift"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| 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. | 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. | 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. Run: gbrain sources writer status --json | agent | `gbrain doctor --only serve_build_drift --json` | 1 | no |++More: [docs/guides/troubleshooting.md#serve-build-drift](../../docs/guides/troubleshooting.md#serve-build-drift)+### serve_port_in_use<a id="serve_port_in_use"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 40f390debb..79730743af 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -14,6 +14,7 @@ a page needs my decision."*## The loop```bash+gbrain doctor --only serve_build_drift --json # first: on a warning, restart serve and workers and stop heregbrain sync status --source <id> --json # every N minutes (read-only)gbrain sync unblock --source <id> --apply --json # when committed_last_10m is 0 and needs_human is falsegbrain sync <next.argv...> # the sync unblock (or status) names: the cursor's own options@@ -22,6 +23,10 @@ gbrain sync <next.argv...> # the sync unblock (or status)**Say to your agent:** *"Repair the files sync held and get the catch-upmoving again; ask me only about the ones gbrain will not decide by itself."*+0. Check the build. `serve_build_drift` warns when serve or a worker on this+ host runs an older gbrain build than this checkout; restart them with the+ command it prints before anything else, and stop until it reads ok+ ([serve build drift](troubleshooting.md#serve-build-drift)).1. Read `status`. `cursor` is where the run stands (`index/total`, the`pinned_target` commit, `last_advance_at`); `committed_last_10m` is thesignal that data is moving (a live process with a flat cursor is notdiff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 008ad54e30..98e10ca040 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -40,6 +40,7 @@| [The drain stopped `drain_stalled` with `cause: owner_wedged_here`](#managed-sync-not-moving) | before the ceiling: wait `retry_after_ms`, then rerun `next.command` (`safe_to_loop` is true); past it: restart the owner process the stop names (`gbrain serve`, the jobs worker or autopilot), then `gbrain sources retry-held <id>` and the same sync | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer status --source <id> --json` (the claim is gone or publishing), then `gbrain sources writer movement <id>` || [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 `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` |@@ -75,7 +76,7 @@<a id="worktree-dirty-hold"></a>**Sync held a file with `worktree_dirty`?** The working tree holds uncommitted bytes for the file that match neither the pinned commit nor the page (an agent mid-edit on a live checkout), so sync held it instead of overwriting the edit and kept going; nothing is lost and the run finished. Commit the file (or restore it), then `gbrain sync unblock --source <id> --apply` re-screens every held file that is now committed and prints the sync to run; a later commit that changes the file re-screens it on its own. A file held three times is reported `needs_human` by `gbrain sync status`: find out what keeps editing it. Bytes committed at HEAD past the pinned target are imported as HEAD has them, never held. See [worktree_dirty](write-refusals.md#worktree_dirty) and the [sync unblock runbook](sync-unblock-runbook.md).-<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write is cut off at its budget, but a cut-off preparation that ignores cancellation keeps its root blocked until the ceiling (600 s from the claim's start), when the owner frees the root and the next claim holds the entry; the rest of the source keeps publishing meanwhile, and a sync beside such an owner prints `stalled <N>s on <step>` with the owner's pid and kind from the allowance to the ceiling instead of stopping. One wedge therefore costs up to ten minutes and one held file, never the run. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch.+<a id="catch-up-stuck"></a>**Managed catch-up stuck (one write `running` for minutes while the rest waits), held N files as `preparation_stalled`, or the drain stopped with `preparation_abandoned`, `preparation_systemic` or `write_capacity`?** Every managed write's *preparation* has a deadline (`persistence.sync_preparation_ms`, default 120 s, for sync members; `persistence.maintenance_preparation_ms`, default 120 s, for maintenance writes; a hard ceiling `persistence.preparation_ceiling_ms`, default 600 s; `persistence.max_preparation_attempts`, default 2; all behind the `preparation_deadlines` write switch), so one stuck write is cut off at its budget, but a cut-off preparation that ignores cancellation keeps its root blocked until the ceiling (600 s from the claim's start), when the owner frees the root and the next claim holds the entry; the rest of the source keeps publishing meanwhile, and a sync beside such an owner prints `stalled <N>s on <step>` with the owner's pid and kind from the allowance to the ceiling instead of stopping. One wedge therefore costs up to ten minutes and one held file, never the run. The runbook branches on what you see; every command below is read-only unless it says otherwise, and the files themselves are never the problem in this branch. Start every branch with `gbrain doctor --only serve_build_drift --json`: on a warning, restart serve and its workers on this build first (see [serve build drift](#serve-build-drift)) and stop there until it reads ok.1. **While it is stuck.** The progress line prints `stalled <N>s on <step>` instead of an ETA. Run `gbrain sources writer status --source <id> --json`: the blocked request's `claim.stall` names the step (`origin_check`, `knowledge_publication`, …), `waiting_on` (`git`, `fs`, `db`, `pool`, or an honest `unknown`), `step_age_ms`, the budget, and the owner process (kind, pid, gbrain version). An owner whose version predates this release never gives up: upgrade it and restart it (`gbrain serve`, the jobs worker or autopilot; the drain's own process ends with the drain). Otherwise wait out the budget: the write is released, retried once, then held. A release does not always free the root: a preparation that ignores cancellation holds its root barrier until the ceiling, and `writer status --json` ends the claim in a `claim.next` that says so (`claim_running` with `retry_after_ms` to the ceiling, or `claim_overdue` as `tell_user_to_run` naming the owner pid once the ceiling has passed or the owner reads `restart_required`).2. **Held files (`preparation_stalled`).** `gbrain sources status <id> --json` lists them with the step each stalled on; no `gbrain repair` applies. After the cause is fixed (or gbrain upgraded), run `gbrain sources retry-held <id>` and then the same sync with the same options, which the hold's `fix` and `retry-held` print, for example `gbrain sync --source <id> --no-pull --no-embed`. If that sync still has a backlog, it finishes the backlog and then re-screens the scheduled files in the same run. Verify with `gbrain sources status <id> --json` (the held count drops) and `gbrain doctor --only git_held_files --json`. A held deletion keeps its page until that retry. A stalled hold also re-screens by itself when the gbrain version changes.@@ -137,6 +138,8 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see<a id="consumers-without-heartbeat"></a>**Doctor warns `consumers_without_heartbeat`?** A running claim on this host is stamped by a process (`claim_phase.owner`: kind, pid, gbrain version) that has no `persistence_consumers` row. Every full consumer on this release renews its row every 10 s, so an owner without one runs a gbrain release from before the heartbeat table: it never defers to the resident consumer and the host runs two full consumers until it is upgraded. The check names the pid, kind and version from the stamp; upgrade and restart that process (after the user agrees). A new sync CLI beside an older `serve` says so on its start line (`owner row missing: older serve or no serve; running own consumer`).+<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="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/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 07fdef66c5..f950c3067a 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -485,7 +485,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| Stop reason | Code | Outcome | What it means | Recovery || --- | --- | --- | --- | --- || <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |-| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. A serve-delegated `no_admission` continues once with the CLI's own consumer. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. Once the run's final checkpoint commits, the pass is in step `finish` (planner statistics and link extraction, which admit nothing): that tail is never read as `no_admission`, link extraction stops after 5 minutes and leaves the rest for `gbrain extract --stale`, and a tail still stuck 30 s past that stops `no_progress` with `step: finish`. A serve-delegated `no_admission` continues once with the CLI's own consumer. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. || <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. || <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. || <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.tsindex c57bef802a..53d67e36fc 100644--- a/src/commands/doctor/checks/persistence-consumers.ts+++ b/src/commands/doctor/checks/persistence-consumers.ts@@ -16,17 +16,29 @@* managed worktree at the binding's path plus a `host.json` minted later* under a different `HOME`/`GBRAIN_HOME`). Names both files and the one-line* `GBRAIN_HOME` fix; never re-identifies anything.+ *+ * #6696 C6: `serve_build_drift` (its own entry, one read) compares the live+ * resident consumers' heartbeat `version` with this binary's VERSION and warns+ * when serve or a worker runs an older build than this checkout, with the+ * installed service's restart command (else the pid) and a verify. A serve+ * that predates heartbeats has no row; `consumers_without_heartbeat` names it.*/+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';import type { Check } from '../../doctor.ts';import type { BrainEngine } from '../../../core/engine.ts';-import { listHostConsumers } from '../../../core/persistence/consumer-heartbeat.ts';+import { listHostConsumers, RESIDENT_CONSUMER_KINDS, type ListedConsumer } from '../../../core/persistence/consumer-heartbeat.ts';+import { compareWriterVersions } from '../../../core/persistence/writer-versions.ts';+import { launchdPlistPath, SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT, systemdUnitPath } from '../../../core/serve-service.ts';+import { VERSION } from '../../../version.ts';import { consumerOverlap, hostIdentityMismatches, ownersWithoutHeartbeat, OVERLAP_MIN_AGE_MS } from '../../../core/persistence/consumer-diagnostics.ts';import { localHostIdentity } from '../../../core/persistence/identity.ts';-import { agentFix, checkError } from '../check-fix.ts';+import { agentFix, checkError, doctorVerify } from '../check-fix.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';const DOCS = 'docs/guides/troubleshooting.md#two-consumers-on-host';const IDENTITY_DOCS = 'docs/guides/troubleshooting.md#host-identity-mismatch';+const DRIFT_DOCS = 'docs/guides/troubleshooting.md#serve-build-drift';const STATUS_ARGV = ['gbrain', 'sources', 'writer', 'status', '--json'];export async function twoConsumersOnHostCheck(engine: BrainEngine, hostId: string): Promise<Check> {@@ -94,6 +106,45 @@ export async function hostIdentityMismatchCheck(engine: BrainEngine): Promise<Ch}}+export 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[] {+ 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)];+}++export async function serveBuildDriftCheck(engine: BrainEngine, hostId: string,+ service: ServiceHost = { platform: process.platform, home: homedir(), uid: process.getuid?.() ?? 501 }): Promise<Check> {+ if (engine.kind === 'pglite') return { name: 'serve_build_drift', status: 'ok', message: 'PGLite admits one process; no consumer heartbeat rows are kept to compare builds.', details: { count: 0, docs: DRIFT_DOCS } };+ try {+ const live = (await listHostConsumers(engine, hostId)).filter(row => row.liveness === 'live' && !row.self && RESIDENT_CONSUMER_KINDS.includes(row.kind));+ const owner = live.find(row => row.mode === 'full' || row.mode === 'promoted') ?? live[0] ?? null;+ const order = (row: ListedConsumer) => compareWriterVersions(row.version, VERSION) ?? -1;+ const older = live.filter(row => order(row) < 0), newer = live.filter(row => order(row) > 0);+ const label = (row: ListedConsumer) => `${row.kind} pid ${row.pid} v${row.version}`;+ const details = { count: older.length, this_version: VERSION, owner: owner ? { kind: owner.kind, pid: owner.pid, mode: owner.mode, version: owner.version } : null,+ older: older.map(row => ({ kind: row.kind, pid: row.pid, mode: row.mode, version: row.version })), newer: newer.map(row => ({ kind: row.kind, pid: row.pid, version: row.version })), docs: DRIFT_DOCS };+ if (!live.length) return { name: 'serve_build_drift', status: 'ok', details,+ message: 'No live gbrain consumer on this host writes a heartbeat row. A serve that predates heartbeats writes none; consumers_without_heartbeat names it when it holds claims.' };+ if (!older.length) return { name: 'serve_build_drift', status: 'ok', details,+ message: newer.length ? `This checkout (v${VERSION}) is older than the running ${newer.map(label).join('; ')}; upgrade this checkout before running one-shot commands from it.`+ : `Every live consumer on this host runs this build (v${VERSION}).` };+ const target = older.find(row => row.kind === 'serve') ?? older[0]!;+ const argv = restartArgv(target, service);+ return { name: 'serve_build_drift', status: 'warn', details,+ message: `serve_build_drift: serve is running an older build than this checkout; restart serve and workers. This binary is v${VERSION}; running: ${older.map(label).join('; ')}. `+ + 'Until they restart, one-shot commands from this checkout run newer code against an older consumer. '+ + `Restart with \`${argv.join(' ')}\`${argv[0] === 'kill' ? ' and start it again the way it was launched' : ''}, then restart each other listed process. `+ + 'A serve that predates heartbeats writes no row; consumers_without_heartbeat names it.',+ fix: { argv, consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('serve_build_drift'), docs: DRIFT_DOCS,+ why: `Restarts ${label(target)} on this build (v${VERSION}); restart every other listed process the same way.` } };+ } catch (error) {+ return checkError('serve_build_drift', 'read the consumer heartbeat rows', error, { details: { count: 'unknown', health: 'unknown', docs: DRIFT_DOCS } });+ }+}+async function runPersistenceConsumers(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);const checks: Check[] = [];@@ -109,3 +160,15 @@ export const persistenceConsumersEntry: DoctorEntry = {emits: ['two_consumers_on_host', 'consumers_without_heartbeat', 'host_identity_mismatch'],run: runPersistenceConsumers,};++async function runServeBuildDrift(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push(await serveBuildDriftCheck(connectedEngine(ctx), localHostIdentity().id));+ return checks;+}++export const serveBuildDriftEntry: DoctorEntry = {+ name: 'serve_build_drift',+ emits: ['serve_build_drift'],+ run: runServeBuildDrift,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 78a9020c1f..118498301f 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -85,7 +85,7 @@ import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { grantNewOpsEntry } from './checks/grant-new-ops.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';-import { persistenceConsumersEntry } from './checks/persistence-consumers.ts';+import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';@@ -195,6 +195,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [coreMemoryEntry,managedSyncMovementEntry,persistenceConsumersEntry,+ serveBuildDriftEntry,atomHeldFailedEntry,fenceIntegrityEntry,searchModeEntry,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7d0866c82b..3043d0ed66 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -568,6 +568,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.223.0', text: 'gbrain.yml `storage:` accepts an opt-in `keep_db:` list of directory prefixes. On the canonical owner host, the resident `gbrain serve`, `gbrain jobs` or `gbrain autopilot` consumer reconciles each drifted page under those prefixes with the database copy (the `gbrain repair file-drift --prefer database` resolution, inside reconcile\'s protections and backups), at most 10 requests every 10 minutes, never twice for the same drift and never past 90% of the write-quota stop line; other hosts and remote or caller writes are unchanged and keep refusing `source_changed`. Doctor `maintenance_write_drift` echoes each declared policy with how many drifted pages it matches and their receipt cost. An unknown key under `storage:` now prints a warning instead of being ignored silently.' },{ since: '0.60.223.0', text: '`gbrain repair content` (the `slug-conflicts` kind) now judges a held `frontmatter_slug_conflict` file with the same screen managed sync froze it with. A held file sync would now import as it is (its `slug:` line names the file\'s own page, or it no longer conflicts) is listed as `import` and imported unchanged, clearing the hold only while it is still the observation the repair read; before, it was skipped as `already_exempt` or `already_clean` and the hold stayed. A file in a source that is a subdirectory of its Git repository now loses its stray `slug:` line instead of being held `still_invalid`. A file sync would hold whatever the repair writes is now held `slug_page_mismatch` naming both slugs, instead of the generic `still_invalid` or `already_exempt` (an alias to the file\'s own page is one).' },{ since: '0.60.223.0', text: 'A managed `gbrain sync` whose final checkpoint committed no longer ends `blocked` / `drain_stalled` / `no_admission` (with advice to move the database to port 5432) while it finishes planner statistics and link extraction. That tail now has its own budget: link extraction stops after 5 minutes and leaves the remaining pages for `gbrain extract --stale`, and a tail that is still stuck 30 s later stops `no_progress` at step `finish`. A run stuck before admission still stops `no_admission` after 5 minutes.' },+ { since: '0.60.223.0', text: 'New doctor check `serve_build_drift` (ops): on a managed Postgres brain it warns "serve is running an older build than this checkout; restart serve and workers" when a live `serve`, jobs worker, autopilot, sync or MCP process on this host reports an older gbrain version in its consumer heartbeat than the binary running doctor. The fix names the installed serve service\'s restart (`systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve`), or the pid to stop and start again, and the verify is `gbrain doctor --only serve_build_drift --json`. Nothing restarts automatically; PGLite reads ok.' },];/** 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 9ea609ad42..cf278f28c8 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -274,6 +274,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['two_consumers_on_host','consumers_without_heartbeat','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','stale_embedding_effects','vector_plan','keyword_plan',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 419b5932af..e041b7d946 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -416,6 +416,7 @@ export const CODES = {search_cursor_requires_keyword: { class: 'caller', summary: "A search cursor was sent without match: \"keyword\"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page).", suggestion: 'Send the next object from the previous search response unchanged; it carries match: "keyword".' },search_mode_local_only: { class: 'caller', summary: "An agent-facing caller set search's mode, which only the brain's operator chooses.", suggestion: 'Omit mode; for keyword-only matching with a total and paging, pass match: "keyword".' },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.' },+ 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'] } } },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.' },setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },diff --git a/test/doctor-serve-build-drift.test.ts b/test/doctor-serve-build-drift.test.tsnew file mode 100644index 0000000000..19946dbcef--- /dev/null+++ b/test/doctor-serve-build-drift.test.ts@@ -0,0 +1,98 @@+/**+ * #6696 C6: a checkout that moved to a newer build while the serve kept running the old one ran new one-shot CLI code+ * against an old consumer for hours, and nothing said so. Doctor `serve_build_drift` compares the live resident+ * consumers' heartbeat `version` (persistence_consumers) with this binary's VERSION in one read and warns with a+ * service-specific restart and a verify; a serve that predates heartbeats is named through `consumers_without_heartbeat`.+ * Stub engines only: the check reads one statement.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { Check } from '../src/commands/doctor.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { VERSION } from '../src/version.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-build-drift-'));+afterAll(() => rmSync(home, { recursive: true, force: true }));++const row = (over: { kind?: string; pid?: number; version?: string; renewedAgoMs?: number; mode?: string } = {}) => ({+ host_id: '00000000-0000-4000-8000-000000000001', pid: over.pid ?? 4242, nonce: `n-${over.pid ?? 4242}`, pid_ns: null, kind: over.kind ?? 'serve', mode: over.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: '/srv/acme-example/.gbrain/persistence/host.json', persistence_home: '/srv/acme-example/.gbrain/persistence', minted_under: null,+ version: over.version ?? VERSION, boot_id: null, process_start: null, renewed_age_ms: String(over.renewedAgoMs ?? 2_000), age_ms: '25200000' });+function stub(rows: unknown[], kind: 'postgres' | 'pglite' = 'postgres') {+ const sql: string[] = [];+ const engine = { kind, executeRaw: async (statement: string) => { sql.push(statement); return rows; } } as unknown as BrainEngine;+ return { engine, sql };+}+async function runEntry(engine: BrainEngine): Promise<Check> {+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.emits.includes('serve_build_drift'));+ expect(entry).toBeDefined();+ const checks = await withEnv({ GBRAIN_HOME: home }, () => entry!.run({ engine, args: [], only: null } as unknown as DoctorContext));+ const check = (checks as Check[]).find(c => c.name === 'serve_build_drift');+ expect(check).toBeDefined();+ return check!;+}++describe('doctor serve_build_drift', () => {+ test('a live serve on an older build warns with a restart and a verify, in one read', async () => {+ const { engine, sql } = stub([row({ version: '0.60.209.0' }), row({ kind: 'jobs', pid: 5151, version: '0.60.209.0', mode: 'waiter_only' })]);+ const check = await runEntry(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('serve is running an older build than this checkout; restart serve and workers');+ expect(check.message).toContain('serve pid 4242 v0.60.209.0');+ expect(check.message).toContain('jobs pid 5151 v0.60.209.0');+ expect(check.message).toContain(`v${VERSION}`);+ expect(check.details).toMatchObject({ count: 2, this_version: VERSION, owner: { kind: 'serve', pid: 4242, version: '0.60.209.0' } });+ const fix = check.fix as { argv: string[]; verify: { argv: string[] }; actor: string };+ expect(fix.argv.length).toBeGreaterThan(0);+ expect(fix.actor).toBe('user');+ expect(fix.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'serve_build_drift', '--json']);+ expect(sql).toHaveLength(1);+ });++ test('consumers on this build, lapsed old rows and short-lived kinds read ok', async () => {+ const same = await runEntry(stub([row()]).engine);+ expect(same.status).toBe('ok');+ const lapsed = await runEntry(stub([row({ version: '0.60.100.0', renewedAgoMs: 120_000 }), row({ kind: 'put', pid: 7, version: '0.60.100.0' })]).engine);+ expect(lapsed.status).toBe('ok');+ expect(lapsed.details).toMatchObject({ count: 0 });+ });++ test('no heartbeat row names consumers_without_heartbeat for a serve that predates heartbeats', async () => {+ const check = await runEntry(stub([]).engine);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('consumers_without_heartbeat');+ });++ test('a serve newer than this checkout is reported, not warned', async () => {+ const check = await runEntry(stub([row({ version: '99.0.0.0' })]).engine);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('older than the running serve');+ });++ test('PGLite keeps no heartbeat rows: not applicable, no read', async () => {+ const { engine, sql } = stub([], 'pglite');+ const check = await runEntry(engine);+ expect(check.status).toBe('ok');+ expect(sql).toHaveLength(0);+ });++ test('the restart is service-specific: systemd unit, launchd agent, else the pid', async () => {+ const { serveBuildDriftCheck } = await import('../src/commands/doctor/checks/persistence-consumers.ts');+ const older = () => stub([row({ version: '0.60.209.0' })]).engine;+ const linuxHome = join(home, 'linux'), macHome = join(home, 'mac');+ mkdirSync(join(linuxHome, '.config', 'systemd', 'user'), { recursive: true });+ writeFileSync(join(linuxHome, '.config', 'systemd', 'user', 'gbrain-serve.service'), '[Unit]\n');+ mkdirSync(join(macHome, 'Library', 'LaunchAgents'), { recursive: true });+ writeFileSync(join(macHome, 'Library', 'LaunchAgents', 'com.gbrain.serve.plist'), '<plist/>');+ const argv = async (service: { platform: string; home: string; uid: number }) => ((await serveBuildDriftCheck(older(), 'host', service)).fix as { argv: string[] }).argv;+ expect(await argv({ platform: 'linux', home: linuxHome, uid: 1000 })).toEqual(['systemctl', '--user', 'restart', 'gbrain-serve.service']);+ expect(await argv({ platform: 'darwin', home: macHome, uid: 501 })).toEqual(['launchctl', 'kickstart', '-k', 'gui/501/com.gbrain.serve']);+ expect(await argv({ platform: 'linux', home: join(home, 'none'), uid: 1000 })).toEqual(['kill', '4242']);+ });+});diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 24a1aa8769..e5badca55c 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -181,6 +181,7 @@" [OK] two_consumers_on_host: PGLite admits one process; no consumer heartbeat rows are kept."," [OK] consumers_without_heartbeat: PGLite admits one process; no consumer heartbeat rows are kept."," [OK] host_identity_mismatch: This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",+ " [OK] serve_build_drift: PGLite admits one process; no consumer heartbeat rows are kept to compare builds."," [OK] extract_atoms_held_failed: No managed atom page or transcript is held after repeated extraction failures."," [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 6e9e2049c4..5ba8248643 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -2238,6 +2238,16 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 2a3fc4c786..31b03ab795 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -2343,6 +2343,16 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },{"category": "brain","details": {@@ -5514,6 +5524,16 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 9178d71e98..39a0aea1cd 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2115,6 +2115,16 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "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 934b02ace6..495967df89 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2123,6 +2123,16 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "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 a042813fdc..c938d62a59 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -773,6 +773,10 @@"category": "ops","name": "host_identity_mismatch"},+ {+ "category": "ops",+ "name": "serve_build_drift"+ },{"category": "brain","name": "extract_atoms_held_failed"