Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): classic symlink, EACCES and absent-from-worktree files become typed holds (GBRA-133 PR 1 item 3)

garrytan465dfaa899ba
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index c7018a8883..5a732bad69 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/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. On a managed source `--skip-failed` and `--include-gitignored` refuse at parse (`refuseManagedForbiddenFlags` in `sync/managed-no-pull.ts`, code `managed_sync_flag_refused`); `--retry-failed` counts every managed failure of the source (one cursor key per source since #6712 PR 1, so no failure sits under another key).
+- `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`: a non-symlink leaf resolves through its parent directory, since Bun's realpathSync fails on a name containing a backslash) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); ahead of it, with holds active, the drain holds a symlink, a permission error or a committed file absent from the working tree (`classic-file-holds.ts`, re-classified each run by `planHoldRescreen` in `sync/holds.ts`); 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. On a managed source `--skip-failed` and `--include-gitignored` refuse at parse (`refuseManagedForbiddenFlags` in `sync/managed-no-pull.ts`, code `managed_sync_flag_refused`); `--retry-failed` counts every managed failure of the source (one cursor key per source since #6712 PR 1, so no failure sits under another key).
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 — 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; #5431 W14 P1.8: the cheap rename goes through `rename-collision.ts` `renamePageOntoSlug`, which repairs `source_path` inside the rename transaction and classifies a unique violation: a tombstone at the destination is merged in one `maintenanceTransaction` (the tombstone re-keyed `<slug>~purged-<id>` with its history, the page moves with its id), a live destination falls through to the add fallback, any other error fails the file without a checkpoint; the fallback's reconcile carries the stale row's identity onto the destination row first (`carryRenameIdentity`: `recordRenameAlias`, `moveSlugBindings`, `movePageIdReferences`); `test/sync-rename-collision.test.ts` on both engines), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain whose pools connect with `retryConnectTimeout`, #5946; 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. #6712 PR 3 (L7): `printSyncHelp` lists the "Managed brains" flags first, then "Classic brains / advanced"; `noteRetryFailedDeprecated` prints the `sync_retry_failed_deprecated` notice once per process (the CLI pipeline and `runSyncInner` both call it).
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index f4a9813c81..2f20455601 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -7,6 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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` delegating to `gbrain git commit-push` (`src/core/git/commit-push.ts`, #6530; guide `docs/guides/shared-checkout-git.md`) that never exits 0 without a confirmed push, and a hook running the harden-captured CLI with `--push-only --require-clean` (both `# gbrain-protocol: 2`; harden never downgrades), 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 owners' non-blocking probe (#6210: rejects `git_unavailable` when unsure); 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 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. Locks, waits, outcomes and the per-checkout conflict record: the guide. Tests: `test/git-commit-push-6530.serial.test.ts`.
+- `src/core/classic-file-holds.ts` — classic sync's deterministic per-file refusals as holds in the shared hold store. `classifyClassicFile(root, relPath, gitRoot)` reads metadata only (lstat, the symlink target's realpath, an open+close of a regular file; for a missing path `git ls-tree HEAD` and `git ls-files -v` with optional locks off) and returns `file_unreadable` (`symlink_in_repo`, `symlink_outside_root`, `symlink_dangling`, `symlink_loop`, `permission_denied`, `not_regular_file`), `absent_from_worktree` (`skip_worktree`, `deleted_locally`), or null (a readable file, a directory, a path HEAD lacks, any other error, all left to the drain's existing paths). `classicFileHoldFix` is `gitHoldFix`'s builder for both codes: the user's step for a symlink or permission, `ask_user` between restore and committing the deletion for an absent file; `<checkout>` is an `inputs` placeholder. Pinned by `test/pathological/s-classic-file-holds.test.ts` (+ its Postgres wrapper).
- `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`.
- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. Per-pattern opt-out without the kill-switch: `content_sanity.disabled_patterns` names built-in junk patterns to skip (a JSON array `["access_denied"]` or a comma list `access_denied,error_title`; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 09381ff09c..082dd1e803 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -28,6 +28,18 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy
## Codes
+### absent_from_worktree
+
+<a id="absent_from_worktree"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced. | Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run. | Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `skip_worktree`, `deleted_locally`.
+
+More: [docs/guides/write-refusals.md#absent_from_worktree](../../docs/guides/write-refusals.md#absent_from_worktree)
+
### access_command_failed
<a id="access_command_failed"></a>
@@ -1386,6 +1398,18 @@ More: [docs/guides/repair.md#file-removed-during-scan](../../docs/guides/repair.
More: [docs/guides/write-refusals.md#file_too_large](../../docs/guides/write-refusals.md#file_too_large)
+### file_unreadable
+
+<a id="file_unreadable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced. | Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run. | Replace the symlink with the regular file (or delete it), make the file readable to the account gbrain runs as, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `symlink_in_repo`, `symlink_outside_root`, `symlink_dangling`, `symlink_loop`, `permission_denied`, `not_regular_file`.
+
+More: [docs/guides/write-refusals.md#file_unreadable](../../docs/guides/write-refusals.md#file_unreadable)
+
### fix_not_writable
<a id="fix_not_writable"></a>
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 3122cbad41..423cc4b3cf 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -127,6 +127,8 @@ Every hold and error has three fields, from one table
| `rename_identity_unreadable` | page | none | yes | always: the file title or id holds characters the database cannot compare |
| `rename_reconcile_failed` | page | none | yes | always: the old page may be a duplicate |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
+| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
+| `absent_from_worktree` | page | none | yes | always: only a person decides whether the file comes back or its deletion is committed |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index bd6e295479..e270fb4629 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -214,6 +214,16 @@ with each file and fix the ones that need no guessing."*
| <a id="write_interrupted-hold"></a>`write_interrupted` | The database ended this file's statements (a statement timeout or cancel) at every attempt, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`write_interrupted`](#write_interrupted). | `gbrain sources writer status --source <source> --json` (read-only) names the load on the write owner; reduce it, then `gbrain sources retry-held <source>` and the same sync with its options. |
| <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. Since 0.60.179.0 (#6513) the same hold covers a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: that refusal used to block the cursor with no exit, because `--retry-failed` replays the same pin against the same bytes, `sources refresh` refuses `sync_in_progress` on the unfinished cursor and `--acknowledge-managed` refuses `cursor_unfinished`. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are not a conflict either: the page imports and the file is left as it is. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |
+| <a id="file_unreadable"></a>`file_unreadable` | Classic or managed sync held one file because it is not a readable regular file inside the source root. Sync never reads or follows it, the rest of the source imports, and the bookmark advances. Classic sync re-screens it on every run, so an out-of-band fix needs no commit. | Follow the reason row below. Each hold's `fix` names the exact step; `gbrain sources status <source> --json` lists the holds. |
+| <a id="file_unreadable-symlink_in_repo"></a>`file_unreadable` (`symlink_in_repo`) | The path is a symlink to another file in the repository. Sync reads only regular files and never follows a symlink. | Replace the symlink with the regular file it stands for (or delete it), or leave it out with `sync.exclude` (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`). The next sync re-screens it. |
+| <a id="file_unreadable-symlink_outside_root"></a>`file_unreadable` (`symlink_outside_root`) | The path is a symlink to a path outside the repository (it can point anywhere on the host), so sync never reads it. Before GBRA-133 classic sync blocked the source for three runs, then auto-skipped it. | Copy the content you want into a regular file at that path (or delete the link), or leave it out with `sync.exclude`. The next sync re-screens it. |
+| <a id="file_unreadable-symlink_dangling"></a>`file_unreadable` (`symlink_dangling`) | The path is a symlink whose target does not exist. Classic sync used to drop it silently. | Replace it with the regular file, or delete it and commit. The next sync re-screens it. |
+| <a id="file_unreadable-symlink_loop"></a>`file_unreadable` (`symlink_loop`) | The path is a symlink that resolves back to itself. Classic sync used to drop it silently. | Replace it with the regular file, or delete it and commit. The next sync re-screens it. |
+| <a id="file_unreadable-permission_denied"></a>`file_unreadable` (`permission_denied`) | gbrain cannot open the file (EACCES or EPERM), for example a file another user owns with mode 000. Before GBRA-133 classic sync blocked the source for three runs, then auto-skipped it. With `sync.holds=fail` it still fails the run as `PERMISSION_DENIED`. | Make it readable to the account gbrain runs as (`chmod u+r -- <checkout>/<path>`, or fix its owner or a parent directory's permissions). The next sync imports it with no commit needed. |
+| <a id="file_unreadable-not_regular_file"></a>`file_unreadable` (`not_regular_file`) | The path is a FIFO, socket or device in the working tree, which sync never opens. | Replace it with the regular file, or leave it out with `sync.exclude`. |
+| <a id="absent_from_worktree"></a>`absent_from_worktree` | Classic sync held a file the commit names that is missing from the working tree. Before GBRA-133 it was treated as "deleted after the pin" and dropped silently. The rest of the source imports and the bookmark advances; the hold re-screens on every run and clears when the file is back on disk (it imports) or leaves the commit. | Follow the reason row below. The fix is `ask_user`: restoring the file and committing its deletion are both valid. |
+| <a id="absent_from_worktree-skip_worktree"></a>`absent_from_worktree` (`skip_worktree`) | A sparse checkout (or a skip-worktree bit set by hand) keeps the committed file off disk. | Ask the user: widen the sparse checkout (`git -C <checkout> sparse-checkout add <dir>`; for a hand-set bit, `git -C <checkout> update-index --no-skip-worktree -- <path>` and `git -C <checkout> restore -- <path>`) and the next sync imports it; or leave it out with `sync.exclude`. Keeping it held is also safe. |
+| <a id="absent_from_worktree-deleted_locally"></a>`absent_from_worktree` (`deleted_locally`) | The committed file was deleted from the checkout and the deletion is not committed. | Ask the user: restore it (`git -C <checkout> restore -- <path>`) and the next sync imports it; or commit the deletion (`gbrain git commit-push --path <checkout> -m 'Delete <path>' -- <path>`) and the next sync clears the hold. |
| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `GBRAIN_SYNC_PARSER_REGRESSION=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |
| <a id="takes_holder_invalid"></a>takes holder (`invalid_params`) | `takes_add`, or `takes_supersede` with an explicit `holder`, was given a holder the takes fence cannot carry: empty, whitespace, or not `world`, `brain`, `people/<slug>` or `companies/<slug>` (a legacy bare slug is accepted). The value is trimmed first, so `" world "` is stored as `world`. Nothing was written: before this release such a holder was published into the fence and every later takes write on that page was refused `target_fence_malformed`. A supersede without an override keeps the row's stored holder. A page whose stored holder is already malformed still refuses every takes write (`invalid_fence`); `gbrain repair fences` is the way out. | Resend with a holder in that grammar (`holder: me` on the brain host resolves the owner's holder). For a page already carrying a malformed holder, preview `gbrain repair fences --slug <slug>` and apply it, or edit the `who` cell by hand. Format: [holders](fence-format.md#holders). |
| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |
diff --git a/llms-full.txt b/llms-full.txt
index df42e76c7a..86f42183cd 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7583,6 +7583,8 @@ Every hold and error has three fields, from one table
| `rename_identity_unreadable` | page | none | yes | always: the file title or id holds characters the database cannot compare |
| `rename_reconcile_failed` | page | none | yes | always: the old page may be a duplicate |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
+| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
+| `absent_from_worktree` | page | none | yes | always: only a person decides whether the file comes back or its deletion is committed |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index f1e13cd999..dfcc81aa8d 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -32,6 +32,7 @@ import { DEFAULT_SOURCE_ID, hasMalformedPathSegment, isCodeFilePath, resolveSlug
import type { SyncActivePack } from './sync-run.ts';
import { isPathContained } from '../../core/path-confine.ts';
import { bindOrigin } from '../../core/persistence/origin-guard.ts';
+import { CLASSIC_FILE_HOLD_CODES, classifyClassicFile, type ClassicFileHold } from '../../core/classic-file-holds.ts';
/** The file at a repo-relative path from git or a hold row, or null when it is missing or resolves outside the source root. */
function fileUnderRoot(root: string, path: string): string | null {
@@ -101,9 +102,13 @@ function currentVersion(filePath: string): string | null | undefined {
* retry request, an older frontmatter reader or fence screen, and holds whose
* verdict depends on database state or the working tree). A held file that is
* gone or no longer synced clears.
+ * GBRA-133: a symlink, permission or absent-from-worktree hold is re-classified
+ * every run and re-screened when its verdict changed (the link replaced by a
+ * file, a chmod, a restore), with no commit needed; gone when the path left
+ * the commit. `gitRoot` bounds a symlink target as in or out of the repository.
* `selected` is null for a path outside this run's scope (left alone).
*/
-export function planHoldRescreen(holds: LegacyHolds, input: { root: string; touched: ReadonlySet<string>; selected: (path: string) => boolean | null }): void {
+export function planHoldRescreen(holds: LegacyHolds, input: { root: string; gitRoot?: string; touched: ReadonlySet<string>; selected: (path: string) => boolean | null }): void {
for (const path of holds.retryPaths) if (!holds.existing.has(path)) holds.retryTaken.push(path);
for (const [path, record] of holds.existing) {
if (input.touched.has(path)) {
@@ -112,6 +117,20 @@ export function planHoldRescreen(holds: LegacyHolds, input: { root: string; touc
}
const selected = input.selected(path);
if (selected === null) continue;
+ if (CLASSIC_FILE_HOLD_CODES.has(record.code)) {
+ const now = selected ? classifyClassicFile(input.root, path, input.gitRoot ?? input.root) : null;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- path is a repo-relative hold path; lstat reads metadata only
+ const present = (() => { try { return !!lstatSync(join(input.root, path)); } catch { return false; } })();
+ if (!selected || (!now && !present)) {
+ holds.gone.push(path);
+ } else if (!holds.active || (now && now.code === record.code && now.reason === record.meta.reason && !holds.retryPaths.has(path))) {
+ continue;
+ } else {
+ holds.rescreen.push(path);
+ }
+ if (holds.retryPaths.has(path)) holds.retryTaken.push(path);
+ continue;
+ }
const filePath = fileUnderRoot(input.root, path);
if (!selected || !filePath) {
holds.gone.push(path);
@@ -201,6 +220,17 @@ export async function holdRefusedImport(engine: BrainEngine, holds: LegacyHolds
}
}
+/** GBRA-133: holds a path classic sync cannot read as a regular file (or that is absent from the working tree); false when the hold cannot be recorded. */
+export async function holdClassicFile(engine: BrainEngine, holds: LegacyHolds, path: string, refusal: ClassicFileHold): Promise<boolean> {
+ try {
+ await recordLegacyHold(engine, holds, { path, refusal, upstreamVersion: null });
+ return true;
+ } catch (e) {
+ serr(` Could not record the hold for ${sanitizePathForDisplay(path)} (${e instanceof Error ? e.message : String(e)}); it counts as a failure this run.`);
+ return false;
+ }
+}
+
/** Bookkeeping for a screened import: the escalation denominator and the recovered-frontmatter tally. */
export function noteScreenedImport(holds: LegacyHolds | null, path: string, result: Pick<ImportResult, 'status' | 'frontmatter_recovery' | 'fences_normalized' | 'fence_issues'>): void {
if (!holds) return;
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index 165a4b21ae..602278afbb 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -30,7 +30,8 @@ import { isWindowsColonTarget } from '../../core/persistence/native-file-target.
import { ERROR_CATALOGUE } from '../../core/error-catalogue.ts';
import { enginePoolStats } from '../../core/postgres-engine/pool-stats.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
-import { clearLegacyHold, holdRefusedImport, noteScreenedImport, type LegacyHolds } from './holds.ts';
+import { clearLegacyHold, holdClassicFile, holdRefusedImport, noteScreenedImport, type LegacyHolds } from './holds.ts';
+import { classifyClassicFile } from '../../core/classic-file-holds.ts';
import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';
@@ -278,6 +279,16 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
progress.tick(1, `skip:${path}`);
return;
}
+ // GBRA-133: a symlink, a permission error or a committed file missing from
+ // the working tree is held (re-screened every run), never failed: it stays
+ // out of failedFiles and the auto-skip streak, so it never gates the bookmark.
+ const unreadable = holds?.active && !company ? classifyClassicFile(syncRepoPath, path, gitContextRoot) : null;
+ if (unreadable && await holdClassicFile(eng, holds!, path, unreadable)) {
+ await markCompleted(run, path);
+ progressAt.last = Date.now();
+ progress.tick(1, `held:${path}`);
+ return;
+ }
if (!company && !existsSync(filePath)) {
// v0.42.x (#1794, Codex #3): the diff is against the PINNED target, but
// importFile reads the live working tree. A file added in lastCommit..pin
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 5e6bcfaa08..6e0cf64a46 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -139,7 +139,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
// nothing else to do still re-screens them, and clears holds of gone files.
const sourceRootMode = scoped && slugRootMode === 'source-root';
if (holds) {
- planHoldRescreen(holds, { root: sourceRootMode ? syncScopeRoot : gitContextRoot, touched: new Set(), selected: path => {
+ planHoldRescreen(holds, { root: sourceRootMode ? syncScopeRoot : gitContextRoot, gitRoot: gitContextRoot, touched: new Set(), selected: path => {
const gitPath = sourceRootMode ? `${syncScopeRelPath}/${path}` : path;
return inScope(gitPath) ? !excluded(gitPath) && isSelectedForRun(gitPath, syncOpts) : null;
} });
diff --git a/src/core/classic-file-holds.ts b/src/core/classic-file-holds.ts
new file mode 100644
index 0000000000..d3b28bf00f
--- /dev/null
+++ b/src/core/classic-file-holds.ts
@@ -0,0 +1,132 @@
+/**
+ * GBRA-133 PR 1: classic (unmanaged) sync's deterministic per-file refusals.
+ * A path the commit names that is not a readable regular file inside the repo
+ * (a symlink, a non-regular file, a permission error) or that is committed but
+ * missing from the working tree (a sparse checkout, a local deletion) is held
+ * in the classic hold store instead of failing the run: it never gates the
+ * bookmark and is re-screened every run, so an out-of-band fix (the symlink
+ * replaced by a file, chmod, git restore) imports it with no new commit.
+ *
+ * `classifyClassicFile` reads only metadata (lstat, realpath of the target,
+ * an open of a regular file, and for a missing path two read-only Git
+ * plumbing calls with optional locks off); it never reads or follows content.
+ * Any other error returns null and keeps today's failure path.
+ * `classicFileHoldFix` is the fix every hold surface renders for these codes.
+ */
+import { closeSync, lstatSync, openSync, realpathSync } from 'node:fs';
+import { join } from 'node:path';
+import { execFileSync } from './spawn.ts';
+import type { Action } from './agent-output.ts';
+import { gitChildEnv } from './git-env.ts';
+import { buildGitInvocation, isWithinRoot } from './sync-git.ts';
+import type { GitHoldRecord } from './persistence/sync-holds.ts';
+
+export type ClassicFileHoldCode = 'file_unreadable' | 'absent_from_worktree';
+export type ClassicFileHoldReason = 'symlink_in_repo' | 'symlink_outside_root' | 'symlink_dangling' | 'symlink_loop' | 'permission_denied' | 'not_regular_file'
+ | 'skip_worktree' | 'deleted_locally';
+export interface ClassicFileHold { code: ClassicFileHoldCode; reason: ClassicFileHoldReason; message: string }
+
+export const CLASSIC_FILE_HOLD_CODES: ReadonlySet<string> = new Set<ClassicFileHoldCode>(['file_unreadable', 'absent_from_worktree']);
+
+const errno = (e: unknown) => (e as NodeJS.ErrnoException | null)?.code;
+const DENIED = new Set(['EACCES', 'EPERM']);
+const SYMLINK_WHAT: Record<string, string> = {
+ symlink_in_repo: 'a symlink to another file in the repository',
+ symlink_outside_root: 'a symlink to a path outside the repository',
+ symlink_dangling: 'a symlink whose target does not exist',
+ symlink_loop: 'a symlink that loops back on itself',
+ not_regular_file: 'not a regular file (a FIFO, socket or device)',
+};
+
+function hold(code: ClassicFileHoldCode, reason: ClassicFileHoldReason, relPath: string): ClassicFileHold {
+ const message = code === 'absent_from_worktree'
+ ? `${relPath} is committed at HEAD but missing from the working tree (${reason === 'skip_worktree' ? 'the sparse checkout or a skip-worktree bit leaves it off disk' : 'it was deleted locally and the deletion is not committed'}), so sync did not import it.`
+ : reason === 'permission_denied' ? `${relPath} cannot be read (permission denied), so sync did not import it.`
+ : `${relPath} is ${SYMLINK_WHAT[reason]}; sync reads only regular files inside the repository and never follows a symlink.`;
+ return { code, reason, message };
+}
+
+/** Read-only Git plumbing in the source root: optional locks off, literal pathspecs, null on any failure. */
+function gitRead(root: string, args: string[]): string | null {
+ try {
+ return execFileSync('git', buildGitInvocation(root, args), { env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0', GIT_LITERAL_PATHSPECS: '1' }),
+ encoding: 'utf-8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] });
+ } catch { return null; }
+}
+
+/** A committed file missing on disk: skip_worktree when the index marks it so, deleted_locally otherwise; null when HEAD has no blob there. */
+function absentFromWorktree(root: string, relPath: string): ClassicFileHold | null {
+ const tree = gitRead(root, ['ls-tree', '-z', 'HEAD', '--', relPath]);
+ if (!tree || !/^(100644|100755|120000) blob /.test(tree)) return null;
+ const flag = gitRead(root, ['ls-files', '-z', '-v', '--', relPath])?.charAt(0);
+ return hold('absent_from_worktree', flag === 'S' ? 'skip_worktree' : 'deleted_locally', relPath);
+}
+
+/**
+ * The hold for `relPath` under `root` (the source root sync joins paths to), or null when it is a readable regular file or
+ * fails some other way. `gitRoot` bounds a symlink target as in or out of the repository.
+ */
+export function classifyClassicFile(root: string, relPath: string, gitRoot: string = root): ClassicFileHold | null {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath is a git path of the synced repo; only metadata is read (lstat, realpath, open+close) and a symlink is never followed for content
+ const full = join(root, relPath);
+ let stat;
+ try { stat = lstatSync(full); } catch (e) {
+ if (DENIED.has(errno(e) ?? '')) return hold('file_unreadable', 'permission_denied', relPath);
+ return errno(e) === 'ENOENT' || errno(e) === 'ENOTDIR' ? absentFromWorktree(root, relPath) : null;
+ }
+ if (stat.isSymbolicLink()) {
+ let target: string;
+ try { target = realpathSync(full); } catch (e) {
+ if (errno(e) === 'ELOOP') return hold('file_unreadable', 'symlink_loop', relPath);
+ if (errno(e) === 'ENOENT') return hold('file_unreadable', 'symlink_dangling', relPath);
+ return DENIED.has(errno(e) ?? '') ? hold('file_unreadable', 'permission_denied', relPath) : null;
+ }
+ let rootReal: string;
+ try { rootReal = realpathSync(gitRoot); } catch { return null; }
+ return hold('file_unreadable', isWithinRoot(target, rootReal) ? 'symlink_in_repo' : 'symlink_outside_root', relPath);
+ }
+ if (stat.isDirectory()) return null;
+ if (!stat.isFile()) return hold('file_unreadable', 'not_regular_file', relPath);
+ try { closeSync(openSync(full, 'r')); } catch (e) {
+ return DENIED.has(errno(e) ?? '') ? hold('file_unreadable', 'permission_denied', relPath) : null;
+ }
+ return null;
+}
+
+/** The fix for a classic file hold: the user's choice for a symlink or a permission, ask_user between restoring and deleting for an absent file. */
+export function classicFileHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'>): Action {
+ const source = record.source_id;
+ const path = record.path;
+ const reason = record.meta.reason as ClassicFileHoldReason | undefined;
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ const docs = `docs/guides/write-refusals.md#${record.code}${reason ? `-${reason}` : ''}`;
+ const checkout = [{ name: 'checkout', how: `the source's checkout: local_path of ${source} in gbrain sources list --json` }];
+ const sync: Action = { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${path} (every sync re-screens it, no commit needed): a readable regular file imports and the hold clears.` };
+ const rest = `the rest of source ${source} keeps syncing`;
+ if (record.code === 'absent_from_worktree' && reason === 'skip_worktree') {
+ const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : path;
+ return { ask_user: true, argv: ['git', '-C', '<checkout>', 'sparse-checkout', 'add', dir], inputs: checkout, consent: [], actor: 'agent', requires_exclusive: false, docs,
+ user_message: `${path} is committed but the sparse checkout (or a skip-worktree bit) keeps it off disk, so sync holds it and ${rest}. Choose: widen the sparse checkout to include it `
+ + `(git -C <checkout> sparse-checkout add ${dir}; for a file whose skip-worktree bit was set by hand, clear the bit and restore the file as ${docs} shows), `
+ + `and the next sync imports it; or leave it out of the brain with sync.exclude (gbrain config get sync.exclude, then gbrain config set sync.exclude '<current list>,${path}'). Keeping it held is also safe.`,
+ why: 'Which files a sparse checkout leaves out is the user\'s choice; sync never imports a file it cannot read from the working tree.', then: sync, verify };
+ }
+ if (record.code === 'absent_from_worktree') {
+ return { ask_user: true, argv: ['git', '-C', '<checkout>', 'restore', '--', path], inputs: checkout, consent: [], actor: 'agent', requires_exclusive: false, docs,
+ user_message: `${path} is committed but was deleted from the checkout and the deletion is not committed, so sync holds it and ${rest}. Choose: restore it `
+ + `(git -C <checkout> restore -- ${path}) and the next sync imports it; or commit the deletion (gbrain git commit-push --path <checkout> -m 'Delete ${path}' -- ${path}) and the next sync clears the hold.`,
+ why: 'Whether the file was deleted on purpose is the user\'s call; restoring brings back the committed bytes, committing the deletion removes it from Git.', then: sync, verify };
+ }
+ if (reason === 'permission_denied') {
+ return { argv: ['chmod', 'u+r', '--', `<checkout>/${path}`], inputs: checkout, consent: [], actor: 'user', requires_exclusive: false, docs,
+ user_message: `gbrain cannot read ${path} (permission denied), so sync holds it and ${rest}. Make it readable to the account gbrain runs as (this chmod, or fix the file's owner or a parent directory's permissions); `
+ + 'the next sync re-screens it and imports it with no commit needed.',
+ why: 'File permissions on the host are the user\'s to change; sync never reads around them.', then: sync, verify };
+ }
+ const what = SYMLINK_WHAT[reason ?? ''] ?? 'not a readable regular file';
+ return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'user', requires_exclusive: false, docs,
+ user_message: `${path} is ${what}, so sync holds it without following it and ${rest}. Replace it in the checkout with the regular file it stands for (or delete it), `
+ + `or leave it out of the brain with sync.exclude: read the current list with this command, then gbrain config set sync.exclude '<current list>,${path}'. The next sync re-screens it with no commit needed.`,
+ why: 'Sync reads only regular files inside the source root and never follows a symlink (a link can point anywhere on the host); which file belongs in the brain is the user\'s call.', then: sync, verify };
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 8ae869b7ca..383ade26e7 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -62,6 +62,7 @@ export interface CodeEntry {
}
export const CODES = {
+ absent_from_worktree: { class: 'caller', retryable: false, reasons: ['skip_worktree', 'deleted_locally'], summary: "Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced.", why: "Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run.", docs: 'docs/guides/write-refusals.md#absent_from_worktree', suggestion: 'Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold.' },
access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },
access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },
access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
@@ -274,6 +275,7 @@ export const CODES = {
fix_not_writable: { class: 'host_only', summary: "A gbrain lint fix was not applied because the file refused the write (EACCES, EPERM or EROFS); the file was left unchanged.", why: "Lint repairs files in place, and this file's permissions or a read-only mount stopped the write; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#fix-not-writable', suggestion: "Make the file writable by the user running gbrain, or pass its directory or file name to gbrain lint --exclude, then lint again." },
file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file), decide with the user, then apply it with the plan hash; the next gbrain sync --source <source> --no-pull re-screens the hold.' },
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
+ file_unreadable: { class: 'caller', retryable: false, reasons: ['symlink_in_repo', 'symlink_outside_root', 'symlink_dangling', 'symlink_loop', 'permission_denied', 'not_regular_file'], summary: "Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced.", why: "Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run.", docs: 'docs/guides/write-refusals.md#file_unreadable', suggestion: 'Replace the symlink with the regular file (or delete it), make the file readable to the account gbrain runs as, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it.' },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 55641342ff..df2ff5a11b 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -39,6 +39,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
rename_identity_unreadable: 'content_refused', rename_reconcile_failed: 'conflict',
file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',
purged_content: 'content_refused', write_gate_rejected: 'content_refused',
+ file_unreadable: 'content_refused', absent_from_worktree: 'file_missing',
file_database_drift: 'drift', raw_file_changed: 'drift', pending_import: 'transient',
source_binding_changed: 'config', unsafe_file_target: 'config',
canonical_file_missing: 'file_missing',
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 4ca55a55c4..7d1a45c2c7 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -91,6 +91,12 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
human_reason: 'A rename imported but the old page could not be removed; a person runs a full sync of the source (it removes pages whose file is gone) or removes the old page with gbrain delete.' },
{ code: 'origin_conflict_decision', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pages differ, their ids conflict or none is the page the path names',
human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },
+ // GBRA-130 A-7 / GBRA-133: the file is not a readable regular file inside the source root (a symlink, a non-regular file, a permission error).
+ { code: 'file_unreadable', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a change to the checkout makes the file readable',
+ human_reason: 'Sync cannot read this file as a regular file inside the source root (a symlink, a non-regular file or a permission error) and never follows it; make it a readable regular file in the checkout (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held <source>.' },
+ // GBRA-133: a committed file missing from the working tree (a sparse checkout, a deletion not committed); classic sync holds it.
+ { code: 'absent_from_worktree', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a person decides whether the file comes back or its deletion is committed',
+ human_reason: 'The file is committed but missing from the checkout; a person restores it (git restore, or widens the sparse checkout) so the next sync imports it, or commits the deletion with gbrain git commit-push, which clears the hold.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index e308389202..3595b1d24a 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -43,6 +43,7 @@ import { FENCE_VERSION } from '../fence-repair/refusal.ts';
import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';
import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';
import { classicRenameHoldFix } from '../classic-rename-holds.ts';
+import { classicFileHoldFix } from '../classic-file-holds.ts';
import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';
import type { SyncDiscovery, SyncRename } from './sync-discovery.ts';
import { isCodeFilePath, isImageFilePath, isMultimodalEnabled } from '../sync.ts';
@@ -72,8 +73,8 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;
export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
| 'legacy_slug_conflict' | 'write_interrupted' | 'origin_conflict'
- /** GBRA-133 PR 1 (classic sync): src/core/classic-rename-holds.ts. */
- | 'rename_identity_unreadable' | 'rename_reconcile_failed';
+ /** GBRA-133 PR 1 (classic sync): src/core/classic-rename-holds.ts and src/core/classic-file-holds.ts. */
+ | 'rename_identity_unreadable' | 'rename_reconcile_failed' | 'file_unreadable' | 'absent_from_worktree';
/**
* Flip lane C: the holds of a write that ran out of attempts, its preparation never settling (`preparation_stalled`)
* or its statements ended by the database every time (`write_interrupted`). The file is not the problem: they route to
@@ -93,7 +94,8 @@ export interface PreparationStallMeta {
/** The `gbrain sync` arguments that resume the cursor with its stored options (after `sources retry-held`). */
sync_argv: string[];
}
-export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason;
+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason
+ | 'symlink_in_repo' | 'symlink_outside_root' | 'symlink_dangling' | 'symlink_loop' | 'permission_denied' | 'not_regular_file' | 'skip_worktree' | 'deleted_locally';
export interface GitHoldMeta {
reason?: GitHoldReason;
@@ -747,6 +749,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
return contentHoldFix(record);
+ case 'file_unreadable': case 'absent_from_worktree': return classicFileHoldFix(record);
default:
return record.meta.reason === 'needs_interpretation'
? repair(true, `Reading ${record.path} needs an interpretation (folded lines, a duplicate key or an unclosed list); the preview shows the exact proposal for approval.`)
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
index 3142f63c97..a05d87c807 100644
--- a/src/core/sync-git.ts
+++ b/src/core/sync-git.ts
@@ -3,9 +3,9 @@
* baseline-commit self-heal, and path-containment guards. Peeled out of
* src/commands/sync.ts (containment sprint C13-C14) as a pure move.
*/
-import { realpathSync } from 'fs';
+import { lstatSync, realpathSync } from 'fs';
import { execFileSync } from './spawn.ts';
-import { isAbsolute, join, relative, sep } from 'path';
+import { basename, dirname, isAbsolute, join, relative, sep } from 'path';
import type { BrainEngine } from './engine.ts';
import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';
import { DELETE_BATCH_SIZE } from './engine-constants.ts';
@@ -616,11 +616,14 @@ export function isWithinRoot(
/**
* #774 NAV-1 TOCTOU: true only if filePath realpath-resolves inside gitRoot.
* Guards symlink escape at the per-file level (a committed symlink whose
- * target lives outside the repo), not just at scope entry.
+ * target lives outside the repo), not just at scope entry. GBRA-133 S-4: a
+ * leaf that is not a symlink resolves through its parent directory (Bun's
+ * realpathSync returns ENOENT for an existing name containing a backslash).
*/
export function isPathSafe(filePath: string, gitRoot: string): boolean {
try {
- return isWithinRoot(realpathSync(filePath), realpathSync(gitRoot));
+ const real = lstatSync(filePath).isSymbolicLink() ? realpathSync(filePath) : join(realpathSync(dirname(filePath)), basename(filePath));
+ return isWithinRoot(real, realpathSync(gitRoot));
} catch {
return false;
}
diff --git a/test/e2e/s-classic-file-holds-postgres.test.ts b/test/e2e/s-classic-file-holds-postgres.test.ts
new file mode 100644
index 0000000000..319c124704
--- /dev/null
+++ b/test/e2e/s-classic-file-holds-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-classic-file-holds.test.ts'));
diff --git a/test/pathological/a18-ledger-path-text.test.ts b/test/pathological/a18-ledger-path-text.test.ts
index 63f557622b..99396977b7 100644
--- a/test/pathological/a18-ledger-path-text.test.ts
+++ b/test/pathological/a18-ledger-path-text.test.ts
@@ -45,7 +45,9 @@ interface Repo { engine: BrainEngine; root: string; sourceId: string; commit(fil
sync(opts?: { skipFailed?: boolean; engine?: BrainEngine }): ReturnType<typeof performSync>; lastCommit(): Promise<string | null> }
/** A legacy (unmanaged) source on a temp git repo whose first sync imported seed.md; the ledger lives under the temp home.
- * concurrency 1: Postgres import workers connect to the configured database_url, not the isolated test database. */
+ * concurrency 1: Postgres import workers connect to the configured database_url, not the isolated test database.
+ * sync.holds=fail: since GBRA-133 the default policy holds an unreadable file (file_unreadable/permission_denied,
+ * test/pathological/s-classic-file-holds.test.ts); the fail-closed policy keeps it on the ledger path pinned here. */
function legacyRepo(databaseUrl: string | undefined, run: (r: Repo) => Promise<void>): Promise<void> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-a18-'));
const root = join(home, 'repo');
@@ -54,6 +56,7 @@ function legacyRepo(databaseUrl: string | undefined, run: (r: Repo) => Promise<v
const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
try {
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.setConfig('sync.holds', 'fail');
git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
const commit = (files: Record<string, string>, msg: string) => {
for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), body); }
diff --git a/test/pathological/s-classic-file-holds.test.ts b/test/pathological/s-classic-file-holds.test.ts
new file mode 100644
index 0000000000..72eb497203
--- /dev/null
+++ b/test/pathological/s-classic-file-holds.test.ts
@@ -0,0 +1,163 @@
+/**
+ * GBRA-133 PR 1 item 3: classic (unmanaged) incremental sync of a file it can
+ * never read as a regular file inside the repo. Before: a symlink (in-repo
+ * S-16, outside S-17, typechange S-21) or a mode-000 file (S-30) failed with a
+ * ledger row, blocked the source's bookmark for three runs, then auto-skipped;
+ * a dangling symlink (S-18), a symlink loop (S-20), a sparse-checkout hole
+ * (S-27) and a committed file deleted from the working tree (S-28) were
+ * dropped silently as "deleted after the pin"; a backslash filename (S-4) read
+ * as a symlink escape because Bun's realpathSync returns ENOENT for it.
+ *
+ * Protects: on first sight each is a typed hold (file_unreadable with its
+ * symlink or permission reason, absent_from_worktree with skip_worktree or
+ * deleted_locally) in the classic hold store, with a fix; the healthy sibling
+ * imports, the cursor reaches HEAD and no ledger row is written. The hold is
+ * re-screened on every run, so an out-of-band fix (the symlink replaced by a
+ * file, chmod, git restore, the sparse checkout widened) imports the file with
+ * no new commit. S-4 imports. An unknown per-file error keeps the three-run
+ * auto-skip. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { chmodSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { cliRenderContext, renderAction, type Next } from '../../src/core/agent-output.ts';
+import type { ClassicFileHoldCode, ClassicFileHoldReason } from '../../src/core/classic-file-holds.ts';
+import { gitHoldItem, readGitSourceHolds, type GitHoldRecord } from '../../src/core/persistence/sync-holds.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';
+import { CASES } from './s-blockers-cases.ts';
+import { md, observe, withProbeEngine, withProbeRepo, type ProbeRepo } from './s-blockers-fixture.ts';
+import { pathologicalArms } from './harness.ts';
+import { permsEnforced } from '../helpers/fs-perms.ts';
+
+const blocker = (id: string) => CASES.find(c => c.id === id)!;
+
+interface HoldCase {
+ id: string;
+ /** Each held path with its expected code, reason and fix (argv and its next on the CLI). */
+ holds: Array<{ path: string; code: ClassicFileHoldCode; reason: ClassicFileHoldReason; argv: string[]; next: Next }>;
+ /** The out-of-band fix (no commit); afterwards each slug in imports exists. */
+ repair(r: ProbeRepo): void;
+ imports: string[];
+ skip?: string | false;
+}
+
+const exclude = ['gbrain', 'config', 'get', 'sync.exclude'];
+const regular = (r: ProbeRepo, path: string, title: string) => { unlinkSync(join(r.root, path)); writeFileSync(join(r.root, path), md(title)); };
+
+const HOLD_CASES: HoldCase[] = [
+ { id: 'S-16', holds: [{ path: 'notes/link.md', code: 'file_unreadable', reason: 'symlink_in_repo', argv: exclude, next: 'tell_user_to_run' }],
+ repair: r => regular(r, 'notes/link.md', 'link'), imports: ['notes/link'] },
+ { id: 'S-17', holds: [{ path: 'notes/out.md', code: 'file_unreadable', reason: 'symlink_outside_root', argv: exclude, next: 'tell_user_to_run' }],
+ repair: r => regular(r, 'notes/out.md', 'out'), imports: ['notes/out'] },
+ { id: 'S-18', holds: [{ path: 'notes/dangling.md', code: 'file_unreadable', reason: 'symlink_dangling', argv: exclude, next: 'tell_user_to_run' }],
+ repair: r => regular(r, 'notes/dangling.md', 'dangling'), imports: ['notes/dangling'] },
+ { id: 'S-20', holds: [{ path: 'loop1.md', code: 'file_unreadable', reason: 'symlink_loop', argv: exclude, next: 'tell_user_to_run' },
+ { path: 'loop2.md', code: 'file_unreadable', reason: 'symlink_loop', argv: exclude, next: 'tell_user_to_run' }],
+ repair: r => { regular(r, 'loop1.md', 'loop one'); regular(r, 'loop2.md', 'loop two'); }, imports: ['loop1', 'loop2'] },
+ { id: 'S-21', holds: [{ path: 'notes/t.md', code: 'file_unreadable', reason: 'symlink_in_repo', argv: exclude, next: 'tell_user_to_run' }],
+ repair: r => regular(r, 'notes/t.md', 't restored'), imports: ['notes/t'] },
+ { id: 'S-27', holds: [{ path: 'hidden/h.md', code: 'absent_from_worktree', reason: 'skip_worktree', argv: ['git', '-C', '<checkout>', 'sparse-checkout', 'add', 'hidden'], next: 'ask_user' }],
+ repair: r => { r.git('sparse-checkout', 'disable'); }, imports: ['hidden/h'] },
+ { id: 'S-28', holds: [{ path: 'notes/gone.md', code: 'absent_from_worktree', reason: 'deleted_locally', argv: ['git', '-C', '<checkout>', 'restore', '--', 'notes/gone.md'], next: 'ask_user' }],
+ repair: r => { r.git('restore', '--', 'notes/gone.md'); }, imports: ['notes/gone'] },
+ { id: 'S-30', holds: [{ path: 'notes/locked.md', code: 'file_unreadable', reason: 'permission_denied', argv: ['chmod', 'u+r', '--', '<checkout>/notes/locked.md'], next: 'tell_user_to_run' }],
+ repair: r => chmodSync(join(r.root, 'notes/locked.md'), 0o644), imports: ['notes/locked'],
+ skip: permsEnforced() ? false : 'file permission bits are not enforced on this host (root or a permissive filesystem)' },
+];
+
+async function holdsOf(r: ProbeRepo): Promise<GitHoldRecord[]> {
+ return (await readGitSourceHolds(r.engine, { sourceIds: [r.sourceId] }))[0]?.holds ?? [];
+}
+const page = async (r: ProbeRepo, slug: string) => (await r.engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [r.sourceId, slug])).length > 0;
+const ledger = (r: ProbeRepo) => loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => ({ path: f.path, code: f.code, state: f.state }));
+
+/** First sync, then the case's odd input committed next to ok/healthy-1.md. */
+async function seeded(r: ProbeRepo, id: string): Promise<void> {
+ const c = blocker(id);
+ await c.prepare?.(r);
+ expect((await r.sync()).status).toBe('first_sync');
+ r.write('ok/healthy-1.md', md('healthy-1'));
+ await c.mutate(r);
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`GBRA-133 classic per-file refusals are typed holds that never gate the bookmark (${backend})`, () => {
+ for (const c of HOLD_CASES) {
+ test.skipIf(!!c.skip)(`${c.id} ${blocker(c.id).name}: held ${c.holds.map(h => h.code + '/' + h.reason).join(', ')}; the sibling imports, the cursor reaches HEAD, no ledger row; an out-of-band fix imports it with no new commit`,
+ () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ await seeded(r, c.id);
+ const second = await observe(r, 'ok/healthy-1');
+ expect({ thrown: second.thrown, status: second.status, cursorAtHead: second.cursorAtHead, healthy: second.healthy, ledger: second.ledger })
+ .toEqual({ thrown: null, status: 'synced', cursorAtHead: true, healthy: true, ledger: [] });
+ const held = (await holdsOf(r)).sort((a, b) => a.path.localeCompare(b.path));
+ expect(held.map(hold => {
+ const item = gitHoldItem(hold);
+ const fix = renderAction(item.fix, cliRenderContext());
+ return { path: hold.path, code: hold.code, reason: hold.meta.reason, argv: fix.argv, next: fix.next, docs: item.docs, verify: fix.verify?.argv };
+ })).toEqual(c.holds.map(h => ({ ...h, docs: 'docs/guides/write-refusals.md#' + h.code + '-' + h.reason, verify: ['gbrain', 'sources', 'status', r.sourceId, '--json'] })));
+
+ // A quiet run keeps the hold, writes no ledger row, and is never blocked.
+ const third = await observe(r, 'ok/healthy-1');
+ expect({ thrown: third.thrown, cursorAtHead: third.cursorAtHead, ledger: third.ledger, held: (await holdsOf(r)).map(h => h.path).sort() })
+ .toEqual({ thrown: null, cursorAtHead: true, ledger: [], held: c.holds.map(h => h.path) });
+
+ // Out-of-band fix, no commit: the re-screen imports it and clears the hold.
+ c.repair(r);
+ const fixed = await observe(r, 'ok/healthy-1');
+ expect({ thrown: fixed.thrown, cursorAtHead: fixed.cursorAtHead, ledger: fixed.ledger, held: await holdsOf(r) })
+ .toEqual({ thrown: null, cursorAtHead: true, ledger: [], held: [] });
+ for (const slug of c.imports) expect({ slug, imported: await page(r, slug) }).toEqual({ slug, imported: true });
+ })), 180_000);
+ }
+
+ test('S-4 a backslash filename imports (no symlink-escape refusal, no ledger row, no hold)', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ await seeded(r, 'S-4');
+ const second = await observe(r, 'ok/healthy-1');
+ expect({ thrown: second.thrown, status: second.status, cursorAtHead: second.cursorAtHead, healthy: second.healthy, ledger: second.ledger, holds: second.gitHolds })
+ .toEqual({ thrown: null, status: 'synced', cursorAtHead: true, healthy: true, ledger: [], holds: [] });
+ const rows = await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=$2', [r.sourceId, 'notes/back\\slash.md']);
+ expect(rows).toEqual([{ source_path: 'notes/back\\slash.md' }]);
+ })), 180_000);
+
+ test('S-28 a held absent file whose deletion is then committed clears, and no page is created', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ await seeded(r, 'S-28');
+ await observe(r, 'ok/healthy-1');
+ expect((await holdsOf(r)).map(h => h.code)).toEqual(['absent_from_worktree']);
+ r.git('rm', '-q', '--cached', '--', 'notes/gone.md');
+ r.git('commit', '-qm', 'delete gone');
+ const after = await observe(r, 'ok/healthy-1');
+ expect({ thrown: after.thrown, cursorAtHead: after.cursorAtHead, ledger: after.ledger, held: await holdsOf(r), page: await page(r, 'notes/gone') })
+ .toEqual({ thrown: null, cursorAtHead: true, ledger: [], held: [], page: false });
+ })), 180_000);
+
+ test('an unknown per-file error is not a hold: it keeps the three-run auto-skip (GBRAIN_SYNC_AUTOSKIP_AFTER=3)', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ expect((await r.sync()).status).toBe('first_sync');
+ r.write('ok/healthy-1.md', md('healthy-1'));
+ r.write('notes/odd.md', md('odd'));
+ r.commitAll('odd');
+ const failing = unknownFailure(engine, 'notes/odd');
+ const statuses: string[] = [];
+ for (let i = 0; i < 3; i++) {
+ statuses.push((await performSync(failing, { repoPath: r.root, sourceId: r.sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 })).status);
+ }
+ expect(statuses).toEqual(['blocked_by_failures', 'blocked_by_failures', 'synced']);
+ expect(ledger(r)).toEqual([{ path: 'notes/odd.md', code: 'UNKNOWN', state: 'auto_skipped' }]);
+ expect(await holdsOf(r)).toEqual([]);
+ expect({ healthy: await page(r, 'ok/healthy-1'), cursorAtHead: (await r.lastCommit()) === r.head() }).toEqual({ healthy: true, cursorAtHead: true });
+ })), 180_000);
+ });
+}
+
+/** The engine whose page reads inside importOnePath throw an unclassified error for one slug. */
+function unknownFailure(engine: BrainEngine, slug: string): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (prop === 'getPage' && typeof value === 'function') {
+ return (...args: unknown[]) => new Error().stack?.includes('importOnePath') && args[0] === slug
+ ? Promise.reject(new Error('an unexpected parser state in an example plugin')) : (value as Function).apply(target, args);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}