Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): transient pass stops build the abandoned streak; an onlyOpen stop never inserts a gone row; pass and holder readers use the database clock (#7982)
garrytanaffcc4f709b2
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 7c7beb65aa..335847c25a 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -25,11 +25,11 @@ See [generations](generations.md).- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.- `src/core/persistence/sync-dry-run-writer.ts` — #7167: `readDryRunWriterState(engine, sourceId)`, the writer state a managed dry run reports (`SyncResult.writer`: open queued/running/recovering requests of the source, the oldest one's age, and `gbrain sources writer status` as the next step) instead of waiting on the writer. A CLI dry run runs once outside the drain (`commands/sync/perform.ts`), so the drain's no-progress governor never abandons a long read as a writer stall, and a dry run that is not delegated to a serve says it previews in this process (`commands/sync-delegate.ts`). Test: `test/sync-dry-run-drain-7167.test.ts`.- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. #7149: a requested re-screen (the `sync-hold-retry` row) is consumed as soon as the pass settles its path (the batch carrying it drained, or the round classified it settled), not only by the stamp, so a pass that stops before its stamp leaves no imported file reported as waiting. Tests: `test/sync-pass-live-6712.test.ts`, `test/unindexed-files-convergence-7149.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`.-- `src/core/persistence/sync-pass-row.ts` — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. `managed-sync-pass` (fingerprint `<source>:<incarnation>`) holds `obligations` (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and `telemetry` (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). `writePassRow` writes it at pin under `assertDrainLease` and afterwards only `WHERE lease_token = $token`. Beside it: `sync-origin-deleted` (deletion markers), `sync-deletes-withheld` (the mass-delete trip) and `sync-pass-cost` (one reservation per group); `SYNC_PASS_ROW_OPS` lists the ops the checkpoint GC keeps for a live incarnation. `passHealth` is the one health rule (`blocked`, `not_converged`, `settle_mismatch`, `open_stalled`, `nothing_pending`); `SETTLE_MISMATCH_STREAK` and `NOT_CONVERGED_REPORT_STREAK` are 3.+- `src/core/persistence/sync-pass-row.ts` — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. `managed-sync-pass` (fingerprint `<source>:<incarnation>`) holds `obligations` (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and `telemetry` (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). `writePassRow` writes it at pin under `assertDrainLease` and afterwards only `WHERE lease_token = $token`; an `onlyOpen` stop write updates a row still open and never inserts one that is gone. `readPassRow` / `readLivePassRows` carry the database clock at the read (`read_at`, `passReadClock`), which the readers compare `updated_at` with. Beside it: `sync-origin-deleted` (deletion markers), `sync-deletes-withheld` (the mass-delete trip) and `sync-pass-cost` (one reservation per group); `SYNC_PASS_ROW_OPS` lists the ops the checkpoint GC keeps for a live incarnation. `passHealth` is the one health rule (`blocked`, `not_converged`, `settle_mismatch`, `open_stalled`, `nothing_pending`); `SETTLE_MISMATCH_STREAK` and `NOT_CONVERGED_REPORT_STREAK` are 3.- `src/core/persistence/sync-pass-readers.ts` — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (`readManagedSyncBacklog`), the blocked-run reader and `sources status` read a non-company source's pass row through `readPassReadings` (`passHealth` plus the checkout HEAD from a hardened `rev-parse` on this host; no checkout means `head: null` and the recorded converged target is trusted). `passResumeArgs` is the plain sync that continues the pass, with the open episode's inherited options; `passStopCode` and `passStuckSince` name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: `test/sync-pass-readers-6712.test.ts`, `test/sync-pass-reader-gaps-6712.test.ts`.- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round (GBRA-108: in slices of `LEGACY_SWEEP_SLICE` (100) whose records commit before the next slice, each followed by a pass-row save and a `managed_sync.legacy_swept` progress event the drain's in-pass governor counts, so a pass stopped mid-sweep keeps its slices and the next pass sweeps only the rest; seam `sync:legacy_slice`; tests `test/sync-legacy-sweep-gbra108.test.ts` and its Postgres twin), the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.- `src/core/persistence/sync-pass-episode.ts` — pass episodes and cost (#6712 PR 4b, design §6, §7): `episodeClosure` closes an episode by inclusion or at the configured selection (a narrower episode never stamps `chunker_version`; a widened one releases its extra paths), `passCostDecision` defers paid embedding when the envelope is unknown or spent, and `reservePassCost` writes one `sync-pass-cost` row per admitted group (fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`, insert-once) inside the group's admission transaction, so a kill keeps the reservation and a replay adds nothing. Tests: `test/sync-pass-completion-6712.test.ts`.-- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.+- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (`abandonedPasses` counts passes left open and passes ended on a transient stop toward `pass_abandoned`; reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). An owner purge of a shared-origin page refuses and names the soft delete (the retention purge for a tombstone). #7311: the retention purge of a shared-origin tombstone is database-only like an `origin_twin` page's (`sharedRetention`: no file target, applied with `source_path`/`source_uri` forgotten, so no deletion marker names the survivor's file); `validate` re-runs the census, and a changed one refuses `revision_conflict` (`sharedTombstoneChanged`, a purge deferral), so the next run takes the normal path. Tests: `test/purge-shared-origin-tombstone-7311.test.ts` (Postgres: `test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts`), `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 996e13bc06..e9de796e0a 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -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. `parseMovementArgs` refuses `--json` or `--warn-only` written with a value (`invalid_params`), except `--json=true`, which it reads as `--json` (#7619). 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 still renewing it, from `readDrainLease`, 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). #7679: `worktree_refresh` is the active refresh of the source's worktree (read in the source statement, so no extra statement) with its holder, `liveness`/`orphaned` and fix; an orphaned one's `--resume` fix becomes `next` unless a person's decision comes first.+- `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 still renewing it, from `readDrainLease`, 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` on the lease read's database clock (`db_now`); #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). #7679: `worktree_refresh` is the active refresh of the source's worktree (read in the source statement, so no extra statement) with its holder, `liveness`/`orphaned` and fix; an orphaned one's `--resume` fix becomes `next` unless a person's decision comes first.- `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. A source whose `local_path` is relative refuses `sync_anchor_relative` (exit 3, an `ask_user` `gbrain sources set-path` fix). 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/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex c9025269a9..b8ab9eb308 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -376,7 +376,7 @@ run converges on the next plain sync with no flag.|---|---|---|---|| `pass_unfinished` | resumable | The newest pass is open or stopped at a deadline. | The plain sync (`resume_argv`); safe to loop. || `pass_interrupted` | resumable | The newest pass is open but no process holds the source's drain lease: its process was killed or crashed (an out-of-memory guard, a timeout) before it ended the pass, so nothing recorded a failure. `live` is null and `interrupted` names the pass, its last write and, when the lock row outlived the process, the holder and the pages it committed. Doctor `managed_sync_blocked` lists it as `pass_interrupted` (warn, then fail after an hour). | The plain sync; if that pass stops the same way, the reason becomes `pass_abandoned`. |-| `pass_abandoned` | blocked | Two passes in a row never ended: the drain stopped them for making no progress, or their process was killed. The newest open pass counts once no process holds the source's drain lease (#7596; a reader without the lease read counts it once its row has not moved for 5 minutes). | `gbrain doctor --json` and a report with the gbrain version and the newest run's `drain.stall`; another plain sync is likely to stop the same way. |+| `pass_abandoned` | blocked | Two passes in a row never ended or ended on the same kind of transient stop: the drain stopped them for making no progress, their process was killed, or each hit a statement timeout, a lost connection or write back-pressure (#7982). The newest open pass counts once no process holds the source's drain lease (#7596; a reader without the lease read counts it once its row has not moved for 5 minutes). | `gbrain doctor --json` and a report with the gbrain version and the newest run's `drain.stall`; another plain sync is likely to stop the same way. || `not_converged` | resumable | The pass used its four rounds while another writer kept changing the level. Everything it admitted stands. | The plain sync; after three such passes in a row `next` is `gbrain doctor --json` and a report, because another sync will not change it. || `settle_mismatch` | resumable | A path keeps settling without reading settled. The next pass re-admits it once; after three passes at one level it is a `settle_mismatch` hold that needs a person. | The plain sync, then report the hold. || `deletes_withheld` | blocked | The pass's deletes crossed the mass-delete threshold (#2828) or an absolute cap (#7130: `sync.max_deletes`, default 500; `sync.max_delete_ratio`, default 0.01 above 50 deletes; per source `<key>.source.<id>`). The record's `trip` names which. It wrote one withheld record and synced everything else; no per-page hold is written. | Ask the user: restore the checkout if it is wrong; when the deletion is intended, raise the cap for that source (`gbrain config set sync.max_deletes.source.<id> <n>`) or run `GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source <id>` on the brain host. `gbrain sync --source <id> --dry-run --json` lists the set and its hash. |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 16f137e91f..44da139367 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -167,7 +167,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.-<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. So does an open pass whose process was killed or crashed with no process left holding its drain lease (code `pass_interrupted`, aged from the pass row's last write), and passes that keep stopping that way (`pass_abandoned`). Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.+<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. So does an open pass whose process was killed or crashed with no process left holding its drain lease (code `pass_interrupted`, aged from the pass row's last write), and passes that keep stopping that way or on a transient stop such as a statement timeout (`pass_abandoned`). Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d7d75adfed..ee209b1fb9 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1755 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1571 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +1 GBRA-247 #8009 provenance_repair_held_8009 row; +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope)+src/core/behavior-change-notice.ts 1572 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex eece806854..c5c25576cb 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1373,6 +1373,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.514.0', id: 'company_db_only_keep_8014', text: 'A company-brain source now keeps a live page under a declared `storage.db_only` directory when its file is not in the approved manifest, and keeps every such page while its gbrain.yml storage section is invalid, as other managed sources do; it used to delete them. The decision reads gbrain.yml at the approved commit, never the working tree.' },{ since: '0.60.514.0', id: 'redaction_marker_not_credential_7997', text: 'The transcript `labeled_credential` detector no longer reads an importer redaction marker (`login **<REDACTED:user-pattern>**`) as a typed user/password pair, so a correctly redacted page clears `gbrain transcripts audit-secrets`; a password written beside a marker is still found. The audit detector version moves to 3, so `gbrain doctor` asks for a fresh audit once.' },{ since: '0.60.516.0', id: 'provenance_repair_held_8009', text: '`gbrain repair provenance` now lists a page whose file sync holds (a `file_drift` hold, for example) as `held`, with the hold\'s code and fix, instead of planning it: the owner page write refuses such a page, so the preview used to count pages the apply could not write and the batch ended with a failed item. The apply also skips a page held after its preview as `held` rather than failing it, so it writes the count the preview printed.' },+ { since: '0.60.516.0', id: 'pass_transient_streak_7982', text: '`gbrain sync status` and doctor `managed_sync_blocked` now read a managed source `blocked` / `pass_abandoned` (next: `gbrain doctor --json` and a report) when its last two sync passes each ended on a transient stop (a statement timeout, a lost connection, write back-pressure, a worktree refresh), as they already did for passes left open; one such pass still reads `resumable` with the plain sync. The idle-pass and stalled-holder readings compare database timestamps with the database clock, so a host clock running ahead no longer reads a running pass as abandoned or a progressing holder as stalled.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex d26c0d9375..41eb9cf75f 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -525,6 +525,8 @@ export interface LockSnapshot {last_refreshed_at: Date | null;/** ms since the most recent refresh, or null when last_refreshed_at is null. */ms_since_last_refresh: number | null;+ /** #7982: the clock the derived fields were computed against: the database's at the read (the reader's only for a row without it). */+ db_now: Date;}/**@@ -572,6 +574,7 @@ function rowToLockSnapshot(row: RawLockRow, readerNow: number): LockSnapshot | nttl_expired: ttlExpires.getTime() < now,last_refreshed_at: lastRefreshed,ms_since_last_refresh: lastRefreshed ? now - lastRefreshed.getTime() : null,+ db_now: new Date(now),};}diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.tsindex 8bd17815ee..a5f4a6806f 100644--- a/src/core/notifier/resident.ts+++ b/src/core/notifier/resident.ts@@ -149,9 +149,9 @@ export function runnerStart(engine: BrainEngine): Pick<CommitNotifierOptions, 'ssyncRunning: async () => (await load()).isDelegatedSyncRunning(),drainHeld: async (sourceId) => {// #7614: a killed holder's lock row defers nothing; the sync this starts takes its expired lease over.- const { holderStalled, readLiveDrainHolder } = await import('../persistence/sync-lease.ts');- const holder = await readLiveDrainHolder(engine, sourceId);- return holder === null ? false : holderStalled(holder) ? 'stalled' : true;+ const { holderStalled, readLiveDrainLease } = await import('../persistence/sync-lease.ts');+ const lease = await readLiveDrainLease(engine, sourceId);+ return lease === null ? false : holderStalled(lease.holder, lease.db_now) ? 'stalled' : true;},};}diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.tsindex 10eb637a9a..d6bba81451 100644--- a/src/core/notifier/status.ts+++ b/src/core/notifier/status.ts@@ -14,7 +14,7 @@ import { missingTable, type DetectionMode, type NotifierState } from './store.tsimport { residentNotifier } from './resident.ts';import { parseOnCommit } from '../commit-notifier.ts';import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';-import { HOLDER_STALL_MS, holderStalled, publicDrainHolder, readLiveDrainHolder, type DrainHolder } from '../persistence/sync-lease.ts';+import { HOLDER_STALL_MS, holderStalled, publicDrainHolder, readLiveDrainLease, type DrainHolder } from '../persistence/sync-lease.ts';type Exec = Pick<BrainEngine, 'executeRaw' | 'kind'>;type FreshnessExec = Exec & Pick<BrainEngine, 'getConfig'>;@@ -151,7 +151,8 @@ export async function readNotifierBlock(engine: BrainEngine, sourceId: string, oconst stalled = row.reason === 'notifier_stalled' || row.state === 'operator_blocked';const resident = live ? { kind: row.owner_kind ?? 'unknown', pid: remote ? null : row.owner_pid === null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id, live } : null;// #7614: a holder that stopped renewing the drain lease (killed) syncs nothing, so it does not stand in for the resident.- const holder = live ? null : await readLiveDrainHolder(engine, sourceId).catch(() => null);+ const lease = live ? null : await readLiveDrainLease(engine, sourceId).catch(() => null);+ const holder = lease?.holder ?? null;// #7243: the resident the row last recorded (the one its trace rows name), whose notifier lease is no longer live.const recorded = !live && row.owner_kind ? { kind: row.owner_kind, pid: remote || row.owner_pid == null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id,seen_at: iso(row.owner_seen_at), lease_expired_at: iso(row.lease_expires_at) } : null;@@ -160,7 +161,7 @@ export async function readNotifierBlock(engine: BrainEngine, sourceId: string, o? `The ${recorded.kind} resident recorded as this source's notifier${recorded.pid ? ` (PID ${recorded.pid})` : ''} holds no live notifier lease${recorded.lease_expired_at ? ` (it lapsed at ${recorded.lease_expired_at})` : ''}, `+ `so nothing watches this source now; this syncs the checkout HEAD now. If that resident is still running, it is not renewing its lease: restart it, and it catches up on its own.`: 'No resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches this source; this syncs the checkout HEAD now. A resident started later catches up on its own.')- : !live ? (holderStalled(holder) ? syncNowFix(sourceId, `No notifier watches this source, and the ${holder!.kind} process holding its drain lease has made no commit or cursor save for ${HOLDER_STALL_MS / 60_000} min or more; `+ : !live ? (holderStalled(holder, lease?.db_now) ? syncNowFix(sourceId, `No notifier watches this source, and the ${holder!.kind} process holding its drain lease has made no commit or cursor save for ${HOLDER_STALL_MS / 60_000} min or more; `+ 'a foreground sync follows it and takes over when its lease lapses.') : null): stalled ? syncNowFix(sourceId, `The notifier made no progress after ${Number(row.attempts ?? 0)} attempts (${row.last_error_code ?? row.reason ?? 'blocked'}); a foreground sync shows the error`+ `${!remote && row.trace_path ? `, and the trace is ${row.trace_path}` : ''}.`) : null;diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.tsindex faea7a0215..b16243a291 100644--- a/src/core/persistence/applied-watermark.ts+++ b/src/core/persistence/applied-watermark.ts@@ -32,7 +32,7 @@ import { execFileBounded } from '../bounded-child-exec.ts';import { gitChildEnv } from '../git-env.ts';import { readGitBehind, type BehindReader } from './sync-freshness.ts';import { countGitHolds } from './sync-holds.ts';-import { holderStalled, publicDrainHolder, readLiveDrainHolder } from './sync-lease.ts';+import { holderStalled, publicDrainHolder, readLiveDrainLease } from './sync-lease.ts';export interface WriteWatermark {source_id: string;@@ -133,7 +133,8 @@ export async function readAppliedWatermark(engine: BrainEngine, sourceId: string: { state: 'complete', commit, before: null, unembedded_pages: 0, held_pages: 0 };}- const holder = await readLiveDrainHolder(engine, sourceId).catch(() => null);+ const lease = await readLiveDrainLease(engine, sourceId).catch(() => null);+ const holder = lease?.holder ?? null;const shown = opts.remote ? publicDrainHolder(holder) : holder;const lastProgress = holder?.progress?.last_progress_at ?? null;return {@@ -156,7 +157,7 @@ export async function readAppliedWatermark(engine: BrainEngine, sourceId: stringheartbeat_age_seconds: ageSeconds(holder?.last_heartbeat_at, now),last_progress_at: lastProgress,progress_age_seconds: ageSeconds(lastProgress, now),- stalled: holderStalled(holder, now),+ stalled: holderStalled(holder, opts.now ?? lease?.db_now),},};}diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.tsindex ef80d96be3..dfe89406e1 100644--- a/src/core/persistence/sync-blocked.ts+++ b/src/core/persistence/sync-blocked.ts@@ -14,11 +14,12 @@* nothing blocked while the source indexed nothing. Such a stop is listed while it is newer than the pass row (no pass has* started since; a converged or idle pass clears it).* #7596: an open pass whose process stopped without ending it (no live drain-lease holder: killed or crashed) is listed as- * `pass_interrupted` from its row's last write, and once passes in a row keep stopping that way, `pass_abandoned` (status's rule).+ * `pass_interrupted` from its row's last write, and once passes in a row keep stopping that way or (#7982) ending on a transient stop,+ * `pass_abandoned` (status's rule).*/import type { BrainEngine } from '../engine.ts';import { readManagedSyncFailures } from './sync-failures.ts';-import { ABANDONED_REPORT_STREAK, passFingerprint } from './sync-pass-row.ts';+import { ABANDONED_REPORT_STREAK, passFingerprint, passReadClock, transientEnding } from './sync-pass-row.ts';import { passFailureKeys } from './sync-cursor-key.ts';import type { ManagedSyncFailure } from './sync-failures.ts';@@ -54,18 +55,23 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: sconst listed = [...failures.filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key) && !passSources.has(failure.source_id)).map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes, ...passStops];+ // #7982: passes that keep ending on the same transient stop (status's rule: the newest counts itself).+ const { abandonedPasses, openPassRowsStill } = await import('./sync-pass-status.ts');+ for (const { source_id, row } of readings) {+ if (transientEnding(row.value.telemetry) && abandonedPasses(row) >= ABANDONED_REPORT_STREAK && !listed.some(blocked => blocked.source_id === source_id)) {+ listed.push({ source_id, code: 'pass_abandoned', run_id: row.value.telemetry.pass_id, blocked_since: passStuckSince(row) });+ }+ }// #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 [{ inspectLocks, syncLockId }, { drainLeaseLive }, { abandonedPasses, openPassRowsStill }] = await Promise.all([- import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts')]);- const now = Date.now();+ const [{ inspectLocks, syncLockId }, { drainLeaseLive }] = await Promise.all([import('../db-lock.ts'), import('./sync-lease.ts')]);// #7614: one read for every open source's lock. A read that failed decides nothing: the quiet-window rule (status's) still counts a streak.const locks = await inspectLocks(engine, open.map(({ source_id }) => syncLockId(source_id))).catch(() => undefined);const candidates = open.map(({ source_id, row }) => {const lock = locks?.get(syncLockId(source_id));const interrupted = locks === undefined ? undefined : !lock || !drainLeaseLive(lock);- return { source_id, row, interrupted, abandoned: abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK };+ return { source_id, row, interrupted, abandoned: abandonedPasses(row, passReadClock(row), interrupted) >= ABANDONED_REPORT_STREAK };}).filter(entry => entry.interrupted || entry.abandoned);// #7614: a pass that ended (releasing its lease) after the pass read changed its row, so it is not listed; nor is an archived source.// A re-read that failed lists nothing new.diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 1301f33b66..fe51065196 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -128,8 +128,9 @@ export async function readDrainHolder(engine: BrainEngine, sourceId: string): Pr/*** #7596: the holder of the source's drain lease and whether it still renews it, by `isLockHolderLive` at the drain TTL (the* rule doctor's `managed_sync_blocked` reads too). A killed holder's lock row stays until a takeover breaks it, but its renewals stop.+ * #7982: `db_now` is the database clock at the lock read, which `holderStalled` compares the holder's database times with.*/-export async function readDrainLease(engine: BrainEngine, sourceId: string): Promise<{ holder: DrainHolder; live: boolean } | null> {+export async function readDrainLease(engine: BrainEngine, sourceId: string): Promise<DrainLeaseReading | null> {const snap = await inspectLock(engine, syncLockId(sourceId));if (!snap) return null;const [row] = await engine.executeRaw<{ meta: { kind?: DrainHolderKind; id?: string | null; version?: string } | string | null }>(@@ -138,13 +139,14 @@ 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: drainLeaseLive(snap) };+ return { holder, live: drainLeaseLive(snap), db_now: snap.db_now.getTime() };}+export interface DrainLeaseReading { holder: DrainHolder; live: boolean; db_now: number }-/** #7614: the drain lease's holder while it still renews the lease, else null: a killed holder's lock row names a process that is gone. */-export async function readLiveDrainHolder(engine: BrainEngine, sourceId: string): Promise<DrainHolder | null> {+/** #7614: the drain lease while its holder still renews it, else null: a killed holder's lock row names a process that is gone. */+export async function readLiveDrainLease(engine: BrainEngine, sourceId: string): Promise<DrainLeaseReading | null> {const lease = await readDrainLease(engine, sourceId);- return lease?.live ? lease.holder : null;+ return lease?.live ? lease : null;}/** #7596: whether the drain lease's holder still renews it: `isLockHolderLive` at the drain TTL, the one rule status and doctor read. */@@ -171,7 +173,7 @@ async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId:last_progress_at: [committedAt, savedAt].filter((value): value is string => !!value).sort().pop() ?? null };}-/** A holder that has held the lease, and made no commit, cursor save or hold write, for `HOLDER_STALL_MS`. */+/** A holder that has held the lease, and made no commit, cursor save or hold write, for `HOLDER_STALL_MS`; `now`: the lease read's `db_now`. */export function holderStalled(holder: DrainHolder | null, now = Date.now()): boolean {if (!holder?.started_at || !holder.progress) return false;const since = Math.max(Date.parse(holder.started_at), holder.progress.last_progress_at ? Date.parse(holder.progress.last_progress_at) : 0);@@ -300,7 +302,8 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, optsif (!(error instanceof LockUnavailableError) || error.lockId !== lockId || !opts.follow) throw error;}const follow = opts.follow;- const holder = await readDrainHolder(engine, sourceId).catch(() => null);+ const lease = await readDrainLease(engine, sourceId).catch(() => null);+ const holder = lease?.holder ?? null;if (seen === undefined) { opts.announce?.(holder, 'start'); reportedAt = Date.now(); }else if (Date.now() - reportedAt >= (opts.tty ? FOLLOW_REPORT_TTY_MS : FOLLOW_REPORT_MS)) { opts.announce?.(holder, 'progress'); reportedAt = Date.now(); }// The holder's commits are this run's committed progress (the progress-aware watchdog window extends with them); a cursor@@ -311,7 +314,7 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, optsif (startedNow === startedSeen && Number(committedNow) > Number(committedSeen)) noteCommittedProgress(); else noteForwardProgress();}seen = now;- if (holder && holderStalled(holder)) return leaseStalledResult(sourceId, holder, { remote: opts.remote });+ if (holder && holderStalled(holder, lease?.db_now)) return leaseStalledResult(sourceId, holder, { remote: opts.remote });const stopAt = followStopAt(startedAt, follow.deadlineAtMs);if (follow.signal?.aborted || Date.now() >= stopAt) return leaseHeldResult(sourceId, holder, { remote: opts.remote, resumeArgv: opts.resumeArgv });await pause(Math.min(FOLLOW_POLL_MS, stopAt - Date.now()), follow.signal);diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsindex da23cd26a1..2d753ac351 100644--- a/src/core/persistence/sync-pass-row.ts+++ b/src/core/persistence/sync-pass-row.ts@@ -72,7 +72,10 @@ export interface ManagedSyncPassValue {converged?: PassConverged;mismatch: Record<string, { level: string | null; streak: number }>;not_converged_streak: number;- /** #7355: at this pass's pin, how many passes in a row before it never ended (their row was left `open`: a pass the drain's governor abandoned, or a killed process). Status counts it only while this pass's row is open. */+ /**+ * #7355: at this pass's pin, how many passes in a row before it never ended (their row was left `open`: a pass the drain's governor abandoned, or a+ * killed process) or (#7982) ended on a transient stop (`transientEnding`). Status counts it only while this pass's row is open or ended transient.+ */abandoned_streak?: number;/** When the current run of unhealthy endings (`blocked`, `not_converged`) began; kept across them, cleared at `synced`/`up_to_date`. The §3.7 readers age a stuck source from it. */stuck_since?: string | null;@@ -134,32 +137,46 @@ export const OPEN_AT_STAMP_CAP = 256;export const SETTLE_MISMATCH_STREAK = 3;/** Consecutive `not_converged` passes after which `fix.next` becomes `report` (design §3.1, DX R9). */export const NOT_CONVERGED_REPORT_STREAK = 3;-/** #7355: passes in a row that never ended (the newest counted once its row has been quiet for ABANDONED_QUIET_MS) before status stops sending the plain sync. */+/**+ * #7355: passes in a row that never ended (the newest counted once its row has been quiet for ABANDONED_QUIET_MS) or (#7982) ended on a transient stop+ * before status stops sending the plain sync.+ */export const ABANDONED_REPORT_STREAK = 2;/** The drain's in-pass no-progress window: an open row quiet this long belongs to no live pass. */export const ABANDONED_QUIET_MS = 5 * 60_000;export const passFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;-export interface PassRow { value: ManagedSyncPassValue; updated_at: string }+/** `read_at`: the database clock at the read (#7982), which the readers compare `updated_at` with; absent on a row built without a read. */+export interface PassRow { value: ManagedSyncPassValue; updated_at: string; read_at?: string }++/** #7982: the clock a reader compares the row's database timestamps with: the database's at the read, else this process's. */+export const passReadClock = (row: PassRow): number => row.read_at ? Date.parse(row.read_at) : Date.now();++/**+ * #7982: a pass that ended on a transient stop (`unrecordedStop`: a statement timeout, a lost connection, write back-pressure, a refresh fence).+ * One that recurs every pass stops every pass, so these endings build the abandoned streak as a pass left open does.+ */+export const transientEnding = (telemetry: Pick<ManagedSyncPassValue['telemetry'], 'outcome' | 'stop_reason'>): boolean =>+ telemetry.outcome === 'resumable' && telemetry.stop_reason === 'transient';type Exec = Pick<BrainEngine, 'executeRaw'>;const iso = (value: Date | string) => new Date(value).toISOString();/** The pass row of one incarnation, or null when no pass has run on it. */export async function readPassRow(engine: Exec, sourceId: string, incarnation: string): Promise<PassRow | null> {- const [row] = await engine.executeRaw<{ value: ManagedSyncPassValue | null; updated_at: Date | string }>(- 'SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [MANAGED_SYNC_PASS_OP, passFingerprint(sourceId, incarnation)]);- return row?.value ? { value: row.value, updated_at: iso(row.updated_at) } : null;+ const [row] = await engine.executeRaw<{ value: ManagedSyncPassValue | null; updated_at: Date | string; read_at: Date | string }>(+ 'SELECT completed_keys->0 AS value, updated_at, now() AS read_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [MANAGED_SYNC_PASS_OP, passFingerprint(sourceId, incarnation)]);+ return row?.value ? { value: row.value, updated_at: iso(row.updated_at), read_at: iso(row.read_at) } : null;}/** The pass rows of the sources' live incarnations (all sources when `sourceIds` is omitted), keyed by source id. */export async function readLivePassRows(engine: Exec, sourceIds?: readonly string[]): Promise<Map<string, PassRow>> {- const rows = await engine.executeRaw<{ source_id: string; value: ManagedSyncPassValue; updated_at: Date | string }>(- `SELECT s.id AS source_id, c.completed_keys->0 AS value, c.updated_at FROM sources s+ const rows = await engine.executeRaw<{ source_id: string; value: ManagedSyncPassValue; updated_at: Date | string; read_at: Date | string }>(+ `SELECT s.id AS source_id, c.completed_keys->0 AS value, c.updated_at, now() AS read_at FROM sources sJOIN op_checkpoints c ON c.op=$1 AND c.fingerprint=s.id||':'||s.incarnation::textWHERE ($2::text[] IS NULL OR s.id=ANY($2::text[]))`, [MANAGED_SYNC_PASS_OP, sourceIds ? [...sourceIds] : null]);- return new Map(rows.filter(row => row.value).map(row => [row.source_id, { value: row.value, updated_at: iso(row.updated_at) }]));+ return new Map(rows.filter(row => row.value).map(row => [row.source_id, { value: row.value, updated_at: iso(row.updated_at), read_at: iso(row.read_at) }]));}/**@@ -167,15 +184,18 @@ export async function readLivePassRows(engine: Exec, sourceIds?: readonly string* just took the lease replaces whatever row a former holder left; otherwise the write lands only while the row still* carries `leaseToken`. Returns false when it did not land (another pass pinned since). `clock`: `telemetry.started_at` is the* transaction's clock (`now()`, as an ISO string), so the write needs no earlier read of it. `onlyOpen`: the write lands only- * on a row still `open`, so a stop after a folded stamp ended the row `synced` never rewrites the stamp's obligations.+ * on a row still `open`, so a stop after a folded stamp ended the row `synced` never rewrites the stamp's obligations, and+ * (#7982) a row gone since the pin is never inserted back (a stop that lost its lease writes unfenced).*/export async function writePassRow(tx: Exec, value: ManagedSyncPassValue, opts: { pin?: boolean; clock?: boolean; onlyOpen?: boolean } = {}): Promise<boolean> {const json = opts.clock ? `jsonb_set($3::text::jsonb,'{telemetry,started_at}',to_jsonb(to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')))` : '$3::text::jsonb';- const rows = await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array(${json}),now())- ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()- WHERE ($4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5)- AND (NOT $6::boolean OR op_checkpoints.completed_keys->0->'telemetry'->>'outcome'='open') RETURNING 1`,- [MANAGED_SYNC_PASS_OP, passFingerprint(value.source_id, value.incarnation), JSON.stringify(value), opts.pin === true, value.lease_token, opts.onlyOpen === true]);+ const params = [MANAGED_SYNC_PASS_OP, passFingerprint(value.source_id, value.incarnation), JSON.stringify(value), opts.pin === true, value.lease_token];+ const rows = opts.onlyOpen+ ? await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array(${json}), updated_at=now()+ WHERE op=$1 AND fingerprint=$2 AND ($4::boolean OR completed_keys->0->>'lease_token'=$5) AND completed_keys->0->'telemetry'->>'outcome'='open' RETURNING 1`, params)+ : await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array(${json}),now())+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()+ WHERE ($4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5) RETURNING 1`, params);return rows.length > 0;}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 1fd45ff4cf..f562e58906 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -27,7 +27,7 @@ import { recordedStop, replaysUnchangedRefusal, resumableRowStop } from './sync-import { adoptLegacyPage, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';-import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,+import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, transientEnding, writePassRow, type ManagedSyncPassValue, type PassEpisode,type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';import { faultPoint } from './fault-points.ts';@@ -404,7 +404,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullconst obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations): { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;- const abandoned = prior?.value.telemetry.outcome === 'open' ? (obligations.abandoned_streak ?? 0) + 1 : 0;+ const abandoned = prior && (prior.value.telemetry.outcome === 'open' || transientEnding(prior.value.telemetry)) ? (obligations.abandoned_streak ?? 0) + 1 : 0;if (abandoned) obligations.abandoned_streak = abandoned; else delete obligations.abandoned_streak;if (handover.episode && !obligations.episode) obligations.episode = handover.episode;const passId = randomUUID();diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex e37bd1e192..c6196d133e 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -10,7 +10,8 @@ import type { SyncAdmissionStatus } from './sync-admission.ts';import { digest } from './digest.ts';import { fileDriftSide, type GitHoldRecord } from './sync-holds.ts';import { readDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';-import { ABANDONED_QUIET_MS, ABANDONED_REPORT_STREAK, MANAGED_SYNC_PASS_OP, NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';+import { ABANDONED_QUIET_MS, ABANDONED_REPORT_STREAK, MANAGED_SYNC_PASS_OP, NOT_CONVERGED_REPORT_STREAK, passHealth, passReadClock, transientEnding, type PassRoundSummary,+ type PassRow } from './sync-pass-row.ts';/*** #7614: the sources whose pass row is still the open one a reader saw (same last write, still `open`, source not@@ -77,11 +78,14 @@ export type PassStatusReason = 'pass_unfinished' | 'pass_interrupted' | 'pass_ab* holds the lease (its process was killed or crashed) and never while one does, since a pass writes its row only per batch.* #7611: nor does the streak an earlier pass stored while a live holder renews the lease: the open pass is running, and the* streak counts again once that holder stops renewing.+ * #7982: a pass that ended on a transient stop counts itself, so passes that hit the same statement timeout every time build the+ * streak too. `now` is the database clock at the row's read (`passReadClock`), never only this process's.*/-export function abandonedPasses(row: PassRow, now = Date.now(), interrupted?: boolean): number {- if (interrupted === false) return 0;- const quiet = row.value.telemetry.outcome === 'open' && (interrupted ?? now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS);- return row.value.telemetry.outcome === 'open' ? (row.value.obligations.abandoned_streak ?? 0) + (quiet ? 1 : 0) : 0;+export function abandonedPasses(row: PassRow, now = passReadClock(row), interrupted?: boolean): number {+ const t = row.value.telemetry, streak = row.value.obligations.abandoned_streak ?? 0;+ if (transientEnding(t)) return streak + 1;+ if (t.outcome !== 'open' || interrupted === false) return 0;+ return streak + ((interrupted ?? now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS) ? 1 : 0);}/**@@ -90,7 +94,7 @@ export function abandonedPasses(row: PassRow, now = Date.now(), interrupted?: bo* #7596 `interrupted`: no process holds the source's drain lease (`readDrainLease`), so an open pass is one whose process* stopped without ending it (killed or crashed), not one still running: `pass_interrupted`.*/-export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now(), interrupted?: boolean): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {+export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = passReadClock(row), interrupted?: boolean): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {const t = row.value.telemetry;if (abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK) return ['blocked', 'pass_abandoned'];if (t.outcome === 'open' && interrupted) return ['resumable', 'pass_interrupted'];@@ -129,7 +133,7 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:why: 'The preview names the parked effect and what a retry runs (read-only); until it commits, the source is never idle.' };case 'pass_abandoned':return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,- why: `The last ${abandonedPasses(row, Date.now(), interrupted)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };+ why: `The last ${abandonedPasses(row, passReadClock(row), interrupted)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed) or on a transient stop that recurs (a statement timeout, a lost connection), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };case 'pass_interrupted':return { ...sync, why: `The newest pass of ${sourceId} stopped before it ended and no process holds its drain lease: its process was killed or crashed (an out-of-memory kill or a timeout), or stopped on an error it does not record (a dropped connection), so nothing recorded a failure. The plain sync continues it from the current level; if that pass stops the same way, status reads pass_abandoned.` };case 'selection_scoped':diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 32390f5955..b2926a5a77 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -44,7 +44,7 @@ import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';import { sha256 } from './digest.ts';import { passResumeArgs } from './sync-pass-readers.ts';import { openPassRowsStill, passConvergence, passStatusNext, passStatusState } from './sync-pass-status.ts';-import { MANAGED_SYNC_PASS_OP, readPassRow, SYNC_DELETES_WITHHELD_OP, type PassRow } from './sync-pass-row.ts';+import { MANAGED_SYNC_PASS_OP, passReadClock, readPassRow, SYNC_DELETES_WITHHELD_OP, type PassRow } from './sync-pass-row.ts';import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionEffectParams, syncAdmissionEffectSql, syncAdmissionSettingSql, syncAdmissionStatus } from './sync-admission.ts';import type { DeletesWithheld } from './sync-markers.ts';import { listIdentityDowngrades, withIdentityRemedies } from '../sync-identity-downgrades.ts';@@ -333,11 +333,11 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst detail = opts.detail !== false;// #6712 PR 4b (design §9): the pass row and the withheld-delete record ride the source read (primary-key probes), so the plain status keeps its statement budget.const admissionSql = syncAdmissionSettingSql(4);- const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; last_sync_at: Date | string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;+ const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; last_sync_at: Date | string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; pass_read_at: Date | string; withheld: DeletesWithheld | null;admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null; admission_pinned: boolean | null; admission_destructive: boolean | null;writeback_failed: string | null; refresh: RefreshProbeRow | string | null }>(`SELECT s.incarnation::text AS incarnation, s.last_commit, s.last_sync_at, EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$7) AS drain_lock,- p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns}, ${syncAdmissionEffectSql(7, 's')},+ p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, now() AS pass_read_at, w.completed_keys->0 AS withheld, ${admissionSql.columns}, ${syncAdmissionEffectSql(7, 's')},(SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed' AND NOT (e.data ? 'settled')AND e.request_id IN (SELECT id::uuid FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.completed_keys->0->'obligations'->'converged'->'writeback')='array'THEN p.completed_keys->0->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id)) ORDER BY e.id LIMIT 1) AS writeback_failed,@@ -407,7 +407,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst p = header?.progress;const estimate = unfinished && p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };// #6712 PR 4b (design §9): the pass row (one primary-key read) and the withheld-delete record make the live `convergence` block.- const passRow: PassRow | null = source.pass_value && source.pass_updated_at ? { value: source.pass_value, updated_at: new Date(source.pass_updated_at).toISOString() } : null;+ const passRow: PassRow | null = source.pass_value && source.pass_updated_at+ ? { value: source.pass_value, updated_at: new Date(source.pass_updated_at).toISOString(), read_at: new Date(source.pass_read_at).toISOString() } : null;const withheld = passRow ? source.withheld : null;// #7243: whoever holds the drain lease is the job doing the work, a serve-owned pass included (one primary-key probe rode the source read).// #7596: a holder that stopped renewing it was killed; an open pass with no live holder was interrupted, not running.@@ -419,7 +420,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst raced = source.drain_lock && lease !== undefined && !holder && passRow?.value.telemetry.outcome === 'open'&& !(await openPassRowsStill(engine, [{ source_id: sourceId, row: passRow }]).catch(() => undefined))?.has(sourceId);const interrupted = lease === undefined || raced || passRow?.value.telemetry.outcome !== 'open' ? undefined : !holder;- const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed, Date.now(), interrupted) : null;+ const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed, passReadClock(passRow), interrupted) : null;const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const human = holds.find(hold => hold.needs_human) ?? (liveError?.needs_human ? liveError : undefined);const refreshRow = typeof source.refresh === 'string' ? JSON.parse(source.refresh) as RefreshProbeRow : source.refresh;@@ -467,7 +468,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at, pinned: source.admission_pinned, destructive: source.admission_destructive });const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed, interrupted) : null;- return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null,+ return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder, lease?.db_now) } : null,interrupted: interrupted && passRow ? { pass_id: passRow.value.telemetry.pass_id, since: passRow.updated_at, holder: lease?.holder ?? null } : null, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob ?? holderJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),diff --git a/test/supervisor-db-lock.test.ts b/test/supervisor-db-lock.test.tsindex b5b4eceef5..b7759825fe 100644--- a/test/supervisor-db-lock.test.ts+++ b/test/supervisor-db-lock.test.ts@@ -32,6 +32,7 @@ function snap(over: Partial<LockSnapshot>): LockSnapshot {ttl_expired: false,last_refreshed_at: new Date(),ms_since_last_refresh: 0,+ db_now: new Date(),...over,};}diff --git a/test/sync-pass-readers-7614.test.ts b/test/sync-pass-readers-7614.test.tsindex 3e8b5e0bac..8cb99f6f83 100644--- a/test/sync-pass-readers-7614.test.ts+++ b/test/sync-pass-readers-7614.test.ts@@ -208,13 +208,75 @@ for (const backend of testBackends()) {else expect(await sync()).toMatchObject({ status: 'partial', reason: 'drain_lease_held' });} finally { installFaultHook(undefined); }const stopped = (await readPassRow(engine, 'default', incarnation!))!;- expect([stopped.value.telemetry.outcome, stopped.value.telemetry.stop_reason, abandonedPasses(stopped)]).toEqual(['resumable', reason, 0]);+ // #7982: a transient ending counts itself; the lost lease between the two resets the streak, so neither reaches the report streak.+ expect([stopped.value.telemetry.outcome, stopped.value.telemetry.stop_reason, abandonedPasses(stopped)]).toEqual(['resumable', reason, reason === 'transient' ? 1 : 0]);expect((await status()).reason).toBe('pass_unfinished');expect(await blocked()).toEqual([]);}expect((await sync()).status).toMatch(/^(up_to_date|synced)$/);});+ synced('#7982: passes that keep ending on a transient stop build a streak; at the report streak status and doctor read pass_abandoned', async ({ engine, root, sync, status, blocked }) => {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const statementTimeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });+ for (const i of [0, 1]) {+ commitFile(root, `timeout-${i}.md`);+ installFaultHook(async point => { if (point === 'sync:round_start') throw statementTimeout(); });+ try { await expect(sync()).rejects.toThrow('statement timeout'); } finally { installFaultHook(undefined); }+ const stopped = (await readPassRow(engine, 'default', incarnation!))!;+ expect([stopped.value.telemetry.outcome, stopped.value.telemetry.stop_reason, abandonedPasses(stopped)]).toEqual(['resumable', 'transient', i + 1]);+ if (i === 0) {+ expect((await status()).reason).toBe('pass_unfinished');+ expect(await blocked()).toEqual([]);+ }+ }+ expect([(await status()).state, (await status()).reason]).toEqual(['blocked', 'pass_abandoned']);+ expect((await status()).next?.argv).toEqual(['gbrain', 'doctor', '--json']);+ expect((await blocked()).map(entry => entry.code)).toEqual(['pass_abandoned']);+ // A pass that ends any other way clears the streak.+ expect((await sync()).status).toMatch(/^(up_to_date|synced)$/);+ expect((await status()).reason).not.toBe('pass_abandoned');+ expect(await blocked()).toEqual([]);+ });++ synced('#7982: a stop after the pass row is gone writes no row back, fenced or not', async ({ engine, root, sync }) => {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const lostConnection = () => Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' });+ for (const [i, thrown] of ([() => new LockStolenError(LOCK, 'the drain lease of source default lapsed in this pass'), lostConnection] as const).entries()) {+ commitFile(root, `gone-${i}.md`);+ installFaultHook(async point => {+ if (point !== 'sync:round_start') return;+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [MANAGED_SYNC_PASS_OP]);+ throw thrown();+ });+ try { await sync().catch(() => undefined); } finally { installFaultHook(undefined); }+ expect(await readPassRow(engine, 'default', incarnation!)).toBeNull();+ }+ });++ synced('#7982: the quiet-window fallback and the holder stall read the database clock, not the reader\'s', async ({ engine, status, blocked }) => {+ // A reader whose clock runs ten minutes ahead of the database (PGLite's clock is the process's own, so only a server can).+ const realNow = Date.now.bind(Date);+ const skew = backend === 'postgres' ? 10 * 60_000 : 0;+ await setPass(engine, 'open', 1); await dead(engine);+ const failed = (['inspectLock', 'inspectLocks'] as const).filter(name => typeof (dbLock as Record<string, unknown>)[name] === 'function')+ .map(name => spyOn(dbLock, name).mockRejectedValue(new Error('lock read failed')));+ const ahead = spyOn(Date, 'now').mockImplementation(() => realNow() + skew);+ try {+ // The lock read failed, so the quiet window decides: the row was written just now on the database clock.+ expect((await status()).reason).toBe('pass_unfinished');+ expect(await blocked()).toEqual([]);+ } finally { ahead.mockRestore(); for (const spy of failed) spy.mockRestore(); }+ // A renewing holder whose newest progress is the pass row's write just now has not stalled.+ await setPass(engine, 'open', 0); await live(engine);+ const ahead2 = spyOn(Date, 'now').mockImplementation(() => realNow() + skew);+ try {+ expect((await status()).live).toMatchObject({ pid: 4242, stalled: false });+ expect(await runnerStart(engine).drainHeld!('default')).toBe(true);+ expect((await readNotifierBlock(engine, 'default'))?.fix ?? null).toBeNull();+ } finally { ahead2.mockRestore(); }+ });+synced('#7614 review: a permission refusal is not a passing stop; the pass row stays open and reads interrupted, then abandoned', async ({ engine, root, sync, status, blocked }) => {const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");for (const i of [0, 1]) {