Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/gbra133-pr3a-stalls' into gbra133-pr3a
garrytan944c6579f49c
diff --cc docs/architecture/key-files/commit-notifier.mdindex f1946c8b2c,2d991a323e..6744e291d4--- a/docs/architecture/key-files/commit-notifier.md+++ b/docs/architecture/key-files/commit-notifier.md@@@ -3,11 -3,11 +3,11 @@@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- - `src/core/commit-notifier.ts` — the notifier core, pure over its seams (store, git reads, the runner). One loop per resident: claims the host lease every heartbeat (`GBRAIN_NOTIFIER_HEARTBEAT_MS`, default 10 s, lease two heartbeats; PGLite has no lease and the brain's holder owns), re-reads `sync.on_commit` and `sync.on_commit.sources` every 30 s (`parseOnCommit` is the one parser), lists the host's sources every 60 s, reads HEAD every poll (`GBRAIN_NOTIFIER_POLL_MS`, 3 s; a watch only nudges), and scans wanted markers every 15 s or on a nudge, with the flag off too. Starts on the leading edge of a quiet HEAD move (no rebase/merge/cherry-pick marker, no `index.lock`), then a 400 ms trailing window (`GBRAIN_NOTIFIER_QUIET_MS`). Per-source single flight under a host cap, least recently started first. Keeps a source due across refused starts, failed or blocked runs and resumable stops; retries at `RETRY_BACKOFF_MS` (5 s, 15 s, 1 min, 5 min) and reports `notifier_stalled` past the last tier without progress; `operator_blocked` waits for HEAD to move. Checks the fence before each start. Every decision is recorded (`decisions`) for tests; state and coverage rows are written on change only. Managed sources never take pull markers. Tests: `test/serve-head-watcher.test.ts` (memory store, `test/helpers/notifier-memory-store.ts`).+ - `src/core/commit-notifier.ts` — the notifier core, pure over its seams (store, git reads, the runner). One loop per resident: claims the host lease every heartbeat (`GBRAIN_NOTIFIER_HEARTBEAT_MS`, default 10 s, lease two heartbeats; PGLite has no lease and the brain's holder owns), re-reads `sync.on_commit` and `sync.on_commit.sources` every 30 s (`parseOnCommit` is the one parser), lists the host's sources every 60 s, reads HEAD every poll (`GBRAIN_NOTIFIER_POLL_MS`, 3 s; a watch only nudges), and scans wanted markers every 15 s or on a nudge, with the flag off too. Starts on the leading edge of a quiet HEAD move (no rebase/merge/cherry-pick marker, no `index.lock`), then a 400 ms trailing window (`GBRAIN_NOTIFIER_QUIET_MS`). Per-source single flight under a host cap, least recently started first. Keeps a source due across refused starts, failed or blocked runs and resumable stops; retries at `RETRY_BACKOFF_MS` (5 s, 15 s, 1 min, 5 min) and reports `notifier_stalled` past the last tier without progress (GBRA-133 PR 3a: a run whose status says `committed` is progress even before `last_commit` moves, and a drain-lease holder that `drainHeld` reports `stalled` is a failed attempt, `drain_holder_stalled`, instead of a silent defer; `test/honest-stalls-gbra133.test.ts`); `operator_blocked` waits for HEAD to move. Checks the fence before each start. Every decision is recorded (`decisions`) for tests; state and coverage rows are written on change only. Managed sources never take pull markers. Tests: `test/serve-head-watcher.test.ts` (memory store, `test/helpers/notifier-memory-store.ts`).- `src/core/notifier/store.ts` — the durable rows (migration `v262-commit-notifier.ts`): `sync_wanted_markers` (source + intent freshness|pull|full, `generation` bumped on every upsert, `first_due_at` kept), `sync_notifier_leases` (one owner per host, fence bumped on takeover, release expires it now), `sync_notifier_sources` (state, retry schedule, last error and trace path, classic syncer host, coverage record). A drainer deletes only `WHERE generation =` the value it read (`clearMarker`, `settleMarkers`); freshness is due while `wanted_head IS DISTINCT FROM last_commit` (no ancestry assumption). `recordLocalSyncer` runs where `writeSyncAnchor` advances `last_commit`: records the syncer host and prunes satisfied markers (the CLI's re-check). `missingTable` lets callers on a pre-v262 brain read "nothing monitored".-- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`.+- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`. #7243: `runnerStart` starts the delegated run with `logLines`, so a background run nobody polls also writes its human lines (the pass's round phase lines and progress) to the serve log as `[serve-sync] job=<id> …` (`test/sync-pass-phase-lines-7243.serial.test.ts`).- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.-- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`).+- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`). #7243: with no live owner and no drain holder, a coverage row that names a resident (`owner_kind`, the resident its trace rows name) gives `recorded_resident` (kind, pid, host, `seen_at`, the lapsed `lease_expired_at`; no pid or host remotely), and the fix names that resident and its lapsed lease instead of "No resident … watches this source" (`test/sync-status-truthful-7243.test.ts`).- `src/core/sync-pending.ts` — GBRA-133 2b.5: the oldest unsynced commit per source and the embedding backlog, read by doctor `managed_sync_latency` and `src/core/source-health.ts`. Behind = checkout HEAD differs from `sources.last_commit` (HEAD only). Dated from the reflog entry that first moved HEAD off `last_commit` (`<git dir>/logs/HEAD` read as a file, last 1 MiB), else the notifier's persisted `first_due_at` (`sync_notifier_sources` while not idle, or a due freshness marker; current incarnation only), else `unknown` with `no_reflog` or `history_rewritten`. `git: false` (a remote doctor) reads the database only; a source the notifier never recorded reads `not_observed`, never current. `readEmbedBacklog` ages live unembedded chunks from `embedding_pending_since` (keyless brains read `disabled`). `managed_sync_latency` grades a waiting commit like a p95 sample (over the target warns, over max(1 h, target) fails, unknown age warns, only with `sync.on_commit` or a target), grades classic sources on a non-managed brain, and reports `details.freshness_by_source` with `keyword_visible` and `embedded` per source (embedded is not graded). Tests: `test/pathological/s-truthful-sync-status.test.ts` + its Postgres twin, `test/sync-freshness-6858.test.ts`.diff --cc docs/architecture/key-files/google-and-loops-continued.mdindex 6cf5026206,c3e54981ad..2b22f33051--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@@ -11,7 -11,7 +11,7 @@@- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.- - **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`. #7243: an announcing drain prints a live pass's round phase lines (`[sync] pass round N: read <n> path(s) at <commit> in <t>; …` and `… importing <n> file(s) and deleting <n> page(s) …`) before the import walk's catch-up and progress lines.-- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. GBRA-133 PR 3a: only page and checkpoint commits are committed progress (a legacy-sweep slice just keeps the governor's quiet clock fresh); an abandoned pass's late progress events are dropped; a stop whose head owner reports `restart_required` is cause `owner_restart_required` (`owner_row`, `drainNext` names the process). Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.++- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. GBRA-133 PR 3a: only page and checkpoint commits are committed progress (a legacy-sweep slice just keeps the governor's quiet clock fresh); an abandoned pass's late progress events are dropped; a stop whose head owner reports `restart_required` is cause `owner_restart_required` (`owner_row`, `drainNext` names the process). Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`. #7243: an announcing drain prints a live pass's round phase lines (`[sync] pass round N: read <n> path(s) at <commit> in <t>; …` and `… importing <n> file(s) and deleting <n> page(s) …`) before the import walk's catch-up and progress lines.- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (`sync-group.ts` `dependencyKeys`, `freezeFollowers`' `taken`) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (`groupStep`, `promoteWindow`). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712). `WINDOW_CANCEL_MESSAGE` and `laneFaultCancelMessage` stay only so older receipts still read as legacy knock-ons. Test: `test/sync-group-member-order.test.ts`.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).diff --cc src/core/behavior-change-notice.tsindex 67da3c7a39,827f161554..e95a7631d5--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -1062,14 -1062,10 +1062,18 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.344.0', text: 'On a transaction-mode pooler URL (PgBouncer or Supabase port 6543, `prepare=false`, or `GBRAIN_PREPARE=false`), gbrain now pipelines the statements of one transaction on the server connection the pooler pins for it, instead of waiting one round trip per statement, so a sync or write over a slow link finishes in fewer round trips. It still never sends a statement behind one that may end the transaction (COMMIT, ROLLBACK, END, ABORT, PREPARE TRANSACTION), never pipelines autocommit statements on such a URL, and keeps prepared statements off, so the pooler cannot hand a statement to another client\'s connection. Set `GBRAIN_PG_TXN_PIPELINE=0` to send one statement per round trip again.' },{ since: '0.60.344.0', text: 'Doctor `managed_sync_latency` now grades the commit that is still waiting, not only commits that already synced: with `sync.on_commit` on or `sync.freshness_target_seconds` set, a source whose checkout HEAD has waited past the target (default 300 s) warns and past one hour fails, dated from the reflog entry that moved HEAD or the notifier\'s recorded first_due_at, and a waiting commit it cannot date (no reflog, rewritten history) warns as unknown. It grades classic sources the same way and reports keyword-visible and embedded freshness per source (`details.freshness_by_source`). `gbrain sources status` compares HEAD only (an uncommitted edit is no longer lag) and dates a behind source\'s lag from when the commit landed instead of from the last no-op sync.' },{ since: '0.60.344.0', text: '`gbrain sources mirror-readonly <id> --dry-run` and `gbrain sources mirror-writable <id> --dry-run` now print the change they would make with a `(dry-run; no side effects)` banner and write nothing (#7086); before, both ignored `--dry-run` and set or cleared the read-only mirror flag.' },+ // GBRA-158 minions wave (#7239).+ { since: '0.60.345.0', text: 'A background job that fails with a deterministic refusal (an error whose code is a caller, consent or host-only refusal the error registry does not mark retryable, or one its site marks `retryable: false`, such as `writer_coordinator_required`, `connector_account_changed`, `not_connected` or an `owner_unavailable` on a host that does not own the checkout) now ends at once as `dead` after one attempt instead of retrying until its attempts run out. Its result carries `job_outcome: "refused"` and `refusal` with the code, reason, message, fix and `gbrain errors <code>`; failures that can pass on retry (rate limits, timeouts, server and unavailable errors, write conflicts, a write still pending) retry as before. Autopilot\'s freshness dispatch then holds that source\'s automatic sync for the failure cooldown of its refusal count (10 minutes doubling to 2 hours, `autopilot.failure_cooldown_min` / `autopilot.failure_cooldown_cap_min`, 0 disables) instead of queueing a sync that is refused again every slot and every commit; it says so once per refused job (`freshness_sync_refused`), a completed sync job clears the hold, and `gbrain sync --source <id>` is never held.' },+ // #7245 (several gbrain builds run at once on one host and nothing reported it).+ { since: '0.60.345.0', text: 'New doctor check `runtime_build_skew`: it warns when serve, the jobs supervisor, worker parents (`gbrain jobs work`, autopilot-spawned ones included) and the job children they spawn run different gbrain builds on this host, or when a process\'s install now holds another build than the one it runs, and names the restart for each (serve first, then the supervisor, then a worker); nothing restarts automatically. The supervisor PID file gains two lines (its version and install root), worker-registry entries carry `version` and `install_root`, and `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. A job child whose build differs from its worker\'s now writes one `job_build_skew:` line into the job\'s history (`gbrain jobs get`) and stderr and still runs; a child missing a readiness protocol or feature its worker needs refuses the job instead, which releases it without counting an attempt and puts the worker on a configuration block until it restarts on one build.' },+ // GBRA-133 PR 3a lane S (#7243 truthful sync status). `since` is stamped at the merge slot.+ { since: 'TBD', text: '`gbrain sync status --json` now prints at most 20 holds without `--detail`: `holds_summary` counts every hold by code and by state (`needs_human`, `actionable`, `held`), and `holds` lists the first 20, needs-human first, after every other field. When holds are left out, `holds_page` carries `returned`, `limit`, `complete`, `next_cursor` and `next_command`; `--detail` pages 100 holds at a time, `--limit <n>` and `--cursor <next_cursor>` page, `--all` prints every hold, and `--hold-state <state>` lists one state. A source whose holds fit on one page prints them as before. The text status lists the same 20 and says how many more there are.' },+ { since: 'TBD', text: '`gbrain sync status` always reports `last_commit` (the commit the source\'s sync applied through) and `live`: the process holding the source\'s drain lease (a serve pass, a sync job, a CLI sync or the cycle) with its pid, heartbeat and progress, `job_id` for a Minions sync job and `stalled`, or null. `live_job_id` also names a sync job that drains a pass, not only a legacy cursor. `convergence` adds `converged_target`, the commit the stored converged obligation records (null when no stamp backs one); `convergence.target` stays the newest pass\'s pinned commit.' },+ { since: 'TBD', text: 'A `last_error` in `gbrain sync status` now also reads `superseded` once a later attempt got past the phase it failed in (a later pass started, read the source, admitted a page or committed one), with `by` naming which and `age_seconds`, and it then sets neither `needs_human`, `state` nor `next`; before, only a later committed page superseded it. The notifier block of `sync status` and doctor adds `recorded_resident`: when its row names a resident whose notifier lease lapsed, the fix names that resident instead of saying no resident watches the source. A managed pass prints `[sync] pass round N: read ...` after each level read and `... importing N file(s) ...` before its import walk, and a resident notifier\'s background run also writes its lines to the serve log (`[serve-sync] job=<id> ...`).' },+ { since: 'TBD', text: 'The `gbrain sync` hard deadline now extends only while the run commits work (a page written, deleted or renamed, or a sync cursor advanced). Screening unchanged files, held files and legacy-sweep slices no longer count, so a run that reaches its default or env deadline having committed nothing stops as a stall: it prints `code=sync_deadline_stalled` with a why and a read-only `gbrain sync status` fix (one JSON object under `--json`) instead of extending as "still progressing". A run delegated to a PGLite owner does the same, adds `deadline_stall` to its JSON and exits 1.' },+ { since: 'TBD', text: 'A managed sync drain stopped by its governor drops the abandoned pass\'s late progress events (no late `[sync] N processed` line, no count added after the stop), and a stop whose head owner reports restart_required now says so: `drain.stall.cause` is `owner_restart_required` with the owner\'s heartbeat row, and `next` tells the host admin to restart that process, then rerun (it used to read `publication_overdue` or `no_progress`).' },+ { since: 'TBD', text: 'The commit notifier counts a resumable sync that committed pages as progress even while `last_commit` has not moved yet (a long managed catch-up no longer reads `notifier_stalled`), and a source whose drain-lease holder has committed nothing for 5 minutes is no longer deferred silently: it counts as a failed attempt (`drain_holder_stalled`), so the retry tiers run and sync status and doctor show the sync-now fix.' },+ { since: 'TBD', text: 'A sync pass\'s checkpoint that its pass can no longer publish (the pass ended, or another pass started) is now refused `sync_pass_superseded` instead of `revision_conflict`: it records no managed-sync failure, reads `superseded` in `gbrain sources writer failures` and does not count as an unresolved terminal failure, and a pass that stops with its checkpoint still pending reports `managedWrite.disposition: superseded` instead of "Re-run the same sync options to resume this request".' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */