Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (pass 2): one drain-lease liveness rule for every live-job reader, read-only serve docs scoped to Postgres
garrytan122b2f2b146a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e0cbfc359..e10f4d3a4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,12 +16,12 @@ identifiers and attribution are available in the pre-removal Git revisionA killed pass used to read `resumable` / `pass_unfinished`, the same as one that stopped cleanly at its deadline, and `live` still named the dead PID because its lock row outlives it. Now an open pass that no process is still renewing reads `pass_interrupted`, a second killed pass reads `pass_abandoned` at once, and doctor's `managed_sync_blocked` lists both. This is the visibility half of #7596; the memory growth itself is still being traced on real data.-Harnesses run one `gbrain serve --access read-only` per session. Each one opened the 3-connection resident direct pool, started a persistence consumer, took the on-commit notifier lease and ran sweeps, so a few sessions could exhaust the session lane (`EMAXCONNSESSION`). A read-only serve now holds 0 session-lane connections and runs none of those duties. Search latency is unchanged: warm p50 about 0.8 s on both lanes at 50 ms RTT, on 3,000 synthetic pages.+Harnesses run one `gbrain serve --access read-only` per session. Each one opened the 3-connection resident direct pool, started a persistence consumer, took the on-commit notifier lease and ran sweeps, so a few sessions could exhaust the session lane (`EMAXCONNSESSION`). On Postgres a read-only serve now holds 0 session-lane connections and runs none of those duties. On PGLite it keeps them, because the CLI's reads and writes go through the one process that owns the database file. Search latency is unchanged: warm p50 about 0.8 s on both lanes at 50 ms RTT, on 3,000 synthetic pages.### Itemized changes-- `src/core/persistence/sync-lease.ts`, `sync-pass-status.ts`, `sync-status.ts`, `sync-blocked.ts`, `src/commands/sync/operator.ts`, `src/commands/doctor/checks/managed-sync-blocked.ts`: `drainHolderLive`, the `pass_interrupted` reason and `interrupted` block, and the doctor listing. Test: `test/sync-pass-interrupted-7596.test.ts`.-- `src/core/direct-pool-profile.ts`, `src/commands/serve.ts`, `src/mcp/server.ts`, `src/mcp/resolve-ipc-binding.ts`: a read-only stdio serve takes the one-shot profile and skips the consumer, the delegated sync, nudge and sweep kinds, the resident tickers and the sweeps. Tests: `test/direct-pool-profile.test.ts` and `test/e2e/serve-read-only-session-lane-postgres.test.ts` (3 direct connections on the previous release, 0 now).+- `src/core/persistence/sync-lease.ts`, `sync-pass-status.ts`, `sync-status.ts`, `sync-blocked.ts`, `src/commands/sync/operator.ts`, `src/commands/doctor/checks/managed-sync-blocked.ts`: `readDrainLease` and `drainLeaseLive` (one liveness rule for status, doctor and the autopilot's live-job check), the `pass_interrupted` reason and `interrupted` block, and the doctor listing. Test: `test/sync-pass-interrupted-7596.test.ts`.+- `src/core/direct-pool-profile.ts`, `src/commands/serve.ts`, `src/mcp/server.ts`, `src/mcp/resolve-ipc-binding.ts`: a read-only stdio serve takes the one-shot profile and, on Postgres, skips the consumer, the delegated sync, nudge and sweep kinds, the resident tickers and the sweeps. Tests: `test/direct-pool-profile.test.ts` and `test/e2e/serve-read-only-session-lane-postgres.test.ts` (3 direct connections on the previous release, 0 now), `test/serve-read-only-pglite-owner-7599.test.ts` (CLI writes beside a read-only PGLite serve).## [0.60.461.0] - 2026-10-25diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 9369dab989..a15d9749fd 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -14,7 +14,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`. #6712 PR 3 (L7): `slug_mode_refused` is an unfinished cursor whose every page committed and whose checkpoint was refused `slug_root_mode_mismatch` while the source still pins the other mode (`slugModeRefusedSql`, bound to the run and request at apply); no sync rediscovers it, so retiring it is how a person keeps the pin, and its slice record is cleared like `checkpoint_moved`'s.- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/sync-pass-handover-6712.test.ts` (the live pass's handover of an older binary's cursors) and `test/persistence-sync-cursor-strategy-6696.test.ts`.-- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. #7596: `drainHolderLive` is `isLockHolderLive`'s rule at the drain TTL; a killed holder's lock row outlives it until a takeover, so status reads it as not live. Pinned by `test/persistence-sync-lease.test.ts`.+- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. #7596: `drainLeaseLive` is `isLockHolderLive`'s rule at the drain TTL (`readDrainLease` returns it with the holder, and `liveSyncJob` counts only a live holder); a killed holder's lock row outlives it until a takeover, so status reads it as not live. Pinned by `test/persistence-sync-lease.test.ts`.- `src/core/persistence/sync-idle-skips.ts` — GBRA-133 (PR 2b): the managed no-op fast path. An idle tick (`stampIdlePass`) records on the drain lease (`idleClear`) whether its pin read no hold of the incarnation, a zero hold summary, no `managed-sync-failure` row of the source and no owed tail (`readIdleFacts` rides the pin's round trip). `idleSkips` names the settles that then have nothing to do (`IDLE_SKIPS`: the hold report in `performManagedPass`; settled failures, which also needs no ledger row of the source; the needs-human sweep, the sync tail and both heals in `perform.ts`). The tick, its lease, its pass row and its result are unchanged; the upstream observation, the remember replay and the ghost-page report still run. `GBRAIN_SYNC_IDLE_FAST_PATH=0` runs every settle. Pinned by `test/sync-idle-skips-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).- `src/core/sync-dispatch-read.ts` — GBRA-133 (PR 2b): the routing read of a single-source CLI sync. `withSyncDispatchRead` (`src/commands/sync/run.ts`, never `--all` or `--watch`) answers the source resolver, the company profile, `resolveSyncPersistenceMode`, the content-directory anchor, the managed-flag refusals, the delegation ladder's mode check and `perform.ts`'s connector check from one combined row per source (`syncDispatchRow`: the sources row, the claim, the company receipt and the mode rows). `endSyncDispatchRead` ends the scope for good where the work starts (`performSync` once the route is chosen, `maybeDelegateManagedSyncToServe` before the hand-off), so every read under the drain lease and after a write stays live; outside the scope, or when the combined read fails, each reader runs its own query. Pinned by `test/sync-dispatch-read-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).@@ -48,7 +48,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `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; 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 writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/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). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). 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` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--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/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. #7604: the supersede check reads the newest committed sequence per (source, slug) once, over the rows after the oldest sample (a materialized CTE), so the read stays linear in the samples after a killed pass leaves tens of thousands of receipts (a per-receipt subquery is quadratic and reaches the 300 s statement timeout). `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.-- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; #7596: a holder that stopped renewing the lease (`drainHolderLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; #7596: a holder that stopped renewing the lease (`readDrainLease`, `drainLeaseLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and `get_write_request`'s `applied`; `gbrain pages status` (#7181) can compose it with its Git view.- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (`get_write_request`): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 738dada3ab..50c69f5124 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -583,14 +583,16 @@ drives `tools/list`, the `gbrain://capabilities` resource (`access:mutations; owner maintenance on the same process (startup migrations, hookIPC banking) is a separate control. The default is `--access full`.-A read-only serve is also not a resident owner, because harnesses start one per-session. It holds no session-lane (direct pool) connection, starts no+On Postgres a read-only serve is also not a resident owner, because harnesses+start one per session. It holds no session-lane (direct pool) connection, starts nopersistence consumer, takes no on-commit notifier lease, runs no startup or idlesweep, and refuses delegated sync and sweep requests; resolve, turn_context andcontext_pack still answer. A read-write `gbrain serve`, `gbrain jobs work` orthe autopilot owns those duties. `gbrain doctor` reports when no process on thehost holds the on-commit notifier (`commit_notifier`) or a persistence consumer-(`two_consumers_on_host`).+(`two_consumers_on_host`). On PGLite a read-only serve keeps those duties: it is+the process that owns the database file, so the CLI's reads and writes go+through it.`gbrain serve --http --access read-only` refuses: narrow HTTP access per tokenwith `gbrain auth rescope-token <name> --operations <op,...>` or`gbrain auth rescope-client <client_id> --allowed-operations <op,...>`diff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.tsindex 32c751eca4..8b0a3677bc 100644--- a/src/commands/doctor/checks/managed-sync-blocked.ts+++ b/src/commands/doctor/checks/managed-sync-blocked.ts@@ -32,7 +32,8 @@ async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]>checks.push({ name: 'managed_sync_blocked', status: over.length ? 'fail' : 'warn', readiness_state: 'degraded',details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },message: `${list}: the managed sync run is stopped on a page that did not commit, its passes keep stopping without converging, or its pass stopped before it ended with no process left to finish it (killed or crashed), so the source indexes nothing new until it is cleared`- + `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}. Freshness sync jobs for the source end dead with the run's next step instead of completed.`,+ + `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}.`+ + (blocked.some(b => b.code !== 'pass_interrupted') ? " Freshness sync jobs for the source end dead with the run's next step instead of completed." : ''),fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],'Read-only: names the page the run stopped on, its fault class and the next step (a hold to reconcile, a repair to preview, or the resume command).','managed_sync_blocked', { docs: DOCS }) });diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex ab46b08286..57eb3b1e02 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -852,9 +852,9 @@ function installStdioLifecycle(// budget). SEPARATE timer from the parent watchdog, through the same// injectable deps.setInterval seam, unref'd per the serve convention so// it can never hold the process open. Cleared in beginShutdown. Kill- // switch: GBRAIN_SWEEP=0 (seam: opts.sweepEnabled). Chunk-level stdin- // 'data' granularity is sufficient — same rationale as armIdle below.- const sweepEnabled = !readOnlyServeSkipsResidentDuties(isReadOnlyServeArgs(args), engine.kind) && (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0')); // #7599: no sweep in a read-only Postgres serve+ // switch: GBRAIN_SWEEP=0 (seam: opts.sweepEnabled). Chunk-level stdin 'data' granularity is sufficient (see armIdle).+ const lean = readOnlyServeSkipsResidentDuties(isReadOnlyServeArgs(args), engine.kind); // #7599: a read-only Postgres serve+ const sweepEnabled = !lean && (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0')); // runs no sweepif (sweepEnabled) {const runIdleSweep = opts.sweep ?? (async (e: BrainEngine) => {// #4409: the runner loads lazily here too — the sweep fires after@@ -912,7 +912,7 @@ function installStdioLifecycle(}// Automatic facts drain (Lane D) and the #6317 movement watch: see installResidentTickers.- factsDrain = readOnlyServeSkipsResidentDuties(isReadOnlyServeArgs(args), engine.kind) ? null : installResidentTickers(engine, opts, deps, () => shuttingDown); // #7599: nor its resident tickers+ factsDrain = lean ? null : installResidentTickers(engine, opts, deps, () => shuttingDown); // #7599: nor its resident tickers// Optional idle-timeout safety net. Default OFF; opt-in via// `--stdio-idle-timeout <seconds>`. The flag is for the rare case wherediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c788c25456..35e72b6ce7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1302,7 +1302,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.460.0', text: 'A legacy fact row whose `notability` or `confidence` is empty (a long-lived database whose column lost its NOT NULL) is now adopted into its page\'s `## Facts` table with the column default (notability `medium`, confidence 1) instead of being refused as unadoptable (`parse`) on every run, which held its page out of fact reconciliation and booked an `integrity_guard` halt each cycle. The fence cell is written first and the row derives its values from it. A row with no kind or visibility is still refused.' },{ since: '0.60.460.0', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },- { since: '0.60.462.0', text: '`gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves are unchanged.' },+ { since: '0.60.462.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves, and any serve on PGLite (the process that owns the database file), are unchanged.' },{ since: '0.60.462.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },];diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.tsindex a84558a58b..9d6a2bffe8 100644--- a/src/core/persistence/sync-blocked.ts+++ b/src/core/persistence/sync-blocked.ts@@ -57,13 +57,14 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s// #7596: an open pass no recorded stop explains, whose drain lease no process renews: its process was killed or crashed.const open = readings.filter(reading => reading.row.value.telemetry.outcome === 'open' && !listed.some(blocked => blocked.source_id === reading.source_id));if (!open.length) return listed;- const [{ inspectLock, isLockHolderLive, syncLockId }, { DRAIN_LEASE_TTL_MINUTES }, { abandonedPasses }] = await Promise.all([+ const [{ inspectLock, syncLockId }, { drainLeaseLive }, { abandonedPasses }] = await Promise.all([import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts')]);const now = Date.now();- for (const { source_id, row } of open) {- const lock = await inspectLock(engine, syncLockId(source_id)).catch(() => undefined);+ const locks = await Promise.all(open.map(({ source_id }) => inspectLock(engine, syncLockId(source_id)).catch(() => undefined)));+ for (const [i, { source_id, row }] of open.entries()) {+ const lock = locks[i];if (lock === undefined) continue;- const interrupted = !lock || !isLockHolderLive(lock, DRAIN_LEASE_TTL_MINUTES);+ const interrupted = !lock || !drainLeaseLive(lock);const abandoned = abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK;if (interrupted || abandoned) listed.push({ source_id, code: abandoned ? 'pass_abandoned' : 'pass_interrupted', run_id: row.value.telemetry.pass_id, blocked_since: abandoned ? passStuckSince(row) : row.updated_at });}diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex bb9de1159d..bf91887a90 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -36,7 +36,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import type { SyncResult } from '../../commands/sync.ts';import type { Action } from '../agent-output.ts';-import { fenceLockRow, inspectLock, isLockHolderLive, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';+import { fenceLockRow, inspectLock, isLockHolderLive, type LockSnapshot, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';import { currentRunDeadline, lastForwardProgressAt, noteCommittedProgress, noteForwardProgress } from '../forward-progress.ts';import { faultPoint } from './fault-points.ts';import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';@@ -120,7 +120,7 @@ export async function inFencedSlices<T>(engine: BrainEngine, sourceId: string, iconst iso = (value: Date | null | undefined) => value ? value.toISOString() : null;-/** The live holder of a source's drain lease (kind and id from the row this module writes beside the lock), or null. */+/** The holder of a source's drain lease (kind and id from the row this module writes beside the lock), live or not (`readDrainLease` says which), or null. */export async function readDrainHolder(engine: BrainEngine, sourceId: string): Promise<DrainHolder | null> {return (await readDrainLease(engine, sourceId))?.holder ?? null;}@@ -138,9 +138,12 @@ export async function readDrainLease(engine: BrainEngine, sourceId: string): Proconst holder: DrainHolder = { kind: meta?.kind ?? 'unknown', id: meta?.id ?? null, host: snap.holder_host, pid: snap.holder_pid,started_at: iso(snap.acquired_at), last_heartbeat_at: iso(snap.last_refreshed_at), version: meta?.version ?? null,progress: await holderProgress(engine, sourceId, snap.acquired_at).catch(() => null) };- return { holder, live: isLockHolderLive(snap, DRAIN_LEASE_TTL_MINUTES) };+ return { holder, live: drainLeaseLive(snap) };}+/** #7596: whether the drain lease's holder still renews it: `isLockHolderLive` at the drain TTL, the one rule status and doctor read. */+export const drainLeaseLive = (snap: LockSnapshot): boolean => isLockHolderLive(snap, DRAIN_LEASE_TTL_MINUTES);+/*** The source's managed-sync commits since `since`, and its last commit, cursor save, (#6712 PR 4b, design v3.2 §3.7)* pass row write or (#7327) hold write at all: a pass writes its row at the pin, per batch and at the stamp, and everydiff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.tsindex 565dc092b6..a19c7446d6 100644--- a/src/core/persistence/sync-movement.ts+++ b/src/core/persistence/sync-movement.ts@@ -121,11 +121,12 @@ interface HoldRow { count: number | string | null; stalled: number | string | nu/*** #6706: the id of the active `sync` Minions job with a live lock that is draining `sourceId`, or null. Never rejects.* #6712 PR 1: a job drains under the source's drain lease, so its holder row names the job first; the job-table read- * stays for a job an older gbrain started (it takes no lease). #7596 `liveHolder`: the holder a caller already read, null- * when it read none still renewing the lease (a killed job's lock row names it until a takeover).+ * stays for a job an older gbrain started (it takes no lease). #7596: a holder that stopped renewing the lease is not live (a+ * killed job's lock row names it until a takeover); `liveHolder` is the live holder a caller already read that way, or null.*/export async function liveSyncJob(engine: BrainEngine, sourceId: string, liveHolder?: DrainHolder | null): Promise<number | null> {- const holder = liveHolder !== undefined ? liveHolder : await (await import('./sync-lease.ts')).readDrainHolder(engine, sourceId).catch(() => null);+ const holder = liveHolder !== undefined ? liveHolder+ : await (await import('./sync-lease.ts')).readDrainLease(engine, sourceId).then(lease => lease?.live ? lease.holder : null, () => null);if (holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id)) return Number(holder.id);// The lease's beacon row (sync-lease.ts) is for older binaries; this build reads the lease holder above.const [row] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM minion_jobs WHERE name='sync' AND status='active' AND lock_until > now() AND queue <> 'gbrain-drain-lease'diff --git a/test/resolve-ipc-binding.test.ts b/test/resolve-ipc-binding.test.tsindex 355dacafd5..8c237bfc70 100644--- a/test/resolve-ipc-binding.test.ts+++ b/test/resolve-ipc-binding.test.ts@@ -16,7 +16,7 @@ import { join } from 'node:path';import net from 'node:net';import { once } from 'node:events';import { bindResolveIpcForServe } from '../src/mcp/resolve-ipc-binding.ts';-import { readIpcSecret, requestSweepStatus, requestSyncStatus, resolveSocketPath, socketHasLiveListener } from '../src/core/context/resolve-ipc.ts';+import { readIpcSecret, requestSweepStart, requestSweepStatus, requestSyncAbort, requestSyncNudge, requestSyncStart, requestSyncStatus, resolveSocketPath, socketHasLiveListener } from '../src/core/context/resolve-ipc.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withEnv } from './helpers/with-env.ts';import { requestPersistenceCapabilities } from '../src/core/persistence/ipc.ts';@@ -112,6 +112,10 @@ describe('bindResolveIpcForServe (#4474)', () => {const want = readOnly ? 'unsupported_kind' : 'unknown_job';expect((sync as { error?: string }).error).toBe(want);expect((sweep as { error?: string }).error).toBe(want);+ if (!readOnly) continue;+ for (const write of [requestSyncStart, requestSyncAbort, requestSyncNudge, requestSweepStart]) {+ expect(((await write(binding.socketPath!, { secret } as never)) as { error?: string }).error).toBe('unsupported_kind');+ }} finally {const closed = binding.server ? once(binding.server, 'close') : Promise.resolve();binding.close();diff --git a/test/serve-idle-sweep-source.serial.test.ts b/test/serve-idle-sweep-source.serial.test.tsindex 0cc5a28212..5d7719f8eb 100644--- a/test/serve-idle-sweep-source.serial.test.ts+++ b/test/serve-idle-sweep-source.serial.test.ts@@ -109,4 +109,18 @@ describe('serve idle sweep source resolution (#4679)', () => {expect(sweepCalls.length).toBe(1);expect(sweepCalls[0].sourceId).toBe('wiki');}, 20_000);++ test('#7599: a read-only serve on Postgres arms no idle sweep; read-write, or on PGLite, it does', async () => {+ const armed: string[] = [];+ for (const [kind, args] of [['postgres', ['--access', 'read-only']], ['postgres', []], ['pglite', ['--access', 'read-only']]] as const) {+ let timers = 0;+ await withEnv({ GBRAIN_SOURCE: undefined }, () => runServe({ ...makeEngine(['default']), kind } as BrainEngine, [...args], {+ stdin: new EventEmitter() as never, signals: new EventEmitter() as never, exit: () => {}, log: () => {}, startMcpServer: async () => {},+ getParentPid: () => 1, probeWatchdog: () => true, setInterval: () => { timers++; return { unref() {} }; }, clearInterval: () => {},+ mcpStdio: false, bootTimeoutMs: 0, sweepEnabled: true, factsDrain: false,+ }));+ armed.push(`${kind} ${args.join(' ') || 'read-write'}: ${timers}`);+ }+ expect(armed).toEqual(['postgres --access read-only: 0', 'postgres read-write: 1', 'pglite --access read-only: 1']);+ }, 20_000);});diff --git a/test/sync-pass-interrupted-7596.test.ts b/test/sync-pass-interrupted-7596.test.tsindex 635b552a8b..43eec98979 100644--- a/test/sync-pass-interrupted-7596.test.ts+++ b/test/sync-pass-interrupted-7596.test.ts@@ -17,7 +17,8 @@ import { syncLockId } from '../src/core/db-lock.ts';import type { BrainEngine } from '../src/core/engine.ts';import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';import { abandonedPasses, passStatusNext, passStatusState } from '../src/core/persistence/sync-pass-status.ts';-import { MANAGED_SYNC_PASS_OP, type PassRow } from '../src/core/persistence/sync-pass-row.ts';+import { MANAGED_SYNC_PASS_OP, type PassRow, readPassRow } from '../src/core/persistence/sync-pass-row.ts';+import { liveSyncJob } from '../src/core/persistence/sync-movement.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { managedBrain } from './helpers/managed-brain.ts';@@ -85,9 +86,12 @@ for (const backend of testBackends()) {expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_interrupted' })]);// A lease that cannot be read decides nothing: the fresh open pass reads unfinished, and doctor lists nothing for it.+ const passRowNow = () => engine.executeRaw(`SELECT completed_keys, updated_at FROM op_checkpoints WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);+ const before = await passRowNow();const lockRead = spyOn(dbLock, 'inspectLock').mockRejectedValue(new Error('lock read failed'));try {status = await readSyncStatus(engine, 'default', { detail: false });+ expect(await passRowNow()).toEqual(before);expect(status.reason).toBe('pass_unfinished');expect(status.interrupted).toBeNull();expect(await blocked()).toEqual([]);@@ -109,6 +113,17 @@ for (const backend of testBackends()) {expect(await doctor()).toMatchObject({ name: 'managed_sync_blocked', status: 'fail' });await lockRow(engine, '3 minutes', '-1 minute');+ // A killed sync job's lock row still names the job: no reader counts it as a live job (the autopilot's freshness skip reads liveSyncJob).+ await engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1', [syncLockId('default')]);+ await engine.executeRaw(`INSERT INTO minion_jobs(name,queue,status,submission_authority,data,max_attempts,max_stalled,lock_token,lock_until,started_at,remove_on_complete,remove_on_fail)+ SELECT 'sync','gbrain-drain-lease','active','{"version":1,"kind":"application"}'::jsonb,$2::text::jsonb,1,0,acquisition_token::text,now()-interval '1 minute',now(),true,true+ FROM gbrain_cycle_locks WHERE id=$1`, [syncLockId('default'), JSON.stringify({ sourceId: 'default', drain_lease_beacon: { kind: 'job', id: '4242' } })]);+ expect(await liveSyncJob(engine, 'default')).toBeNull();+ status = await readSyncStatus(engine, 'default', { detail: false });+ expect([status.reason, status.live, status.live_job_id]).toEqual(['pass_interrupted', null, null]);+ expect(status.interrupted?.holder).toMatchObject({ kind: 'job', id: '4242' });+ await engine.executeRaw("DELETE FROM minion_jobs WHERE queue='gbrain-drain-lease'");+// A holder that renewed the lease just now is a pass still running: not interrupted, not blocked.await lockRow(engine, '1 second', '2 minutes');status = await readSyncStatus(engine, 'default', { detail: false });@@ -116,6 +131,23 @@ for (const backend of testBackends()) {expect(status.live).toMatchObject({ pid: 4242 });expect(status.interrupted).toBeNull();expect(await blocked()).toEqual([]);++ // Resuming: a plain sync takes the dead holder's expired lock over and ends the pass, and after a second+ // interrupted pass it also clears the streak. Nothing reads interrupted or abandoned afterwards.+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const resume = async () => {+ const result = await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });+ const ended = (await readPassRow(engine, 'default', incarnation!))!;+ expect([result.status, ended.value.telemetry.outcome, abandonedPasses(ended), passStatusState(ended, null)]).toEqual(['up_to_date', 'up_to_date', 0, null]);+ expect(await engine.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1', [syncLockId('default')])).toHaveLength(0);+ expect(await blocked()).toEqual([]);+ expect((await readSyncStatus(engine, 'default', { detail: false })).interrupted).toBeNull();+ };+ await lockRow(engine, '3 minutes', '-1 minute');+ await resume();+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,'{0,telemetry,outcome}','"open"'),'{0,obligations,abandoned_streak}','1') WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);+ expect((await readSyncStatus(engine, 'default', { detail: false })).reason).toBe('pass_abandoned');+ await resume();}, { databaseUrl, setup: ({ root }) => {git(root, ['init', '-q']);writeFileSync(join(root, 'a.md'), '---\ntype: concept\ntitle: a\n---\n\nA note about a.\n');