Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): stop git pull on --timeout and job abort; give sync a 5-min lease (#6101)

time-attackea6f3036c1b9
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index b232c2baa6..1e166074c6 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, 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; 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). `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 — 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; 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). `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 ef5a010ac8..d35e86140d 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, 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 `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/handlers/contextual-reindex-per-chunk.ts` — per-page contextual re-embed handler. 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 5fa9deeb7a..7388cb7f65 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`, 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` (`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/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. `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? })` 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/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/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index 3eedf925d2..fb69d45f67 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 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 and `sync`
+also 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 7a74985fdc..1c83601e44 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 default to 300 s via
+clamped value that will actually be stored); long LLM handlers and `sync` 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 d5b5f8077b..fb157be62f 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -13,6 +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 {
readSyncAnchor,
resolveSlugRootMode,
@@ -32,7 +33,7 @@ import {
unique,
} from '../../core/sync-git.ts';
import { buildPartialResult } from '../../core/sync-lock.ts';
-import { massReconcileAllowed, MASS_RECONCILE_RATIO } from '../../core/sync-reconcile.ts';
+import { composeAbortSignals, massReconcileAllowed, MASS_RECONCILE_RATIO } from '../../core/sync-reconcile.ts';
import {
DEFAULT_SOURCE_ID,
resolveSlugForPath,
@@ -598,26 +599,32 @@ 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());
try {
const { pullRepo } = await import('../../core/git-remote.ts');
- // v0.41.13.0 (T3 / D-V4-mech-7): if the operator set --timeout,
- // bound the pull subprocess to a fraction of the remaining budget.
- // We pass a safe default (the operator's full --timeout if set, else
- // pullRepo's own 300s default). The catch below distinguishes
- // timeout (ETIMEDOUT / SIGTERM on err.cause) from ordinary pull
+ // 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.
- pullRepo(gitContextRoot);
+ await pullRepo(gitContextRoot, { signal: composeAbortSignals(opts.signal, stopPull.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 execFileSync errors
- // in GitOperationError, so `error.code === 'ETIMEDOUT'` and
- // `error.signal === 'SIGTERM'` live on `.cause`, NOT on the top-
- // level error. Inspect `.cause` to distinguish a real timeout
- // (return partial reason='pull_timeout') from ordinary failure
- // (keep the existing warn-and-continue R2 invariant).
+ // 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
@@ -625,7 +632,7 @@ async function pullAndResolveHead(
const causeSignal = (cause && typeof cause === 'object' && 'signal' in cause)
? (cause as { signal?: unknown }).signal
: undefined;
- const isTimeout = causeCode === 'ETIMEDOUT' || causeSignal === 'SIGTERM';
+ const isTimeout = causeCode === 'ETIMEDOUT' || causeCode === 'ABORT_ERR' || causeSignal === 'SIGTERM';
if (isTimeout) {
return { done: buildPartialResult({
fromCommit: lastCommit,
@@ -643,6 +650,8 @@ async function pullAndResolveHead(
} else {
serr(`Warning: git pull failed: ${msg.slice(0, 200)}`); // #1315 stderr-first
}
+ } finally {
+ deregisterStopPull();
}
}
diff --git a/src/core/bounded-child-exec.ts b/src/core/bounded-child-exec.ts
new file mode 100644
index 0000000000..c7a677c303
--- /dev/null
+++ b/src/core/bounded-child-exec.ts
@@ -0,0 +1,90 @@
+/**
+ * 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.
+ */
+import { readFileSync } from 'fs';
+import { execFile, type ChildProcess, type ExecFileException } from 'child_process';
+
+const BOUNDED_EXEC_TERM_GRACE_MS = 2_000;
+
+/**
+ * Whether a stopped child has exited even if the runtime lost its exit event:
+ * on Linux an exited-but-unreaped child is a zombie ('Z' in /proc/<pid>/stat).
+ * Elsewhere only the delivered exit counts, so the grace timer bounds the wait.
+ */
+function childHasExited(child: ChildProcess): boolean {
+ if (child.exitCode !== null || child.signalCode !== null) return true;
+ if (process.platform !== 'linux' || child.pid === undefined) return false;
+ try {
+ const stat = readFileSync(`/proc/${child.pid}/stat`, 'utf8');
+ return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
+ } catch {
+ return true;
+ }
+}
+
+export interface BoundedExecOptions {
+ timeout: number;
+ env?: NodeJS.ProcessEnv;
+ maxBuffer?: number;
+ signal?: AbortSignal;
+}
+
+/**
+ * `execFile` that settles within `timeout` or on abort even when the runtime
+ * never delivers the child's exit or pipe close. Bun drops one-shot pipe
+ * events (and, before 1.3.14, pidfd exit events: oven-sh/bun#30301) when a
+ * callback re-enters the event loop (bun:test `expect().resolves/.rejects`;
+ * pipe loss still reproduces on 1.4.2): execFile's
+ * callback and its own `timeout` then never fire and the child stays a zombie,
+ * so the deadline and abort are enforced with our own timer.
+ *
+ * Stopping sends SIGTERM first so git can remove its lockfiles (a SIGKILLed
+ * `git add`/`commit` leaves `.git/index.lock` behind and every later git call
+ * in that worktree fails), then SIGKILLs after a short grace period and
+ * settles from the timer even if the exit event never arrives.
+ */
+export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string; stderr: string }> {
+ const { timeout, signal, ...rest } = options;
+ return new Promise(resolve => {
+ let settled = false;
+ const finish = (error: ExecFileException | null, stdout: string, stderr = '') => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ resolve({ error, stdout, stderr });
+ };
+ let stopped: ExecFileException | null = null;
+ let escalation: ReturnType<typeof setTimeout> | undefined;
+ let poll: ReturnType<typeof setInterval> | undefined;
+ const settleStopped = () => {
+ clearTimeout(escalation);
+ clearInterval(poll);
+ finish(stopped, '', '');
+ };
+ const child = execFile(file, args, { ...rest, encoding: 'utf8' }, (error, stdout, stderr) => {
+ clearTimeout(escalation);
+ clearInterval(poll);
+ if (stopped) finish(stopped, '', '');
+ else finish(error, stdout, stderr);
+ });
+ const stop = (message: string, code: string) => {
+ if (stopped) return;
+ stopped = Object.assign(new Error(message), { code, killed: true, signal: 'SIGTERM' as const });
+ child.kill('SIGTERM');
+ poll = setInterval(() => { if (childHasExited(child)) settleStopped(); }, 25);
+ escalation = setTimeout(() => {
+ child.kill('SIGKILL');
+ settleStopped();
+ }, BOUNDED_EXEC_TERM_GRACE_MS);
+ };
+ const timer = setTimeout(() => stop(`${file} did not finish within ${timeout}ms`, 'ETIMEDOUT'), timeout);
+ const onAbort = () => stop(`${file} was aborted`, 'ABORT_ERR');
+ if (signal?.aborted) onAbort();
+ else signal?.addEventListener('abort', onAbort, { once: true });
+ });
+}
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index 0a3ca07898..9b56c734df 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -33,7 +33,8 @@ import {
existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync,
} from 'fs';
import { join, dirname, relative, isAbsolute } from 'path';
-import { execFile, execFileSync, execSync, type ChildProcess, type ExecFileException } from 'child_process';
+import { execFileSync, execSync } from 'child_process';
+import { execFileBounded } from './bounded-child-exec.ts';
import {
GIT_ENV, GIT_ENV_AUTH, divergenceSafePull, detectDefaultBranch, pushProbe,
type PullOutcome, type PushProbeResult,
@@ -47,6 +48,8 @@ import { loadFilingRules, type FilingRulesDoc } from './filing-audit.ts';
// don't ship their own — see resolveFilingRules().
import filingRulesDoc from '../../skills/_brain-filing-rules.json';
+export { execFileBounded, type BoundedExecOptions } from './bounded-child-exec.ts';
+
// ── Types ───────────────────────────────────────────────────────────────────
export type StepName =
@@ -482,87 +485,6 @@ export function isDurabilityHardened(repoPath: string): boolean {
}
}
-const BOUNDED_EXEC_TERM_GRACE_MS = 2_000;
-
-/**
- * Whether a stopped child has exited even if the runtime lost its exit event:
- * on Linux an exited-but-unreaped child is a zombie ('Z' in /proc/<pid>/stat).
- * Elsewhere only the delivered exit counts, so the grace timer bounds the wait.
- */
-function childHasExited(child: ChildProcess): boolean {
- if (child.exitCode !== null || child.signalCode !== null) return true;
- if (process.platform !== 'linux' || child.pid === undefined) return false;
- try {
- const stat = readFileSync(`/proc/${child.pid}/stat`, 'utf8');
- return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
- } catch {
- return true;
- }
-}
-
-export interface BoundedExecOptions {
- timeout: number;
- env?: NodeJS.ProcessEnv;
- maxBuffer?: number;
- signal?: AbortSignal;
-}
-
-/**
- * `execFile` that settles within `timeout` or on abort even when the runtime
- * never delivers the child's exit or pipe close. Bun drops one-shot pipe
- * events (and, before 1.3.14, pidfd exit events: oven-sh/bun#30301) when a
- * callback re-enters the event loop (bun:test `expect().resolves/.rejects`;
- * pipe loss still reproduces on 1.4.2): execFile's
- * callback and its own `timeout` then never fire and the child stays a zombie,
- * so the deadline and abort are enforced with our own timer.
- *
- * Stopping sends SIGTERM first so git can remove its lockfiles (a SIGKILLed
- * `git add`/`commit` leaves `.git/index.lock` behind and every later git call
- * in that worktree fails), then SIGKILLs after a short grace period and
- * settles from the timer even if the exit event never arrives.
- */
-export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string; stderr: string }> {
- const { timeout, signal, ...rest } = options;
- return new Promise(resolve => {
- let settled = false;
- const finish = (error: ExecFileException | null, stdout: string, stderr = '') => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- signal?.removeEventListener('abort', onAbort);
- resolve({ error, stdout, stderr });
- };
- let stopped: ExecFileException | null = null;
- let escalation: ReturnType<typeof setTimeout> | undefined;
- let poll: ReturnType<typeof setInterval> | undefined;
- const settleStopped = () => {
- clearTimeout(escalation);
- clearInterval(poll);
- finish(stopped, '', '');
- };
- const child = execFile(file, args, { ...rest, encoding: 'utf8' }, (error, stdout, stderr) => {
- clearTimeout(escalation);
- clearInterval(poll);
- if (stopped) finish(stopped, '', '');
- else finish(error, stdout, stderr);
- });
- const stop = (message: string, code: string) => {
- if (stopped) return;
- stopped = Object.assign(new Error(message), { code, killed: true, signal: 'SIGTERM' as const });
- child.kill('SIGTERM');
- poll = setInterval(() => { if (childHasExited(child)) settleStopped(); }, 25);
- escalation = setTimeout(() => {
- child.kill('SIGKILL');
- settleStopped();
- }, BOUNDED_EXEC_TERM_GRACE_MS);
- };
- const timer = setTimeout(() => stop(`${file} did not finish within ${timeout}ms`, 'ETIMEDOUT'), timeout);
- const onAbort = () => stop(`${file} was aborted`, 'ABORT_ERR');
- if (signal?.aborted) onAbort();
- else signal?.addEventListener('abort', onAbort, { once: true });
- });
-}
-
/** A git probe that does not block the event loop; a failed probe reads as ''. */
async function gitOutput(repoPath: string, args: string[]): Promise<string> {
const { error, stdout } = await execFileBounded('git', ['-C', repoPath, ...args], { timeout: 10_000, env: { ...process.env, ...GIT_ENV } });
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 54ba6a52ad..b60feab1fc 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -19,6 +19,7 @@ import { execFileSync } from 'child_process';
import { lstatSync, existsSync, readdirSync } from 'fs';
import { join } from 'path';
import { isInternalUrl } from './url-safety.ts';
+import { execFileBounded } from './bounded-child-exec.ts';
/**
* Git CLI accepts two flag positions:
@@ -266,21 +267,25 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
* GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1 escape hatch reaches sync's pull —
* 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.
*/
-export function pullRepo(repoPath: string, opts: { timeoutMs?: number } = {}): void {
+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'];
- try {
- execFileSync('git', args, {
- stdio: ['ignore', 'pipe', 'pipe'],
- timeout: opts.timeoutMs ?? 300_000,
- env: { ...process.env, ...GIT_ENV },
- });
- } catch (e) {
+ const { error, stderr } = await execFileBounded('git', args, {
+ timeout: opts.timeoutMs ?? 300_000,
+ signal: opts.signal,
+ env: { ...process.env, ...GIT_ENV },
+ });
+ if (error) {
throw new GitOperationError(
'pull',
- `git pull failed in ${repoPath}: ${gitErrorDetail(e)}`,
- e,
+ `git pull failed in ${repoPath}: ${gitErrorDetail(Object.assign(error, { stderr }))}`,
+ error,
);
}
}
diff --git a/src/core/minions/handler-timeouts.ts b/src/core/minions/handler-timeouts.ts
index a5f2714005..75de49237f 100644
--- a/src/core/minions/handler-timeouts.ts
+++ b/src/core/minions/handler-timeouts.ts
@@ -106,6 +106,10 @@ 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.
+ sync: FIVE_MIN_MS,
contextual_reindex_per_chunk: FIVE_MIN_MS,
chronicle_extract: TWO_MIN_MS,
'facts-absorb': TWO_MIN_MS,
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index bb39637627..e7b4bd9a01 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -59,10 +59,14 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
deleted: (job.data.github_item as Record<string, unknown>).deleted === true,
}
: undefined;
+ // Under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and
+ // aborts only the worker's shutdown signal, so the sync and its git pull stop on either signal.
+ const { composeAbortSignals } = await import('../../sync-reconcile.ts');
+ const signal = composeAbortSignals(job.signal, job.shutdownSignal);
let result;
try {
result = await performSync(engine, {
- repoPath, sourceId, noPull, noEmbed, noExtract, signal: job.signal,
+ repoPath, sourceId, noPull, noEmbed, noExtract, signal,
explicitProcessing: explicitSyncProcessing(job.data),
concurrency: concurrencyOverride,
...(githubItem ? { githubItem } : {}),
@@ -87,7 +91,7 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
// A cancelled durable job must not complete or schedule follow-up work,
// even when a direct sync interruption has a resumable partial result.
- if (job.signal?.aborted) throw job.signal.reason ?? new Error('Sync job cancelled');
+ if (signal?.aborted) throw signal.reason ?? new Error('Sync job cancelled');
// v0.40 D22: auto_embed_backfill defaults TRUE when sourceId is set AND
// the feature flag is enabled. Submits a child embed-backfill job
diff --git a/test/git-remote-pull-file-transport.serial.test.ts b/test/git-remote-pull-file-transport.serial.test.ts
index 82575452f1..dd0ad6d58d 100644
--- a/test/git-remote-pull-file-transport.serial.test.ts
+++ b/test/git-remote-pull-file-transport.serial.test.ts
@@ -72,18 +72,18 @@ describe('#3836 durableSsrfFlags env toggle (unit)', () => {
});
describe('#3836 pullRepo honors the file-transport escape hatch', () => {
- test('default posture: pull over the file transport still refuses', () => {
+ test('default posture: pull over the file transport still refuses', async () => {
const { writer, reader } = makeTrio();
pushSecondCommit(writer);
- expect(() => pullRepo(reader)).toThrow(GitOperationError);
+ await expect(pullRepo(reader)).rejects.toThrow(GitOperationError);
expect(existsSync(join(reader, 'NEW.md'))).toBe(false);
});
- test('GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1: sync-style pull succeeds and lands the new commit', () => {
+ test('GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1: sync-style pull succeeds and lands the new commit', async () => {
const { writer, reader } = makeTrio();
pushSecondCommit(writer);
process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
- pullRepo(reader);
+ await pullRepo(reader);
expect(readFileSync(join(reader, 'NEW.md'), 'utf-8')).toContain('second commit');
});
diff --git a/test/git-remote.test.ts b/test/git-remote.test.ts
index b96b39b551..f1db28c835 100644
--- a/test/git-remote.test.ts
+++ b/test/git-remote.test.ts
@@ -334,7 +334,7 @@ describe('pullRepo', () => {
const repo = join(FAKE_GIT_DIR, 'pull-target');
mkdirSync(repo, { recursive: true });
await withEnv({ PATH: fakePath() }, async () => {
- pullRepo(repo);
+ await pullRepo(repo);
});
const argv = readArgvLog()[0];
expect(argv[0]).toBe('-C');
@@ -357,7 +357,7 @@ describe('pullRepo', () => {
mkdirSync(repo, { recursive: true });
setMode('fail');
await withEnv({ PATH: fakePath() }, async () => {
- expect(() => pullRepo(repo)).toThrow(GitOperationError);
+ await expect(pullRepo(repo)).rejects.toThrow(GitOperationError);
});
rmSync(repo, { recursive: true, force: true });
});
@@ -520,11 +520,11 @@ describe('#1315 — stderr-first GitOperationError (real git, file-origin repo)'
// skipIf: pins "git's own fatal: appears within the first 200 chars" —
// unrunnable behind an ambient git PATH shim that prints its own stderr
// first (e.g. Conductor's auth-broker wrapper). See helpers/git-stderr-probe.
- test.skipIf(!gitStderrLeads())('pullRepo message leads with the real git stderr, not the Command-failed envelope', () => {
+ test.skipIf(!gitStderrLeads())('pullRepo message leads with the real git stderr, not the Command-failed envelope', async () => {
const mirror = mkFileOriginMirror();
let threw: GitOperationError | undefined;
try {
- pullRepo(mirror);
+ await pullRepo(mirror);
} catch (e) {
threw = e as GitOperationError;
}
diff --git a/test/jobs-format-detail.test.ts b/test/jobs-format-detail.test.ts
index ba2eb816b7..de1a337c8d 100644
--- a/test/jobs-format-detail.test.ts
+++ b/test/jobs-format-detail.test.ts
@@ -95,7 +95,7 @@ describe('lock lease rendering (#4145)', () => {
});
test('unset lease on an unmapped handler renders no lease line (worker default applies)', () => {
- const out = formatJobDetail(job({ name: 'sync', lock_duration_ms: null }));
+ const out = formatJobDetail(job({ name: 'shell', lock_duration_ms: null }));
expect(out).not.toContain('Lock lease:');
});
});
diff --git a/test/minions.test.ts b/test/minions.test.ts
index 29264797b8..e0a0e41cce 100644
--- a/test/minions.test.ts
+++ b/test/minions.test.ts
@@ -729,8 +729,9 @@ describe('MinionWorker', () => {
describe('MinionQueue: Lock Management', () => {
test('lock renewed during execution', async () => {
- await queue.add('sync', {});
- const claimed = await queue.claim('tok1', 30000, 'default', ['sync']);
+ // An unmapped name, so the claim takes the worker's 30s lease.
+ await queue.add('noop', {});
+ const claimed = await queue.claim('tok1', 30000, 'default', ['noop']);
const originalLockUntil = claimed!.lock_until!.getTime();
const renewed = await queue.renewLock(claimed!.id, 'tok1', 60000);
@@ -3431,6 +3432,14 @@ 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('an unmapped handler keeps NULL lease → worker default horizon (legacy behavior)', async () => {
await queue.add('shortling', {});
const before = Date.now();
diff --git a/test/persistence-writer-fences.test.ts b/test/persistence-writer-fences.test.ts
index 09b5541dfb..8958fb8185 100644
--- a/test/persistence-writer-fences.test.ts
+++ b/test/persistence-writer-fences.test.ts
@@ -104,7 +104,7 @@ test('durable root records fence new processes, symlink aliases and separate use
expect(() => assertManagedFilesystemWrite(target)).toThrow('managed canonical worktree');
}
expect(() => cloneRepo('https://example.com/brain.git', root)).toThrow('managed canonical worktree');
- expect(() => pullRepo(root)).toThrow('managed canonical worktree');
+ await expect(pullRepo(root)).rejects.toThrow('managed canonical worktree');
await expect(hardenBrainRepo({ repoPath: root, sourceId })).rejects.toMatchObject({ code: 'writer_coordinator_required' });
let inherited: (() => void) | undefined;
await withFilesystemPublication([root], async () => {
diff --git a/test/sync-pull-abort.test.ts b/test/sync-pull-abort.test.ts
new file mode 100644
index 0000000000..9f4c1c7057
--- /dev/null
+++ b/test/sync-pull-abort.test.ts
@@ -0,0 +1,186 @@
+/**
+ * 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);
+});