Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync,import): retry per-worker PostgresEngine connects, including CONNECT_TIMEOUT (#5946)
time-attack95f84f416e64
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex f1e1b896ad..b2c3110dfe 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Parallel `--workers` child pools connect through `db.ts`'s `connectWorkerEngine` (`connectWithRetry` with `isRetryableWorkerConnectError`): the startup retry set plus postgres.js `CONNECT_TIMEOUT`, because the parent engine has already reached the same URL, so a timeout there is a starved handshake rather than a bad route (incremental sync's worker pools in `sync/imports.ts` do the same; `GBRAIN_NO_RETRY_CONNECT=1` opts out). Pinned by `test/worker-connect-retry.serial.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex b232c2baa6..8184402852 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Single-source and `--all` deliver that intrinsic >100-file embed deferral the same way: a queued `embed-backfill` on a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit `--no-embed` single-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`. Managed single-source and `--all` CLI envelopes retain structured `failures`, `failure_codes`, `run_id`, `target_commit`, and `counts_scope: run_cumulative`; blocked results exit nonzero. `--retry-failed` requires explicit idle ordinary-source fresh admission with the same options; no managed `--skip-failed`. Google/GitHub API source kinds route before the managed Git cursor. Managed connector `--retry-failed` explicitly admits a linked replacement after authority, source/owner, cursor and idle-state checks; pending work and old terminal receipts are not replaced. Unsupported connector dry-run, Git filtering/working-tree/code and `--skip-failed` options refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority.Refactor wave 1 (W4 sync): `src/commands/sync.ts` is now the façade — it keeps the `SyncResult` / `SyncOpts` types, `runSync`, `resolveParallelism`, `syncOneSource` and re-exports every moved symbol, so importers need no change. The implementation described above lives in `src/commands/sync/` (next entry). Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.-- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed). `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.+- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain with the CONNECT_TIMEOUT-tolerant worker connect retry; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed). `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex dc03b7b52d..614e1bc71f 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -350,6 +350,7 @@ test/upgrade.serial.test.ts R2 R2: mock.module(${repoRoot}src/core/binary-self-utest/v0_28_5-fix-wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)test/v0_37_fix_wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS, OPENAI_API_KEY (+4 more))test/v0_37_gap_fill.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_NON_INTERACTIVE)+test/worker-connect-retry.serial.test.ts R2 R2: mock.module(../src/core/postgres-engine.ts) replaces modules for every file in the processtest/worker-lock-renewal-e2e.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)test/worker-registry.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/workspace-push.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT, PATH (+1 more))diff --git a/src/commands/import.ts b/src/commands/import.tsindex 7af63264a0..577d986ac4 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -844,7 +844,7 @@ export async function runImport(}} else {const { PostgresEngine } = await import('../core/postgres-engine.ts');- const { resolvePoolSize } = await import('../core/db.ts');+ const { resolvePoolSize, connectWorkerEngine } = await import('../core/db.ts');// Each child keeps the established two-connection pool. GBRAIN_POOL_SIZE// controls the parent pool; GBRAIN_MAX_CONNECTIONS clamps the child// count above so the combined footprint stays within the operator's cap.@@ -860,7 +860,7 @@ export async function runImport(for (let i = 0; i < actualWorkers; i++) {if (signal?.aborted) break;const eng = new PostgresEngine();- await eng.connect({ database_url: databaseUrl, poolSize: workerPoolSize });+ await connectWorkerEngine(eng, { database_url: databaseUrl, poolSize: workerPoolSize });workerEngines.push(eng);}diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.tsindex 36478a36cd..9043a30af0 100644--- a/src/commands/sync/imports.ts+++ b/src/commands/sync/imports.ts@@ -423,7 +423,7 @@ async function drainImports(}} else {const { PostgresEngine } = await import('../../core/postgres-engine.ts');- const { resolvePoolSize } = await import('../../core/db.ts');+ const { resolvePoolSize, connectWorkerEngine } = await import('../../core/db.ts');const workerPoolSize = Math.min(2, resolvePoolSize(2));const workerCount = Math.min(effectiveConcurrency, importsToDo.length);const databaseUrl = config.database_url;@@ -439,7 +439,7 @@ async function drainImports(// already-connected engines on any one failure.for (let i = 0; i < workerCount; i++) {const eng = new PostgresEngine();- await eng.connect({ database_url: databaseUrl, poolSize: workerPoolSize });+ await connectWorkerEngine(eng, { database_url: databaseUrl, poolSize: workerPoolSize });workerEngines.push(eng);}diff --git a/src/core/db.ts b/src/core/db.tsindex d03e4d4376..4d4124ceeb 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -5,7 +5,7 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';import type { BrainEngine } from './engine.ts';import { verifySchema } from './schema-verify.ts';-import { isRetryableConnError } from './retry-matcher.ts';+import { isRetryableConnError, isRetryableWorkerConnectError } from './retry-matcher.ts';let sql: ReturnType<typeof postgres> | null = null;let connectedUrl: string | null = null;@@ -430,6 +430,8 @@ export interface ConnectWithRetryOpts {baseDelayMs?: number;noRetry?: boolean;log?: (line: string) => void;+ /** Which errors earn another attempt. Defaults to `isRetryableDbConnectError`. */+ isRetryable?: (err: unknown) => boolean;}export async function connectWithRetry(@@ -449,7 +451,7 @@ export async function connectWithRetry(return;} catch (e: unknown) {lastErr = e;- const retryable = isRetryableDbConnectError(e);+ const retryable = (opts.isRetryable ?? isRetryableDbConnectError)(e);const isLast = i === attempts - 1;if (!retryable || isLast) {throw e;@@ -463,3 +465,19 @@ export async function connectWithRetry(// Unreachable, but TS needs the throw.throw lastErr;}++/**+ * Connect one per-worker pool of a parallel `import` or incremental `sync`.+ * Each is a fresh TCP + TLS + auth handshake, and one that failed used to+ * abort the whole import (under `sync --all`, drop the whole source). Same+ * bounded retry as the CLI's startup connect (3 attempts, 1s/2s backoff;+ * GBRAIN_NO_RETRY_CONNECT=1 opts out), plus CONNECT_TIMEOUT: the parent engine+ * already reached this URL, so a timeout here is a starved handshake, not a+ * bad route (see isRetryableWorkerConnectError).+ */+export function connectWorkerEngine(+ engine: BrainEngine,+ config: EngineConfig & { poolSize: number },+): Promise<void> {+ return connectWithRetry(engine, config, { isRetryable: isRetryableWorkerConnectError });+}diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.tsindex cfcbbcaa95..cae9eee185 100644--- a/src/core/retry-matcher.ts+++ b/src/core/retry-matcher.ts@@ -159,6 +159,29 @@ export function isConnectionEndedError(err: unknown): boolean {return /CONNECTION_ENDED/i.test(msg);}+/**+ * Is this a transient failure of a PER-WORKER pool's connect (the extra+ * PostgresEngine pools that parallel `import` and `sync` open, one per worker)?+ *+ * Everything `isRetryableConnError` accepts, plus postgres.js's library code+ * `CONNECT_TIMEOUT` ("write CONNECT_TIMEOUT host:port", or "undefined:undefined"+ * once the socket has been upgraded to TLS). The general matcher leaves that+ * code out on purpose: on a process's FIRST connect a timeout usually means+ * the host does not route (pg-access-classify's `network_unreachable`), and+ * the fix is the URL, not a retry.+ *+ * A worker pool is different by construction. It is opened only after the+ * parent engine has connected to the same `database_url`, so the route is+ * proven, and a handshake that misses `connect_timeout` there was starved+ * rather than misrouted: most often by the client's own event loop, held by a+ * synchronous stretch (a large repository walk) longer than the timeout. No+ * session was established, so a fresh attempt is safe.+ */+export function isRetryableWorkerConnectError(err: unknown): boolean {+ if (isRetryableConnError(err)) return true;+ return getCode(err) === 'CONNECT_TIMEOUT' || /CONNECT_TIMEOUT/.test(getMessage(err));+}+/*** Convenience: is this error retryable for ANY reason (connection drop OR* statement timeout)? Backfill uses this — callers that need finer-graineddiff --git a/test/db-connect-timeout.test.ts b/test/db-connect-timeout.test.tsindex 809a3f0006..7d4519ae67 100644--- a/test/db-connect-timeout.test.ts+++ b/test/db-connect-timeout.test.ts@@ -20,6 +20,7 @@ import { createServer, type AddressInfo, type Socket } from 'net';import * as db from '../src/core/db.ts';import { ConnectionManager } from '../src/core/connection-manager.ts';import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { withEnv } from './helpers/with-env.ts';const BASE = 'postgres://user:[email protected]:5432/gbrain';@@ -61,13 +62,16 @@ function fatal(): Buffer {async function openSilentEndpoint() {const held: Socket[] = [];let refusing = false;+ let accepted = 0;const server = createServer(socket => {+ accepted += 1;held.push(socket);socket.on('data', () => { if (refusing && !socket.writableEnded) socket.end(fatal()); });});await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));return {url: `postgres://[email protected]:${(server.address() as AddressInfo).port}/gbrain`,+ get accepted() { return accepted; },refuse() { refusing = true; for (const socket of held.splice(0)) socket.end(fatal()); },close() { server.close(); },};@@ -147,3 +151,32 @@ describe('the URL connect_timeout reaches every pool', () => {}});});++describe('worker connect retry composes with the URL connect_timeout (#5946)', () => {+ const quietly = async <T>(fn: () => Promise<T>) => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try { return await fn(); } finally { warnSpy.mockRestore(); }+ };++ test('each retried worker connect gives up at the URL value and dials again', async () => {+ const engine = new PostgresEngine();+ cleanups.push(() => engine.disconnect());+ const started = Date.now();+ const error = await quietly(() => withEnv({ GBRAIN_NO_RETRY_CONNECT: undefined }, () =>+ db.connectWorkerEngine(engine, { database_url: `${endpoint.url}?connect_timeout=1`, poolSize: 1 }).catch(e => e)));+ const elapsed = Date.now() - started;+ expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');+ expect(endpoint.accepted).toBe(3);+ expect(elapsed).toBeGreaterThanOrEqual(5_000);+ expect(elapsed).toBeLessThan(9_500);+ }, 20_000);++ test('GBRAIN_NO_RETRY_CONNECT=1 makes the worker connect a single attempt', async () => {+ const engine = new PostgresEngine();+ cleanups.push(() => engine.disconnect());+ const error = await quietly(() => withEnv({ GBRAIN_NO_RETRY_CONNECT: '1' }, () =>+ db.connectWorkerEngine(engine, { database_url: `${endpoint.url}?connect_timeout=1`, poolSize: 1 }).catch(e => e)));+ expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');+ expect(endpoint.accepted).toBe(1);+ }, 20_000);+});diff --git a/test/minions.test.ts b/test/minions.test.tsindex 29264797b8..2fbc255188 100644--- a/test/minions.test.ts+++ b/test/minions.test.ts@@ -2742,6 +2742,30 @@ describe('connectWithRetry / isRetryableDbConnectError', () => {).rejects.toThrow();expect(attempts).toBe(1);});++ test('connectWithRetry: isRetryable decides which errors earn another attempt; the default is unchanged', async () => {+ const { connectWithRetry } = await import('../src/core/db.ts');+ const { isRetryableWorkerConnectError } = await import('../src/core/retry-matcher.ts');+ const timeout = Object.assign(new Error('write CONNECT_TIMEOUT undefined:undefined'), { code: 'CONNECT_TIMEOUT' });+ let attempts = 0;+ const fakeEngine = {+ connect: async () => {+ attempts++;+ if (attempts === 1) throw timeout;+ },+ } as unknown as Parameters<typeof connectWithRetry>[0];++ await expect(+ connectWithRetry(fakeEngine, { database_url: 'postgres://x' }, { baseDelayMs: 1, log: () => {} })+ ).rejects.toBe(timeout);+ expect(attempts).toBe(1);++ attempts = 0;+ await connectWithRetry(fakeEngine, { database_url: 'postgres://x' }, {+ baseDelayMs: 1, log: () => {}, isRetryable: isRetryableWorkerConnectError,+ });+ expect(attempts).toBe(2);+ });});// ---------------------------------------------------------------------------diff --git a/test/retry-matcher.test.ts b/test/retry-matcher.test.tsindex da066ef828..24fda27eab 100644--- a/test/retry-matcher.test.ts+++ b/test/retry-matcher.test.ts@@ -4,6 +4,7 @@ import {isLockTimeoutError,isRetryableConnError,isRetryableError,+ isRetryableWorkerConnectError,} from '../src/core/retry-matcher.ts';function pgError(code: string, message: string): Error & { code: string } {@@ -134,3 +135,40 @@ describe('isRetryableError', () => {expect(isRetryableError(new Error('foreign key violation'))).toBe(false);});});++describe('isRetryableWorkerConnectError', () => {+ // The two shapes postgres.js 3.4.x builds for `Errors.connection('CONNECT_TIMEOUT', ...)`:+ // the TCP socket's host:port, or undefined:undefined once secure() has swapped+ // in the tls.connect() socket.+ const beforeTls = pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT db.example.test:5432');+ const afterTls = pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT undefined:undefined');++ test('retries CONNECT_TIMEOUT in both shapes, and via the message when a wrapper dropped the code', () => {+ expect(isRetryableWorkerConnectError(beforeTls)).toBe(true);+ expect(isRetryableWorkerConnectError(afterTls)).toBe(true);+ expect(isRetryableWorkerConnectError(new Error('write CONNECT_TIMEOUT db.example.test:5432'))).toBe(true);+ });++ test('accepts everything the general connection matcher accepts', () => {+ for (const err of [+ new Error('connection refused'),+ new Error('the database system is starting up'),+ pgError('CONNECTION_ENDED', 'write CONNECTION_ENDED'),+ pgError('53300', 'too many connections for role'),+ ]) {+ expect(isRetryableConnError(err)).toBe(true);+ expect(isRetryableWorkerConnectError(err)).toBe(true);+ }+ });++ test('still refuses permanent errors and statement / lock timeouts', () => {+ expect(isRetryableWorkerConnectError(pgError('3D000', 'database "gbrain" does not exist'))).toBe(false);+ expect(isRetryableWorkerConnectError(pgError('57014', 'canceling statement due to statement timeout'))).toBe(false);+ expect(isRetryableWorkerConnectError(pgError('55P03', 'could not obtain lock on row'))).toBe(false);+ });++ test('the general matcher is not widened: a first connect still fails fast on CONNECT_TIMEOUT', () => {+ expect(isRetryableConnError(beforeTls)).toBe(false);+ expect(isRetryableConnError(afterTls)).toBe(false);+ });+});diff --git a/test/worker-connect-retry.serial.test.ts b/test/worker-connect-retry.serial.test.tsnew file mode 100644index 0000000000..a15380a81c--- /dev/null+++ b/test/worker-connect-retry.serial.test.ts@@ -0,0 +1,150 @@+/**+ * A per-worker pool connect survives one transient CONNECT_TIMEOUT.+ *+ * Parallel `import` (which `sync --full` runs) and incremental `sync` open one+ * PostgresEngine pool per worker, each a fresh TCP + TLS + auth handshake,+ * after the parent engine has already connected to the same URL. That connect+ * had no retry, and `isRetryableConnError` does not accept postgres.js's+ * `CONNECT_TIMEOUT` anyway, so one handshake that missed `connect_timeout`+ * threw out of the worker loop: the import failed, and under `sync --all` the+ * whole source was dropped. The usual cause is the client, not the server: a+ * long synchronous stretch in the same process (one source's repository walk)+ * holds the event loop while another source's handshake is in flight.+ *+ * Serial (`.serial.test.ts`): a top-level mock.module stands in for the worker+ * engines so each connect can be scripted to fail; nothing dials a database.+ */+import { afterAll, beforeAll, beforeEach, expect, mock, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import * as importFiles from '../src/core/import-file.ts';+import * as sourceFilesystem from '../src/core/minions/source-filesystem.ts';+import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';+import { runImport } from '../src/commands/import.ts';+import { performSync } from '../src/commands/sync.ts';+import { withEnv } from './helpers/with-env.ts';++let connects = 0;+let scriptedFailures: Error[] = [];++mock.module('../src/core/postgres-engine.ts', () => ({+ PostgresEngine: class {+ readonly kind = 'postgres';+ async connect(): Promise<void> {+ connects += 1;+ const failure = scriptedFailures.shift();+ if (failure) throw failure;+ }+ async disconnect(): Promise<void> {}+ },+}));++/** The shape postgres.js throws when the connect timer fires after the TLS upgrade. */+const connectTimeout = () =>+ Object.assign(new Error('write CONNECT_TIMEOUT undefined:undefined'), { code: 'CONNECT_TIMEOUT' });++const home = mkdtempSync(join(tmpdir(), 'gbrain-worker-connect-retry-'));+const emptyDir = join(home, 'empty-import');+const repo = join(home, 'repo');+let engine: PGLiteEngine;++const isolated = (fn: () => Promise<void>) => withEnv({+ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_MAX_CONNECTIONS: undefined,+ GBRAIN_POOL_SIZE: undefined, GBRAIN_NO_RETRY_CONNECT: undefined,+}, fn);++function git(...args: string[]): string {+ return execFileSync('git', ['-C', repo, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'core.hooksPath=/dev/null', ...args], { encoding: 'utf8' }).trim();+}++function writePage(name: string): void {+ writeFileSync(join(repo, `${name}.md`), `---\ntype: note\ntitle: ${name}\n---\n\nWorker connect fixture ${name}.\n`);+}++beforeAll(async () => isolated(async () => {+ mkdirSync(emptyDir);+ mkdirSync(repo);+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'),+ JSON.stringify({ engine: 'postgres', database_url: 'postgresql://example.invalid/gbrain_test' }));+ writePage('base');+ execFileSync('git', ['init', '-q', repo]);+ git('add', '.');+ git('commit', '-qm', 'base');+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+}), 60_000);++afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); });++beforeEach(() => {+ connects = 0;+ scriptedFailures = [];+});++/** Capture the retry line connectWithRetry writes to stderr. */+async function withCapturedWarnings(fn: () => Promise<unknown>): Promise<string[]> {+ const lines: string[] = [];+ const warnSpy = spyOn(console, 'warn').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });+ try { await fn(); } finally { warnSpy.mockRestore(); }+ return lines;+}++test('import: a worker connect that times out once is retried, and the import completes', () => isolated(async () => {+ // The worker pools here are mocks; the import runs inside an already-held+ // fixture-root lock, as nested sync imports do (import-connection-budget's seam).+ const heldRoot = realpathSync(emptyDir);+ const lockSpy = spyOn(sourceFilesystem, 'hasSourceFilesystemLock').mockImplementation(path => path === heldRoot);+ const parent = { kind: 'postgres', executeRaw: async () => [], getConfig: async () => null } as unknown as BrainEngine;+ scriptedFailures = [connectTimeout()];+ try {+ const warnings = await withCapturedWarnings(() => runImport(parent, ['--no-embed', '--workers', '2', emptyDir]));+ expect(connects).toBe(3); // two workers, one of them on its second attempt+ expect(warnings.some(line => line.includes('CONNECT_TIMEOUT') && line.includes('retrying'))).toBe(true);+ } finally {+ lockSpy.mockRestore();+ }+}));++test('sync: a worker connect that times out once is retried, and the source still syncs', () => isolated(async () => {+ // First sync (serial, on PGLite) sets the bookmark; the next commit's two+ // pages then go through the incremental parallel drain.+ const first = await performSync(engine, { repoPath: repo, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });+ expect(first.status).toBe('first_sync');+ writePage('alpha');+ writePage('beta');+ git('add', '.');+ git('commit', '-qm', 'two more pages');++ // The worker engines are mocks, so the per-file import is stubbed. The+ // parent is the PGLite engine reporting itself as Postgres; the real PGLite+ // engine holds the filesystem lock, and the caller-held scope stands in for+ // the per-source lease (`skipLock`), as in import-cancellation's harness.+ const importSpy = spyOn(importFiles, 'importFile').mockImplementation(async (_eng, _file, path) =>+ ({ status: 'imported', slug: path.slice(0, -3), chunks: 1 }));+ const parent = new Proxy(engine, { get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop); return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ scriptedFailures = [connectTimeout()];+ try {+ let result: Awaited<ReturnType<typeof performSync>> | undefined;+ const warnings = await withCapturedWarnings(async () => {+ result = await withSourceFilesystemLock(engine, repo, () => performSync(parent, {+ repoPath: repo, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 2, skipLock: true,+ }));+ });+ expect(result?.status).toBe('synced');+ expect(result?.added).toBe(2);+ expect(importSpy).toHaveBeenCalledTimes(2);+ expect(connects).toBe(3);+ expect(warnings.some(line => line.includes('CONNECT_TIMEOUT') && line.includes('retrying'))).toBe(true);+ } finally {+ importSpy.mockRestore();+ }+}), 60_000);