Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Save a sync pass as resumable when SIGTERM or SIGHUP stops it (GST-2869) (#9600)
Garry Tan71123d8183e0
diff --git a/behavior-changes.d/mirror_compare_names_writable_route_gst2869.md b/behavior-changes.d/mirror_compare_names_writable_route_gst2869.mdindex a813cbda21..fca5698371 100644--- a/behavior-changes.d/mirror_compare_names_writable_route_gst2869.md+++ b/behavior-changes.d/mirror_compare_names_writable_route_gst2869.md@@ -1,4 +1,4 @@---kind: fix----On a read-only mirror source, gbrain repair file-drift --held without --prefer no longer names a --prefer file (or --prefer database) preview for a page that differs from its file, in the page's why or in next_actions. Those previews read every mirror page as database-only and found nothing. The comparison keeps each page's verdict and evidence and says the page stays held until the user makes the source writable again with gbrain sources mirror-writable <id>.+On a read-only mirror source, gbrain repair file-drift --held without --prefer no longer names a --prefer file (or --prefer database) preview for a page that differs from its file or a held deleted page whose file differs, in the page's why or in next_actions. Those previews read every mirror page as database-only and found nothing. The comparison keeps each page's verdict and evidence and says the page stays held until the user makes the source writable again with gbrain sources mirror-writable <id>.diff --git a/behavior-changes.d/rehold_retry_not_progress_gst2869.md b/behavior-changes.d/rehold_retry_not_progress_gst2869.mdindex dabc942ecb..fcaa60386c 100644--- a/behavior-changes.d/rehold_retry_not_progress_gst2869.md+++ b/behavior-changes.d/rehold_retry_not_progress_gst2869.md@@ -1,4 +1,4 @@---kind: fix----A stopped sync pass no longer counts as progress when the only holds it rewrote were re-checked because gbrain sync unblock or gbrain sources retry-held asked (the hold is now marked retry_only), or when the rewrite brought a transient hold (preparation_stalled, write_interrupted, or a page write that failed while frozen) to its attempt cap. Before, such a re-hold reset the abandoned-pass count once per retry round, so a source could stay pass_interrupted instead of reaching pass_abandoned.+A stopped sync pass no longer counts as progress when the only holds it rewrote were re-checked because gbrain sync unblock or gbrain sources retry-held asked and kept their code and file bytes (the hold is now marked retry_only; a retry that changed either restarts the hold and still counts once), or when the rewrite brought a transient hold (preparation_stalled, write_interrupted, or a page write that failed while frozen) to its attempt cap. Before, such a re-hold reset the abandoned-pass count once per retry round, so a source could stay pass_interrupted instead of reaching pass_abandoned.diff --git a/behavior-changes.d/sync_sigterm_recorded_gst2869.md b/behavior-changes.d/sync_sigterm_recorded_gst2869.mdnew file mode 100644index 0000000000..ee5e4a4d36--- /dev/null+++ b/behavior-changes.d/sync_sigterm_recorded_gst2869.md@@ -0,0 +1,4 @@+---+kind: fix+---+gbrain sync stopped by SIGTERM or SIGHUP during a managed pass (an outer timeout, a supervisor stop, a closed terminal) now records the stop before it exits. The pass ends resumable with stop reason terminated, the drain stops terminated, gbrain sync status reads pass_terminated with the plain sync as its next step, and the run exits 143 (129 for SIGHUP). Before, the row was left open and status read pass_interrupted. A pass stopped this way that committed nothing still counts toward pass_abandoned, as a killed pass did. A second signal, or a run still saving or printing its result 3 seconds after the handler starts, exits as before. On PGLite the handler can start tens of seconds after the signal, as it already did before this change, so a supervisor that kills the process sooner leaves the pass open as before: it reads pass_interrupted and the plain sync resumes it. Ctrl-C and a sync job inside jobs work are unchanged.diff --git a/changelog.d/gbra-568-sync-sigterm.md b/changelog.d/gbra-568-sync-sigterm.mdnew file mode 100644index 0000000000..fbe8f3e1a7--- /dev/null+++ b/changelog.d/gbra-568-sync-sigterm.md@@ -0,0 +1,7 @@+**`gbrain sync` stopped by SIGTERM or SIGHUP now records why its pass stopped.**++### Fixed+- A managed `gbrain sync` that gets SIGTERM or SIGHUP in the middle of a pass saves the pass as resumable with stop reason `terminated`, prints its result and resume command, and exits 143 (129 for SIGHUP). `gbrain sync status` reads `pass_terminated` instead of guessing `pass_interrupted`, and the drain's JSON stop reads `terminated` instead of `deadline`. A pass stopped this way that committed nothing still counts toward `pass_abandoned`. A second signal, or a run still saving or printing its result 3 seconds after the handler starts, exits as before. On PGLite the handler can start tens of seconds after the signal, as it already did before this change, so a supervisor that kills the process sooner leaves the pass open as today; it reads `pass_interrupted` and the plain sync resumes it. Ctrl-C and sync jobs inside `jobs work` are unchanged (GST-2869).+- On a read-only mirror, `gbrain repair file-drift --held` no longer names a `--prefer` preview for a held deleted page whose file differs either; it names `gbrain sources mirror-writable <id>` like the other mirror pages. The sync-unblock runbook's `pass_abandoned` row now says that a retry whose re-check changed the hold's code or file bytes still counts as progress once.++<!-- behavior-change: sync_sigterm_recorded_gst2869 -->diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex fc49051537..60893ac68a 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -27,7 +27,7 @@ See [generations](generations.md) and [continued entries](canonical-reconciliati- `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 (reasons `pass_unfinished`, `pass_terminated` (GST-2869: a SIGTERM or SIGHUP stopped the pass and it recorded `terminated`), `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 491aa2ea82..b54132b7bc 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -33,7 +33,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-slug-mode.ts` — #6694: the checkpoint's slug-root mode against the source's pinned `slug_root_mode`. `emptySyncScope` (source root is the repository root, both realpathed) lets `sync-prepare.ts`'s checkpoint `UPDATE` accept either pin and keep the pinned one; at a subdirectory a differing pin is diagnosed by `pinnedSlugModeMismatch` after the guarded `UPDATE` matched nothing and refused `slug_root_mode_mismatch` (cause and the person's two choices from `slugModeMismatchCause`); anything else stays `revision_conflict` (`CHECKPOINT_MOVED_MESSAGE`). `slugModeCheckpointRevivable` is the second revival predicate of `sync-run.ts` `reviveCheckpoint`: a checkpoint refused `slug_root_mode_mismatch`, or an older release's moved-checkpoint `revision_conflict`, is revived when `last_commit` still equals the run's `from` and the pin is unset, equal to the run's mode or the scope is empty; `retryFailedStart` does not consult it, so `--retry-failed` keeps its rediscovery. Test: `test/sync-slug-root-mode-6694.test.ts` (both engines).- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).-- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file still holds the working-tree bytes that refused, compared by hash rather than by mtime), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.+- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file still holds the working-tree bytes that refused, compared by hash rather than by mtime), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`. GST-2869: `SyncTerminated` is the abort reason `gbrain sync` gives its run on SIGTERM or SIGHUP; `abortStop` reads the first abort's reason, so the pass row ends `terminated` instead of `timeout` (from its catch, its rolled-back pin or a batch that returned `timeout`) and the drain stops `terminated`; `managedPassLive` (`sync-pass-episode.ts`, the pass-cost registry) says a managed pass is running in this process, the only time sync owns those signals (`withTerminationOwner` in `src/commands/sync/run.ts`, CLI entry only, never under another owner).- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. A retryable sync fault's `action` follows its operation (`faultOperation`: a `put_page` under a `canonical_reconcile` or `managed_*` intent kind reads as that kind): `submit_job` and a canonical reconcile keep the sync retry, a caller-submitted page or memory write (`RESUBMITTED_WRITES`) gets the read-only writer-status inspect and a resubmit with a new request_id, a `managed_*` write the inspect and a rerun of its command, any other operation (and a compacted `put_page`, whose intent kind is gone) the inspect alone with `safe_actions: ['none']`. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. `legacy_publication_refusal` and `retired_operation` (a `revision_conflict` with origin `grandfather_retired` or a `managed_grandfather` intent, #7837) are historical whatever build wrote them, since only a request an older build admitted produces them. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, each selected before the supersession lateral join, which with the summary's probe tests the failed row's intent kind first so later large sync intents are not detoasted per row (#8729), at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups, a `sync_fault` group also split by its operation, with an exact `drill_down` argv each; `--operation` filters on `faultOperation`). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex 6393632765..d5b7eb38a7 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_arr... (line truncated to 2000 chars)- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`); `retireAfterLastItem` applies one item and clears the set only after the last item returns, so an item that throws keeps it and the printed apply resumes with the same `--expect` (`test/repair-timeline-order.test.ts`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/pro... (line truncated to 2000 chars)+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal, signals?)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE (GST-2869: `signals` narrows the claim, so `gbrain sync` takes only SIGTERM/SIGHUP and a broken pipe keeps the generic path; `hasSignalOwner()` lets sync stand aside under a worker's owner) and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/pro... (line truncated to 2000 chars)- `src/core/read-heartbeat.ts` + `src/cli/slow-read.ts` — slow whole-brain reads say what they are doing. A `CliCommandRecord.slowRead(args)` (`src/cli/command-table.ts`) names the read for doctor, sync status, sources status, orphans, anomalies, status and diag; `beginCommandRead` (skipped for `--help` and `--quiet`) wraps the CLI_ONLY dispatch in `src/cli/main.ts` and calls `beginSlowRead`, which prints one stderr start line and an unref'd `still reading` line every `READ_HEARTBEAT_EVERY_MS` (10 s); stdout is untouched. `withReadMeta(doc)` adds `elapsed_ms` and `complete` to a `--json` document and lists `incomplete` (`{field, reason}`) from the markers the documents already carry (`incompleteFields`: a `status: not_read` object, `complete: false` or a `*_complete: false` key, `budget_hit: true`, a doctor check unknown for its budget); an error envelope gets `elapsed_ms` only and an array stays bare. `writeStdoutFinal` (`cli-force-exit.ts`) applies it to a guarded document during a slow read, and orphans, sources status and status call it directly. `noteInterrupted` prints the interrupt line and, under `--json`, writes `{error: 'interrupted', signal, read, elapsed_ms, complete: false}` at once through the writer `cli-force-exit.ts` registers (`setInterruptedDocumentWriter`); a SIGINT handler is installed only when nothing else listens. The fallback document for exits 129, 130 and 143 is `code: 'interrupted'`. Pinned by `test/read-heartbeat-cli.test.ts` (real spawned CLI fixture `test/fixtures/slow-read-cli.ts`: SIGTERM, SIGINT, SIGHUP, SIGKILL after SIGTERM, no `--json`, a kill outside a read) and `test/read-meta-diag.test.ts`.- `src/commands/diag.ts` (+ `src/cli/commands/diag.ts`, `src/cli/help/diag.ts`) — `gbrain diag [--json] [--budget-ms N] [--query TEXT]`, read-only and refused on a thin client: one bounded bundle an agent pastes whole. `collectDiag` runs six sections in turn, each through `diagSection` under min(its cap in `DIAG_SECTION_CAP_MS`, what is left of the budget, default 30 s): `gbrain` (version, engine, runtime), `skew` (doctor `runtime_build_skew` and `writer_version`), `sources` (per source `last_sync_at`, last commit, `behind_head` from `readGitBehind`, the managed pass row's state from `readLivePassRows`), `holds` (counts per source and code), `pool` (Postgres only: backends by state, lock waits, idle transactions over 60 s, `pg_stat_database` session endings on 14+) and `search` (one search's stage timings and result count, never its results). Each section carries `elapsed_ms` and `status` `ok`, `not_read` (reason `budget`), `not_applicable` or `error` (with its code); the bundle carries `elapsed_ms`, `complete` and `incomplete`, error sections included. It never reads a source's file level (`sync status --detail`). Pinned by `test/read-meta-diag.test.ts`.diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 0f5311366d..6f078512c3 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -104,6 +104,7 @@ The run ends in exactly one outcome:| --- | --- | --- | --- || `synced` | 0 | The pass converged and stamped (a company-brain source: the cursor reached its target). A pass at a selection other than the configured one adds `selection_scoped` and does not advance `last_commit`; a pass that held files a person must decide adds `held_needs_human` (their count in `held_needs_human`). | Nothing; held files wait on a person (`gbrain sync status --source <id>`). || `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; accepted writes are intact. | Rerun `next.command`; safe in a loop. |+| `resumable` / `terminated` | 143 (129 for SIGHUP) | A SIGTERM or SIGHUP (an outer `timeout`, a supervisor stop, a closed terminal) reached `gbrain sync` during a managed pass, which recorded its stop first; accepted writes are intact. A second signal, or a run still saving the pass 3 s after the handler starts, exits as before and leaves the pass open (`gbrain sync status` reads `pass_interrupted`); a run that saved the pass but is still printing its result then exits without it, and the pass reads `pass_terminated`; on PGLite the handler can start tens of seconds after the signal, so a supervisor that kills the process sooner leaves the pass open the same way. | Rerun `next.command`; either way the plain sync resumes it. || `resumable` / `not_converged` | 0 | The pass used its four rounds while another writer kept changing the level; everything it admitted stands. | Rerun `next.command`. After three in a row `next` is a report (`gbrain doctor --json`), not another sync. || `resumable` / `admission_paused` | 0 | `sync.admission` is `imports_only` or `classify_only`. | Ask the user; `gbrain config set sync.admission normal` ends the pause. || `blocked` / `reconcile_host_required` or `grant_scope` | 1 | A remote caller or a partial grant admitted what it could; the rest (holds, markers, keep_db writes, the stamp) needs the owner host. | Tell the user to run `gbrain sync --source <id> --no-pull` on the brain host. |diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f4343ffbcc..3d8b1eb132 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -3751,7 +3751,8 @@ gbrain repair file-drift --source <id> --held --json # compare every h<a id="file-drift-compare-mirror"></a>On a [read-only mirror](multi-source-brains.md#read-only-mirror-sources)(GST-2843), the held comparison reads each held page's file too: a page that-differs reads `prefer_file` or `needs_human` with its `evidence`, one that+differs reads `prefer_file` or `needs_human` with its `evidence` (a held deleted+page whose file differs reads `needs_human` and names the same route), one thatmatches reads `release_hold`, and only a page whose file is gone reads`no_drift` with `database_only`. Every compared page in `details.pages`carries `evidence` (null when nothing was read). The comparison names nodiff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 006d5a2c62..1dbed1abc3 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -398,7 +398,8 @@ 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 or ended on the same kind of transient stop, and neither saved work before it stopped. A pass saved work when it committed a page, held a path it had not held before, or re-checked a held path and cleared that hold's re-check trigger (the hold is no longer due, and a `file_drift` hold names the page's current revision); saved work moved the source, so it resets the count. A pass that only reported progress does not count, nor does one that only re-held a page edited again before it (the hold is marked `basis_moved`), re-held a path only because `sync unblock` or `sources retry-held` asked (`retry_only`), or brought a transient hold to its attempt cap. So passes that only re-hold a page edited again before each of them still end `pass_abandoned`, and from that page's third hold `sync status` reports `needs_human: true` with the page's decision. Passes stop this way when 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. |+| `pass_terminated` | resumable | A SIGTERM or SIGHUP (an outer `timeout`, a supervisor stop, a closed terminal) reached `gbrain sync` during a managed pass, and the pass recorded its stop (`stop_reason: terminated`, drain stop `terminated`) before the run exited 143 (129 for SIGHUP). A second signal, or a run still saving the pass 3 s after the handler starts, exits as before and leaves the row open (`pass_interrupted`); a run that saved the pass but is still printing its result then exits without it, and the row reads `pass_terminated`. On PGLite the handler can start tens of seconds after the signal, as it already did before, so a supervisor that kills the process before then leaves the row open the same way; that pass reads `pass_interrupted` and the plain sync resumes it. Ctrl-C still records `timeout` and exits 0, and a sync job inside `jobs work` keeps the worker's own shutdown. | The plain sync; if that pass is stopped the same way before it saves work, the reason becomes `pass_abandoned`. |+| `pass_abandoned` | blocked | Two passes in a row never ended, were stopped by a termination signal, or ended on the same kind of transient stop, and neither saved work before it stopped. A pass saved work when it committed a page, held a path it had not held before, or re-checked a held path and cleared that hold's re-check trigger (the hold is no longer due, and a `file_drift` hold names the page's current revision); saved work moved the source, so it resets the count. A pass that only reported progress does not count, nor does one that only re-held a page edited again before it (the hold is marked `basis_moved`), re-held a path with the same code and bytes only because `sync unblock` or `sources retry-held` asked (`retry_only`; a retry whose re-check changed the hold's code or file bytes restarts the hold, so that pass still counts once), or brought a transient hold to its attempt cap. So passes that only re-hold a page edited again before each of them still end `pass_abandoned`, and from that page's third hold `sync status` reports `needs_human: true` with the page's decision. Passes stop this way when 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 61bd9ed4f8..85f4779ac3 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -196,7 +196,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 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-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, on a termination signal (a pass a SIGTERM or SIGHUP stopped records it and reads `pass_terminated`) 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/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 5be12dce61..58f104029c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -679,7 +679,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| Stop reason | Code | Outcome | What it means | Recovery || --- | --- | --- | --- | --- |-| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain, or a `sync` job reached its own deadline (its `timeout_ms` less a 60 s reserve). Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. A `sync` job that queued a follow-up (`continuation_job_id`) names it in `next` instead: watch it, don't start a second sync beside it. |+| <a id="drain-stopped-at-its-deadline"></a>`deadline`, `terminated` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain, or a `sync` job reached its own deadline (its `timeout_ms` less a 60 s reserve). `terminated`: a SIGTERM or SIGHUP reached `gbrain sync` during a managed pass, which recorded its stop before the run exited 143 (129 for SIGHUP). Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. A `sync` job that queued a follow-up (`continuation_job_id`) names it in `next` instead: watch it, don't start a second sync beside it. || <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_progress` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like (older builds named this cause `no_admission`; it is retired, and a receipt carrying it means the same). The pass returns when the run's final checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) runs after the drain lease is released, outside this governor, bounded at 5 minutes; the checkpoint's own transaction records it as owed, so a process that dies before it leaves it for the next sync of the source, and a failed or cut-short tail keeps the run `synced` with a `[gbrain notice sync_tail_degraded]` whose fix is `gbrain extract --stale --source-id <id>`. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. || <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. || <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |diff --git a/llms-full.txt b/llms-full.txtindex 883419fa9d..f6880b2e1c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6355,6 +6355,7 @@ The run ends in exactly one outcome:| --- | --- | --- | --- || `synced` | 0 | The pass converged and stamped (a company-brain source: the cursor reached its target). A pass at a selection other than the configured one adds `selection_scoped` and does not advance `last_commit`; a pass that held files a person must decide adds `held_needs_human` (their count in `held_needs_human`). | Nothing; held files wait on a person (`gbrain sync status --source <id>`). || `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; accepted writes are intact. | Rerun `next.command`; safe in a loop. |+| `resumable` / `terminated` | 143 (129 for SIGHUP) | A SIGTERM or SIGHUP (an outer `timeout`, a supervisor stop, a closed terminal) reached `gbrain sync` during a managed pass, which recorded its stop first; accepted writes are intact. A second signal, or a run still saving the pass 3 s after the handler starts, exits as before and leaves the pass open (`gbrain sync status` reads `pass_interrupted`); a run that saved the pass but is still printing its result then exits without it, and the pass reads `pass_terminated`; on PGLite the handler can start tens of seconds after the signal, so a supervisor that kills the process sooner leaves the pass open the same way. | Rerun `next.command`; either way the plain sync resumes it. || `resumable` / `not_converged` | 0 | The pass used its four rounds while another writer kept changing the level; everything it admitted stands. | Rerun `next.command`. After three in a row `next` is a report (`gbrain doctor --json`), not another sync. || `resumable` / `admission_paused` | 0 | `sync.admission` is `imports_only` or `classify_only`. | Ask the user; `gbrain config set sync.admission normal` ends the pause. || `blocked` / `reconcile_host_required` or `grant_scope` | 1 | A remote caller or a partial grant admitted what it could; the rest (holds, markers, keep_db writes, the stamp) needs the owner host. | Tell the user to run `gbrain sync --source <id> --no-pull` on the brain host. |@@ -9126,7 +9127,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 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-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, on a termination signal (a pass a SIGTERM or SIGHUP stopped records it and reads `pass_terminated`) 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/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex 2f299ce46e..bd87ebbe44 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -19,7 +19,8 @@ export async function run(engine: BrainEngine, args: string[]): Promise<void> {const { runSync, SyncLockBusyError } = await import('../../commands/sync.ts');try {// #6696 (A5): an operator's sync is interactive; autopilot's sync jobs run outside this command, as background.- await withAdmissionOrigin('interactive', () => runSync(engine, args));+ // GST-2869: only this entry lets sync own SIGTERM/SIGHUP; a worker's sync job (sync-retry-failed) keeps the worker's.+ await withAdmissionOrigin('interactive', () => runSync(engine, args, { ownSignals: true }));} catch (err) {// D1/D2: a busy sync lock is a retryable sync_in_progress refusal (its// message names the holder and the --break-lock recovery), not andiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 3266996a00..7494f9a4ff 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -5,7 +5,7 @@ import { DEFAULT_PARALLEL_SOURCES } from '../core/sync-concurrency.ts';import { withHumanLogsToStderr, withSourcePrefix } from '../core/console-prefix.ts';import { msysToNativePath } from '../core/path-confine.ts';import { performSync } from './sync/perform.ts';-import { runSyncInner } from './sync/run.ts';+import { clearTerminationFallback, runSyncInner } from './sync/run.ts';// Refactor wave 1 (W4 sync): the implementation lives in src/commands/sync/.// This file keeps the SyncResult / SyncOpts types and every export, so@@ -441,7 +441,7 @@ export {composeAbortSignals,} from '../core/sync-reconcile.ts';-export async function runSync(engine: BrainEngine, args: string[]) {+export async function runSync(engine: BrainEngine, args: string[], opts: { ownSignals?: boolean } = {}) {// #4888: under --json, stdout is reserved for the ONE JSON envelope (#4684:// the cost-gate status object rides inside it as `cost_gate`); every slog()// human line from performSync and its callees routes to stderr instead.@@ -449,7 +449,7 @@ export async function runSync(engine: BrainEngine, args: string[]) {// `sync status|unblock --json` (sync/operator.ts) write through// writeJsonDocument, the guard's only stdout path.const stopTrace = startMemoryTrace('sync');- try { const out = await (args.includes('--json') ? withHumanLogsToStderr(() => runSyncInner(engine, args)) : runSyncInner(engine, args)); await (await import('./sources-add-next.ts')).noteSyncOutOfSearch(engine, args); return out; } finally { stopTrace(); }+ try { const out = await (args.includes('--json') ? withHumanLogsToStderr(() => runSyncInner(engine, args, opts)) : runSyncInner(engine, args, opts)); await (await import('./sources-add-next.ts')).noteSyncOutOfSearch(engine, args); return out; } finally { stopTrace(); clearTerminationFallback(); }}/**diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 8ea760bf04..098a806207 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -299,7 +299,8 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'statecase 'recovery_blocked': return `Source ${status.source_id} is blocked: a write's recovery record found changed bytes on disk.`;case 'pass_unfinished': return `Source ${status.source_id} is resumable: the newest sync pass did not finish; the next sync continues it.`;case 'pass_interrupted': return `Source ${status.source_id} is resumable: the newest sync pass stopped before it ended and no process owns it (killed, crashed or stopped by an unrecorded error); the next sync continues it.`;- case 'pass_abandoned': return `Source ${status.source_id} is blocked: its sync passes keep stopping before they end; another plain sync will not change that (report what doctor shows).`;+ case 'pass_terminated': return `Source ${status.source_id} is resumable: a termination signal (SIGTERM or SIGHUP) stopped the newest sync pass, which recorded its stop; the next sync continues it.`;+ case 'pass_abandoned': return `Source ${status.source_id} is blocked: its sync passes keep stopping before they end (killed, stopped by a signal or by a recurring transient stop); another plain sync will not change that (report what doctor shows).`;case 'not_converged': return `Source ${status.source_id} is resumable: the newest sync pass ran out of rounds before every path settled.`;case 'settle_mismatch': return `Source ${status.source_id} is resumable: a path keeps settling without reading settled; three passes in a row hold it.`;case 'deletes_withheld': return `Source ${status.source_id} is blocked: sync withheld a mass delete; the rest of the source is synced.`;diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 783e709ca6..87cbfd7ec4 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -40,7 +40,7 @@ import {import { runSyncTrigger } from './trigger.ts';import { drainJsonFields, formatDrainSummary, syncOutcome } from '../../core/persistence/sync-drain.ts';import { readManagedMode } from '../../core/persistence/ownership.ts';-import { writeJsonDocument } from '../../core/cli-force-exit.ts';+import { setCliExitVerdict, writeJsonDocument } from '../../core/cli-force-exit.ts';import { cliRenderContext, renderNotice, type Notice } from '../../core/agent-output.ts';/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */@@ -99,7 +99,7 @@ function printTailNotice(result: SyncResult): void {for (const notice of runNotices(result)) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);}-export async function runSyncInner(engine: BrainEngine, args: string[]) {+export async function runSyncInner(engine: BrainEngine, args: string[], opts: { ownSignals?: boolean } = {}) {// v0.40 Federated Sync v2: `gbrain sync trigger` subcommand// Routes to runSyncTrigger which queues a 'sync' minion job with// auto_embed_backfill=true. Falls through to the normal sync path@@ -137,16 +137,16 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {// --all is set and accept maxAgeSeconds for age-gated breaks.if (breakLock || forceBreakLock) return await runSyncBreakLock(engine, args, { syncAll, jsonOut, forceBreakLock, maxAgeSeconds });// GBRA-133: one single-source run reads its routing rows once (core/sync-dispatch-read.ts); --all and --watch read live.- if (syncAll || flags.watch) return runRoutedSync(engine, args, flags);+ if (syncAll || flags.watch) return runRoutedSync(engine, args, flags, opts);const { syncDispatchRow, withSyncDispatchRead } = await import('../../core/sync-dispatch-read.ts');return withSyncDispatchRead(engine, () => {const explicit = args.find((a, i) => args[i - 1] === '--source');if (explicit) void syncDispatchRow(engine, explicit);- return runRoutedSync(engine, args, flags);+ return runRoutedSync(engine, args, flags, opts);});}-async function runRoutedSync(engine: BrainEngine, args: string[], flags: ReturnType<typeof parseSyncFlags>): Promise<void> {+async function runRoutedSync(engine: BrainEngine, args: string[], flags: ReturnType<typeof parseSyncFlags>, opts: { ownSignals?: boolean } = {}): Promise<void> {const { repoPath, dryRun, skipFailed, syncAll, jsonOut } = flags;let { noEmbed } = flags;const fanout = parseSyncFanoutFlags(args, syncAll);@@ -198,9 +198,9 @@ async function runRoutedSync(engine: BrainEngine, args: string[], flags: ReturnTif (syncAll && (args.includes('--no-delegate') || process.env.GBRAIN_SYNC_NO_DELEGATE === '1')) {(await import('../../core/persistence/consumer-election.ts')).forceOwnConsumer('opted_out');}- if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError, resumeCommand });+ if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError, resumeCommand, ownSignals: opts.ownSignals === true });- return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand, args });+ return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand, args, ownSignals: opts.ownSignals === true });}/** #6288: `gbrain sync --source <id> --acknowledge-managed <request_id|path>` removes only recorded failures the imported commit settles. */@@ -376,13 +376,13 @@ async function resolveCliSyncSource(async function runSyncAll(engine: BrainEngine,flags: SyncFlags & SyncFanoutFlags,- input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string },+ input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string; ownSignals: boolean },): Promise<void> {const {dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, noSchemaPack, includeGitignored,workingTree, missingPathMode, jsonOut, yesFlag, serialFlag, noAutoEmbed, maxSources, concurrency, timeoutSeconds,} = flags;- const { noEmbed, embeddingCredentialError, resumeCommand } = input;+ const { noEmbed, embeddingCredentialError, resumeCommand, ownSignals } = input;// v0.41.31: SELECT carries last_commit + chunker_version so the inline// cost preview's "unchanged source → 0" short-circuit can mirror sync's// own "do work?" gate (sync.ts:1057+1075) + doctor's sync_freshness.@@ -635,7 +635,9 @@ async function runSyncAll(? Math.min(runnableSources.length, maxSources ?? 8): 1;- await dispatchSyncAll({ fanOutEligible: fanOutEligible && !managedSerial, effectiveParallel, concurrency, runnableSources, runOne, writeHuman, humanSink, perSourceResults, onAllSigint });+ // GST-2869: a termination signal aborts the shared controller, so sources not yet dispatched return before any work.+ await withTerminationOwner(ownSignals, allInterrupt, () => dispatchSyncAll({ fanOutEligible: fanOutEligible && !managedSerial, effectiveParallel, concurrency, runnableSources, runOne, writeHuman, humanSink, perSourceResults, onAllSigint }));+ const terminated = await terminatedExit(allInterrupt);const okCount = perSourceResults.filter((r) => r.status === 'ok').length;const errCount = perSourceResults.filter((r) => r.status === 'error').length;@@ -650,9 +652,9 @@ async function runSyncAll(// v0.42.7 (#1696): brain-wide extraction-lag nudge after the --all wave.// Best-effort, stderr-only; skipped on dry-run.- if (!dryRun) await maybeExtractionNudge(engine);+ if (!dryRun && terminated === null) await maybeExtractionNudge(engine);// Monthly backup-coverage stale-only refresh (trusted local engine holder).- if (!dryRun) await maybeBackupCoverageRefresh(engine);+ if (!dryRun && terminated === null) await maybeBackupCoverageRefresh(engine);// #3068: any source wedged on a failed pull (partial/pull_failed) makes// the whole --all run non-zero — it will not self-heal on retry, so a@@ -661,6 +663,7 @@ async function runSyncAll(const pullFailedCount = perSourceResults.filter((r) => r.status === 'ok' && r.result && isFailedPartial(r.result),).length;+ if (terminated !== null) { setCliExitVerdict(terminated); return; }if (errCount > 0 || pullFailedCount > 0) process.exit(1);return;}@@ -825,17 +828,56 @@ function emitSyncAllEnvelope(input: {}/** Single-source sync (one run, or `--watch`). */+/** GST-2869: 128 + the signal number, the exit a supervisor that sent the signal expects. */+const terminationExit = (signal: NodeJS.Signals): number => signal === 'SIGHUP' ? 129 : 143;++/**+ * GST-2869: while a managed pass this CLI runs is live, the first SIGTERM or SIGHUP aborts `interrupt` with `SyncTerminated`,+ * so the pass records `resumable` / `terminated` and the run prints its result, then exits 128 + n. A second signal, a signal+ * with no live pass, or a run whose save or result outlasts process-cleanup's window takes today's cleanup-and-exit. Never under another+ * owner (a worker's sync job): the newest owner would take that owner's signals.+ */+async function withTerminationOwner<T>(ownSignals: boolean, interrupt: AbortController, run: () => Promise<T>): Promise<T> {+ const cleanup = await import('../../core/process-cleanup.ts');+ if (!ownSignals || cleanup.hasSignalOwner()) return run();+ const { SyncTerminated } = await import('../../core/persistence/sync-stop-class.ts');+ const { managedPassLive } = await import('../../core/persistence/sync-pass-episode.ts');+ const release = cleanup.registerSignalOwner('sync', signal => {+ if (interrupt.signal.aborted || !managedPassLive()) { release(); process.kill(process.pid, signal); return; }+ process.stderr.write(`[sync] ${signal}: saving the pass and stopping; send it again to exit now\n`);+ interrupt.abort(new SyncTerminated(signal));+ terminationFallback = setTimeout(() => { release(); void cleanup.triggerCleanupAndExit(terminationExit(signal)); }, cleanup.CLEANUP_DEADLINE_MS);+ terminationFallback.unref?.();+ }, ['SIGTERM', 'SIGHUP']);+ try { return await run(); } finally { release(); }+}++let terminationFallback: ReturnType<typeof setTimeout> | undefined;++/** GST-2869: drops the fallback a termination armed once the whole run is done, so the result and its reads stay inside the window. */+export function clearTerminationFallback(): void {+ clearTimeout(terminationFallback);+ terminationFallback = undefined;+}++/** GST-2869: the exit of a run `withTerminationOwner` stopped, or null. */+async function terminatedExit(interrupt: AbortController): Promise<number | null> {+ const { SyncTerminated } = await import('../../core/persistence/sync-stop-class.ts');+ const reason: unknown = interrupt.signal.reason;+ return reason instanceof SyncTerminated ? terminationExit(reason.signal) : null;+}+async function runSingleSourceSync(engine: BrainEngine,flags: SyncFlags & SyncFanoutFlags,- input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string; args: string[] },+ input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string; args: string[]; ownSignals: boolean },): Promise<void> {const {repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,includeGitignored, workingTree, jsonOut, redactPaths, yesFlag, noAutoEmbed, strategyArg, srcSubpath,excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,} = flags;- const { sourceId, companyPolicy, noEmbed, resumeCommand, args } = input;+ const { sourceId, companyPolicy, noEmbed, resumeCommand, args, ownSignals } = input;// #7630: before the cost gate walks the directory.await assertSyncAnchorAbsolute(engine, { sourceId, repoPath });// v0.41.13.0 (T6) — single-source --timeout: same per-source AbortController@@ -937,7 +979,7 @@ async function runSingleSourceSync(// #6317 (D1 a′): on a managed Postgres brain whose host a live serve owns, the drain runs inside that serve as this// CLI's writer and returns the same SyncResult; every other case keeps this process's own consumer.const delegated = companyPolicy ? null : await (await import('../sync-delegate.ts')).maybeDelegateManagedSyncToServe(engine, args, opts);- result = delegated?.kind === 'delegated' ? delegated.result : await performSync(engine, opts);+ result = delegated?.kind === 'delegated' ? delegated.result : await withTerminationOwner(ownSignals, singleSourceInterrupt, () => performSync(engine, opts));} catch (error) {// A refused managed dry run (a case- or separator-only spelling pair) still carries its convergence receipt in the// refusal's envelope; the refusal and its exit code are unchanged.@@ -961,19 +1003,19 @@ async function runSingleSourceSync(// which PGLite's Emscripten runtime clobbers mid-run — see// src/core/cli-force-exit.ts).// #5984: the managed drain's verdict decides; a drain that stopped at its deadline with a pending write is resumable (exit 0).- if (syncOutcome(result) === 'blocked' || isFailedPartial(result)) {- const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');- setCliExitVerdict(1);- }+ if (syncOutcome(result) === 'blocked' || isFailedPartial(result)) setCliExitVerdict(1);+ // GST-2869: a run a termination signal stopped exits 128 + n, ahead of every other verdict, and skips the post-pass extras.+ const terminated = await terminatedExit(singleSourceInterrupt);+ if (terminated !== null) setCliExitVerdict(terminated);// v0.42.7 (#1696, D5): extraction-lag nudge after a completed single-source// sync. Fire on every non-error completion (synced | first_sync | up_to_date)// — NOT just 'synced'; a fresh/--full import (`first_sync`) is the biggest// un-extracted backlog. Scoped to this source; best-effort, stderr-only.- if (shouldNudgeAfterSync(result.status)) await maybeExtractionNudge(engine, sourceId);+ if (terminated === null && shouldNudgeAfterSync(result.status)) await maybeExtractionNudge(engine, sourceId);// Monthly backup-coverage: the sync CLI legitimately holds the engine// (trusted local), so the stale-only compute piggybacks here — covering// active CLI users without any serve involvement. Dry-run stays pure.- if (result.status !== 'dry_run') await maybeBackupCoverageRefresh(engine);+ if (terminated === null && result.status !== 'dry_run') await maybeBackupCoverageRefresh(engine);// Issue #2 + eng-review pass-2 finding #1 + Codex P1: manage .gitignore ONLY// on successful sync. Skip on dry-run (don't mutate disk in preview mode)// and blocked_by_failures (sync state is inconsistent — defer .gitignorediff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 88efddb023..08e0207508 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -24,6 +24,7 @@ import { cliRenderContext, renderAction, type Action, type RenderedAction } fromimport { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.ts';import { clearDrainStep, DrainPassAbandoned, markPassAbandoned, readDrainStep } from './drain-step.ts';+import { abortStop } from './sync-stop-class.ts';import { PUBLICATION_CEILING_DEFAULT_MS, readPublicationCeilingMs } from './publication-deadline.ts';import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';import { describeHostConsumer, headBlockedNext, headBlockerText, headClaimability, type HeadBlocker } from './head-blocker.ts';@@ -45,7 +46,9 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio/** #6712 PR 1: another drainer holds the source's drain lease (or took it from this run); resumable, the next run follows it. */| 'drain_lease_held'/** #6712 PR 4b (design v3.2 §9): the live pass's stops. `not_converged` and `admission_paused` are resumable; the rest need the host or a report. */- | 'not_converged' | 'admission_paused' | 'grant_scope' | 'reconcile_host_required' | 'reconcile_read_incomplete';+ | 'not_converged' | 'admission_paused' | 'grant_scope' | 'reconcile_host_required' | 'reconcile_read_incomplete'+ /** GST-2869: `gbrain sync` took SIGTERM or SIGHUP and stopped its pass; resumable, the same command continues it. */+ | 'terminated';/** The pass's status reasons that end a drain, with their outcome (design v3.2 §9). */const PASS_STOPS: Partial<Record<string, { outcome: DrainOutcome; reason: DrainStopReason }>> = {not_converged: { outcome: 'resumable', reason: 'not_converged' }, admission_paused: { outcome: 'resumable', reason: 'admission_paused' },@@ -620,11 +623,11 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {if (passStop) return finish(result, passStop.outcome, passStop.reason);if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');if (result.managedWrite && result.managedWrite.write_error !== 'write_pending') return finish(result, 'blocked', 'blocked_by_failures');- if (result.status === 'partial' && (result.reason === 'timeout' || signal?.aborted)) return finish(result, 'resumable', 'deadline');+ if (result.status === 'partial' && (result.reason === 'timeout' || signal?.aborted)) return finish(result, 'resumable', abortStop(signal) === 'terminated' ? 'terminated' : 'deadline');const outcome = syncOutcome({ ...result, drain: undefined });return finish(result, outcome, outcome === 'resumable' ? 'deadline' : undefined);}- if (signal?.aborted) return finish(result, 'resumable', 'deadline');+ if (signal?.aborted) return finish(result, 'resumable', abortStop(signal) === 'terminated' ? 'terminated' : 'deadline');const wait = result.writeWait;if (wait?.status === 'blocked') {return finish(result, 'blocked', BLOCKED_HEAD_REASONS.has(wait.cause) ? wait.cause as DrainStopReason : 'recovery_required');@@ -958,6 +961,7 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {connection_lost: 'sync_drain_connection_lost', capacity_paused: 'sync_drain_capacity_paused', drain_lease_held: 'sync_drain_lease_held',not_converged: 'sync_drain_not_converged', admission_paused: 'sync_drain_admission_paused', grant_scope: 'sync_drain_grant_scope',reconcile_host_required: 'sync_drain_reconcile_host_required', reconcile_read_incomplete: 'sync_drain_reconcile_read_incomplete',+ terminated: 'sync_drain_deadline',};/**@@ -1057,6 +1061,7 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: swhy: abandoned? `A write's preparation outran its budget in this process${d?.stall?.step ? ` (stuck at step ${d.stall.step}${d.stall.waiting_on && d.stall.waiting_on !== 'unknown' ? `, waiting on ${d.stall.waiting_on}` : ''})` : ''}, so the sync exited to end it; `+ 'its cursor and accepted writes are intact. The same command resumes where it stopped, and an entry that stalls again is held instead of re-entered.'+ : d?.stop_reason === 'terminated' ? 'The sync stopped on a termination signal (SIGTERM or SIGHUP) and recorded its pass with its cursor and accepted writes intact; the same command resumes where it stopped.': 'The sync stopped at its deadline with its cursor and accepted writes intact; the same command resumes where it stopped.', ...(docs ? { docs } : {}) };}if (d?.stop_reason === 'preparation_systemic') {@@ -1149,7 +1154,7 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s+ `Run the sync from a process that can write the source's lock directory (the owner's gbrain serve, or this command outside the sandbox), then rerun: ${resumeCommand}`,...(docs ? { docs } : {}) };}- const writerBlocked = d?.stop_reason && d.stop_reason !== 'blocked_by_failures' && d.stop_reason !== 'deadline';+ const writerBlocked = d?.stop_reason && d.stop_reason !== 'blocked_by_failures' && d.stop_reason !== 'deadline' && d.stop_reason !== 'terminated';if (writerBlocked) {return { command: `gbrain sources writer status ${sourceId}`, safe_to_loop: false, retry_after_ms: 0, ...estimate,why: d!.stop_reason === 'drain_stalled'diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.tsindex 375fe06932..4fe349fde5 100644--- a/src/core/persistence/sync-pass-episode.ts+++ b/src/core/persistence/sync-pass-episode.ts@@ -133,6 +133,8 @@ const passCostScopes = new Map<string, PassCostScope>();export function registerPassCost(passId: string, scope: PassCostScope): void { passCostScopes.set(passId, scope); }export function unregisterPassCost(passId: string): void { passCostScopes.delete(passId); }+/** GST-2869: a managed pass is running in this process (registered after its pin, until it ends); `gbrain sync` owns a signal only then. */+export const managedPassLive = (): boolean => passCostScopes.size > 0;const costPrefix = (sourceId: string, incarnation: string, scope?: string) => `${sourceId}:${incarnation}:${scope === undefined ? '' : `${scope}:`}`;diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsindex e457550244..f535c49c63 100644--- a/src/core/persistence/sync-pass-row.ts+++ b/src/core/persistence/sync-pass-row.ts@@ -164,9 +164,11 @@ export const passReadClock = (row: PassRow): number => row.read_at ? Date.parse(/*** #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.+ * GST-2869: so does a pass a termination signal stopped (`terminated`), as it did when it was left open, in every reader:+ * the next pin's carry, abandonedPasses and sync-blocked.*/export const transientEnding = (telemetry: Pick<ManagedSyncPassValue['telemetry'], 'outcome' | 'stop_reason'>): boolean =>- telemetry.outcome === 'resumable' && telemetry.stop_reason === 'transient';+ telemetry.outcome === 'resumable' && (telemetry.stop_reason === 'transient' || telemetry.stop_reason === 'terminated');type Exec = Pick<BrainEngine, 'executeRaw'>;const iso = (value: Date | string) => new Date(value).toISOString();diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 7873b15372..75c36efad9 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -23,7 +23,7 @@ import type { Cursor, RetryWait } from './sync-run.ts';import { getWriteRequestById } from './journal.ts';import type { WriteRequest } from './model.ts';import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';-import { recordedStop, replaysUnchangedRefusal, resumableRowStop } from './sync-stop-class.ts';+import { abortStop, recordedStop, replaysUnchangedRefusal, resumableRowStop } from './sync-stop-class.ts';import { adoptLegacyPage, incomingId, partialCloneTreeRefusal, 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';@@ -833,7 +833,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prpass: { pass_id: passId, kind, round: value.telemetry.round, outcome: value.telemetry.outcome, stop_reason: value.telemetry.stop_reason, candidates: candidatesFirst,settled: S.size + yieldSettled, remaining: value.telemetry.remaining, not_converged_streak: value.obligations.not_converged_streak } });// A caller abort records the stop on the pass row (the pin it rolled back is replaced).- if (await pinPassRow(engine, value, input)) { await save('resumable', 'timeout', true).catch(() => undefined); return result('partial', 'timeout'); }+ if (await pinPassRow(engine, value, input)) { await save('resumable', abortStop(input.signal), true).catch(() => undefined); return result('partial', 'timeout'); }assertActive();registerPassCost(passId, { sourceId, incarnation, scope: costScope, pricePerMTok: currentEmbeddingPricePerMTok() });/** The batch cursor sync-run.ts drains: the discovery shape with no cursor row behind it. */@@ -886,7 +886,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst outcome: PassOutcome = drained.status === 'blocked_by_failures' ? 'blocked' : 'resumable';const blockedOn = drained.managedWrite?.path ? drained.managedWrite.write_request.request_id : null;if (outcome === 'blocked' && blockedOn && obligations.blocked?.request_id !== blockedOn) obligations.blocked = { request_id: blockedOn, pass_id: passId };- await save(outcome, drained.reason ?? (outcome === 'blocked' ? 'blocked_by_failures' : null));+ await save(outcome, drained.reason === 'timeout' ? abortStop(input.signal) : drained.reason ?? (outcome === 'blocked' ? 'blocked_by_failures' : null));const { runId: _run, managedCursor: _cursor, ...rest } = drained;return { ...rest, ...result(drained.status, drained.reason) };};@@ -1045,7 +1045,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prif (input.signal?.aborted && error instanceof Error && error.name === 'AbortError') {// A folded stamp with nothing since ended the pass: the abort stops nothing it owes.if (folded?.done === doneKey()) return synced(true);- await save('resumable', 'timeout', false, true, true).catch(() => undefined); return result('partial', 'timeout');+ await save('resumable', abortStop(input.signal), false, true, true).catch(() => undefined); return result('partial', 'timeout');}// A Git listing that did not finish cleanly classifies nothing (design v3.2 §9): the pass stops blocked, having written nothing for that round.if (error instanceof SyncTreeReadIncomplete) { await save('blocked', 'reconcile_read_incomplete').catch(() => undefined); const refusal = partialCloneTreeRefusal(context.gitRoot, sourceId, head); if (refusal) throw refusal; return result('blocked_by_failures', 'reconcile_read_incomplete'); }diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex aeaff0cee3..177a6cffe0 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -88,6 +88,7 @@ const RESCREEN_PAGE = 500;* only re-hold a page that keeps moving build the streak too.* GST-2869: nor is a rewrite marked `retry_only` (re-checked only because `sync unblock` or `sources retry-held` asked, with* nothing due), nor one that brought a transient hold to its attempt cap: both leave the path where it was, waiting on a person.+ * A `retry_only` rewrite that changed the hold's code or bytes restarted `held_at`, so the first branch still counts it once.*/export async function passBanked(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string, telemetry: { pass_id: string; started_at: string }): Promise<boolean> {const [row] = await engine.executeRaw<{ banked: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_source_bindings b ON b.worktree_id=r.worktree_id@@ -111,7 +112,7 @@ export async function passBanked(engine: Pick<BrainEngine, 'executeRaw'>, source}}-export type PassStatusReason = 'pass_unfinished' | 'pass_interrupted' | 'pass_abandoned' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';+export type PassStatusReason = 'pass_unfinished' | 'pass_interrupted' | 'pass_terminated' | 'pass_abandoned' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';/*** #7355: passes in a row that never ended, the newest open one included once its row has been quiet past the no-progress@@ -141,6 +142,7 @@ export function passStatusState(row: PassRow, withheld: DeletesWithheld | null,const t = row.value.telemetry;if (abandonedPasses(row, now, interrupted, banked) >= ABANDONED_REPORT_STREAK) return ['blocked', 'pass_abandoned'];if (t.outcome === 'open' && interrupted) return ['resumable', 'pass_interrupted'];+ if (t.outcome === 'resumable' && t.stop_reason === 'terminated') return ['resumable', 'pass_terminated'];if (t.outcome === 'open' || (t.outcome === 'resumable' && t.stop_reason !== 'not_converged' && t.stop_reason !== 'admission_paused')) return ['resumable', 'pass_unfinished'];if (t.stop_reason === 'admission_paused') return ['resumable', 'admission_paused'];if (t.stop_reason === 'not_converged' || (row.value.obligations.not_converged_streak ?? 0) > 0) return ['resumable', 'not_converged'];@@ -179,7 +181,9 @@ 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, passReadClock(row), interrupted, banked)} 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).${seen ? ` The newest pass was${seen}` : ''}` };+ why: `The last ${abandonedPasses(row, passReadClock(row), interrupted, banked)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, their process was killed, or a termination signal stopped them) 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).${seen ? ` The newest pass was${seen}` : ''}` };+ case 'pass_terminated':+ return { ...sync, why: `The newest pass of ${sourceId} was stopped by a termination signal (SIGTERM or SIGHUP: an outer timeout, a supervisor stop or a closed terminal) and recorded its stop at ${row.updated_at}. The plain sync continues it from the current level.` };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.${seen ? ` It was${seen}` : ''}` };case 'selection_scoped':diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex b3c4f61d1b..22b084c016 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -251,6 +251,8 @@ export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'held_n'pass_abandoned',// #7596: the newest pass's process stopped (killed or crashed) without ending it.'pass_interrupted',+ // GST-2869: a termination signal (SIGTERM or SIGHUP) stopped the newest pass, which recorded its stop.+ 'pass_terminated',// GST-2515: nothing else is pending, but the checkout's HEAD is past the last synced commit.'commits_waiting'] as const;export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];diff --git a/src/core/persistence/sync-stop-class.ts b/src/core/persistence/sync-stop-class.tsindex 3d5f9b2a8e..e44f53adf3 100644--- a/src/core/persistence/sync-stop-class.ts+++ b/src/core/persistence/sync-stop-class.ts@@ -34,6 +34,21 @@ export function unrecordedStop(error: unknown): 'lease_lost' | 'transient' | nul|| isRetryableConnError(error) || isStatementTimeoutError(error) ? 'transient' : null;}+/**+ * GST-2869: the abort reason `gbrain sync` gives the run it owns when it takes SIGTERM or SIGHUP during a managed pass. The pass+ * ends its row `resumable` / `terminated` and the drain stops `terminated`; a deadline or SIGINT keeps `timeout` / `deadline`.+ */+export class SyncTerminated extends Error {+ // Named AbortError: a check that throws the signal's reason itself (`throwIfAborted`) must still read as the caller's abort.+ constructor(readonly signal: NodeJS.Signals) { super(`sync stopped by ${signal}`); this.name = 'AbortError'; }+}++/**+ * The stop reason a caller's abort records on the pass row, whether the pass caught it or a batch returned `timeout` for it:+ * the first abort's reason wins (AbortSignal.any keeps it).+ */+export const abortStop = (signal?: AbortSignal): 'terminated' | 'timeout' => signal?.reason instanceof SyncTerminated ? 'terminated' : 'timeout';+/** The stop reason a pass row ends `resumable` with: `unrecordedStop` less a permission refusal. */export function resumableRowStop(error: unknown): 'lease_lost' | 'transient' | null {return error instanceof OperationError && error.code === 'permission_denied' ? null : unrecordedStop(error);diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.tsindex 9b5d83d333..2984d5ec1e 100644--- a/src/core/process-cleanup.ts+++ b/src/core/process-cleanup.ts@@ -45,7 +45,7 @@import { noteInterrupted } from './read-heartbeat.ts';-const CLEANUP_DEADLINE_MS = 3_000;+export const CLEANUP_DEADLINE_MS = 3_000;interface CleanupEntry {name: string;@@ -57,7 +57,7 @@ const registry = new Map<symbol, CleanupEntry>();* recent registration wins; while one is registered, termination signals* and a broken stdout/stderr pipe go to it instead of the generic* cleanup-then-exit pass. */-const signalOwners: Array<{ key: symbol; onSignal: (signal: NodeJS.Signals) => void }> = [];+const signalOwners: Array<{ key: symbol; onSignal: (signal: NodeJS.Signals) => void; signals?: readonly NodeJS.Signals[] }> = [];let installed = false;let cleanupPass: Promise<void> | null = null;/** Refs to every listener attached by installSignalHandlers, keyed by@@ -112,20 +112,26 @@ export function abortOnCleanupPass(name: string): { signal: AbortSignal; release* then calls `triggerCleanupAndExit` (or exits) itself. Repeated signals are* forwarded again, so `onSignal` must be idempotent. Crashes* (uncaughtException / unhandledRejection) keep the generic path.+ * GST-2869: `signals` narrows the claim; a signal it leaves out (a broken pipe for `gbrain sync`) takes the generic path.** Returns a deregister handle (idempotent).*/-export function registerSignalOwner(name: string, onSignal: (signal: NodeJS.Signals) => void): () => void {+export function registerSignalOwner(name: string, onSignal: (signal: NodeJS.Signals) => void, signals?: readonly NodeJS.Signals[]): () => void {const key = Symbol(name);- signalOwners.push({ key, onSignal });+ signalOwners.push({ key, onSignal, ...(signals ? { signals } : {}) });return () => {const i = signalOwners.findIndex((o) => o.key === key);if (i >= 0) signalOwners.splice(i, 1);};}+/** Whether a command already claimed the termination signals (`registerSignalOwner`). */+export function hasSignalOwner(): boolean {+ return signalOwners.length > 0;+}+function forwardToSignalOwner(signal: NodeJS.Signals): boolean {- const owner = signalOwners[signalOwners.length - 1];+ const owner = signalOwners.findLast(o => !o.signals || o.signals.includes(signal));if (!owner) return false;try { owner.onSignal(signal); }catch (err) {diff --git a/src/core/repair/file-drift-compare.ts b/src/core/repair/file-drift-compare.tsindex 9f58b302cc..2f4ed251b4 100644--- a/src/core/repair/file-drift-compare.ts+++ b/src/core/repair/file-drift-compare.ts@@ -96,7 +96,8 @@ export async function comparePage(engine: BrainEngine, sourceId: string, target:const held = { ...(side ? { side } : {}), ...(hold?.meta.state ? { state: hold.meta.state } : {}), ...(hold ? { path: hold.path } : {}) };if (side === 'deleted' && hold?.meta.state && hold.meta.state !== 'file_gone') {const state = hold.meta.state;- return { item, slug, ...held, would: 'needs_human', why: `the page at ${hold.path} is deleted and the file differs (${state}); --prefer database would ${fileDriftActionVerb('deleted', state, 'database')} and --prefer file would ${fileDriftActionVerb('deleted', state, 'file')}, so a person decides` };+ return { item, slug, ...held, would: 'needs_human', why: target.mirror ? `the page at ${hold.path} is deleted and the file differs (${state}), so a person decides; ${mirrorDriftRoute(sourceId)}`+ : `the page at ${hold.path} is deleted and the file differs (${state}); --prefer database would ${fileDriftActionVerb('deleted', state, 'database')} and --prefer file would ${fileDriftActionVerb('deleted', state, 'file')}, so a person decides` };}if (slug === null) return { item, slug, ...held, would: 'unknown', why: 'the hold names no page; the next sync re-classifies it' };try {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 13b966d9b9..7cbe615d13 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -732,6 +732,7 @@ test/sync-plain-directory-7973.test.tstest/sync-prescreen-both-delta-6712.test.tstest/sync-prescreen-drift-6712.test.tstest/sync-restored-file-purge.test.ts+test/sync-sigterm-gst2869.test.tstest/sync-slug-root-mode-6694.test.tstest/sync-staged-catchup.test.tstest/sync-status-commits-waiting-gst2515.test.tsdiff --git a/test/sync-mirror-parked-gst2843.test.ts b/test/sync-mirror-parked-gst2843.test.tsindex d7ac531b51..69d734d7de 100644--- a/test/sync-mirror-parked-gst2843.test.ts+++ b/test/sync-mirror-parked-gst2843.test.ts@@ -16,7 +16,7 @@ import { describe, expect, setSystemTime, spyOn, test } from 'bun:test';import { randomUUID } from 'node:crypto';import * as gitStream from '../src/core/persistence/sync-git-stream.ts';import { execFileSync } from 'node:child_process';-import { mkdirSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';@@ -56,7 +56,7 @@ const coordinated = (engine: BrainEngine, sql: string, params: unknown[] = []) =engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));const mirror = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only": true}'::jsonb WHERE id='default'`);const incarnation = async (engine: BrainEngine) => (await engine.executeRaw<{ i: string }>("SELECT incarnation::text AS i FROM sources WHERE id='default'"))[0]!.i;-const holdRows = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; upstream_version: string | null; meta: Record<string, unknown> } }>(+const holdRows = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; upstream_version: string | null; held_at: string; meta: Record<string, unknown> } }>("SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => r);/** Pages as an older gbrain left them: no import record, and a revision no import or write request produced. */const legacy = async (engine: BrainEngine) => {@@ -230,6 +230,16 @@ describe.each(testBackends())('GST-2843: the held comparison on a read-only mirrawait engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only": false}'::jsonb WHERE id='default'`);expect(classes(await repair(engine, { slugs: ['notes/newer-file'], prefer: 'file' }))).toEqual({ 'notes/newer-file': 'prefer_file' });}, { databaseUrl, setup: heldSetup }), 240_000);+ test('GST-2869: on a mirror a held deleted page whose file differs names the writable route, not a --prefer preview', () => managedBrain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await mirror(engine);+ await seedHold(engine, 'notes/same', { side: 'deleted', state: 'tombstone_edited' });+ const compared = await repair(engine, { held: true }) as Plan;+ const [page] = (compared.details!.pages as Array<{ slug: string; would: string; why: string }>).filter(found => found.slug === 'notes/same');+ expect(page!.would).toBe('needs_human');+ expect(page!.why).not.toContain('--prefer');+ expect(page!.why).toContain('gbrain sources mirror-writable default');+ }, { databaseUrl, setup: heldSetup }), 240_000);});describe.each(testBackends())('GST-2869: a re-hold that settled nothing is not saved work (%s)', backend => {@@ -250,6 +260,24 @@ describe.each(testBackends())('GST-2869: a re-hold that settled nothing is not sexpect(await passBanked(engine, 'default', inc, telemetry)).toBe(false);}, { databaseUrl, setup: notes(1) }), 240_000);+ test('a retry whose re-check changed the hold restarts it, so that pass still counts as progress once', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ files(root, { 'notes/broken': '---\ntype: concept\ntitle: [unclosed\n---\n\nBody.\n' });+ commitAll(root, 'a file sync cannot import');+ await performManagedSync(engine, OPTS);+ const held = (await holdRows(engine)).find(h => h.path === 'notes/broken.md')!;+ const inc = await incarnation(engine);+ files(root, { 'notes/broken': '---\ntype: concept\ntitle: [still unclosed\n---\n\nOther body.\n' });+ commitAll(root, 'still broken, other bytes');+ await requestGitHoldRetry(engine, 'default', inc, ['notes/broken.md']);+ await stoppedSync(engine, 0);+ const telemetry = (await readPassRow(engine, 'default', inc))!.value.telemetry;+ const again = (await holdRows(engine)).find(h => h.path === 'notes/broken.md')!;+ expect([again.meta.retry_only, again.held_at === held.held_at]).toEqual([true, false]);+ expect(await passBanked(engine, 'default', inc, telemetry)).toBe(true);+ const row = readFileSync(join(import.meta.dir, '..', 'docs', 'guides', 'sync-unblock-runbook.md'), 'utf8').split('\n').find(line => line.startsWith('| `pass_abandoned` |'))!;+ expect(row).toContain('a retry whose re-check changed the hold\'s code or file bytes restarts the hold, so that pass still counts once');+ }, { databaseUrl, setup: notes(1) }), 240_000);test('a re-hold that brought a transient hold to its attempt cap does not count as progress', () => managedBrain(async ({ engine }) => {const inc = await incarnation(engine);const before = '2026-01-01T00:00:00.000Z', started = '2026-01-02T00:00:00.000Z', during = '2026-01-02T00:05:00.000Z';diff --git a/test/sync-sigterm-gst2869.test.ts b/test/sync-sigterm-gst2869.test.tsnew file mode 100644index 0000000000..c9fbbd05b1--- /dev/null+++ b/test/sync-sigterm-gst2869.test.ts@@ -0,0 +1,378 @@+/**+ * GST-2869: `gbrain sync` stopped by SIGTERM or SIGHUP in the middle of a managed pass recorded nothing: process-cleanup's+ * generic handler released the locks and exited 143, the pass row stayed open and status could only guess `pass_interrupted`.+ * The CLI now owns those signals while a managed pass is live: the pass ends its row `resumable` / `terminated`, the drain+ * stops `terminated`, status reads `pass_terminated`, the run exits 128 + n, and a terminated pass that committed nothing+ * still builds the abandoned streak in every reader. A worker's sync job, or a run without the CLI opt-in, keeps today's path.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { performSync, runSync } from '../src/commands/sync.ts';+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';+import * as processCleanup from '../src/core/process-cleanup.ts';+import { _resetForTests, CLEANUP_DEADLINE_MS, hasSignalOwner, installSignalHandlers, registerSignalOwner } from '../src/core/process-cleanup.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';+import { abandonedPasses, passStatusNext, passStatusState } from '../src/core/persistence/sync-pass-status.ts';+import * as passRowModule from '../src/core/persistence/sync-pass-row.ts';+import * as watermarkModule from '../src/core/persistence/applied-watermark.ts';+import { MANAGED_SYNC_PASS_OP, readPassRow, transientEnding, type PassRow } from '../src/core/persistence/sync-pass-row.ts';+import { abortStop, SyncTerminated } from '../src/core/persistence/sync-stop-class.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { waitFor } from './helpers/wait-for.ts';++const git = (root: string, args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const now = Date.parse('2026-11-17T12:00:00Z');+const row = (outcome: string, stop: string | null, streak?: number): PassRow => ({ updated_at: new Date(now - 10_000).toISOString(),+ value: { source_id: 's', incarnation: 'i', lease_token: 't', obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {}, ...(streak ? { abandoned_streak: streak } : {}) },+ telemetry: { pass_id: 'p', target: 'h', started_at: '', ended_at: null, kind: 'full', round: 0, outcome, stop_reason: stop, candidates: 0, settled: 0, remaining: 0, counts: {}, duration_ms: null } } } as never);++afterEach(() => { installFaultHook(undefined); _resetForTests(); setCliExitVerdict(0); });++describe('GST-2869: a terminated pass', () => {+ test('reads pass_terminated with the plain sync next, and counts toward the abandoned streak unless it banked work', () => {+ const terminated = row('resumable', 'terminated');+ expect(transientEnding(terminated.value.telemetry)).toBe(true);+ expect(passStatusState(terminated, null, null, now, true)).toEqual(['resumable', 'pass_terminated']);+ const next = passStatusNext('s', 'pass_terminated', terminated, ['--source', 's'], null, true);+ expect(next.argv).toEqual(['gbrain', 'sync', '--source', 's']);+ expect(next.why).toContain('termination signal');+ expect(abandonedPasses(terminated, now, true)).toBe(1);+ expect(abandonedPasses(terminated, now, true, true)).toBe(0);+ expect(passStatusState(row('resumable', 'terminated', 1), null, null, now, true)).toEqual(['blocked', 'pass_abandoned']);+ // A deadline or SIGINT stop keeps resetting the streak, as before.+ expect(transientEnding(row('resumable', 'timeout').value.telemetry)).toBe(false);+ expect(passStatusState(row('resumable', 'timeout'), null, null, now, true)).toEqual(['resumable', 'pass_unfinished']);+ });++ test('the first abort decides the stop reason: a deadline that fired first stays a timeout', () => {+ const deadline = new AbortController(), signal = new AbortController();+ const both = AbortSignal.any([deadline.signal, signal.signal]);+ deadline.abort(new Error('deadline'));+ signal.abort(new SyncTerminated('SIGTERM'));+ expect(abortStop(both)).toBe('timeout');+ const first = new AbortController(), later = new AbortController();+ const other = AbortSignal.any([first.signal, later.signal]);+ first.abort(new SyncTerminated('SIGHUP'));+ later.abort(new Error('deadline'));+ expect(abortStop(other)).toBe('terminated');+ expect(abortStop(undefined)).toBe('timeout');+ });++ test('a signal owner can claim only some signals; the rest take the generic path', async () => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ try {+ installSignalHandlers();+ const seen: string[] = [];+ const release = registerSignalOwner('t', signal => { seen.push(signal); }, ['SIGTERM', 'SIGHUP']);+ expect(hasSignalOwner()).toBe(true);+ process.emit('SIGTERM');+ process.emit('SIGHUP');+ expect(seen).toEqual(['SIGTERM', 'SIGHUP']);+ process.emit('SIGPIPE' as never);+ expect(seen).toEqual(['SIGTERM', 'SIGHUP']);+ // The generic path ran: its cleanup pass then exits 141.+ await Bun.sleep(50);+ expect(exit).toHaveBeenCalledWith(141);+ release();+ expect(hasSignalOwner()).toBe(false);+ } finally { exit.mockRestore(); }+ });+});++const SYNC = ['--source', 'default', '--no-pull', '--no-embed', '--json'];+const page = (i: number, tag: string) => `---\ntype: concept\ntitle: p${i}\n---\n\nNote ${i}${tag}.\n`;+const seed = ({ root }: { root: string }) => {+ git(root, ['init', '-q']);+ for (let i = 0; i < 40; i++) { mkdirSync(join(root, `d${i % 4}`), { recursive: true }); writeFileSync(join(root, `d${i % 4}/p${i}.md`), page(i, '')); }+ git(root, ['add', '-A']); git(root, ['commit', '-qm', 'init']);+};+const editAll = (root: string, tag: string) => {+ for (let i = 0; i < 40; i++) writeFileSync(join(root, `d${i % 4}/p${i}.md`), page(i, `, ${tag}`));+ git(root, ['commit', '-qam', tag]);+};+const quiet = async <T>(run: () => Promise<T>): Promise<T> => {+ const out = spyOn(process.stdout, 'write').mockImplementation((() => true) as never);+ try { return await run(); } finally { out.mockRestore(); }+};+/** Emits `signal` the first time the next pass reaches `at`, as a supervisor's kill lands mid-pass. */+const signalAtRound = (signal: NodeJS.Signals, at = 'sync:round_start') => {+ let sent = false;+ installFaultHook(point => { if (point === at && !sent) { sent = true; process.emit(signal as never); } });+};+const passRow = async (engine: BrainEngine) => {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ return (await readPassRow(engine, 'default', incarnation))!.value;+};++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test(`GST-2869 [${backend}]: SIGTERM mid-pass records terminated, exits 143, and the next sync resumes`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ expect(currentExitCode()).toBe(0);+ editAll(root, 'one');+ signalAtRound('SIGTERM');+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(currentExitCode()).toBe(143);+ expect(exit).not.toHaveBeenCalled();+ expect(kill).not.toHaveBeenCalled();+ expect(hasSignalOwner()).toBe(false);+ const ended = await passRow(engine);+ expect([ended.telemetry.outcome, ended.telemetry.stop_reason]).toEqual(['resumable', 'terminated']);+ const status = await readSyncStatus(engine, 'default', { detail: false });+ expect([status.state, status.reason]).toEqual(['resumable', 'pass_terminated']);+ expect(status.next?.argv?.slice(0, 4)).toEqual(['gbrain', 'sync', '--source', 'default']);++ setCliExitVerdict(0);+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ expect(currentExitCode()).toBe(0);+ expect((await passRow(engine)).telemetry.outcome).toBe('synced');+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ test(`GST-2869 [${backend}]: SIGTERM inside a batch records terminated, not the batch's timeout`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ editAll(root, 'batch');+ signalAtRound('SIGTERM', 'sync:batch_entries');+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(currentExitCode()).toBe(143);+ const ended = await passRow(engine);+ expect([ended.telemetry.outcome, ended.telemetry.stop_reason]).toEqual(['resumable', 'terminated']);+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ test(`GST-2869 [${backend}]: two terminated passes that committed nothing carry the streak through the pin and read pass_abandoned`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ editAll(root, 'two');+ for (const signal of ['SIGTERM', 'SIGHUP'] as const) {+ setCliExitVerdict(0);+ signalAtRound(signal);+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(currentExitCode()).toBe(signal === 'SIGHUP' ? 129 : 143);+ }+ expect((await passRow(engine)).obligations.abandoned_streak).toBe(1);+ const status = await readSyncStatus(engine, 'default', { detail: false });+ expect([status.state, status.reason]).toEqual(['blocked', 'pass_abandoned']);+ expect((await readBlockedManagedSyncs(engine, ['default'])).filter(entry => entry.source_id === 'default'))+ .toEqual([expect.objectContaining({ code: 'pass_abandoned' })]);+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ test(`GST-2869 [${backend}]: under another owner (a worker) or without the CLI opt-in, sync claims no signal`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ const seen: string[] = [];+ const releaseWorker = registerSignalOwner('jobs-work', signal => { seen.push(signal); });+ editAll(root, 'three');+ signalAtRound('SIGTERM');+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ releaseWorker();+ expect(seen).toEqual(['SIGTERM']);+ expect(currentExitCode()).toBe(0);+ expect((await passRow(engine)).telemetry.outcome).toBe('synced');+ let ownedDuringPass: boolean | undefined;+ editAll(root, 'four');+ installFaultHook(point => { if (point === 'sync:round_start') ownedDuringPass ??= hasSignalOwner(); });+ await quiet(() => runSync(engine, SYNC));+ expect(ownedDuringPass).toBe(false);+ expect((await passRow(engine)).telemetry.outcome).toBe('synced');+ } finally { exit.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=a second SIGTERM while the pass saves exits now through the generic path (release + re-raise);+ // fails_when=the interrupt.signal.aborted guard in the sync signal owner is dropped; why_new=no test sends a second signal;+ // seam=none; no_claim=the real process death (process.kill mocked; pglite unit only)+ test(`GST-2869 [${backend}]: a second SIGTERM while the pass saves re-raises it through the generic path`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ editAll(root, 'twice');+ let sent = false;+ installFaultHook(point => { if (point === 'sync:round_start' && !sent) { sent = true; process.emit('SIGTERM' as never); process.emit('SIGTERM' as never); } });+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(kill).toHaveBeenCalledTimes(1);+ expect(kill).toHaveBeenCalledWith(process.pid, 'SIGTERM');+ expect(hasSignalOwner()).toBe(false);+ expect(currentExitCode()).toBe(143);+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=a SIGTERM before any managed pass is live takes the generic path and records no terminated pass;+ // fails_when=the !managedPassLive() guard is dropped, so a pre-pass signal aborts the run instead of exiting;+ // why_new=existing arms signal only mid-pass; seam=none; no_claim=the real process death (process.kill mocked; pglite unit only)+ test(`GST-2869 [${backend}]: a SIGTERM with no live managed pass takes the generic path and records nothing`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ editAll(root, 'early');+ signalAtRound('SIGTERM', 'sync:lease_acquired');+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(kill).toHaveBeenCalledWith(process.pid, 'SIGTERM');+ expect(currentExitCode()).toBe(0);+ const ended = await passRow(engine);+ expect([ended.telemetry.outcome, ended.telemetry.stop_reason]).toEqual(['synced', null]);+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=a save that outlasts the cleanup window still exits 128 + n through triggerCleanupAndExit (143 SIGTERM, 129 SIGHUP);+ // fails_when=the fallback timer is dropped, uses another delay, or exits with a fixed or wrong code; why_new=no arm reaches the fallback;+ // seam=none; no_claim=a real 3 s wall-clock wait (the timer callback is captured and fired by hand; cleanup exit spied)+ test(`GST-2869 [${backend}]: a save that outlasts the cleanup window exits 128 + n through the generic cleanup`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ const trigger = spyOn(processCleanup, 'triggerCleanupAndExit').mockImplementation((async () => undefined) as never);+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ for (const [signal, code] of [['SIGTERM', 143], ['SIGHUP', 129]] as const) {+ setCliExitVerdict(0);+ editAll(root, `late-${signal}`);+ const fallbacks: Array<() => void> = [];+ let sent = false;+ installFaultHook(point => {+ if (point !== 'sync:round_start' || sent) return;+ sent = true;+ const realSetTimeout = globalThis.setTimeout;+ globalThis.setTimeout = ((fn: () => void, ms?: number, ...rest: unknown[]) => {+ if (ms === CLEANUP_DEADLINE_MS) fallbacks.push(fn);+ return realSetTimeout(fn, ms, ...rest);+ }) as typeof setTimeout;+ try { process.emit(signal as never); } finally { globalThis.setTimeout = realSetTimeout; }+ });+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ installFaultHook(undefined);+ expect(currentExitCode()).toBe(code);+ expect(trigger).not.toHaveBeenCalled();+ expect(fallbacks).toHaveLength(1);+ fallbacks[0]();+ expect(trigger).toHaveBeenCalledWith(code);+ trigger.mockClear();+ }+ } finally { exit.mockRestore(); kill.mockRestore(); trigger.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=a terminated run keeps the cleanup fallback armed until its result is out, so a stalled read after the save still exits;+ // fails_when=the fallback is cleared when the pass returns, before the watermark read and the JSON result; why_new=other arms finish fast;+ // seam=none; no_claim=a real stalled database (the watermark read is held by a spy)+ test(`GST-2869 [${backend}]: a terminated run keeps the fallback armed until its result is out`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ let release: (value: null) => void = () => undefined;+ const stalled = new Promise<null>(resolve => { release = resolve; });+ const watermark = spyOn(watermarkModule, 'readAppliedWatermark');+ const realSetTimeout = globalThis.setTimeout, realClearTimeout = globalThis.clearTimeout;+ const fallbacks: unknown[] = [], cleared = new Set<unknown>();+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ editAll(root, 'stalled-tail');+ let sent = false;+ installFaultHook(point => {+ if (point !== 'sync:round_start' || sent) return;+ sent = true;+ globalThis.setTimeout = ((fn: () => void, ms?: number, ...rest: unknown[]) => {+ const handle = realSetTimeout(fn, ms, ...rest);+ if (ms === CLEANUP_DEADLINE_MS) fallbacks.push(handle);+ return handle;+ }) as typeof setTimeout;+ try { process.emit('SIGTERM' as never); } finally { globalThis.setTimeout = realSetTimeout; }+ });+ globalThis.clearTimeout = ((handle?: Parameters<typeof clearTimeout>[0]) => { cleared.add(handle); realClearTimeout(handle); }) as typeof clearTimeout;+ watermark.mockClear();+ watermark.mockImplementation((() => stalled) as never);+ const running = quiet(() => runSync(engine, SYNC, { ownSignals: true }));+ await waitFor(() => watermark.mock.calls.length > 0, { timeoutMs: 60_000 });+ expect(fallbacks).toHaveLength(1);+ expect(cleared.has(fallbacks[0])).toBe(false);+ release(null);+ await running;+ installFaultHook(undefined);+ expect(cleared.has(fallbacks[0])).toBe(true);+ expect(currentExitCode()).toBe(143);+ expect((await passRow(engine)).telemetry.stop_reason).toBe('terminated');+ } finally { globalThis.clearTimeout = realClearTimeout; watermark.mockRestore(); exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=gbrain sync --all stopped by SIGTERM records the pass terminated and exits 143;+ // fails_when=runSyncAll stops wrapping dispatch in the signal owner or drops the terminated exit verdict;+ // why_new=existing arms run single-source only; seam=none; no_claim=the skipped extraction and backup extras (not observed; pglite unit only)+ test(`GST-2869 [${backend}]: sync --all stopped by SIGTERM records terminated and exits 143`, () => managedBrain(async ({ engine, root }) => {+ const exit = spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const kill = spyOn(process, 'kill').mockImplementation((() => true) as never);+ const ALL = ['--all', '--no-pull', '--no-embed', '--json'];+ try {+ installSignalHandlers();+ await quiet(() => runSync(engine, ALL, { ownSignals: true }));+ expect(currentExitCode()).toBe(0);+ editAll(root, 'all');+ signalAtRound('SIGTERM');+ await quiet(() => runSync(engine, ALL, { ownSignals: true }));+ installFaultHook(undefined);+ expect(currentExitCode()).toBe(143);+ expect(exit).not.toHaveBeenCalled();+ expect(kill).not.toHaveBeenCalled();+ expect(hasSignalOwner()).toBe(false);+ const ended = await passRow(engine);+ expect([ended.telemetry.outcome, ended.telemetry.stop_reason]).toEqual(['resumable', 'terminated']);+ } finally { exit.mockRestore(); kill.mockRestore(); }+ }, { databaseUrl, setup: seed }), 120_000);++ // Value: protects=an abort the sync took as a termination, landing while the pass row is pinned, saves stop_reason terminated;+ // fails_when=the pin-site save goes back to a fixed 'timeout'; why_new=existing arms abort after the pin; seam=none;+ // no_claim=a real signal at the pin (managedPassLive is false there); a writePassRow spy aborts right after the pin write+ test(`GST-2869 [${backend}]: a termination abort while the pass is pinned records terminated, not timeout`, () => managedBrain(async ({ engine, root }) => {+ await quiet(() => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true }));+ editAll(root, 'pin');+ const controller = new AbortController();+ const realWrite = passRowModule.writePassRow;+ const write = spyOn(passRowModule, 'writePassRow').mockImplementation(async (tx, value, opts = {}) => {+ const written = await realWrite(tx, value, opts);+ if (opts.pin && !opts.clock && value.telemetry.outcome === 'open' && !controller.signal.aborted) controller.abort(new SyncTerminated('SIGTERM'));+ return written;+ });+ try {+ await quiet(() => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, drain: true, signal: controller.signal }));+ } finally { write.mockRestore(); }+ expect(controller.signal.aborted).toBe(true);+ const ended = await passRow(engine);+ expect([ended.telemetry.outcome, ended.telemetry.stop_reason, ended.telemetry.round]).toEqual(['resumable', 'terminated', 0]);+ }, { databaseUrl, setup: seed }), 120_000);+}++/**+ * Measured on a generated 24,000-hold PGLite mirror: a real SIGTERM reached the sync handler 19-33 s after the signal while+ * the pass's progress timers kept firing, and master's generic handler waits as long. Once the handler runs, the row is+ * saved within milliseconds, which the pglite arms above pin. This names the wait so a fix has a test to turn green.+ */+test.todo('GST-2869 follow-up [pglite]: a real SIGTERM reaches the sync handler within the 3 s window while a managed pass writes pages', () => {});