Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(sync): our own implementation of the #6101 fix (#6101)

time-attack092b9271cce5
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index ab1052e4a6..9221b0197f 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Single-source and `--all` deliver that intrinsic >100-file embed deferral the same way: a queued `embed-backfill` on a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit `--no-embed` single-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`. Managed single-source and `--all` CLI envelopes retain structured `failures`, `failure_codes`, `run_id`, `target_commit`, and `counts_scope: run_cumulative`; blocked results exit nonzero. `--retry-failed` requires explicit idle ordinary-source fresh admission with the same options; no managed `--skip-failed`. Google/GitHub API source kinds route before the managed Git cursor. Managed connector `--retry-failed` explicitly admits a linked replacement after authority, source/owner, cursor and idle-state checks; pending work and old terminal receipts are not replaced. Unsupported connector dry-run, Git filtering/working-tree/code and `--skip-failed` options refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority.
Refactor wave 1 (W4 sync): `src/commands/sync.ts` is now the façade — it keeps the `SyncResult` / `SyncOpts` types, `runSync`, `resolveParallelism`, `syncOneSource` and re-exports every moved symbol, so importers need no change. The implementation described above lives in `src/commands/sync/` (next entry). Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.
-- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — the pull stops as `pull_timeout` on the sync signal or the SIGTERM/SIGHUP cleanup pass, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain with the CONNECT_TIMEOUT-tolerant worker connect retry; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.
+- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain with the CONNECT_TIMEOUT-tolerant worker connect retry; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.
- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index b8a972eaff..63a863bf38 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError` and `JobDeferredError(reason, message, retryInMs)`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction. A `JobDeferredError` returns the job to `delayed` for `retryInMs` through `MinionQueue.deferJob` (no attempt counted, no stacktrace entry); the worker, the facts drain and the isolation codec (`errorKind: 'deferred'`) all route it (`test/facts-absorb-keyless-deferral.test.ts`).
-- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`, `extract` (a brain-wide `extract --stale` pass); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers and `sync`, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). `DEFAULT_CHAT_PER_TURN_TIMEOUT_MS` (30 min) and `resolveChatPerTurnTimeoutMs` resolve `ai.chat.per_turn_timeout_ms`, the per-turn chat timeout the subagent handler hands every gateway-loop turn (`ToolLoopOpts.turnTimeoutMs` → `ChatOpts.timeoutMs`, replacing the 300 s gateway backstop) and the oneshot sub-budget ceiling; the job's own signal still ends a turn at the job deadline (#4921). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts` + `test/minions/subagent-turn-timeout.test.ts`.
+- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`, `extract` (a brain-wide `extract --stale` pass); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers and for `sync` (its blocking git helpers can each outlast a 30 s lease), 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). `DEFAULT_CHAT_PER_TURN_TIMEOUT_MS` (30 min) and `resolveChatPerTurnTimeoutMs` resolve `ai.chat.per_turn_timeout_ms`, the per-turn chat timeout the subagent handler hands every gateway-loop turn (`ToolLoopOpts.turnTimeoutMs` → `ChatOpts.timeoutMs`, replacing the 300 s gateway backstop) and the oneshot sub-budget ceiling; the job's own signal still ends a turn at the job deadline (#4921). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts` + `test/minions/subagent-turn-timeout.test.ts`.
- `src/core/minions/handlers/contextual-reindex-per-chunk.ts` — per-page contextual re-embed handler. With `expected_source_id` it resolves the page in that source only and fails the job as stale when the page is missing there, never falling back to a same-slug page in another source; without it, it tries `default` and then every live source (`test/contextual-reindex-lease-release.test.ts`). Resolves `models.contextual_synopsis` once and isolates cross-worker leases by the full resolved model id. `GBRAIN_CONTEXTUAL_SYNOPSIS_RPM` controls the cap; `GBRAIN_CONTEXTUAL_HAIKU_RPM` is the compatibility alias.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 6863bdd5a0..3eacb5bb49 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.
-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the non-blocking probe long-running persistence owners use; it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (`src/core/bounded-child-exec.ts`, re-exported here; `pullRepo` uses it too), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events (still on 1.4.2) and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the non-blocking probe long-running persistence owners use; it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events (still on 1.4.2) and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.
@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/git-head.ts` — local git HEAD freshness probe for `gbrain doctor`. `isSourceUnchangedSinceSync(localPath, lastCommit, opts?)` returns true iff `localPath` is a git repo whose current HEAD matches `lastCommit`; when `opts.requireCleanWorkingTree` is true also requires a clean working tree (mirrors `gbrain sync`'s force-walk gate at `sync.ts:1075` so doctor and sync agree on "is there work to do?"). `requireCleanWorkingTree` is `boolean | 'ignore-untracked'` — in `'ignore-untracked'` mode the clean probe runs `git status --porcelain --untracked-files=no` so a quiet repo with stray untracked dirs (`?? companies/`, `?? media/`) is still "unchanged" (sync's incremental path keys off the commit diff and does not import untracked files by default — it counts them as `uncommitted` drift with a stderr warning; `--working-tree` opts into importing them); `GitCleanProbe` gains an `ignoreUntracked?` second arg. Two probe seams (`_setGitHeadProbeForTests`, `_setGitCleanProbeForTests`) keep unit tests R2-compliant (no `mock.module`). Uses `execFileSync` with array args so shell metachars in `local_path` cannot escape to a shell (the test runs real `execFileSync` against `'/nonexistent/$(touch <sentinel>)/repo'` and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) so the caller falls back to its time-based check. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (`sources.chunker_version` vs `CHUNKER_VERSION` from `src/core/chunkers/code.ts`). Pinned by `test/core/git-head.test.ts` (incl. the shell-injection guard).
-- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last used by the sync cost-estimator's fetch-first path, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `http.followRedirects=false`, `protocol.file.allow=never`, `protocol.ext.allow=never`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>`. `pullRepo` argv: `git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only` — `durableSsrfFlags()`, not the hardcoded `GIT_SSRF_FLAGS`: identical `-c` flags except `protocol.file.allow` honors the `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` escape hatch. `pullRepo(repoPath, { timeoutMs?, signal? })` is async on `execFileBounded`: it stops at `timeoutMs` (default 300 s) or when `signal` aborts and rejects with a `GitOperationError` whose `.cause.code` is `ETIMEDOUT` or `ABORT_ERR` (git does not forward that SIGTERM to the `git fetch` the pull spawned). `fetchRemote` uses the same helper. Pinned by `test/git-remote.test.ts` position-anchored guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on ANY `pull --rebase` failure (the catch doesn't classify the cause — it's treated as a conflict) after up to two best-effort `rebase --abort` attempts (each swallows its own failure; `conflict_aborted` is still returned even if rebase state remains), else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike `cloneRepo`, which still uses the hardcoded `GIT_SSRF_FLAGS` and stays strict.
+- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last used by the sync cost-estimator's fetch-first path, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `http.followRedirects=false`, `protocol.file.allow=never`, `protocol.ext.allow=never`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>`. `pullRepo` argv: `git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only` — `durableSsrfFlags()`, not the hardcoded `GIT_SSRF_FLAGS`: identical `-c` flags except `protocol.file.allow` honors the `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` escape hatch. `pullRepo(repoPath, { timeoutMs?, signal? })` runs git through `execFileBounded`, so the caller's event loop keeps running; an aborted `signal` or the `timeoutMs` deadline (300 s by default) stops it, and `isStoppedGitPull(err)` separates that stop from a real git failure by reading the `GitOperationError` cause (`ETIMEDOUT`, `ABORT_ERR` or `SIGTERM`). Only `git pull` itself is signalled; the `git fetch` and transport it spawned are not. `fetchRemote` uses the same helper. Pinned by `test/git-remote.test.ts` position-anchored guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on ANY `pull --rebase` failure (the catch doesn't classify the cause — it's treated as a conflict) after up to two best-effort `rebase --abort` attempts (each swallows its own failure; `conflict_aborted` is still returned even if rebase state remains), else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike `cloneRepo`, which still uses the hardcoded `GIT_SSRF_FLAGS` and stays strict.
- `src/core/import-checkpoint.ts` — `loadCheckpoint(path, currentDir)`, `saveCheckpoint(path, cp)`, `resumeFilter(allFiles, dir, completed)`, `clearCheckpoint(path)`, `resolveImportTargetDir(dir)`, and the `ImportCheckpoint` type. Payload: `{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}`; `dir` is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary `runImport` revalidates all current files via `importFile`'s existing content-hash comparison rather than using `resumeFilter`. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged. `loadCheckpoint` returns `null` for missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard. `saveCheckpoint` sorts paths and atomically writes via `.tmp` + `rename()`; save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via `gbrainPath()`, preserving `GBRAIN_HOME` isolation. Pinned by `test/import-checkpoint.test.ts`, `test/import-resume.test.ts`, and `test/import-json-stdout.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index c3f08a9415..fabee825ae 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -24,7 +24,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_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests and `sync-import-provenance` rows of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-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>`). 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`).
-- `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. `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/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.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/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`.
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index fb69d45f67..3af70992a3 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -385,8 +385,8 @@ the worker asks the database the authoritative question (one fenced
re-check), so a starved-but-healthy job recovers its lease and keeps
working. Eviction happens only on a fenced miss (the row was genuinely
reclaimed — requeued with no attempt burned) or after a hard backstop
-(default 2× the lease) during a total outage. Long LLM handlers and `sync`
-also get a 300 s lock lease by default (`HANDLER_DEFAULT_LOCK_DURATION_MS`)
+(default 2× the lease) during a total outage. Long LLM handlers, plus
+`sync`, get a 300 s lock lease by default (`HANDLER_DEFAULT_LOCK_DURATION_MS`)
instead of the worker-global 30 s, and the stall sweep grants a 15 s
reclaim grace so a just-recovered worker's renewal beats the sweep.
The remaining exposure: a genuinely dead worker's long-lease job waits
diff --git a/docs/guides/queue-operations-runbook.md b/docs/guides/queue-operations-runbook.md
index 1c83601e44..0ba825ca58 100644
--- a/docs/guides/queue-operations-runbook.md
+++ b/docs/guides/queue-operations-runbook.md
@@ -199,7 +199,7 @@ deadline math.
Per-job lease: `gbrain jobs submit --lock-duration-ms N` (clamped
[5 s, 1 h] — enforced at submit, re-applied to the resolved lease at
claim, and backed by a database range constraint; `--dry-run` echoes the
-clamped value that will actually be stored); long LLM handlers and `sync` default to 300 s via
+clamped value that will actually be stored); `sync` and the long LLM handlers default to 300 s via
`HANDLER_DEFAULT_LOCK_DURATION_MS` in `src/core/minions/handler-timeouts.ts`.
Renewal cadence is `min(lease/2, 60 s)`. Trade-off: a genuinely dead
worker's long-lease job requeues after lease + grace + one sweep interval.
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index fb157be62f..e1c9db656c 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -13,7 +13,7 @@ import { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';
import { serr, slog } from '../../core/console-prefix.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { loadOpCheckpoint, clearOpCheckpoint } from '../../core/op-checkpoint.ts';
-import { registerCleanup } from '../../core/process-cleanup.ts';
+import { abortOnCleanupPass } from '../../core/process-cleanup.ts';
import {
readSyncAnchor,
resolveSlugRootMode,
@@ -599,41 +599,26 @@ async function pullAndResolveHead(
const _t0 = Date.now();
serr(`[gbrain phase] sync.git_pull start`);
opts.onProgress?.({ phase: 'git_pull' });
- // SIGTERM/SIGHUP (the --timeout hard-deadline watchdog, a service stop)
- // end the process through the cleanup pass, not opts.signal. Stop the
- // pull there too, so an orphaned `git pull` cannot fast-forward the
- // working tree after gbrain has exited.
- const stopPull = new AbortController();
- const deregisterStopPull = registerCleanup('sync-git-pull', async () => stopPull.abort());
+ // Two things can stop this sync while git waits on the remote: opts.signal
+ // (--timeout, SIGINT, a job's timeout or cancel, lost lock) and the
+ // process cleanup pass (the hard-deadline watchdog's SIGTERM, a service
+ // stop). Both stop the pull: a `git pull` still running after this
+ // process exits could fast-forward the tree behind a released lock.
+ const { pullRepo, isStoppedGitPull } = await import('../../core/git-remote.ts');
+ const shutdown = abortOnCleanupPass('sync-git-pull');
try {
- const { pullRepo } = await import('../../core/git-remote.ts');
- // v0.41.13.0 (T3 / D-V4-mech-7): the operator's --timeout bounds the
- // pull. opts.signal carries it (plus SIGINT, the job's timeout/cancel
- // and lock loss), and pullRepo stops the subprocess when it aborts;
- // pullRepo's own 300s deadline caps a run with no --timeout. The
- // catch below distinguishes a stopped pull from ordinary pull
- // failure. Pull applies to the whole git repo (gitContextRoot), not
- // just the sync scope — git has no per-subdir pull.
- await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, stopPull.signal) });
+ // v0.41.13.0 (T3 / D-V4-mech-7): the pull is bounded by the operator's
+ // --timeout through opts.signal, and by pullRepo's own 300s default
+ // when no --timeout is set. Pull applies to the whole git repo
+ // (gitContextRoot), not just the sync scope — git has no per-subdir pull.
+ await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, shutdown.signal) });
serr(`[gbrain phase] sync.git_pull done ${Date.now() - _t0}ms`);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
serr(`[gbrain phase] sync.git_pull error ${Date.now() - _t0}ms (${msg.slice(0, 200)})`);
- // v0.41.13.0 (T3 / D-V4-mech-7): pullRepo wraps the subprocess error
- // in GitOperationError, so a stopped pull's `code` (ETIMEDOUT at its
- // deadline, ABORT_ERR on abort) and `signal === 'SIGTERM'` live on
- // `.cause`, NOT on the top-level error. Inspect `.cause` to tell a
- // stopped pull (return partial reason='pull_timeout') from ordinary
- // failure (keep the existing warn-and-continue R2 invariant).
- const cause: unknown = e instanceof Error && 'cause' in e ? (e as { cause?: unknown }).cause : undefined;
- const causeCode = (cause && typeof cause === 'object' && 'code' in cause)
- ? (cause as { code?: unknown }).code
- : undefined;
- const causeSignal = (cause && typeof cause === 'object' && 'signal' in cause)
- ? (cause as { signal?: unknown }).signal
- : undefined;
- const isTimeout = causeCode === 'ETIMEDOUT' || causeCode === 'ABORT_ERR' || causeSignal === 'SIGTERM';
- if (isTimeout) {
+ // A stopped pull returns partial reason='pull_timeout' with the anchor
+ // untouched; any other pull failure keeps the R2 warn-and-continue path.
+ if (isStoppedGitPull(e)) {
return { done: buildPartialResult({
fromCommit: lastCommit,
toCommit: lastCommit ?? '',
@@ -651,7 +636,7 @@ async function pullAndResolveHead(
serr(`Warning: git pull failed: ${msg.slice(0, 200)}`); // #1315 stderr-first
}
} finally {
- deregisterStopPull();
+ shutdown.release();
}
}
diff --git a/src/core/bounded-child-exec.ts b/src/core/bounded-child-exec.ts
index c7a677c303..efe5cc0732 100644
--- a/src/core/bounded-child-exec.ts
+++ b/src/core/bounded-child-exec.ts
@@ -1,9 +1,9 @@
/**
- * Bounded child-process execution: `execFileBounded` settles at its deadline
- * or on abort from its own timer, whatever the runtime delivers. A leaf module
- * (no gbrain imports), so modules that `brain-repo-durability.ts` imports,
- * such as `git-remote.ts`, can use it without an import cycle;
- * `brain-repo-durability.ts` re-exports it for its existing callers.
+ * `execFileBounded`: run a child process that always settles by its deadline
+ * or on abort, using our own timer rather than trusting the runtime's exit
+ * events. It lives in this dependency-free module so that `git-remote.ts`,
+ * which `brain-repo-durability.ts` itself imports, can use it too;
+ * `brain-repo-durability.ts` re-exports it for its older callers.
*/
import { readFileSync } from 'fs';
import { execFile, type ChildProcess, type ExecFileException } from 'child_process';
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index b60feab1fc..4d9ec9afdb 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -268,26 +268,40 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
* self-hosted local-filesystem remotes could clone but never pull. Default
* stays `never`; the origin was already validated at clone time.
*
- * The pull runs off the event loop and stops at `timeoutMs` or when `signal`
- * aborts (sync passes its --timeout / job signal), so a remote that never
- * answers cannot wedge the caller. A stopped pull rejects with a
- * GitOperationError whose `.cause.code` is ETIMEDOUT or ABORT_ERR.
+ * Runs asynchronously so the caller's event loop stays live while git waits
+ * on the remote: --timeout timers, signal handlers and job-lease renewals keep
+ * firing. The child is stopped when `opts.signal` aborts or after
+ * `opts.timeoutMs` (default 5 min); `isStoppedGitPull` recognizes the error
+ * that produces, so callers can tell "we stopped it" from "git failed".
*/
export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<void> {
assertManagedFilesystemWrite(repoPath);
- const args: string[] = ['-C', repoPath, ...durableSsrfFlags(), 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
- const { error, stderr } = await execFileBounded('git', args, {
+ const argv = ['-C', repoPath, ...durableSsrfFlags(), 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
+ const run = await execFileBounded('git', argv, {
timeout: opts.timeoutMs ?? 300_000,
- signal: opts.signal,
env: { ...process.env, ...GIT_ENV },
+ signal: opts.signal,
});
- if (error) {
- throw new GitOperationError(
- 'pull',
- `git pull failed in ${repoPath}: ${gitErrorDetail(Object.assign(error, { stderr }))}`,
- error,
- );
- }
+ if (!run.error) return;
+ // execFile hands stderr back beside the error rather than on it, so lead
+ // with it here to keep the #1315 stderr-first message.
+ const reason = run.stderr.trim() || run.error.message;
+ throw new GitOperationError('pull', `git pull failed in ${repoPath}: ${reason}`, run.error);
+}
+
+/**
+ * Whether a `pullRepo` rejection means the pull was stopped (its deadline
+ * passed, its signal aborted, or something outside sent git SIGTERM) rather
+ * than git reporting a failure. GitOperationError keeps the subprocess error
+ * as `cause`, so the stop markers are read there: `code` ETIMEDOUT/ABORT_ERR
+ * or `signal` SIGTERM.
+ */
+export function isStoppedGitPull(err: unknown): boolean {
+ if (!(err instanceof Error)) return false;
+ const cause = (err as { cause?: unknown }).cause;
+ if (cause === null || typeof cause !== 'object') return false;
+ const { code, signal } = cause as { code?: unknown; signal?: unknown };
+ return code === 'ETIMEDOUT' || code === 'ABORT_ERR' || signal === 'SIGTERM';
}
/**
diff --git a/src/core/minions/handler-timeouts.ts b/src/core/minions/handler-timeouts.ts
index 75de49237f..622a477ca8 100644
--- a/src/core/minions/handler-timeouts.ts
+++ b/src/core/minions/handler-timeouts.ts
@@ -106,9 +106,9 @@ export const HANDLER_DEFAULT_LOCK_DURATION_MS: Readonly<Record<string, number>>
'connector-sync': FIVE_MIN_MS,
'autopilot-cycle': FIVE_MIN_MS,
'autopilot-global-maintenance': FIVE_MIN_MS,
- // `sync` runs inline by default, and each of its other git calls (diff,
- // ls-files, rev-parse) blocks the event loop for up to its own 30s
- // timeout: as long as the whole worker-default lease.
+ // A sync job's synchronous git helpers (sync-git.ts, 30s timeout each) can
+ // hold the event loop for a full 30s worker lease on their own, so a
+ // healthy sync would lose its lock without a longer default.
sync: FIVE_MIN_MS,
contextual_reindex_per_chunk: FIVE_MIN_MS,
chronicle_extract: TWO_MIN_MS,
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index acced74c83..a11b282daa 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -88,6 +88,18 @@ export function registerCleanup(name: string, fn: () => Promise<void>): () => vo
};
}
+/**
+ * An AbortSignal that aborts when the cleanup pass runs (an unowned
+ * SIGTERM/SIGHUP, a crash, a broken stdout pipe), for in-flight work that
+ * must not outlive the process, such as a child process gbrain started.
+ * Call `release` when that work settles; a released signal never aborts.
+ */
+export function abortOnCleanupPass(name: string): { signal: AbortSignal; release: () => void } {
+ const controller = new AbortController();
+ const release = registerCleanup(name, async () => { controller.abort(); });
+ return { signal: controller.signal, release };
+}
+
/**
* #5062: claim the process's termination signals (SIGTERM, SIGHUP, SIGPIPE
* and a broken stdout/stderr pipe). Without an owner the generic handler
diff --git a/test/minions.test.ts b/test/minions.test.ts
index ea2a19fd37..51df16b930 100644
--- a/test/minions.test.ts
+++ b/test/minions.test.ts
@@ -3456,12 +3456,17 @@ describe('MinionQueue: per-job lock lease (#4145)', () => {
expect(horizon).toBeLessThan(360_000);
});
- test('sync claims the 300s lease, so a slow pull or parse stretch cannot lapse a 30s one', async () => {
- await queue.add('sync', {});
- const before = Date.now();
- const claimed = await queue.claim('tok-sync-lease', 30_000, 'default', ['sync']);
- expect(claimed!.lock_duration_ms).toBe(300_000);
- expect(claimed!.lock_until!.getTime() - before).toBeGreaterThan(250_000);
+ test('a sync job gets the 5-minute default lease while an unmapped job claimed the same way keeps 30s', async () => {
+ await queue.add('sync', { sourceId: 'default' });
+ await queue.add('lease-control', {});
+ const syncJob = await queue.claim('tok-sync', 30_000, 'default', ['sync']);
+ const control = await queue.claim('tok-control', 30_000, 'default', ['lease-control']);
+ expect(syncJob!.lock_duration_ms).toBe(5 * 60_000);
+ expect(control!.lock_duration_ms).toBeNull();
+ const syncHorizon = syncJob!.lock_until!.getTime() - syncJob!.started_at!.getTime();
+ const controlHorizon = control!.lock_until!.getTime() - control!.started_at!.getTime();
+ expect(syncHorizon).toBeGreaterThan(4 * 60_000);
+ expect(controlHorizon).toBeLessThan(60_000);
});
test('an unmapped handler keeps NULL lease → worker default horizon (legacy behavior)', async () => {
diff --git a/test/process-cleanup.test.ts b/test/process-cleanup.test.ts
index 4a97b9ae78..42cc37c04e 100644
--- a/test/process-cleanup.test.ts
+++ b/test/process-cleanup.test.ts
@@ -22,6 +22,7 @@
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import {
+ abortOnCleanupPass,
registerCleanup,
registerSignalOwner,
triggerCleanupAndExit,
@@ -170,6 +171,33 @@ describe('triggerCleanupAndExit', () => {
});
});
+describe('abortOnCleanupPass', () => {
+ function swallowExit(): () => void {
+ const real = process.exit;
+ (process as any).exit = () => {};
+ return () => { (process as any).exit = real; };
+ }
+
+ test('aborts its signal when the cleanup pass runs', async () => {
+ const shutdown = abortOnCleanupPass('child-work');
+ expect(shutdown.signal.aborted).toBe(false);
+ const restore = swallowExit();
+ try { await triggerCleanupAndExit(143); } finally { restore(); }
+ expect(shutdown.signal.aborted).toBe(true);
+ });
+
+ test('a released signal is deregistered and stays live through a later cleanup pass', async () => {
+ const shutdown = abortOnCleanupPass('finished-work');
+ expect(_registeredCleanupCountForTests()).toBe(1);
+ shutdown.release();
+ shutdown.release();
+ expect(_registeredCleanupCountForTests()).toBe(0);
+ const restore = swallowExit();
+ try { await triggerCleanupAndExit(143); } finally { restore(); }
+ expect(shutdown.signal.aborted).toBe(false);
+ });
+});
+
describe('installSignalHandlers', () => {
test('is idempotent (second call is NO-OP)', () => {
const beforeListeners = process.listenerCount('SIGTERM');
diff --git a/test/sync-git-pull-stop.test.ts b/test/sync-git-pull-stop.test.ts
new file mode 100644
index 0000000000..394cbd7706
--- /dev/null
+++ b/test/sync-git-pull-stop.test.ts
@@ -0,0 +1,266 @@
+/**
+ * Stopping a sync must stop its `git pull` (#6101).
+ *
+ * Protects: while `git pull` waits on a remote that never replies, the
+ * process keeps running its event loop, and each stop route (the sync signal,
+ * the process cleanup pass, a signal-owned worker shutdown) ends the pull
+ * promptly with partial `pull_timeout` and the sync anchor untouched.
+ * Regression it catches: a synchronous pull (execFileSync) freezes timers and
+ * signal handling for the pull's whole 300s deadline, so none of the routes
+ * fire; dropping the cleanup-pass registration or the signal threading
+ * silences one route. Negative controls: a remote that refuses at once is an
+ * ordinary pull failure (the existing `pull_failed` result, never
+ * `pull_timeout`), and an error without a stop marker is not read as stopped.
+ *
+ * The remote is `ssh://fixture.invalid/...` with `core.sshCommand` pointing at
+ * a local script (`ssh.variant=simple`, so git sends no `-G` probe). The
+ * "silent" script records its pid and sleeps far longer than any bound below;
+ * the "refusing" script prints a fatal line and exits 128.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { performSync } from '../src/commands/sync.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import * as gitRemote from '../src/core/git-remote.ts';
+import {
+ _registeredCleanupCountForTests,
+ _resetForTests as resetCleanupRegistry,
+ installSignalHandlers,
+ registerSignalOwner,
+ triggerCleanupAndExit,
+} from '../src/core/process-cleanup.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+// Longer than PROMPT_STOP_MS, so a pull nobody stopped cannot pass; short
+// enough that a blocking pull only stalls the run for this long.
+const SILENT_REMOTE_SECONDS = 25;
+const PROMPT_STOP_MS = 12_000;
+
+const workdir = mkdtempSync(join(tmpdir(), 'gbrain-pull-stop-'));
+const brain = join(workdir, 'brain');
+const silentPidFile = join(workdir, 'silent-remote.pid');
+const silentRemote = join(workdir, 'silent-remote.sh');
+const refusingRemote = join(workdir, 'refusing-remote.sh');
+const syncOpts = { repoPath: brain, sourceId: 'default', noEmbed: true, noExtract: true } as const;
+
+let engine: PGLiteEngine;
+let schemaVersion: string | null;
+
+function gitIn(args: string[]): string {
+ return execFileSync('git', ['-C', brain, ...args], { encoding: 'utf8' }).trim();
+}
+
+function useRemote(script: string): void {
+ gitIn(['config', 'core.sshCommand', script]);
+}
+
+async function untilRemoteAnswersCall(): Promise<void> {
+ const giveUp = Date.now() + 30_000;
+ while (!existsSync(silentPidFile)) {
+ if (Date.now() > giveUp) throw new Error('git pull never dialled the silent remote');
+ await Bun.sleep(20);
+ }
+}
+
+async function syncAnchor(): Promise<string | null> {
+ const rows = await engine.executeRaw<{ last_commit: string | null }>(`SELECT last_commit FROM sources WHERE id = 'default'`);
+ return rows[0]?.last_commit ?? null;
+}
+
+function captureExit(): { codes: Array<number | undefined>; restore: () => void } {
+ const codes: Array<number | undefined> = [];
+ const real = process.exit;
+ process.exit = ((code?: number) => { codes.push(code); }) as typeof process.exit;
+ return { codes, restore: () => { process.exit = real; } };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ schemaVersion = await engine.getConfig('version');
+
+ mkdirSync(join(brain, 'notes'), { recursive: true });
+ const repo = await makeGitFixture(brain);
+ writeFileSync(join(brain, 'notes', 'pull-stop.md'), '---\ntitle: Pull stop fixture\n---\n\nA note for the pull-stop tests.\n');
+ repo.commitAll('seed note');
+ const branch = gitIn(['rev-parse', '--abbrev-ref', 'HEAD']);
+ gitIn(['remote', 'add', 'origin', 'ssh://fixture.invalid/brain.git']);
+ gitIn(['config', `branch.${branch}.remote`, 'origin']);
+ gitIn(['config', `branch.${branch}.merge`, `refs/heads/${branch}`]);
+ gitIn(['config', 'ssh.variant', 'simple']);
+
+ writeFileSync(silentRemote, `#!/bin/sh\necho $$ > '${silentPidFile}'\nexec sleep ${SILENT_REMOTE_SECONDS}\n`);
+ writeFileSync(refusingRemote, `#!/bin/sh\necho 'fatal: fixture remote refused the connection' >&2\nexit 128\n`);
+ chmodSync(silentRemote, 0o755);
+ chmodSync(refusingRemote, 0o755);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(workdir, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ rmSync(silentPidFile, { force: true });
+ useRemote(silentRemote);
+});
+
+afterEach(() => {
+ resetCleanupRegistry();
+ if (!existsSync(silentPidFile)) return;
+ const pid = Number(readFileSync(silentPidFile, 'utf8').trim());
+ try { process.kill(pid, 'SIGKILL'); } catch { /* the transport already exited */ }
+});
+
+describe('pullRepo against a silent remote', () => {
+ test('the event loop keeps ticking while git waits on the remote', async () => {
+ const controller = new AbortController();
+ const settled = gitRemote.pullRepo(brain, { signal: controller.signal }).catch(() => undefined);
+ await untilRemoteAnswersCall();
+ let ticks = 0;
+ const timer = setInterval(() => { ticks++; }, 10);
+ await Bun.sleep(300);
+ clearInterval(timer);
+ controller.abort();
+ await settled;
+ expect(ticks).toBeGreaterThanOrEqual(10);
+ }, 60_000);
+
+ test('an abort stops the pull and the rejection reads as stopped', async () => {
+ const controller = new AbortController();
+ const outcome = gitRemote.pullRepo(brain, { signal: controller.signal }).then(() => 'resolved', (e: unknown) => e);
+ await untilRemoteAnswersCall();
+ const abortedAt = performance.now();
+ controller.abort();
+ const err = await outcome;
+ expect(performance.now() - abortedAt).toBeLessThan(PROMPT_STOP_MS);
+ expect(err).toBeInstanceOf(gitRemote.GitOperationError);
+ expect((err as gitRemote.GitOperationError).op).toBe('pull');
+ expect(gitRemote.isStoppedGitPull(err)).toBe(true);
+ }, 60_000);
+
+ test('the timeoutMs deadline stops the pull and reads as stopped', async () => {
+ const started = performance.now();
+ const err = await gitRemote.pullRepo(brain, { timeoutMs: 1_500 }).then(() => 'resolved', (e: unknown) => e);
+ expect(performance.now() - started).toBeLessThan(PROMPT_STOP_MS);
+ expect(err).toBeInstanceOf(gitRemote.GitOperationError);
+ expect(gitRemote.isStoppedGitPull(err)).toBe(true);
+ }, 60_000);
+
+ test('negative control: a refusing remote is a real failure, reported stderr-first', async () => {
+ useRemote(refusingRemote);
+ const err = await gitRemote.pullRepo(brain).then(() => 'resolved', (e: unknown) => e);
+ expect(err).toBeInstanceOf(gitRemote.GitOperationError);
+ expect(gitRemote.isStoppedGitPull(err)).toBe(false);
+ expect((err as Error).message).toStartWith(`git pull failed in ${brain}: fatal: fixture remote refused the connection`);
+ }, 60_000);
+});
+
+describe('isStoppedGitPull', () => {
+ test('recognizes only the stop markers on the cause', () => {
+ const wrap = (cause: unknown) => new gitRemote.GitOperationError('pull', 'git pull failed', cause);
+ expect(gitRemote.isStoppedGitPull(wrap({ code: 'ETIMEDOUT' }))).toBe(true);
+ expect(gitRemote.isStoppedGitPull(wrap({ code: 'ABORT_ERR' }))).toBe(true);
+ expect(gitRemote.isStoppedGitPull(wrap({ signal: 'SIGTERM' }))).toBe(true);
+ expect(gitRemote.isStoppedGitPull(wrap({ code: 1, signal: null }))).toBe(false);
+ expect(gitRemote.isStoppedGitPull(wrap(undefined))).toBe(false);
+ expect(gitRemote.isStoppedGitPull(new Error('git pull failed'))).toBe(false);
+ expect(gitRemote.isStoppedGitPull('ABORT_ERR')).toBe(false);
+ });
+});
+
+describe('performSync stop routes during the pull', () => {
+ test('aborting the sync signal returns partial pull_timeout and keeps the anchor', async () => {
+ await performSync(engine, { ...syncOpts, noPull: true });
+ const anchorBefore = await syncAnchor();
+ expect(anchorBefore).toBe(gitIn(['rev-parse', 'HEAD']));
+
+ const controller = new AbortController();
+ const running = performSync(engine, { ...syncOpts, signal: controller.signal });
+ await untilRemoteAnswersCall();
+ const abortedAt = performance.now();
+ controller.abort();
+ const result = await running;
+
+ expect(performance.now() - abortedAt).toBeLessThan(PROMPT_STOP_MS);
+ expect(result.status).toBe('partial');
+ expect(result.reason).toBe('pull_timeout');
+ expect(await syncAnchor()).toBe(anchorBefore);
+ }, 60_000);
+
+ test('the process cleanup pass stops the pull, and a finished pull leaves no cleanup entry behind', async () => {
+ await performSync(engine, { ...syncOpts, noPull: true });
+ const entriesBefore = _registeredCleanupCountForTests();
+
+ const running = performSync(engine, syncOpts);
+ await untilRemoteAnswersCall();
+ const exit = captureExit();
+ const cleanupAt = performance.now();
+ try {
+ await triggerCleanupAndExit(129);
+ } finally {
+ exit.restore();
+ }
+ const result = await running;
+
+ expect(exit.codes).toEqual([129]);
+ expect(performance.now() - cleanupAt).toBeLessThan(PROMPT_STOP_MS);
+ expect(result.status).toBe('partial');
+ expect(result.reason).toBe('pull_timeout');
+ expect(_registeredCleanupCountForTests()).toBe(entriesBefore);
+ }, 60_000);
+
+ test('negative control: a refusing remote is the ordinary pull_failed path, not pull_timeout', async () => {
+ await performSync(engine, { ...syncOpts, noPull: true });
+ useRemote(refusingRemote);
+ const entriesBefore = _registeredCleanupCountForTests();
+
+ const result = await performSync(engine, syncOpts);
+
+ expect(result.reason).toBe('pull_failed');
+ expect(_registeredCleanupCountForTests()).toBe(entriesBefore);
+ }, 60_000);
+
+ test('a signal-owned worker shutdown hands the sync job back without an attempt and frees the sync lock', async () => {
+ await performSync(engine, { ...syncOpts, noPull: true });
+ const anchorBefore = await syncAnchor();
+ // The worker refuses to claim without a schema version; resetPgliteState clears config.
+ await engine.setConfig('version', schemaVersion!);
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('sync', { repoPath: brain, sourceId: 'default', pull: true, auto_embed_backfill: false });
+ const worker = new MinionWorker(engine, { pollInterval: 20, healthCheckInterval: 0, stalledInterval: 600_000 });
+ worker.register('sync', makeSyncHandler(engine));
+ // `gbrain jobs work` owns SIGTERM, so the cleanup pass never runs and only
+ // the worker's shutdown signal can reach the pull.
+ const dropOwner = registerSignalOwner('pull-stop-worker', () => worker.requestShutdown());
+ const workerDone = worker.start();
+ let drainMs = Number.POSITIVE_INFINITY;
+ try {
+ await untilRemoteAnswersCall();
+ installSignalHandlers();
+ const signalledAt = performance.now();
+ process.emit('SIGTERM');
+ await workerDone;
+ drainMs = performance.now() - signalledAt;
+ } finally {
+ dropOwner();
+ }
+
+ expect(drainMs).toBeLessThan(PROMPT_STOP_MS);
+ const [row] = await engine.executeRaw<{ status: string; attempts_made: number }>(
+ 'SELECT status, attempts_made FROM minion_jobs WHERE id = $1', [job.id],
+ );
+ expect(row).toEqual({ status: 'waiting', attempts_made: 0 });
+ expect(await syncAnchor()).toBe(anchorBefore);
+ expect((await performSync(engine, { ...syncOpts, noPull: true })).status).toBe('up_to_date');
+ }, 60_000);
+});
diff --git a/test/sync-pull-abort.test.ts b/test/sync-pull-abort.test.ts
deleted file mode 100644
index 9f4c1c7057..0000000000
--- a/test/sync-pull-abort.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * A sync whose `git pull` reaches a remote that never answers must stop when
- * the sync is told to stop, and report partial `pull_timeout` with the anchor
- * unchanged. Two stop routes reach the pull: the sync signal (the operator's
- * --timeout, SIGINT, a job's timeout or cancel, lock loss) and the
- * SIGTERM/SIGHUP cleanup pass (the --timeout hard-deadline watchdog, a service
- * stop). The pull used to run synchronously under a fixed 300s timeout, so
- * neither could interrupt it and the event loop stalled for the whole wait.
- *
- * The stalled remote is an ssh:// origin whose transport (GIT_SSH_COMMAND) is
- * a script that accepts the connection and never answers. It records its pid
- * so each case can unwind the `git fetch` that `git pull` leaves behind.
- */
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { execFileSync } from 'node:child_process';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { performSync } from '../src/commands/sync.ts';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { _resetForTests as resetProcessCleanup, installSignalHandlers, registerSignalOwner, triggerCleanupAndExit } from '../src/core/process-cleanup.ts';
-import { MinionQueue } from '../src/core/minions/queue.ts';
-import { MinionWorker } from '../src/core/minions/worker.ts';
-import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
-import { GitOperationError, pullRepo } from '../src/core/git-remote.ts';
-import { makeGitFixture } from './helpers/git-fixture.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-const root = mkdtempSync(join(tmpdir(), 'gbrain-sync-pull-abort-'));
-const repo = join(root, 'brain');
-const stalledPids = join(root, 'stalled.pids');
-const stalledTransport = join(root, 'stalled-ssh');
-// Longer than the 15s bound below, so a pull that is not stopped cannot pass.
-const STALL_SECONDS = 30;
-const SYNC_OPTS = { repoPath: repo, sourceId: 'default', noEmbed: true, noExtract: true } as const;
-
-let engine: PGLiteEngine;
-let schemaVersion: string | null = null;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
- schemaVersion = await engine.getConfig('version');
-
- mkdirSync(join(repo, 'people'), { recursive: true });
- const fixture = await makeGitFixture(repo);
- writeFileSync(join(repo, 'people', 'alice-example.md'), '---\ntype: person\ntitle: Alice Example\n---\n\nAlice is a person.\n');
- fixture.commitAll('add a page');
- const branch = execFileSync('git', ['-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).trim();
- execFileSync('git', ['-C', repo, 'remote', 'add', 'origin', 'ssh://stalled.invalid/brain.git']);
- execFileSync('git', ['-C', repo, 'config', `branch.${branch}.remote`, 'origin']);
- execFileSync('git', ['-C', repo, 'config', `branch.${branch}.merge`, `refs/heads/${branch}`]);
-
- // `-G` is git's OpenSSH-variant probe; answer it the way OpenSSH does.
- writeFileSync(stalledTransport, `#!/bin/sh\n[ "$1" = "-G" ] && exit 0\necho $$ >> '${stalledPids}'\nexec sleep ${STALL_SECONDS}\n`);
- chmodSync(stalledTransport, 0o755);
-}, 60_000);
-
-afterAll(async () => {
- await engine.disconnect();
- rmSync(root, { recursive: true, force: true });
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
- rmSync(stalledPids, { force: true });
-});
-
-afterEach(() => {
- if (!existsSync(stalledPids)) return;
- for (const pid of readFileSync(stalledPids, 'utf8').split('\n').filter(Boolean)) {
- try { process.kill(Number(pid), 'SIGKILL'); } catch { /* already exited */ }
- }
-});
-
-async function anchor(): Promise<string | null> {
- const [row] = await engine.executeRaw<{ last_commit: string | null }>(`SELECT last_commit FROM sources WHERE id = 'default'`);
- return row?.last_commit ?? null;
-}
-
-/** Resolves once the pull has connected to the stalled remote. */
-async function pullReachedRemote(): Promise<void> {
- const deadline = Date.now() + STALL_SECONDS * 1000;
- while (!existsSync(stalledPids)) {
- if (Date.now() > deadline) throw new Error('git pull never reached the stalled remote');
- await Bun.sleep(25);
- }
-}
-
-describe('sync stops a git pull whose remote never answers', () => {
- test('pullRepo rejects with ABORT_ERR on its cause when its signal aborts mid-pull', async () => {
- await withEnv({ GIT_SSH_COMMAND: stalledTransport }, async () => {
- const controller = new AbortController();
- const pull = pullRepo(repo, { signal: controller.signal }).then(() => null, (e: unknown) => e);
- await pullReachedRemote();
- controller.abort();
- const error = await pull;
- expect(error).toBeInstanceOf(GitOperationError);
- expect(((error as GitOperationError).cause as { code?: string }).code).toBe('ABORT_ERR');
- });
- }, 60_000);
-
- test('aborting the sync signal stops the pull: partial pull_timeout, anchor unchanged', async () => {
- await withEnv({ GIT_SSH_COMMAND: stalledTransport }, async () => {
- await performSync(engine, { ...SYNC_OPTS, noPull: true });
- const before = await anchor();
- expect(before).not.toBeNull();
-
- const controller = new AbortController();
- const started = performance.now();
- const sync = performSync(engine, { ...SYNC_OPTS, signal: controller.signal });
- await pullReachedRemote();
- controller.abort();
- const result = await sync;
-
- expect(result.status).toBe('partial');
- expect(result.reason).toBe('pull_timeout');
- expect(performance.now() - started).toBeLessThan(15_000);
- expect(await anchor()).toBe(before);
- });
- }, 60_000);
-
- test('the SIGTERM/SIGHUP cleanup pass stops the pull before the process exits', async () => {
- await withEnv({ GIT_SSH_COMMAND: stalledTransport }, async () => {
- await performSync(engine, { ...SYNC_OPTS, noPull: true });
-
- const started = performance.now();
- const sync = performSync(engine, SYNC_OPTS);
- await pullReachedRemote();
- const exit = process.exit;
- const exitCodes: Array<number | undefined> = [];
- process.exit = ((code?: number) => { exitCodes.push(code); }) as typeof process.exit;
- try {
- await triggerCleanupAndExit(143);
- } finally {
- process.exit = exit;
- resetProcessCleanup();
- }
- const result = await sync;
-
- expect(exitCodes).toEqual([143]);
- expect(result.status).toBe('partial');
- expect(result.reason).toBe('pull_timeout');
- expect(performance.now() - started).toBeLessThan(15_000);
- });
- }, 60_000);
-
- test('a worker-run sync job stops its pull when a signal-owned worker shuts down, and leaves no sync lock', async () => {
- await withEnv({ GIT_SSH_COMMAND: stalledTransport }, async () => {
- await performSync(engine, { ...SYNC_OPTS, noPull: true });
- const before = await anchor();
- // resetPgliteState clears config rows; the worker checks the schema version before claiming.
- await engine.setConfig('version', schemaVersion!);
- const queue = new MinionQueue(engine);
- const job = await queue.add('sync', { repoPath: repo, sourceId: 'default', pull: true, auto_embed_backfill: false });
- const worker = new MinionWorker(engine, { pollInterval: 20, healthCheckInterval: 0, stalledInterval: 600_000 });
- worker.register('sync', makeSyncHandler(engine));
- // As `gbrain jobs work` does: the owner takes SIGTERM, so the generic cleanup pass never runs.
- const releaseOwner = registerSignalOwner('jobs-work', () => worker.requestShutdown());
- const running = worker.start();
- let stoppedMs = Infinity;
- try {
- await pullReachedRemote();
- const started = performance.now();
- installSignalHandlers();
- process.emit('SIGTERM');
- await running;
- stoppedMs = performance.now() - started;
- } finally {
- releaseOwner();
- resetProcessCleanup();
- }
-
- // Well inside the worker's 30s drain window: the job signal stopped the pull, the drain did not time out.
- expect(stoppedMs).toBeLessThan(15_000);
- const [row] = await engine.executeRaw<{ status: string; attempts_made: number }>('SELECT status, attempts_made FROM minion_jobs WHERE id = $1', [job.id]);
- expect(row.status).toBe('waiting');
- expect(row.attempts_made).toBe(0);
- expect(await anchor()).toBe(before);
- const next = await performSync(engine, { ...SYNC_OPTS, noPull: true });
- expect(next.status).toBe('up_to_date');
- });
- }, 60_000);
-});