Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.24.0 fix(sync): delegate sync through a live serve over resolve-IPC (#4362)
Garry Tan7e3ce95bbf4c
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex ed262f20c8..5fdb343318 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 881fa84292..75ac654fe6 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 3e7dee0b21..7e8622ebf8 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -174,6 +174,15 @@ jobs:env:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_testGBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ - name: Run serve-delegated sync suite+ # Serve-delegated sync (PGLite): a real `gbrain serve` owns the+ # single-writer lock while real `gbrain sync` subprocesses delegate+ # through its IPC socket, get SIGKILLed mid-run, and resume. Own+ # invocation line, and deliberately NO DATABASE_URL — the suite is+ # PGLite-only (env DATABASE_URL is a live gbrain config source and+ # would flip the sandboxed brain to Postgres; the file also+ # self-strips). Named files only, no glob.+ run: bun test --timeout=240000 test/e2e/sync-delegation-under-serve.serial.test.tstier2:name: Tier 2 (LLM Skills)diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 58d0044408..2ad5c68893 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.23.0 -->+<!-- gbrain-runbook-stamp: 0.46.24.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c193ad6a5c..358e77702d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,57 @@All notable changes to GBrain will be documented in this file.+## [0.46.24.0] - 2026-08-20++**`gbrain sync` now works while your agent's brain is live.** On a PGLite+brain, a running `gbrain serve` (the MCP server your agent harness spawns)+owns the database's single-writer connection, and a sync used to require+stopping the serve — killing your agent's memory to feed it. Sync now+delegates the run to the serve process over its local IPC socket: the lock+owner does the work, the CLI streams progress, and your agent stays up the+whole time.++### Added+- Serve-delegated sync: `gbrain sync` under a live `gbrain serve` runs inside+ the serve process (secret-gated `sync_start`/`sync_status`/`sync_abort`+ kinds on the existing resolve-IPC socket; never raw SQL). The CLI prints a+ delegation banner with the job id, polls progress (phases, banked-file+ counts), and prints the same result a direct sync would. Ctrl-C aborts to a+ durable checkpoint the next sync resumes from; a second Ctrl-C exits+ without waiting.+- Embeds under delegation are always deferred and drained by the serve's idle+ maintenance sweep afterwards (the serve's environment/API keys apply);+ `--no-embed` also suppresses the drain. The inline embed cost gate is never+ silently bypassed.+- Bounded by construction: the client always sends its resolved hard deadline+ (interactive default 3600s) so a job whose client died still ends;+ `--no-hard-deadline` is the only unbounded encoding. A serve shutdown+ mid-sync aborts the job and waits a bounded settle+ (`GBRAIN_SERVE_SYNC_SETTLE_MS`, default 3000ms) for the checkpoint flush+ before disconnecting.+- Safety posture: unsupported sync flags (`--repo`, `--all`, `--watch`,+ `--exclude`, `--workers`, `--json`, …) refuse BY NAME under delegation+ (default-deny — a silently dropped flag would perform the wrong sync), with+ three remediations in every message. Opt-outs: `--no-delegate` /+ `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve).+ `serve --http` exposes no IPC and keeps the stop-the-serve behavior.++### Changed+- The `LiveServeLockError` message now says sync runs through the live serve+ automatically; stopping the serve remains the remedy for OTHER CLI write+ commands.+- `docs/architecture/serve-sync-concurrency.md` rewritten around delegation+ (limits table, crash/resume notes, unchanged hang-triage recipes).++To take advantage of v0.46.24.0:+- `gbrain upgrade` (or reinstall the binary), then restart any running+ `gbrain serve` so it registers the sync IPC kinds — a serve from an older+ version answers with a typed "restart the serve" refusal instead of+ delegating.+- If a serve dies mid-delegated-sync, re-run `gbrain sync` to resume from the+ checkpoint; a dead-PID sync lock younger than 60s can be cleared with+ `gbrain sync --force-break-lock`.+## [0.46.23.0] - 2026-08-19**A 23-contribution community wave, plus an end to silently lost pages.**diff --git a/README.md b/README.mdindex c41de8a243..85b76d0513 100644--- a/README.md+++ b/README.md@@ -468,10 +468,13 @@ gbrain sync --no-schema-pack --no-pull --no-embed --yes`gbrain schema lint` warns on the classic nested-quantifier ReDoSshapes (`(a+)+`, `(a*)*`, …) in pack regexes, and the runtime capsinference-regex input length (override via `GBRAIN_MAX_REGEX_INPUT_CHARS`).-Third, on a PGLite brain, stop `gbrain serve` before a large sync —-PGLite is single-writer and a live MCP server contends for the write-lock. See [`docs/architecture/serve-sync-concurrency.md`](docs/architecture/serve-sync-concurrency.md)-for the full triage.+Third, on a PGLite brain with a live `gbrain serve` (your agent's MCP+server), `gbrain sync` delegates the run to the serve process over its+local IPC socket — the lock owner does the work, your agent stays up,+and Ctrl-C aborts to a checkpoint the next sync resumes from. Embeds+defer to the serve's background sweep. See+[`docs/architecture/serve-sync-concurrency.md`](docs/architecture/serve-sync-concurrency.md)+for the limits (unsupported flags, `serve --http`) and the full triage.**`gbrain init --migrate-only` / a schema migration fails on Windowswith `getaddrinfo ENOTFOUND`?** Upgrade — schema bring-up now runs itsdiff --git a/TODOS.md b/TODOS.mdindex 42cdb9ab27..56b9d80672 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,38 @@# TODOS+## Serve-delegated sync follow-ups (v0.46.24.0)++- [ ] **P3 — `sync --all` under delegation.** **What:** delegate a multi-source+ sync per-source through a live serve. **Why:** v0.46.24.0 refuses `--all`+ under a live serve — the client has no engine to enumerate sources, and the+ PGLite fan-out is serial anyway. **Context:** the serve could enumerate its+ own sources and run per-source delegated jobs sequentially (the runner is+ single-flight by design), or the client could gain a `sync_sources` IPC kind.+ Per-source `gbrain sync --source X` delegates today, so this is convenience,+ not capability. Start: `src/commands/sync-delegate.ts` (the `--all` refusal),+ `src/core/serve-sync-runner.ts`. Effort: M (CC: S). Priority: P3.+- [ ] **P3 — `serve --http` sync IPC.** **What:** register the resolve-IPC+ listener (and the sync kinds) on the HTTP serve path. **Why:** delegation is+ stdio-serve-only — an HTTP serve still forces stop-the-serve syncs.+ **Context:** `src/commands/serve-http.ts` is at its module-size cap; the+ wiring needs its own module. The IPC block in `src/mcp/server.ts:186` is the+ shape to extract/share. Effort: M (CC: S). Priority: P3.+- [ ] **P3 — delegated post-sync steps.** **What:** the direct-CLI post-steps+ (`manageGitignoreAtGitRoot`, the extraction-lag nudge) don't run for+ delegated syncs. **Why:** both need an engine or repo-adjacent context the+ client doesn't have; both already have "defer to next clean sync" postures,+ so nothing breaks — but a brain synced ONLY through delegation never gets+ the .gitignore management. **Context:** run them serve-side after a done+ job, or client-side without an engine where possible. Start:+ `src/core/serve-sync-runner.ts` (post-done hook). Effort: S. Priority: P3.+- [ ] **P3 — N-process delegation hammer in tests/heavy/.** **What:** a+ `tests/heavy/serve_sync_delegation.sh` modeled on `sync_lock_regression.sh`:+ one serve + M concurrent `gbrain sync` clients, assert one delegated job at+ a time (`busy` for the rest), no leaked lock rows, bounded MCP latency+ during the run. **Why:** the e2e covers the arc; the hammer covers+ contention shapes. Effort: M. Priority: P3.++## Key-aware model routing wave follow-ups (filed 2026-08-17; plan: ~/.claude/plans/system-instruction-you-are-working-enchanted-lark.md)- [ ] **P2 — More providers in `PROVIDER_TIER_DEFAULTS` (+ discovery).** **What:**@@ -2137,7 +2170,9 @@ are the bar). Plan + GSTACK REVIEW REPORT at`gbrain serve` or any write path blocks on the lock until watch exits.WATCH_HELP documents the monopoly; the fix is an IPC rung in watch'sresolver (reuse `resolveViaIpc` like the ambient reflex's ladder) so a- running serve answers and watch never takes the lock. **Why:** watch ++ running serve answers and watch never takes the lock (v0.46.24.0's+ serve-delegated sync built the additive-kind groundwork — `sync_start`/+ `sync_status` in resolve-ipc.ts are the pattern to copy). **Why:** watch +serve concurrently is the natural agent topology. **Where:**`src/commands/watch.ts`, `src/core/context/resolve-ipc.ts` (red-team RT2).- [ ] **P3 — capability/version gate for host-injected reflex resolvers.**diff --git a/VERSION b/VERSIONindex b972109fc4..345bfa49d4 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.23.0\ No newline at end of file+0.46.24.0diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex c65c5c61da..c7d2cdb33a 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -30,7 +30,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` (#4143) early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would reopen the #1337 race). Teardown defense is layered and honestly scoped (#4284): the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved, the #1762 re-pump class) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the `#4284` structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary regresses to the Bun-vfs ENOENT class (#1340). `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver (#4116): tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).-- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.+- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (ported from electric-sql/pglite PR #994 by @yestheboxer, Apache-2.0, rejected upstream as "should be a separate tool" — gbrain is that tool). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the #3596 engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Its confirmation prompt (and `src/commands/reinit-pglite.ts`'s) writes to stderr so `--json` stdout stays clean, refuses non-TTY stdin in-prompt (defense-in-depth behind the caller-side "Non-TTY environment requires --yes" guard), resolves `false` on EOF/close instead of parking forever on a closed or piped stdin, and cleans up its listeners; `--yes`/`-y` stays the non-interactive path. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the #2348 concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.@@ -50,7 +50,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/reindex-code.ts` — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds (#2139); `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE regression for the cost-preview fix), `test/reindex-cost-refusal.test.ts`.- `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name used by FTS. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.-- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). 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 prior 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 (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `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) not the old 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 — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer 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). 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 #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); 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 no longer exits 2 — it auto-defers; #2139.) 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). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. 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 (#1970). 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 (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, 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 (#2426 — "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.serial.test.ts`. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping 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 `willEmbedSynchronously` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, parallel) 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, or `--serial`) 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 embeds to capped backfill jobs and exits 0 (NEVER exit 2 — the wedged-cron fix); `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). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | posture_tokenmax`) + a paste-ready `hint`; `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` (PGLite single-writer serve↔sync contention + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). 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 (#753/#774): `--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 #1433 metafile posture); an all-excluded run warns loudly (NAV-4). 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`: Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: 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.serial.test.ts`.+- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). 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 prior 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 (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `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) not the old 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 — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer 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). 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 #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); 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 no longer exits 2 — it auto-defers; #2139.) 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). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. 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 (#1970). 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 (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, 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 (#2426 — "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.serial.test.ts`. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping 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 `willEmbedSynchronously` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, parallel) 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, or `--serial`) 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 embeds to capped backfill jobs and exits 0 (NEVER exit 2 — the wedged-cron fix); `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). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | posture_tokenmax`) + a paste-ready `hint`; `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 (#753/#774): `--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 #1433 metafile posture); an all-excluded run warns loudly (NAV-4). 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`: Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: 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.serial.test.ts`.- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column).- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` (#1972) — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the #2084 contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.@@ -296,7 +296,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces thisv0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.-- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. Pinned by `test/serve-stdio-lifecycle.test.ts`.+- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. On PGLite brains the resolve-IPC block also registers the serve-delegated sync handlers (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) in their OWN try/catch — a runner failure logs `[serve-sync] handlers unavailable` and the original kinds still start — gated off with `GBRAIN_SERVE_SYNC_IPC=0`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts`.- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the extracted validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface, D7), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock` (D8). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier (amendment 33/D10): true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the amendment-33 honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). New logging paths route through this helper, not `JSON.stringify(params)`.- `src/mcp/validate-params.ts` — param normalization + validation extracted from dispatch (WP3, direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per process — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts.- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list (WP1). `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts.@@ -307,7 +307,7 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind})- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. Every OAuth/admin/audit SQL call routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page, in the `default` source, since untrusted payloads carry no source grant). confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count` (amendment 23 stopgap). Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (amendment 33/D10; the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client).- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (the #2339 class; PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases). Credit @Aragorn2046 + @seungsu-kr.+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`). Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases). Credit @Aragorn2046 + @seungsu-kr.- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); bare `catch {}` in `verifyAccessToken`/`getClient` replaced by `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; pre-v0.34 clients backfill to `source_id='default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)` (the inline version used `rest[takesIdx + 1]` resolving to `rest[0]` when `takesIdx === -1`, excluding the name from the positional search). Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.@@ -567,9 +567,10 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (#4043; fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push previously blocked harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content); also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip).- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.-- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched.+- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob.- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP).+- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the #2139 cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo).diff --git a/docs/architecture/serve-sync-concurrency.md b/docs/architecture/serve-sync-concurrency.mdindex 13c21bf60a..802a3f1da2 100644--- a/docs/architecture/serve-sync-concurrency.md+++ b/docs/architecture/serve-sync-concurrency.md@@ -1,33 +1,67 @@# `gbrain serve` ↔ `gbrain sync` concurrency (PGLite)-**Short version: on a PGLite brain, stop `gbrain serve` before a large sync.**+**Short version: on a PGLite brain, `gbrain sync` runs even while `gbrain+serve` is live — the sync is delegated to the serve process, which already+owns the single-writer connection.**-## Why+## How it worksPGLite is a single-writer embedded Postgres (WASM). A running `gbrain serve`-(stdio or HTTP MCP) holds an open PGLite connection on the brain's data-directory. `gbrain sync` needs to write to that same data directory. The two-contend for PGLite's single-writer connection / write-lock — **this is NOT the-`gbrain-sync` advisory lock** (that's a separate, DB-row coordination lock for-two concurrent *syncs*). Confusing the two sends you debugging the wrong surface.--Symptoms of serve↔sync contention on PGLite:--- `gbrain sync` blocks acquiring the PGLite write lock, or makes very slow- progress, while a `gbrain serve` process is alive on the same brain.-- Killing stale `gbrain serve` MCP processes frees the lock and sync proceeds.--## What to do--1. Stop any `gbrain serve` process for this brain before a large sync:- ```bash- pkill -f 'gbrain serve' # or stop your MCP client / Claude Desktop / Cursor- gbrain sync --no-pull --no-embed --yes- ```-2. Restart `gbrain serve` after the sync completes.--This contention does **not** apply to the Postgres engine — Postgres tolerates-concurrent connections, so `serve` and `sync` can run simultaneously there.+(stdio MCP) holds an open PGLite connection on the brain's data directory for+its lifetime, guarded by the data-dir lock (`<dataDir>/.gbrain-lock/`), and a+live holder is never displaced (#2348).++When `gbrain sync` finds a live serve holding the lock, it does not fail —+it delegates:++1. The CLI probes the lock file (read-only). A live `serve` holder routes the+ sync over the serve's IPC socket (`<dataDir>/.gbrain-resolve.sock`,+ secret-gated `sync_start` / `sync_status` / `sync_abort` kinds — the same+ typed-narrow-request channel the retrieval reflex uses; raw SQL never+ crosses the wire).+2. The serve process runs `performSync` on the connection it already owns+ (one delegated job at a time) and the CLI polls progress (phases, banked+ file counts) once a second, printing the final result exactly like a+ direct sync.+3. Ctrl-C sends `sync_abort`: the job settles as a typed partial and the+ next `gbrain sync` resumes from the durable checkpoint. A second Ctrl-C+ exits without waiting.+4. Embeds are ALWAYS deferred under delegation (the inline embed cost gate+ lives in the direct-CLI path) — the serve's idle maintenance sweep drains+ pending embeds afterwards, using the serve process's environment/API keys.+ `--no-embed` also suppresses that drain.++MCP traffic and the delegated sync share the serve's one connection, so the+agent stays *available* throughout, with degraded latency during heavy import+phases (long statements block the event loop; the import yields periodically).++## Limits++| Situation | Behavior |+|---|---|+| Unsupported flags (`--repo`, `--all`, `--watch`, `--workers`, `--exclude`, `--src-subpath`, `--json`, `--break-lock`, anything unclassified) | Refuses by name (default-deny — a silently dropped flag would perform the wrong sync). Drop the flag, stop the serve, or pass `--no-delegate`. |+| `serve --http` | No IPC listener — delegation unavailable; sync refuses politely. Stop the HTTP serve to sync. |+| Serve older than this gbrain version | Typed `stale_serve` refusal — restart the serve on the current version. |+| Mounted brains (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`) | Never delegate; the normal connect path applies. |+| Opt-outs | `--no-delegate` or `GBRAIN_SYNC_NO_DELEGATE=1` (client), `GBRAIN_SERVE_SYNC_IPC=0` (serve refuses to register the kinds). |+| Deadlines | The client always sends its resolved hard deadline (interactive default 3600s); the serve bounds the job even if the client dies. `--no-hard-deadline` is the only unbounded encoding. |+| Serve shutdown mid-sync | The serve aborts the job and waits a bounded settle (`GBRAIN_SERVE_SYNC_SETTLE_MS`, default 3000) for the checkpoint flush before disconnecting; the next sync resumes. |++Contention with a live **non-serve** holder (another sync, embed, dream) is+unchanged: bounded 1s-poll wait up to the acquire timeout — that coordination+belongs to the `gbrain-sync:*` advisory row lock, which is a DIFFERENT lock+from the PGLite data-dir lock. Confusing the two sends you debugging the+wrong surface. None of this applies to the Postgres engine, which tolerates+concurrent connections.++## If the serve dies mid-sync++Progress is checkpointed — re-run `gbrain sync` to resume. Two notes:++- The dead serve's `gbrain-sync:<source>` row lock is only auto-reclaimed+ once it is ≥60s old (PID-reuse defense). If the re-run reports a dead-PID+ sync lock, `gbrain sync --force-break-lock` clears it immediately.+- The dead serve's PGLite data-dir lock is reaped automatically (dead PID).## Diagnosing a sync hangdiff --git a/llms-full.txt b/llms-full.txtindex 2834e65fda..fd4939ee2f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2150,10 +2150,13 @@ gbrain sync --no-schema-pack --no-pull --no-embed --yes`gbrain schema lint` warns on the classic nested-quantifier ReDoSshapes (`(a+)+`, `(a*)*`, …) in pack regexes, and the runtime capsinference-regex input length (override via `GBRAIN_MAX_REGEX_INPUT_CHARS`).-Third, on a PGLite brain, stop `gbrain serve` before a large sync —-PGLite is single-writer and a live MCP server contends for the write-lock. See [`docs/architecture/serve-sync-concurrency.md`](docs/architecture/serve-sync-concurrency.md)-for the full triage.+Third, on a PGLite brain with a live `gbrain serve` (your agent's MCP+server), `gbrain sync` delegates the run to the serve process over its+local IPC socket — the lock owner does the work, your agent stays up,+and Ctrl-C aborts to a checkpoint the next sync resumes from. Embeds+defer to the serve's background sweep. See+[`docs/architecture/serve-sync-concurrency.md`](docs/architecture/serve-sync-concurrency.md)+for the limits (unsupported flags, `serve --http`) and the full triage.**`gbrain init --migrate-only` / a schema migration fails on Windowswith `getaddrinfo ENOTFOUND`?** Upgrade — schema bring-up now runs itsdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex f23d12baa3..58582eaba3 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 805bb36153..470b7d48ab 100644--- a/package.json+++ b/package.json@@ -170,7 +170,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.23.0",+ "version": "0.46.24.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 504a901be7..e3197769b9 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex b41158af6b..dc029f06a1 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex e834ea4291..019d4915e3 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.23.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.24.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex abe6da8b52..65da5df778 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 1cd67c6cf8..4954f9ee7b 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.23.0",+ "version": "0.46.24.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 1cfb807390..3f3cd2aec0 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.23.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.24.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex ca37baa3ef..a7f2586fe7 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.23.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.24.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex f4515ad892..5777e74384 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -15,6 +15,15 @@// No brace expansion, no ?, no [ ].export const E2E_TEST_MAP: Record<string, string[]> = {+ // Serve-delegated sync: wire types, job runner, CLI ladder, and the IPC+ // plumbing all feed the delegation-under-serve E2E.+ "src/core/context/sync-ipc.ts": ["test/e2e/sync-delegation-under-serve.serial.test.ts"],+ "src/core/serve-sync-runner.ts": ["test/e2e/sync-delegation-under-serve.serial.test.ts"],+ "src/commands/sync-delegate.ts": ["test/e2e/sync-delegation-under-serve.serial.test.ts"],+ "src/core/context/resolve-ipc.ts": [+ "test/e2e/bootstrap-hook-under-serve.serial.test.ts",+ "test/e2e/sync-delegation-under-serve.serial.test.ts",+ ],// Source-aware ranking, hybrid search, intent classification."src/core/search/**": ["test/e2e/search-quality.test.ts",diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 8795175d8a..878a75a760 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,9 +8,9 @@ src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7src/core/postgres-engine.ts 5837 ratchet grown v0.46.23.0: putPage empty-overwrite guard (#4335)src/core/pglite-engine.ts 5881 ratchet grown v0.46.23.0: putPage empty-overwrite guard (#4335)src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted-src/commands/sync.ts 4311 ratchet grown v0.46.22.0 phone wave: github source kind (#4104)+src/commands/sync.ts 4327 ratchet grown v0.46.24.0 serve-delegated sync: onProgress seam + help textsrc/core/ai/gateway.ts 4428 ratchet watchlist; merged: dream-wave turn permits + key-aware effective-model reconfigure + env-only worker refresh + discovery endpoint-trust docstring-src/cli.ts 3486 ratchet grown v0.46.23.0: awaited stdout delivery (#3423)+src/cli.ts 3499 ratchet grown v0.46.24.0: serve-delegated sync preflight hooksrc/core/cycle.ts 3080 ratchet grown v0.46.20.0 phase-boundary split (resolveCyclePhases + normalizeQueuedSourcePhases + deriveStatus exclusion filter)src/commands/serve-http.ts 3194 ratchet grown v0.46.23.0 review fix wave: github-kind webhook gating + case-insensitive repo matchsrc/commands/jobs.ts 3027 ratchet grown v0.46.22.0 phone wave: github source sync job (#4104)diff --git a/src/cli.ts b/src/cli.tsindex 104644e7f8..e800cdeb69 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2483,6 +2483,19 @@ async function handleCliOnly(command: string, args: string[]) {}}+ // Serve-delegated sync preflight (PGLite host brains only): a live `gbrain+ // serve` owns the single-writer lock, so connectEngine below would throw+ // LiveServeLockError — instead the sync runs INSIDE the serve over its IPC+ // socket (commands/sync-delegate.ts). Handled === delegated or politely+ // refused (exit verdict set inside); false falls through unchanged.+ if (command === 'sync') {+ const cfgSync = loadConfig();+ if (cfgSync?.engine === 'pglite' && cfgSync.database_path && !cfgSync.database_url) {+ const { maybeDelegateSyncToServe } = await import('./commands/sync-delegate.ts');+ if (await maybeDelegateSyncToServe(cfgSync.database_path, args)) return;+ }+ }+// Thin-client `jobs` dispatch: `list` and `get` route over MCP (v0.32// routing branches in commands/jobs.ts) and never touch a local engine —// but falling through to connectEngine() below fabricates an emptydiff --git a/src/commands/serve.ts b/src/commands/serve.tsindex d4952f8a8b..c73c51d2de 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -3,6 +3,12 @@ import type { BrainEngine } from '../core/engine.ts';import { startMcpServer } from '../mcp/server.ts';import { VERB_NAMES } from '../core/verbs.ts';import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';+import {+ delegatedSyncSettleMs,+ isDelegatedSyncRunning,+ maybeDrainDeferredEmbeds,+ shutdownDelegatedSync,+} from '../core/serve-sync-runner.ts';// Maximum time the stdio path will wait for engine.disconnect() (PGLite// close + advisory lock release) before forcing exit. Keeps a wedged@@ -388,15 +394,25 @@ function installStdioLifecycle(// to trap us forever. If we hit the deadline we still exit; the// lock dir is advisory and the next process's stale-lock check// (process.kill(pid, 0) → ESRCH) will reclaim it.+ // A running delegated sync extends the deadline by exactly its settle+ // bound: shutdownDelegatedSync must finish its abort+settle against the+ // live engine BEFORE disconnect, and a fixed 5s would force-exit mid-+ // settle (second-outside-voice finding EV1).+ const settleExtensionMs = isDelegatedSyncRunning() ? delegatedSyncSettleMs() : 0;const deadline = setTimeout(() => {deps.log(- `GBrain MCP server: cleanup deadline (${CLEANUP_DEADLINE_MS}ms) exceeded — forcing exit`,+ `GBrain MCP server: cleanup deadline (${CLEANUP_DEADLINE_MS + settleExtensionMs}ms) exceeded — forcing exit`,);deps.exit(0);- }, CLEANUP_DEADLINE_MS);+ }, CLEANUP_DEADLINE_MS + settleExtensionMs);deadline.unref?.();Promise.resolve()+ // Idempotent shared promise — mcp/server.ts's shutdown races here on+ // the same signals; whichever runs first does the abort+settle, the+ // other awaits it. Must precede disconnect (settle writes need the+ // live engine; the disconnect-mode drain is allowAbort:false).+ .then(() => shutdownDelegatedSync()).then(() => engine.disconnect()).catch((err: unknown) => {const msg = err instanceof Error ? err.message : String(err);@@ -502,12 +518,18 @@ function installStdioLifecycle(const sweepEnabled = opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0');if (sweepEnabled) {const runIdleSweep = opts.sweep ?? (async (e: BrainEngine) => {+ // A delegated sync owns the event loop right now — sweeping under it+ // is pointless contention; the next idle tick catches up.+ if (isDelegatedSyncRunning()) return;// Lazy import keeps the sweep core off the serve boot path.const { runMaintenanceSweep } = await import('../core/sweep.ts');await runMaintenanceSweep(e, {sourceId: process.env.GBRAIN_SOURCE || 'default',budgetMs: IDLE_SWEEP_BUDGET_MS,});+ // Deferred-embed drain: delegated syncs always run noEmbed (the #2139+ // cost gate lives in runSync); the lock owner closes that loop here.+ await maybeDrainDeferredEmbeds(e);});let stdinSawData = false;let sweepInFlight = false;diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsnew file mode 100644index 0000000000..4a9a727887--- /dev/null+++ b/src/commands/sync-delegate.ts@@ -0,0 +1,375 @@+/**+ * Serve-delegated sync — the CLI half (decision ladder + poll loop).+ *+ * On a PGLite brain a live `gbrain serve` holds the single-writer lock for+ * its lifetime, so `gbrain sync` cannot open the brain (LiveServeLockError+ * since #2348 — a live holder is never displaced). Instead of failing, the+ * pre-connect hook in cli.ts calls maybeDelegateSyncToServe: when the holder+ * is a live serve, the sync runs INSIDE the serve over the resolve-IPC socket+ * (sync_start / sync_status / sync_abort; wire shapes in+ * core/context/sync-ipc.ts, execution in core/serve-sync-runner.ts) and this+ * module polls progress and prints the result.+ *+ * Decision ladder (returns false = fall through to the normal connect path):+ * 0. --no-delegate / GBRAIN_SYNC_NO_DELEGATE=1 → false (opt-out).+ * 1. Non-host brain (mounts) → false — delegation targets the host data dir.+ * 2. No live holder, or a live NON-serve holder → false (existing behavior:+ * dead-PID reap / bounded wait in acquireLock).+ * 3. Live serve + any argv token outside the explicit allowlist →+ * DEFAULT-DENY refusal naming the flag (a silently-dropped --exclude+ * would perform the WRONG sync; refusing is the only safe default).+ * 4. Live serve + socket answers → delegate: banner, 1s status polls,+ * Ctrl-C → sync_abort (second Ctrl-C hard-exits), printSyncResult.+ * 5. Live serve + no socket / stale serve / unauthorized → polite typed+ * refusal with remediation, exit verdict 1 — never a raw stack.+ *+ * Every refusal names three ways out: drop the flag (when flag-caused), stop+ * the serve, or --no-delegate.+ */++import { randomUUID } from 'node:crypto';+import { existsSync } from 'node:fs';+import { serr } from '../core/console-prefix.ts';+import { probeLivePgliteHolder } from '../core/bootstrap/uninstall.ts';+import {+ IPC_UNAVAILABLE,+ readIpcSecret,+ requestSyncAbort,+ requestSyncStart,+ requestSyncStatus,+ resolveSocketPath,+ type SyncStartIpcResult,+} from '../core/context/resolve-ipc.ts';+import type { DelegatedSyncOptions, SyncStatusResponse, WireSyncResult } from '../core/context/sync-ipc.ts';+import type { SyncResult } from './sync.ts';++/** Poll cadence for sync_status while a delegated job runs. */+const POLL_MS = 1000;+/**+ * Consecutive failed polls tolerated before declaring the socket dead. A+ * delegated import can block the serve's event loop for stretches (long+ * synchronous WASM statements), so transient timeouts are EXPECTED; the PID+ * probe below distinguishes "busy" from "gone" every PID_PROBE_EVERY misses.+ */+const MAX_POLL_FAILURES = 60;+const PID_PROBE_EVERY = 5;++/**+ * Flags forwardable over the wire (boolean → DelegatedSyncOptions field).+ * Everything not in this table, VALUE_FLAGS, or IGNORED_FLAGS refuses —+ * default-deny is what keeps a future flag from being silently dropped.+ */+export const WIRE_BOOL_FLAGS: Record<string, keyof DelegatedSyncOptions> = {+ '--full': 'full',+ '--dry-run': 'dryRun',+ '--no-pull': 'noPull',+ '--no-embed': 'noEmbed',+ '--no-extract': 'noExtract',+ '--no-schema-pack': 'noSchemaPack',+ '--skip-failed': 'skipFailed',+ '--retry-failed': 'retryFailed',+ '--include-gitignored': 'includeGitignored',+};+/** Value-taking flags the ladder consumes itself (never forwarded verbatim). */+export const VALUE_FLAGS = new Set(['--source', '--timeout', '--hard-deadline']);+/** Flags that are meaningful only outside delegation (or handled pre-ladder). */+export const IGNORED_FLAGS = new Set(['--yes', '--no-delegate', '--no-hard-deadline']);++export type ParsedDelegatedArgs =+ | { ok: true; options: Omit<DelegatedSyncOptions, 'timeoutSeconds'>; explicitSource: string | null }+ | { ok: false; refused: string };++/**+ * Pure argv classifier (exported for the drift-pin test). timeoutSeconds is+ * derived separately (resolveSyncHardDeadline needs env/TTY context).+ */+export function parseDelegatedSyncArgs(args: string[]): ParsedDelegatedArgs {+ const options: Record<string, unknown> = {};+ let explicitSource: string | null = null;+ for (let i = 0; i < args.length; i++) {+ const tok = args[i];+ if (WIRE_BOOL_FLAGS[tok]) {+ options[WIRE_BOOL_FLAGS[tok]] = true;+ continue;+ }+ if (IGNORED_FLAGS.has(tok)) continue;+ if (VALUE_FLAGS.has(tok)) {+ const v = args[i + 1];+ if (v === undefined || v.startsWith('--')) return { ok: false, refused: `${tok} (missing value)` };+ if (tok === '--source') explicitSource = v;+ i++; // --timeout / --hard-deadline are consumed by the deadline derivation+ continue;+ }+ // Default-deny: subcommands (`trigger`), unsupported flags (--repo,+ // --all, --watch, --exclude, --workers, --json, …) and anything future.+ return { ok: false, refused: tok };+ }+ return { ok: true, options: options as Omit<DelegatedSyncOptions, 'timeoutSeconds'>, explicitSource };+}++/**+ * The client's hard deadline for the delegated job, in seconds. 0 = the user+ * explicitly waived the bound (--no-hard-deadline) — the ONLY unbounded+ * encoding; an interactive TTY default (null from resolveSyncHardDeadline)+ * maps to the same 3600s the non-TTY default uses, so a job whose client+ * dies is always bounded.+ */+export async function deriveDelegatedTimeoutSeconds(+ args: string[],+ opts: { isTty?: boolean; env?: Record<string, string | undefined> } = {},+): Promise<number> {+ if (args.includes('--no-hard-deadline')) return 0;+ const { resolveSyncHardDeadline } = await import('../core/sync-reconcile.ts');+ const res = resolveSyncHardDeadline(args, {+ isTty: opts.isTty ?? Boolean(process.stdout.isTTY),+ env: opts.env ?? process.env,+ });+ if (!res) return 3600;+ return Math.max(1, Math.round(res.deadlineMs / 1000));+}++async function setVerdict(code: number): Promise<void> {+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');+ setCliExitVerdict(code);+}++function remediation(pid: number, extra?: string): string {+ return (+ (extra ? `${extra} ` : '') ++ `Ways out: ${extra ? '' : 'drop the unsupported flag, '}stop the serve (PID ${pid}) and re-run, ` ++ `or pass --no-delegate to skip delegation.`+ );+}++/**+ * Pre-connect delegation ladder. Returns true when the sync was HANDLED here+ * (delegated to a live serve, or politely refused with the exit verdict set);+ * false falls through to the normal connectEngine path unchanged.+ */+export async function maybeDelegateSyncToServe(dataDir: string, args: string[]): Promise<boolean> {+ // 0. Explicit opt-outs.+ if (args.includes('--no-delegate') || process.env.GBRAIN_SYNC_NO_DELEGATE === '1') return false;+ // 1. Mounts never delegate — the socket/secret/lock all belong to the HOST+ // brain's data dir; a mounted brain's sync must take the normal path.+ try {+ const { resolveBrainId } = await import('../core/brain-resolver.ts');+ const { getCliOptions } = await import('../core/cli-options.ts');+ if (resolveBrainId(getCliOptions().brain) !== 'host') return false;+ } catch { /* resolver trouble → normal path (fail open to old behavior) */ }+ // 2. Holder probe (read-only; never reaps).+ const holder = probeLivePgliteHolder(dataDir);+ if (!holder || !holder.serve) return false;++ // 3. Argv gate (default-deny).+ const parsed = parseDelegatedSyncArgs(args);+ if (!parsed.ok) {+ serr(+ `[sync] a live \`gbrain serve\` (PID ${holder.pid}) holds this PGLite brain, and ` ++ `\`${parsed.refused}\` isn't supported through serve-delegated sync. ` ++ remediation(holder.pid),+ );+ await setVerdict(1);+ return true;+ }++ // Engine-free source tiers (env var, .gbrain-source dotfile) — the client+ // has no engine to run the DB tiers; absent → the serve's bound/default.+ let sourceId: string | undefined;+ try {+ const { resolveSourceIdEngineFree } = await import('../core/source-resolver.ts');+ const resolved = resolveSourceIdEngineFree(parsed.explicitSource);+ if (resolved === '__all__') {+ serr(+ `[sync] --source __all__ isn't supported through serve-delegated sync (the client has ` ++ `no engine to enumerate sources). ${remediation(holder.pid, 'Sync one source at a time (--source <id>).')}`,+ );+ await setVerdict(1);+ return true;+ }+ sourceId = resolved ?? undefined;+ } catch (e) {+ serr(`[sync] ${e instanceof Error ? e.message : String(e)}`);+ await setVerdict(1);+ return true;+ }++ // 4. Socket + secret.+ const sock = resolveSocketPath(dataDir);+ const secret = readIpcSecret(dataDir);+ if (!existsSync(sock) || !secret) {+ serr(+ `[sync] a live \`gbrain serve\` (PID ${holder.pid}) holds this PGLite brain's ` ++ `single-writer lock but exposes no sync IPC (older gbrain, \`serve --http\`, or ` ++ `GBRAIN_SERVE_SYNC_IPC=0). ` + remediation(holder.pid, 'Restart that serve on this gbrain version.'),+ );+ await setVerdict(1);+ return true;+ }++ const options: DelegatedSyncOptions = {+ ...parsed.options,+ ...(sourceId ? { sourceId } : {}),+ timeoutSeconds: await deriveDelegatedTimeoutSeconds(args),+ };+ const clientToken = randomUUID();++ let start = await requestSyncStart(sock, { secret, clientToken, options });+ if (start === IPC_UNAVAILABLE) {+ // Race: the serve may have died between probe and connect — or it started+ // the job and the ack was lost. Re-probe; alive → ONE retry with the SAME+ // token (busy/attach semantics make it safe), dead → normal path.+ const still = probeLivePgliteHolder(dataDir);+ if (!still || !still.serve) return false;+ start = await requestSyncStart(sock, { secret, clientToken, options });+ if (start === IPC_UNAVAILABLE) {+ serr(+ `[sync] the live \`gbrain serve\` (PID ${holder.pid}) is not answering its IPC socket. ` ++ remediation(holder.pid, 'It may be wedged.'),+ );+ await setVerdict(1);+ return true;+ }+ }+ if ('degraded' in (start as object)) {+ serr(+ `[sync] the running \`gbrain serve\` (PID ${holder.pid}) predates serve-delegated sync. ` ++ remediation(holder.pid, 'Restart it on this gbrain version.'),+ );+ await setVerdict(1);+ return true;+ }+ const startResp = start as Exclude<SyncStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;+ if (!startResp.ok) {+ const messages: Record<string, string> = {+ busy: `another delegated sync (job ${startResp.jobId ?? '?'}) is already running inside the serve — wait for it to finish and re-run.`,+ unauthorized: `the serve rejected the IPC secret — restart the serve (it re-provisions \`.gbrain-ipc-secret\`) and re-run.`,+ shutting_down: `the serve is shutting down — re-run in a moment (or after it exits, sync runs directly).`,+ source_mismatch: `the serve is bound to a different source than this sync targets — run \`gbrain sync --source <the serve's source>\`, or stop the serve to sync this source directly.`,+ unsupported_kind: `the serve has sync delegation disabled (GBRAIN_SERVE_SYNC_IPC=0 or a startup failure).`,+ };+ const detail = messages[startResp.error ?? ''] ??+ `the serve refused the delegated sync (${startResp.error}).`;+ serr(`[sync] ${detail} ${remediation(holder.pid, '')}`);+ await setVerdict(1);+ return true;+ }++ const jobId = startResp.jobId!;+ if (startResp.completed) {+ serr(`[sync] attached to an already-completed delegated sync (job ${jobId}).`);+ } else {+ serr(+ `[sync] live \`gbrain serve\` (PID ${holder.pid}) holds the PGLite lock — delegating ` ++ `the sync through it (job ${jobId}; Ctrl-C aborts, progress is checkpointed).`,+ );+ }++ return pollToCompletion({ dataDir, sock, secret, jobId, pid: holder.pid, options });+}++async function pollToCompletion(ctx: {+ dataDir: string;+ sock: string;+ secret: string;+ jobId: string;+ pid: number;+ options: DelegatedSyncOptions;+}): Promise<boolean> {+ const { dataDir, sock, secret, jobId, pid, options } = ctx;+ let failures = 0;+ let lastPhase: string | undefined;+ let lastBanked: number | undefined;+ let abortRequested = false;++ const onSigint = () => {+ if (abortRequested) process.exit(130);+ abortRequested = true;+ serr('[sync] Ctrl-C — aborting the delegated sync (progress is checkpointed; re-run to resume). Ctrl-C again to exit without waiting.');+ void requestSyncAbort(sock, { secret, jobId });+ process.once('SIGINT', onSigint);+ };+ process.once('SIGINT', onSigint);++ const crashHint = () =>+ serr(+ `[sync] progress is checkpointed — re-run \`gbrain sync\` to resume. Note: the dead ` ++ `serve's sync lock row may take up to 60s to become reclaimable; if the re-run reports ` ++ `a dead-PID lock, \`gbrain sync --break-lock\` clears it.`,+ );++ try {+ for (;;) {+ await new Promise((r) => setTimeout(r, POLL_MS));+ const s = await requestSyncStatus(sock, { secret, jobId });+ if (s === IPC_UNAVAILABLE || 'degraded' in (s as object)) {+ failures++;+ if (failures % PID_PROBE_EVERY === 0) {+ const still = probeLivePgliteHolder(dataDir);+ if (!still || !still.serve) {+ serr(`[sync] the serve (PID ${pid}) died mid-sync.`);+ crashHint();+ await setVerdict(1);+ return true;+ }+ }+ if (failures >= MAX_POLL_FAILURES) {+ serr(`[sync] the serve (PID ${pid}) stopped answering its IPC socket mid-sync.`);+ crashHint();+ await setVerdict(1);+ return true;+ }+ continue;+ }+ failures = 0;+ const status = s as SyncStatusResponse;+ if (!status.ok) {+ if (status.error === 'unknown_job') {+ serr(`[sync] the serve restarted mid-sync (job ${jobId} is gone).`);+ crashHint();+ } else {+ serr(`[sync] delegated sync failed: ${status.error}`);+ }+ await setVerdict(1);+ return true;+ }+ if (status.phase && status.phase !== lastPhase) {+ lastPhase = status.phase;+ serr(`[sync] serve: ${status.phase}`);+ }+ if (status.bankedFiles !== undefined && status.bankedFiles !== lastBanked) {+ lastBanked = status.bankedFiles;+ serr(`[sync] serve: banked ${status.bankedFiles} file(s)`);+ }+ if (status.state === 'error') {+ serr(`[sync] delegated sync failed inside the serve: ${status.jobError ?? 'unknown error'}`);+ await setVerdict(1);+ return true;+ }+ if (status.state === 'done' && status.result) {+ await printDelegatedResult(status.result, options);+ return true;+ }+ // running / aborting → keep polling.+ }+ } finally {+ process.off('SIGINT', onSigint);+ }+}++async function printDelegatedResult(wire: WireSyncResult, options: DelegatedSyncOptions): Promise<void> {+ const { printSyncResult } = await import('./sync.ts');+ const { pagesAffectedTotal, ...rest } = wire;+ const result: SyncResult = { ...rest, pagesAffected: wire.pagesAffected };+ printSyncResult(result);+ if (pagesAffectedTotal > wire.pagesAffected.length) {+ serr(`[sync] (+${pagesAffectedTotal - wire.pagesAffected.length} more pages affected — list truncated for the IPC wire)`);+ }+ if (!options.dryRun && !options.noEmbed && result.added + result.modified > 0) {+ serr('[sync] embeds deferred — the serve drains them in background sweeps (its environment/keys apply).');+ }+ // Mirror runSync's verdict rule (#3068): a pull_failed partial will not+ // self-heal — exit non-zero so cron sees the wedge.+ if (result.status === 'partial' && result.reason === 'pull_failed') {+ await setVerdict(1);+ }+}diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex f39b664593..3d81d71a69 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -412,6 +412,14 @@ export interface SyncOpts {* Precedent: CycleOpts.signal at src/core/cycle.ts (v0.22.1 #403).*/signal?: AbortSignal;+ /**+ * Serve-delegated sync progress seam: fired at phase boundaries and on every+ * durable checkpoint flush (cumulative bankedFiles). Sync-fire, never+ * awaited — the delegated-job runner mirrors these into the record that+ * `sync_status` IPC polls read. Absent for direct CLI runs (stderr+ * breadcrumbs already cover that surface).+ */+ onProgress?: (p: { phase: string; bankedFiles?: number }) => void;}// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,@@ -563,6 +571,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy// report names WHICH phase spun. Doesn't fix #1342 but converts// "hung with no output" into actionable diagnostic data.serr(`[gbrain phase] sync.resolve_repo`);+ opts.onProgress?.({ phase: 'resolve_repo' });// Resolve repo pathconst repoPath = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');if (!repoPath) {@@ -843,6 +852,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syif (!opts.dryRun && !opts.noPull && !detachedHead && originRemotePresent) {const _t0 = Date.now();serr(`[gbrain phase] sync.git_pull start`);+ opts.onProgress?.({ phase: 'git_pull' });try {const { pullRepo } = await import('../core/git-remote.ts');// v0.41.13.0 (T3 / D-V4-mech-7): if the operator set --timeout,@@ -1407,6 +1417,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syif (ok) {consecutiveFlushFailures = 0;bankedFiles += batch.length;+ opts.onProgress?.({ phase: 'import', bankedFiles });} else {// Not durably banked — re-merge so the next flush retries this batch.for (const p of batch) pendingCheckpointPaths.add(p);@@ -2683,6 +2694,7 @@ async function performFullSync(// #753/#774: thread exclude (--exclude CLI) + slugRoot (monorepo subdir).const _fullImportT0 = Date.now();serr(`[gbrain phase] sync.fullsync.import start strategy=${opts.strategy ?? 'markdown'}`);+ opts.onProgress?.({ phase: 'full_import' });const result = await runImport(engine, importArgs, {commit: headCommit,strategy: opts.strategy,@@ -3044,11 +3056,15 @@ Options:--watch Re-sync continuously on an interval.--interval N Watch-mode interval in seconds (default 60).--no-pull Skip 'git pull' before the sync (useful for tests).+ --no-delegate On a PGLite brain with a live 'gbrain serve', sync+ normally delegates the run to the serve process over+ its IPC socket (the lock owner does the work; embeds+ defer to serve's background sweep). This flag (or+ GBRAIN_SYNC_NO_DELEGATE=1) opts out — sync then fails+ fast if a live serve holds the brain.--no-schema-pack Skip loading the active schema pack (no per-file packregex runs; pages use legacy prefix typing). Escapehatch if a suspect pack regex is wedging sync.- PGLite is single-writer: stop 'gbrain serve' before a- large sync (see docs/architecture/serve-sync-concurrency.md).GBRAIN_SYNC_TRACE=1 names the file being imported (hang triage).--all Sync every registered source instead of just thedefault (multi-source brains).@@ -4261,7 +4277,7 @@ async function maybeExtractionNudge(engine: BrainEngine, sourceId?: string): Pro* when `--json` is set, so banners stay off stdout and the JSON envelope* pipes cleanly through `jq` (D4).*/-function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = process.stdout) {+export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = process.stdout) {const write = (line: string) => sink.write(line + '\n');switch (result.status) {case 'up_to_date':diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1472ca93ad..f49cfc39ca 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -62,7 +62,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],'integrity': ['--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--json', '--limit', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],+ 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],'lint': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--surface', '--timeout', '--token-ttl'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--help', '--include-flagged', '--include-frontmatter', '--index-audit', '--infer-dates', '--input', '--json', '--kind', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--nice', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--run-id', '--safe', '--scope', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--target', '--target-score', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--yes'],@@ -85,7 +85,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-code': ['--abi', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--older-than', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],'reindex-search-vector': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--json', '--migrate-only', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--yes'],+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--yes'],'remote': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--scopes', '--source', '--surface', '--timeout', '--token-ttl'],'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],@@ -96,17 +96,17 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'salience': ['--brain', '--days', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--slug-prefix', '--source', '--surface', '--timeout', '--token-ttl'],'schema': ['--alias', '--aliases', '--all', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--inverse', '--json', '--kind', '--no-embedding', '--no-extract', '--pack', '--page-type', '--pattern', '--pending', '--prefix', '--primitive', '--reset', '--resolve', '--schema-pack', '--since', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--target-type', '--thin', '--to', '--token-ttl', '--with-db'],'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],- 'serve': ['--all', '--bind', '--bound-slug-prefixes', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--name', '--no-embedding', '--once', '--parallel', '--port', '--prefix', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--yes'],+ 'serve': ['--all', '--bind', '--bound-slug-prefixes', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--name', '--no-embedding', '--no-hard-deadline', '--once', '--parallel', '--port', '--prefix', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--verbose', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--model', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models', '--verbose', '--yes'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force', '--force-unlock', '--format', '--from', '--from-pages', '--frontmatter', '--full', '--harness', '--help', '--homepage', '--http', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-embedding', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--surface', '--target', '--tier', '--token-ttl', '--trust', '--url', '--verbose', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],'sources': ['--abbrev-ref', '--abort', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],- 'status': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content', '--content-audit', '--count', '--date', '--days', '--deadline-ms', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--json', '--judge-model', '--kind', '--lang', '--limit', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-sources', '--max-usd', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--reenrich-after', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--section', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--trusted-extraction', '--type', '--types', '--url', '--verbose', '--verify', '--version', '--watch', '--what', '--where', '--who', '--window', '--with-db', '--workers', '--yes'],+ 'status': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content', '--content-audit', '--count', '--date', '--days', '--deadline-ms', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--json', '--judge-model', '--kind', '--lang', '--limit', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-sources', '--max-usd', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--reenrich-after', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--section', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--trusted-extraction', '--type', '--types', '--url', '--verbose', '--verify', '--version', '--watch', '--what', '--where', '--who', '--window', '--with-db', '--workers', '--yes'],'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'],'sweep': ['--batch-limit', '--brain', '--budget-ms', '--help', '--json', '--once', '--source', '--timeout'],- 'sync': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--json', '--kind', '--lang', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--yes'],+ 'sync': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--json', '--kind', '--lang', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--yes'],'takes': ['--brain', '--bucket-size', '--by', '--claim', '--dir', '--domain', '--dry-run', '--evidence', '--expired', '--fast', '--federated', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embedding', '--no-federated', '--outcome', '--path', '--quality', '--repo', '--restore-only', '--row', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--surface', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--max-usd', '--mcp-only', '--model', '--no-embedding', '--rounds', '--save', '--since', '--source', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--code', '--compile', '--days', '--dry-run', '--embed', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.tsindex bafb89e6ca..a9a5a1cc2a 100644--- a/src/core/context/resolve-ipc.ts+++ b/src/core/context/resolve-ipc.ts@@ -28,6 +28,15 @@* request (`{ok:true, block:null}`, no echo) and the client degrades to a* typed { degraded: 'stale_serve' } instead of trusting the empty block.*+ * sync_start / sync_status / sync_abort (secret-gated, protocol:2):+ * serve-delegated sync — a `gbrain sync` CLI that finds a live serve+ * holding the PGLite lock delegates the run through these kinds instead+ * of failing on LiveServeLockError. Wire shapes + option validation live+ * in sync-ipc.ts; execution lives in serve-sync-runner.ts. Start+poll+ * (never a held-open connection): every request stays one line / one+ * response, and an old serve answers `unknown_kind:sync_start` so the+ * client degrades to the documented stop-the-serve refusal.+ ** Local-only (unix socket in a 0700 dir on the brain's data dir, socket mode* 0600 set before readiness is announced) — no network surface.*/@@ -48,6 +57,14 @@ import type { EntityCandidate } from './entity-salience.ts';import type { WindowTurn } from './entity-salience.ts';import type { PointerBlock } from './retrieval-reflex.ts';import type { TurnContextResult } from './turn-context.ts';+import type {+ SyncAbortRequest,+ SyncAbortResponse,+ SyncStartRequest,+ SyncStartResponse,+ SyncStatusRequest,+ SyncStatusResponse,+} from './sync-ipc.ts';const SOCK_NAME = '.gbrain-resolve.sock';const SECRET_NAME = '.gbrain-ipc-secret';@@ -69,6 +86,15 @@ export const CONTEXT_PACK_CLIENT_TIMEOUT_MS = 1000;/** Assembler deadline. Backstop = +200; client 1000 leaves a real transport* margin (adversarial review: 800+200 == client timeout was zero margin). */export const CONTEXT_PACK_SERVER_BUDGET_MS = 600;+/**+ * Delegated-sync kinds are O(1) in-memory registrations/reads — no assembly+ * work, so no server-side budget race. start is a touch wider: its handler+ * validates options and registers the job before answering, and a serve loop+ * mid-import can sit on a long WASM statement before dispatching.+ */+export const SYNC_START_CLIENT_TIMEOUT_MS = 1500;+export const SYNC_STATUS_CLIENT_TIMEOUT_MS = 1000;+export const SYNC_ABORT_CLIENT_TIMEOUT_MS = 1000;const MAX_MSG_BYTES = 256 * 1024;/** Marker the client returns when no server is reachable (vs. a real null result). */@@ -169,7 +195,13 @@ export interface ContextPackRequest {manifestOnly?: boolean;}-export type IpcRequest = ResolveRequest | TurnContextRequest | ContextPackRequest;+export type IpcRequest =+ | ResolveRequest+ | TurnContextRequest+ | ContextPackRequest+ | SyncStartRequest+ | SyncStatusRequest+ | SyncAbortRequest;export interface ResolveResponse {ok: boolean;@@ -199,11 +231,18 @@ export type ResolveHandler = (req: ResolveRequest) => Promise<PointerBlock | nulexport type TurnContextHandler = (req: TurnContextRequest) => Promise<TurnContextResult | null>;export type ContextPackHandler = (req: ContextPackRequest) => Promise<TurnContextResult | null>;+export type SyncStartIpcHandler = (req: SyncStartRequest) => SyncStartResponse | Promise<SyncStartResponse>;+export type SyncStatusIpcHandler = (req: SyncStatusRequest) => SyncStatusResponse | Promise<SyncStatusResponse>;+export type SyncAbortIpcHandler = (req: SyncAbortRequest) => SyncAbortResponse | Promise<SyncAbortResponse>;+/** Handler MAP replacing the single closure [ENG-3]. */export interface IpcHandlers {resolve: ResolveHandler;turn_context?: TurnContextHandler;context_pack?: ContextPackHandler;+ sync_start?: SyncStartIpcHandler;+ sync_status?: SyncStatusIpcHandler;+ sync_abort?: SyncAbortIpcHandler;}export interface IpcServerOpts {@@ -421,6 +460,65 @@ export async function requestContextPack(return resp as ContextPackResponse;}+// ── Delegated-sync clients ────────────────────────────────────────────────++/** Client-facing shapes (kind/protocol filled in by the helpers). */+export type SyncStartClientRequest = Omit<SyncStartRequest, 'kind' | 'protocol'>;+export type SyncStatusClientRequest = Omit<SyncStatusRequest, 'kind' | 'protocol'>;+export type SyncAbortClientRequest = Omit<SyncAbortRequest, 'kind' | 'protocol'>;++export type SyncStartIpcResult = SyncStartResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;+export type SyncStatusIpcResult = SyncStatusResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;+export type SyncAbortIpcResult = SyncAbortResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;++/**+ * Delegated-sync clients: same fail-soft ladder as requestTurnContext —+ * transport trouble → IPC_UNAVAILABLE; a response without the protocol echo+ * (a pre-delegation serve answered `unknown_kind:*` or treated the line as a+ * resolve request) → { degraded: 'stale_serve' }; otherwise the server's+ * typed response, INCLUDING ok:false rejections ('busy', 'unauthorized',+ * 'unknown_job', …) that the sync CLI turns into remediation text. Never throw.+ */+export async function requestSyncStart(+ socketPath: string,+ req: SyncStartClientRequest,+ opts: { timeoutMs?: number } = {},+): Promise<SyncStartIpcResult> {+ const line = JSON.stringify({ kind: 'sync_start', protocol: 2, ...req } satisfies SyncStartRequest);+ return syncRoundTrip<SyncStartResponse>(socketPath, line, opts.timeoutMs ?? SYNC_START_CLIENT_TIMEOUT_MS);+}++export async function requestSyncStatus(+ socketPath: string,+ req: SyncStatusClientRequest,+ opts: { timeoutMs?: number } = {},+): Promise<SyncStatusIpcResult> {+ const line = JSON.stringify({ kind: 'sync_status', protocol: 2, ...req } satisfies SyncStatusRequest);+ return syncRoundTrip<SyncStatusResponse>(socketPath, line, opts.timeoutMs ?? SYNC_STATUS_CLIENT_TIMEOUT_MS);+}++export async function requestSyncAbort(+ socketPath: string,+ req: SyncAbortClientRequest,+ opts: { timeoutMs?: number } = {},+): Promise<SyncAbortIpcResult> {+ const line = JSON.stringify({ kind: 'sync_abort', protocol: 2, ...req } satisfies SyncAbortRequest);+ return syncRoundTrip<SyncAbortResponse>(socketPath, line, opts.timeoutMs ?? SYNC_ABORT_CLIENT_TIMEOUT_MS);+}++async function syncRoundTrip<Resp extends { ok: boolean; protocol: 2 }>(+ socketPath: string,+ line: string,+ timeoutMs: number,+): Promise<Resp | TurnContextStaleServe | typeof IPC_UNAVAILABLE> {+ if (Buffer.byteLength(line, 'utf8') + 1 > MAX_MSG_BYTES) return IPC_UNAVAILABLE;+ const resp = await roundTrip(socketPath, line, timeoutMs);+ if (resp === IPC_UNAVAILABLE) return IPC_UNAVAILABLE;+ if (!resp || typeof resp !== 'object') return IPC_UNAVAILABLE;+ if ((resp as { protocol?: unknown }).protocol !== 2) return { degraded: 'stale_serve' };+ return resp as Resp;+}+/** One request line out, one response line back. Fail-soft to IPC_UNAVAILABLE. */function roundTrip(socketPath: string,@@ -560,6 +658,18 @@ export async function startResolveIpcServer(resp = JSON.stringify(await handleContextPack(parsed as ContextPackRequest, handlers, opts),);+ } else if (kind === 'sync_start') {+ resp = JSON.stringify(+ await handleSyncKind(parsed as SyncStartRequest, handlers.sync_start, opts),+ );+ } else if (kind === 'sync_status') {+ resp = JSON.stringify(+ await handleSyncKind(parsed as SyncStatusRequest, handlers.sync_status, opts),+ );+ } else if (kind === 'sync_abort') {+ resp = JSON.stringify(+ await handleSyncKind(parsed as SyncAbortRequest, handlers.sync_abort, opts),+ );} else {resp = JSON.stringify({ ok: false, error: `unknown_kind:${String(kind)}` });}@@ -675,6 +785,29 @@ async function handleContextPack(}}+/**+ * Shared auth ladder for the delegated-sync kinds — same fail-closed posture+ * as turn_context (handler absent → unsupported_kind; protocol mismatch →+ * unsupported_protocol; missing/wrong secret → unauthorized). No budget race:+ * the handlers are O(1) in-memory operations in serve-sync-runner.ts.+ */+async function handleSyncKind<Req extends { protocol: number; secret: string }, Resp extends { ok: boolean; protocol: 2 }>(+ req: Req,+ handler: ((req: Req) => Resp | Promise<Resp>) | undefined,+ opts: IpcServerOpts,+): Promise<Resp | { ok: false; protocol: 2; error: string }> {+ if (!handler) return { ok: false, protocol: 2, error: 'unsupported_kind' };+ if (req.protocol !== 2) return { ok: false, protocol: 2, error: 'unsupported_protocol' };+ if (!opts.secret || !secretMatches(req.secret, opts.secret)) {+ return { ok: false, protocol: 2, error: 'unauthorized' };+ }+ try {+ return await handler(req);+ } catch (e) {+ return { ok: false, protocol: 2, error: (e as Error).message };+ }+}+/** Remove a socket file whose owning process is gone (or any leftover file). */export function cleanupStaleSocket(socketPath: string): void {try {diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.tsnew file mode 100644index 0000000000..d8f15c8234--- /dev/null+++ b/src/core/context/sync-ipc.ts@@ -0,0 +1,216 @@+/**+ * Serve-delegated sync IPC — wire types + validation.+ *+ * A live `gbrain serve` holds a PGLite brain's single-writer connection for+ * its lifetime, so a concurrent `gbrain sync` process cannot open the brain.+ * These kinds let the sync CLI delegate the run to the serve process over the+ * existing resolve-IPC socket: the lock owner does the work, the CLI polls.+ * Same trust posture as turn_context — narrow typed requests, secret-gated,+ * raw SQL never crosses the wire.+ *+ * sync_start { options, clientToken } → { ok, jobId } | { ok:false, error }+ * sync_status { jobId } → job state + progress + final result+ * sync_abort { jobId } → begins cooperative abort (typed partial)+ *+ * This module is deliberately a LEAF: pure types + pure functions, imported by+ * both the resolve-ipc client/server plumbing and the serve-sync-runner. It+ * must not import resolve-ipc.ts (cycle) or any engine module.+ */++import { isValidSourceId } from '../source-id.ts';+import type { SyncResult } from '../../commands/sync.ts';++// ── Options allowlist ──────────────────────────────────────────────────────++/**+ * The single field table that drives the validator, the CLI wire-builder, and+ * the serve-side SyncOpts builder — one source of truth so the three sites+ * can't drift. Everything NOT in this table is rejected fail-closed: the wire+ * must never smuggle repoPath / srcSubpath / exclude / skipLock / lockId /+ * concurrency into the serve process. `noEmbed` here does NOT reach+ * performSync — delegated jobs ALWAYS run noEmbed (the #2139 cost gate lives+ * in runSync, which a delegated run never passes through); the flag records+ * that the USER declined embeds, which suppresses the serve's deferred-embed+ * drain (absent → the serve sweep drains them later).+ */+export const DELEGATED_SYNC_OPTION_FIELDS = {+ sourceId: 'string',+ dryRun: 'boolean',+ full: 'boolean',+ noPull: 'boolean',+ noEmbed: 'boolean',+ noExtract: 'boolean',+ noSchemaPack: 'boolean',+ skipFailed: 'boolean',+ retryFailed: 'boolean',+ includeGitignored: 'boolean',+ timeoutSeconds: 'number',+} as const;++export type DelegatedSyncOptionField = keyof typeof DELEGATED_SYNC_OPTION_FIELDS;++/** Hard ceiling on a delegated job's runtime (24h) — matches the sync hard-deadline scale. */+export const DELEGATED_SYNC_TIMEOUT_MAX_SECONDS = 86_400;++export interface DelegatedSyncOptions {+ /** Must satisfy the canonical source-id shape; validated at the boundary. */+ sourceId?: string;+ dryRun?: boolean;+ full?: boolean;+ noPull?: boolean;+ /** User explicitly declined embeds — suppresses the deferred-embed drain. */+ noEmbed?: boolean;+ noExtract?: boolean;+ noSchemaPack?: boolean;+ skipFailed?: boolean;+ retryFailed?: boolean;+ includeGitignored?: boolean;+ /**+ * REQUIRED — the client always sends its resolved hard deadline so a job+ * whose client died stays bounded. `0` is the single unbounded encoding+ * (an explicit `--no-hard-deadline`); nonzero values clamp to+ * [1, DELEGATED_SYNC_TIMEOUT_MAX_SECONDS].+ */+ timeoutSeconds: number;+}++export type DelegatedSyncValidation =+ | { ok: true; options: DelegatedSyncOptions }+ | { ok: false; error: string };++/**+ * Fail-closed wire validation: unknown keys reject (this is what keeps+ * server-only SyncOpts fields unreachable from the socket), wrong types+ * reject, sourceId must be shape-valid, timeoutSeconds must be a+ * non-negative integer (0 = no server timer). Returns a NEW object built+ * from the field table — never the caller's reference.+ */+export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidation {+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ return { ok: false, error: 'invalid_options:options' };+ }+ const rec = raw as Record<string, unknown>;+ for (const key of Object.keys(rec)) {+ if (!(key in DELEGATED_SYNC_OPTION_FIELDS)) {+ return { ok: false, error: `invalid_options:${key}` };+ }+ }+ const out: Record<string, unknown> = {};+ for (const [key, type] of Object.entries(DELEGATED_SYNC_OPTION_FIELDS)) {+ const v = rec[key];+ if (v === undefined) continue;+ if (typeof v !== type) return { ok: false, error: `invalid_options:${key}` };+ out[key] = v;+ }+ const timeout = out.timeoutSeconds;+ if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout < 0) {+ return { ok: false, error: 'invalid_options:timeoutSeconds' };+ }+ out.timeoutSeconds = Math.min(timeout, DELEGATED_SYNC_TIMEOUT_MAX_SECONDS);+ if (out.sourceId !== undefined && !isValidSourceId(out.sourceId as string)) {+ return { ok: false, error: 'invalid_options:sourceId' };+ }+ return { ok: true, options: out as unknown as DelegatedSyncOptions };+}++// ── Progress + result shapes ───────────────────────────────────────────────++/** Fired by performSync's onProgress seam; mirrored into the job record. */+export interface SyncProgressEvent {+ phase: string;+ bankedFiles?: number;+}++/** pagesAffected cap so a 250K-file sync's result fits the 256KB message cap. */+export const WIRE_PAGES_AFFECTED_MAX = 50;++export interface WireSyncResult extends Omit<SyncResult, 'pagesAffected'> {+ /** First WIRE_PAGES_AFFECTED_MAX slugs only — see pagesAffectedTotal. */+ pagesAffected: string[];+ pagesAffectedTotal: number;+}++export function toWireSyncResult(r: SyncResult): WireSyncResult {+ const { pagesAffected, ...rest } = r;+ return {+ ...rest,+ pagesAffected: pagesAffected.slice(0, WIRE_PAGES_AFFECTED_MAX),+ pagesAffectedTotal: pagesAffected.length,+ };+}++// ── Wire request / response types ──────────────────────────────────────────++export type DelegatedSyncState = 'running' | 'aborting' | 'done' | 'error';++export interface SyncStartRequest {+ kind: 'sync_start';+ protocol: 2;+ secret: string;+ /**+ * Client-generated idempotency token. A retry after a lost ack that gets+ * `busy` with a MATCHING token is attaching to its own job; a retry whose+ * token matches the RETAINED TERMINAL job gets `{ok, jobId, completed:true}`+ * instead of a duplicate run.+ */+ clientToken: string;+ options: DelegatedSyncOptions;+}++export type SyncStartError =+ | 'busy'+ | 'unauthorized'+ | 'unsupported_protocol'+ | 'unsupported_kind'+ | 'shutting_down'+ | 'source_mismatch'+ | string; // `invalid_options:<field>`++export interface SyncStartResponse {+ ok: boolean;+ protocol: 2;+ jobId?: string;+ /** On `busy`: the running job's clientToken so a retrying owner can attach. */+ clientToken?: string;+ /** True when a token retry matched the retained terminal job — poll sync_status for its result. */+ completed?: boolean;+ error?: SyncStartError;+}++export interface SyncStatusRequest {+ kind: 'sync_status';+ protocol: 2;+ secret: string;+ jobId: string;+}++export interface SyncStatusResponse {+ ok: boolean;+ protocol: 2;+ state?: DelegatedSyncState;+ sourceId?: string;+ startedAt?: number;+ elapsedMs?: number;+ phase?: string;+ bankedFiles?: number;+ /** Present when state === 'done' (including typed partials). */+ result?: WireSyncResult;+ /** Present when state === 'error' — the job's failure message. */+ jobError?: string;+ /** ok:false protocol errors: 'unauthorized' | 'unknown_job' | 'unsupported_kind' | 'unsupported_protocol'. */+ error?: string;+}++export interface SyncAbortRequest {+ kind: 'sync_abort';+ protocol: 2;+ secret: string;+ jobId: string;+}++export interface SyncAbortResponse {+ ok: boolean;+ protocol: 2;+ state?: DelegatedSyncState;+ error?: string;+}diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.tsindex 34920273a2..5a0d7fef11 100644--- a/src/core/pglite-lock.ts+++ b/src/core/pglite-lock.ts@@ -251,7 +251,8 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutMthrow new LiveServeLockError(`GBrain's local database is already open through \`gbrain serve\` (MCP, PID ${lockPid}). ` +`This brain uses PGLite, so a separate CLI process cannot open it at the same time. ` +- `Stop \`gbrain serve\`, then retry this CLI command. ` ++ `\`gbrain sync\` runs through the live serve automatically (serve-delegated sync); ` ++ `for other CLI write commands, stop \`gbrain serve\` and retry. ` +`(\`gbrain serve\` is usually spawned by your agent harness — close or exit that ` +`Claude Code/Codex session to release the database.) ` +`Or keep it running and use its MCP tools instead. ` +diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.tsnew file mode 100644index 0000000000..ec80784eac--- /dev/null+++ b/src/core/serve-sync-runner.ts@@ -0,0 +1,370 @@+/**+ * Serve-delegated sync job runner — the serve process's execution half of the+ * sync_start / sync_status / sync_abort IPC kinds (wire shapes + validation in+ * context/sync-ipc.ts; socket plumbing in context/resolve-ipc.ts; CLI half in+ * commands/sync-delegate.ts).+ *+ * One job at a time, in-memory, module-singleton. Correctness does NOT rest on+ * the single-flight guard — performSync still takes the `gbrain-sync:<source>`+ * DB row lock — the guard just answers `busy` fast and keeps the event-loop+ * load bounded. The last TERMINAL job is retained (keyed by clientToken) so a+ * client that lost the start ack can attach to its own finished run instead of+ * starting a duplicate.+ *+ * sync_start(valid, idle, not shutting down)+ * │+ * ┌────▼────┐ abort()/deadline/shutdown ┌──────────┐+ * │ running │────────────────────────────▶│ aborting │+ * └──┬───┬──┘ └────┬─────┘+ * │ │ performSync throws │ settles (typed partial)+ * ▼ ▼ ▼+ * ┌──────┐ ┌───────┐ done │ error (retained until next start)+ * │ done │ │ error │+ * └──────┘ └───────┘+ *+ * Shutdown contract: shutdownDelegatedSync() is an IDEMPOTENT SHARED promise —+ * serve.ts's beginShutdown and mcp/server.ts's shutdown both race here on+ * every signal, and the second caller must await the first, never double-run.+ * It must be awaited BEFORE engine.disconnect(): the disconnect-mode drain+ * passes allowAbort:false and runs after `_db` is early-nulled, so a job's+ * settle writes (final checkpoint flush, row-lock release) only succeed+ * against the still-live engine. The registered BackgroundWorkDrainer is a+ * BACKSTOP for disconnect paths that never called us, not the primary path.+ *+ * Embeds: delegated jobs ALWAYS run with noEmbed (the #2139 inline cost gate+ * lives in runSync, which a delegated run never passes through) and this+ * module drains them afterwards via maybeDrainDeferredEmbeds — the lock owner+ * closes its own embedding loop. NOT submitEmbedBackfill: on PGLite nothing+ * drains minion_jobs (workers refuse the engine) and a stuck `waiting` row+ * cooldown-blocks every later submit.+ */++import { randomUUID } from 'node:crypto';+import type { BrainEngine } from './engine.ts';+import { registerBackgroundWorkDrainer } from './background-work.ts';+import {+ toWireSyncResult,+ validateDelegatedSyncOptions,+ type DelegatedSyncState,+ type SyncAbortResponse,+ type SyncStartResponse,+ type SyncStatusResponse,+ type WireSyncResult,+} from './context/sync-ipc.ts';++interface DelegatedSyncJob {+ id: string;+ clientToken: string;+ state: DelegatedSyncState;+ sourceId?: string;+ startedAt: number;+ finishedAt?: number;+ phase?: string;+ bankedFiles?: number;+ result?: WireSyncResult;+ jobError?: string;+ controller: AbortController;+ /** Resolves when the job reaches done/error — the shutdown settle target. */+ settled: Promise<void>;+}++/** Running job, or the retained last terminal job (replaced by the next start). */+let current: DelegatedSyncJob | null = null;+let shuttingDown = false;+let shutdownPromise: Promise<void> | null = null;+let drainerRegistered = false;++/** Deferred-embed drain state (see maybeDrainDeferredEmbeds). */+let deferredEmbedsPending = false;+let deferredEmbedSourceId: string | undefined;+let embedDrainRunning = false;+let embedDrainController = new AbortController();++const isTerminal = (s: DelegatedSyncState): boolean => s === 'done' || s === 'error';++function log(msg: string): void {+ process.stderr.write(`[serve-sync] ${msg}\n`);+}++/**+ * Bound on the shutdown settle wait (ms). serve.ts extends its cleanup+ * deadline by exactly this much while a job is running, so the settle always+ * fits inside the deadline that would otherwise force-exit at 5s.+ */+export function delegatedSyncSettleMs(env: Record<string, string | undefined> = process.env): number {+ const raw = Number(env.GBRAIN_SERVE_SYNC_SETTLE_MS ?? '3000');+ if (!Number.isFinite(raw) || raw < 0) return 3000;+ return Math.min(raw, 60_000);+}++/** True while a delegated job occupies the event loop (sweep ticks skip). */+export function isDelegatedSyncRunning(): boolean {+ return current !== null && !isTerminal(current.state);+}++/**+ * Handle a sync_start request. `rawOptions` is the untrusted wire payload —+ * validated here (the runner is the single authority) even though the IPC+ * layer types it.+ */+export function startDelegatedSync(+ engine: BrainEngine,+ rawOptions: unknown,+ clientToken: string,+ opts: { boundSourceId?: string } = {},+): SyncStartResponse {+ if (typeof clientToken !== 'string' || clientToken.length === 0 || clientToken.length > 128) {+ return { ok: false, protocol: 2, error: 'invalid_options:clientToken' };+ }+ // Token attach: a retry after a lost ack finds its own job — running+ // (attach and keep polling) or retained-terminal (fetch the result) —+ // instead of erroring or duplicate-running.+ if (current && current.clientToken === clientToken) {+ return isTerminal(current.state)+ ? { ok: true, protocol: 2, jobId: current.id, completed: true }+ : { ok: true, protocol: 2, jobId: current.id };+ }+ if (shuttingDown) {+ return { ok: false, protocol: 2, error: 'shutting_down' };+ }+ if (current && !isTerminal(current.state)) {+ return { ok: false, protocol: 2, error: 'busy', jobId: current.id };+ }+ const v = validateDelegatedSyncOptions(rawOptions);+ if (!v.ok) return { ok: false, protocol: 2, error: v.error };+ const options = v.options;+ if (options.sourceId && opts.boundSourceId && options.sourceId !== opts.boundSourceId) {+ return { ok: false, protocol: 2, error: 'source_mismatch' };+ }++ const controller = new AbortController();+ const job: DelegatedSyncJob = {+ id: randomUUID(),+ clientToken,+ state: 'running',+ sourceId: options.sourceId ?? opts.boundSourceId,+ startedAt: Date.now(),+ controller,+ settled: Promise.resolve(),+ };+ current = job;+ ensureDrainerRegistered();++ // Per-job hard deadline: 0 is the single unbounded encoding (an explicit+ // --no-hard-deadline); every other value keeps the job bounded even when+ // the polling client died.+ let deadlineTimer: ReturnType<typeof setTimeout> | null = null;+ if (options.timeoutSeconds > 0) {+ deadlineTimer = setTimeout(() => {+ if (!isTerminal(job.state)) {+ log(`abort job=${job.id} reason=deadline after ${options.timeoutSeconds}s`);+ job.state = 'aborting';+ controller.abort();+ }+ }, options.timeoutSeconds * 1000);+ deadlineTimer.unref?.();+ }++ job.settled = (async () => {+ try {+ const { performSync } = await import('../commands/sync.ts');+ let sourceId = job.sourceId;+ if (!sourceId) {+ const { resolveSourceWithTier } = await import('./source-resolver.ts');+ sourceId = (await resolveSourceWithTier(engine, null)).source_id;+ job.sourceId = sourceId;+ }+ log(+ `start job=${job.id} source=${sourceId ?? 'default'} ` ++ `opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,+ );+ const r = await performSync(engine, {+ sourceId,+ dryRun: options.dryRun,+ full: options.full,+ noPull: options.noPull,+ noExtract: options.noExtract,+ noSchemaPack: options.noSchemaPack,+ skipFailed: options.skipFailed,+ retryFailed: options.retryFailed,+ includeGitignored: options.includeGitignored,+ // ALWAYS deferred — see module header. Drained by maybeDrainDeferredEmbeds.+ noEmbed: true,+ signal: controller.signal,+ onProgress: (p) => {+ job.phase = p.phase;+ if (p.bankedFiles !== undefined) job.bankedFiles = p.bankedFiles;+ },+ });+ job.result = toWireSyncResult(r);+ job.state = 'done';+ log(+ `done job=${job.id} status=${r.status} added=${r.added} modified=${r.modified} ` ++ `deleted=${r.deleted} in=${Math.round((Date.now() - job.startedAt) / 1000)}s`,+ );+ // Wire noEmbed means the USER declined embeds — honor it by skipping+ // the drain too (performSync above always ran noEmbed regardless).+ if (!options.dryRun && !options.noEmbed && r.added + r.modified > 0) {+ deferredEmbedsPending = true;+ deferredEmbedSourceId = sourceId;+ scheduleEmbedDrain(engine);+ }+ } catch (e) {+ job.jobError = e instanceof Error ? e.message : String(e);+ job.state = 'error';+ log(`error job=${job.id}: ${job.jobError}`);+ } finally {+ if (deadlineTimer) clearTimeout(deadlineTimer);+ job.finishedAt = Date.now();+ }+ })();++ return { ok: true, protocol: 2, jobId: job.id };+}++/** Handle a sync_status poll. */+export function getDelegatedSyncStatus(jobId: string): SyncStatusResponse {+ const job = current;+ if (!job || job.id !== jobId) {+ return { ok: false, protocol: 2, error: 'unknown_job' };+ }+ return {+ ok: true,+ protocol: 2,+ state: job.state,+ sourceId: job.sourceId,+ startedAt: job.startedAt,+ elapsedMs: (job.finishedAt ?? Date.now()) - job.startedAt,+ phase: job.phase,+ bankedFiles: job.bankedFiles,+ ...(job.state === 'done' && job.result ? { result: job.result } : {}),+ ...(job.state === 'error' && job.jobError ? { jobError: job.jobError } : {}),+ };+}++/** Handle a sync_abort request — cooperative; the client keeps polling to settle. */+export function abortDelegatedSync(jobId: string): SyncAbortResponse {+ const job = current;+ if (!job || job.id !== jobId) {+ return { ok: false, protocol: 2, error: 'unknown_job' };+ }+ if (!isTerminal(job.state)) {+ log(`abort job=${job.id} reason=client`);+ job.state = 'aborting';+ job.controller.abort();+ }+ return { ok: true, protocol: 2, state: job.state };+}++/**+ * Idempotent shutdown settle: abort the running job and wait (bounded) for its+ * settle writes to land against the still-live engine. Both serve shutdown+ * paths call this BEFORE engine.disconnect(); the second caller awaits the+ * first run. New sync_start requests refuse with 'shutting_down' from the+ * first call onward. Never throws.+ */+export function shutdownDelegatedSync(timeoutMs?: number): Promise<void> {+ shuttingDown = true;+ if (shutdownPromise) return shutdownPromise;+ shutdownPromise = (async () => {+ try { embedDrainController.abort(); } catch { /* noop */ }+ const job = current;+ if (!job || isTerminal(job.state)) return;+ log(`abort job=${job.id} reason=shutdown`);+ job.state = 'aborting';+ job.controller.abort();+ const bound = timeoutMs ?? delegatedSyncSettleMs();+ await Promise.race([+ job.settled,+ new Promise<void>((r) => { const t = setTimeout(r, bound); t.unref?.(); }),+ ]);+ if (!isTerminal(job.state)) {+ log(`shutdown settle bound (${timeoutMs ?? delegatedSyncSettleMs()}ms) elapsed with job=${job.id} unsettled; proceeding (checkpoint resume covers the tail)`);+ }+ })().catch(() => { /* never throws */ });+ return shutdownPromise;+}++/**+ * BACKSTOP for disconnect paths that never awaited shutdownDelegatedSync().+ * The disconnect-mode drain runs with allowAbort:false after `_db` is nulled,+ * so this drain aborts inline and waits within the registry's bound; settle+ * writes may fail 'not connected' there — intended, resume covers it.+ */+function ensureDrainerRegistered(): void {+ if (drainerRegistered) return;+ drainerRegistered = true;+ registerBackgroundWorkDrainer({+ name: 'serve-delegated-sync',+ order: 40,+ async drain(timeoutMs: number): Promise<{ unfinished: number }> {+ const job = current;+ if (!job || isTerminal(job.state)) return { unfinished: 0 };+ job.state = 'aborting';+ job.controller.abort();+ await Promise.race([+ job.settled,+ new Promise<void>((r) => { const t = setTimeout(r, timeoutMs); t.unref?.(); }),+ ]);+ return { unfinished: isTerminal(job.state) ? 0 : 1 };+ },+ });+}++/**+ * Deferred-embed drain — the lock owner's replacement for the inline embed+ * step delegated jobs skip. Bounded per invocation by runEmbedCore's internal+ * wall clock; `pending` clears only when a run finds nothing left to embed,+ * so successive idle ticks converge on a fully-embedded brain. Keyless rule:+ * no embedding provider ⇒ leave pending (a later keyed serve drains it).+ * Never throws.+ */+export async function maybeDrainDeferredEmbeds(engine: BrainEngine): Promise<void> {+ if (!deferredEmbedsPending || embedDrainRunning || shuttingDown) return;+ if (isDelegatedSyncRunning()) return;+ embedDrainRunning = true;+ try {+ const { detectCapabilities } = await import('./capability.ts');+ if (!detectCapabilities().embeddings.available) return;+ const { runEmbedCore } = await import('../commands/embed.ts');+ const r = await runEmbedCore(engine, {+ stale: true,+ sourceId: deferredEmbedSourceId,+ signal: embedDrainController.signal,+ });+ log(`embed-drain embedded=${r.embedded} failures=${r.failures} source=${deferredEmbedSourceId ?? 'all'}`);+ // Nothing left to embed and nothing failing ⇒ the deferred backlog is done.+ if (r.embedded === 0 && r.failures === 0) {+ deferredEmbedsPending = false;+ deferredEmbedSourceId = undefined;+ }+ } catch (e) {+ log(`embed-drain failed: ${e instanceof Error ? e.message : String(e)}`);+ } finally {+ embedDrainRunning = false;+ }+}++/** One-shot post-job kick so embeds don't wait for the next 10-min idle tick. */+function scheduleEmbedDrain(engine: BrainEngine): void {+ const t = setTimeout(() => {+ void maybeDrainDeferredEmbeds(engine);+ }, 5_000);+ t.unref?.();+}++/** Test seam: reset every module singleton (serial tests only). */+export function __resetDelegatedSyncForTests(): void {+ current = null;+ shuttingDown = false;+ shutdownPromise = null;+ deferredEmbedsPending = false;+ deferredEmbedSourceId = undefined;+ embedDrainRunning = false;+ embedDrainController = new AbortController();+}++/** Test seam: report whether the deferred-embed backlog is pending. */+export function __deferredEmbedsPendingForTests(): boolean {+ return deferredEmbedsPending;+}diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex fad43881d3..0c1bcb164d 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -17,6 +17,7 @@ import {startResolveIpcServer,cleanupStaleSocket,ensureIpcSecret,+ type IpcHandlers,} from '../core/context/resolve-ipc.ts';import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';import { lexicalArmsEnabled } from '../core/context/reflex.ts';@@ -196,6 +197,30 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpStry {ipcSecret = ensureIpcSecret(cfg.database_path);} catch { /* turn_context disabled; resolve unaffected */ }+ // Serve-delegated sync kinds — built in their OWN try/catch so a+ // runner import/registration failure can never take resolve /+ // turn_context / context_pack down with it (this whole block's shared+ // catch would otherwise swallow the error and start NO listener).+ // Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not+ // registered and clients get 'unsupported_kind' (the polite refusal).+ let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort'> = {};+ if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {+ try {+ const runner = await import('../core/serve-sync-runner.ts');+ syncHandlers = {+ sync_start: (req) =>+ runner.startDelegatedSync(engine, req.options, req.clientToken, {+ boundSourceId: defaultSource,+ }),+ sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId),+ sync_abort: (req) => runner.abortDelegatedSync(req.jobId),+ };+ } catch (e) {+ process.stderr.write(+ `[serve-sync] handlers unavailable: ${e instanceof Error ? e.message : String(e)}\n`,+ );+ }+ }resolveServer = await startResolveIpcServer(resolveSocket,{@@ -244,6 +269,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// the runtime owns entity merge, banking, the since-cursor, and the// complete-pack-only monotonic cursor advance.context_pack: makeContextPackIpcHandler(engine, defaultSource),+ ...syncHandlers,},{// The IPC resolve path IS the ambient reflex channel. Logging happens@@ -307,6 +333,11 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSimport('../core/context/checkpoint-harvest.ts').then((m) => m.shutdownCheckpointHarvest()).catch(() => {})+ // Delegated-sync settle BEFORE disconnect (idempotent shared promise —+ // serve.ts's beginShutdown races here on the same signals): the job's+ // final checkpoint flush and row-lock release need the live engine.+ .then(() => import('../core/serve-sync-runner.ts').then((m) => m.shutdownDelegatedSync()))+ .catch(() => {}).then(() => Promise.resolve(engine.disconnect?.())).catch(() => {}).finally(() => process.exit(code));diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 112b61c58f..3c08176b25 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.46.23.0 -->+<!-- gbrain-template-stamp: 0.46.24.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/context/resolve-ipc-sync-kinds.test.ts b/test/context/resolve-ipc-sync-kinds.test.tsnew file mode 100644index 0000000000..2825e6563b--- /dev/null+++ b/test/context/resolve-ipc-sync-kinds.test.ts@@ -0,0 +1,138 @@+/**+ * Delegated-sync IPC kinds — protocol pins (resolve-ipc.ts + sync-ipc.ts).+ *+ * What these protect:+ * - secret gating fails CLOSED (no secret configured → unauthorized, wrong+ * secret → unauthorized) — the sync kinds are mutating/admin class.+ * - a serve WITHOUT sync handlers (kill switch, or handler-build failure)+ * answers unsupported_kind with the protocol echo — clients refuse politely.+ * - a PRE-DELEGATION serve (legacy resolve-only) yields the typed+ * stale_serve degrade, never a trusted empty response.+ * - the protocol echo rides every response (the [A9] stale-serve detector).+ *+ * Parallel-safe: hermetic tmpdir sockets, no env mutation, no engine.+ */++import { describe, test, expect, afterEach } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ IPC_UNAVAILABLE,+ requestSyncAbort,+ requestSyncStart,+ requestSyncStatus,+ resolveSocketPath,+ startResolveIpcServer,+ type IpcHandlers,+} from '../../src/core/context/resolve-ipc.ts';+import type { SyncStartResponse, SyncStatusResponse } from '../../src/core/context/sync-ipc.ts';++const servers: Array<{ close: () => void }> = [];+const dirs: string[] = [];+afterEach(() => {+ for (const s of servers.splice(0)) { try { s.close(); } catch { /* noop */ } }+ for (const d of dirs.splice(0)) { try { rmSync(d, { recursive: true, force: true }); } catch { /* noop */ } }+});++function tmpDir(): string {+ const d = mkdtempSync(join(tmpdir(), 'ssi-'));+ dirs.push(d);+ return d;+}++const SECRET = 'test-secret';++function stubHandlers(): IpcHandlers {+ return {+ resolve: async () => null,+ sync_start: (req) =>+ ({ ok: true, protocol: 2, jobId: `job-for-${req.clientToken}` }) satisfies SyncStartResponse,+ sync_status: (req) =>+ ({ ok: true, protocol: 2, state: 'running', startedAt: 1, elapsedMs: 2, phase: 'import', ...(req.jobId === 'gone' ? { ok: false, error: 'unknown_job', state: undefined } : {}) }) as SyncStatusResponse,+ sync_abort: () => ({ ok: true, protocol: 2, state: 'aborting' }),+ };+}++async function startServer(dir: string, handlers: IpcHandlers, secret?: string) {+ const sock = resolveSocketPath(dir);+ const server = await startResolveIpcServer(sock, handlers, { secret });+ expect(server).not.toBeNull();+ servers.push(server!);+ return sock;+}++describe('delegated-sync IPC kinds', () => {+ test('round-trip: sync_start reaches the handler and echoes protocol 2', async () => {+ const sock = await startServer(tmpDir(), stubHandlers(), SECRET);+ const r = await requestSyncStart(sock, {+ secret: SECRET,+ clientToken: 'tok-1',+ options: { timeoutSeconds: 60 },+ });+ expect(r).not.toBe(IPC_UNAVAILABLE);+ const resp = r as SyncStartResponse;+ expect(resp.ok).toBe(true);+ expect(resp.protocol).toBe(2);+ expect(resp.jobId).toBe('job-for-tok-1');+ });++ test('wrong secret → unauthorized (all three kinds)', async () => {+ const sock = await startServer(tmpDir(), stubHandlers(), SECRET);+ const start = await requestSyncStart(sock, { secret: 'nope', clientToken: 't', options: { timeoutSeconds: 60 } });+ expect((start as SyncStartResponse).error).toBe('unauthorized');+ const status = await requestSyncStatus(sock, { secret: 'nope', jobId: 'j' });+ expect((status as SyncStatusResponse).error).toBe('unauthorized');+ const abort = await requestSyncAbort(sock, { secret: 'nope', jobId: 'j' });+ expect((abort as SyncStatusResponse).error).toBe('unauthorized');+ });++ test('NO secret configured → unauthorized (fail closed, never open service)', async () => {+ const sock = await startServer(tmpDir(), stubHandlers(), undefined);+ const r = await requestSyncStart(sock, { secret: SECRET, clientToken: 't', options: { timeoutSeconds: 60 } });+ expect((r as SyncStartResponse).ok).toBe(false);+ expect((r as SyncStartResponse).error).toBe('unauthorized');+ });++ test('handlers absent (kill switch / build failure) → unsupported_kind WITH echo', async () => {+ const sock = await startServer(tmpDir(), { resolve: async () => null }, SECRET);+ const r = await requestSyncStart(sock, { secret: SECRET, clientToken: 't', options: { timeoutSeconds: 60 } });+ const resp = r as SyncStartResponse;+ expect(resp.ok).toBe(false);+ expect(resp.error).toBe('unsupported_kind');+ expect(resp.protocol).toBe(2);+ });++ test('pre-delegation serve → stale_serve degrade (no protocol echo on unknown_kind)', async () => {+ // A genuinely OLD serve's dispatcher has no sync branches: it answers+ // `{ok:false, error:'unknown_kind:sync_start'}` WITHOUT the protocol echo.+ // (A NEW serve without handlers answers unsupported_kind WITH the echo —+ // pinned above.) Simulate the old wire shape with a raw NDJSON server.+ const dir = tmpDir();+ const sock = resolveSocketPath(dir);+ const net = await import('node:net');+ const raw = net.createServer((conn) => {+ conn.on('data', () => {+ conn.write(JSON.stringify({ ok: false, error: 'unknown_kind:sync_start' }) + '\n');+ conn.end();+ });+ });+ await new Promise<void>((r) => raw.listen(sock, () => r()));+ servers.push(raw);+ const r = await requestSyncStart(sock, { secret: SECRET, clientToken: 't', options: { timeoutSeconds: 60 } });+ expect(r).toEqual({ degraded: 'stale_serve' });+ });++ test('absent socket → IPC_UNAVAILABLE (caller re-probes the holder)', async () => {+ const r = await requestSyncStatus(resolveSocketPath(tmpDir()), { secret: SECRET, jobId: 'j' });+ expect(r).toBe(IPC_UNAVAILABLE);+ });++ test('handler exceptions surface as typed ok:false, never a dropped connection', async () => {+ const handlers = stubHandlers();+ handlers.sync_abort = () => { throw new Error('boom'); };+ const sock = await startServer(tmpDir(), handlers, SECRET);+ const r = await requestSyncAbort(sock, { secret: SECRET, jobId: 'j' });+ expect(r).toEqual({ ok: false, protocol: 2, error: 'boom' });+ });+});diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.tsnew file mode 100644index 0000000000..5de10fb21c--- /dev/null+++ b/test/context/sync-ipc-validation.test.ts@@ -0,0 +1,164 @@+/**+ * Wire validation pins for serve-delegated sync (sync-ipc.ts).+ *+ * The validator is the trust boundary between the unix socket and the serve+ * process's SyncOpts: unknown keys MUST reject (that is the only thing keeping+ * repoPath / skipLock / lockId / concurrency unreachable from the wire), and+ * timeoutSeconds is the bounded-job guarantee.+ */++import { describe, expect, test } from 'bun:test';+import {+ DELEGATED_SYNC_OPTION_FIELDS,+ DELEGATED_SYNC_TIMEOUT_MAX_SECONDS,+ WIRE_PAGES_AFFECTED_MAX,+ toWireSyncResult,+ validateDelegatedSyncOptions,+} from '../../src/core/context/sync-ipc.ts';+import type { SyncResult } from '../../src/commands/sync.ts';++describe('validateDelegatedSyncOptions', () => {+ test('accepts the full allowlisted set and returns a fresh object', () => {+ const raw = {+ sourceId: 'notes',+ dryRun: true,+ full: false,+ noPull: true,+ noEmbed: false,+ noExtract: false,+ noSchemaPack: true,+ skipFailed: false,+ retryFailed: false,+ includeGitignored: true,+ timeoutSeconds: 3600,+ };+ const v = validateDelegatedSyncOptions(raw);+ expect(v.ok).toBe(true);+ if (!v.ok) throw new Error('unreachable');+ expect(v.options).toEqual(raw);+ expect(v.options).not.toBe(raw as never);+ });++ test('minimal valid payload: only timeoutSeconds', () => {+ const v = validateDelegatedSyncOptions({ timeoutSeconds: 60 });+ expect(v.ok).toBe(true);+ });++ test.each([+ ['repoPath', { repoPath: '/tmp/evil', timeoutSeconds: 60 }],+ ['skipLock', { skipLock: true, timeoutSeconds: 60 }],+ ['lockId', { lockId: 'gbrain-cycle', timeoutSeconds: 60 }],+ ['concurrency', { concurrency: 8, timeoutSeconds: 60 }],+ ['srcSubpath', { srcSubpath: '../escape', timeoutSeconds: 60 }],+ ['exclude', { exclude: ['*'], timeoutSeconds: 60 }],+ ['signal', { signal: {}, timeoutSeconds: 60 }],+ ['onProgress', { onProgress: () => {}, timeoutSeconds: 60 }],+ ])('rejects unknown/smuggled key %s fail-closed', (key, raw) => {+ const v = validateDelegatedSyncOptions(raw);+ expect(v.ok).toBe(false);+ if (v.ok) throw new Error('unreachable');+ expect(v.error).toBe(`invalid_options:${key}`);+ });++ test.each([+ ['non-object', null],+ ['array', []],+ ['string', 'sync'],+ ])('rejects a %s payload', (_label, raw) => {+ const v = validateDelegatedSyncOptions(raw);+ expect(v.ok).toBe(false);+ });++ test('rejects wrong-typed allowlisted fields', () => {+ expect(validateDelegatedSyncOptions({ dryRun: 'yes', timeoutSeconds: 60 }).ok).toBe(false);+ expect(validateDelegatedSyncOptions({ sourceId: 42, timeoutSeconds: 60 }).ok).toBe(false);+ });++ test('timeoutSeconds is required, integer, non-negative; 0 means no server timer', () => {+ expect(validateDelegatedSyncOptions({})).toEqual({+ ok: false,+ error: 'invalid_options:timeoutSeconds',+ });+ expect(validateDelegatedSyncOptions({ timeoutSeconds: -1 }).ok).toBe(false);+ expect(validateDelegatedSyncOptions({ timeoutSeconds: 1.5 }).ok).toBe(false);+ const zero = validateDelegatedSyncOptions({ timeoutSeconds: 0 });+ expect(zero.ok).toBe(true);+ if (zero.ok) expect(zero.options.timeoutSeconds).toBe(0);+ });++ test('timeoutSeconds clamps to the 24h ceiling', () => {+ const v = validateDelegatedSyncOptions({ timeoutSeconds: 999_999_999 });+ expect(v.ok).toBe(true);+ if (v.ok) expect(v.options.timeoutSeconds).toBe(DELEGATED_SYNC_TIMEOUT_MAX_SECONDS);+ });++ test('sourceId must satisfy the canonical shape', () => {+ expect(validateDelegatedSyncOptions({ sourceId: 'UPPER', timeoutSeconds: 60 })).toEqual({+ ok: false,+ error: 'invalid_options:sourceId',+ });+ expect(validateDelegatedSyncOptions({ sourceId: '-lead', timeoutSeconds: 60 }).ok).toBe(false);+ expect(validateDelegatedSyncOptions({ sourceId: 'ok-source', timeoutSeconds: 60 }).ok).toBe(true);+ });++ test('field table and options interface stay in lockstep', () => {+ // The validator iterates the table; if a field is added to the interface+ // but not the table it becomes unreachable from the wire — this pin makes+ // that drift loud.+ expect(Object.keys(DELEGATED_SYNC_OPTION_FIELDS).sort()).toEqual([+ 'dryRun',+ 'full',+ 'includeGitignored',+ 'noEmbed',+ 'noExtract',+ 'noPull',+ 'noSchemaPack',+ 'retryFailed',+ 'skipFailed',+ 'sourceId',+ 'timeoutSeconds',+ ]);+ });+});++describe('toWireSyncResult', () => {+ const base: SyncResult = {+ status: 'synced',+ fromCommit: 'aaa',+ toCommit: 'bbb',+ added: 2,+ modified: 1,+ deleted: 0,+ renamed: 0,+ chunksCreated: 3,+ embedded: 0,+ pagesAffected: [],+ };++ test('passes small results through with an exact total', () => {+ const r = toWireSyncResult({ ...base, pagesAffected: ['a', 'b'] });+ expect(r.pagesAffected).toEqual(['a', 'b']);+ expect(r.pagesAffectedTotal).toBe(2);+ });++ test('truncates pagesAffected past the cap and reports the true total', () => {+ const pages = Array.from({ length: WIRE_PAGES_AFFECTED_MAX + 1 }, (_, i) => `p/${i}`);+ const r = toWireSyncResult({ ...base, pagesAffected: pages });+ expect(r.pagesAffected).toHaveLength(WIRE_PAGES_AFFECTED_MAX);+ expect(r.pagesAffectedTotal).toBe(WIRE_PAGES_AFFECTED_MAX + 1);+ expect(r.pagesAffected[0]).toBe('p/0');+ });++ test('preserves partial-result fields', () => {+ const r = toWireSyncResult({+ ...base,+ status: 'partial',+ reason: 'timeout',+ filesImported: 7,+ bankedFiles: 7,+ });+ expect(r.status).toBe('partial');+ expect(r.reason).toBe('timeout');+ expect(r.bankedFiles).toBe(7);+ });+});diff --git a/test/e2e/sync-delegation-under-serve.serial.test.ts b/test/e2e/sync-delegation-under-serve.serial.test.tsnew file mode 100644index 0000000000..25bcd131fc--- /dev/null+++ b/test/e2e/sync-delegation-under-serve.serial.test.ts@@ -0,0 +1,275 @@+/**+ * Serve-delegated sync — end-to-end pins (the whole arc, real processes).+ *+ * A REAL `gbrain serve` subprocess owns a temp PGLite brain's single-writer+ * lock while REAL `gbrain sync` subprocesses run against the same brain:+ *+ * Pin 1 — delegation happy path: `gbrain sync --no-pull --yes` under the+ * live serve exits 0 via the delegation banner, and the job's+ * sync_status (queried over the real socket with the on-disk+ * secret) reports done with the seeded pages imported.+ * Pin 2 — default-deny refusal: `gbrain sync --repo <dir>` under the live+ * serve exits 1 with the named-flag remediation, no stack trace.+ * Pin 3 — chaos: SIGKILL the serve mid-delegated-sync → the client exits 1+ * with the checkpoint-resume hint (and the 60s lock-grace note).+ * Pin 4 — resume: `sync --force-break-lock` clears the dead holder's row,+ * then a DIRECT `gbrain sync` (dead PGLite lock reaped by+ * acquireLock — the ladder's rung-2 regression) completes from the+ * checkpoint and the pages are really in the brain.+ *+ * Serial + e2e: spawns subprocesses, cold PGLite init, one brain shared+ * across ordered pins. The serve child is SIGKILLed in afterAll no matter+ * what. PGLite-only — this file must run WITHOUT DATABASE_URL (the env strip+ * below also guards against a CI-injected one).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { execSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++import { ipcSecretPath, readIpcSecret, requestSyncStatus, resolveSocketPath } from '../../src/core/context/resolve-ipc.ts';+import type { SyncStatusResponse } from '../../src/core/context/sync-ipc.ts';+import { createEngine } from '../../src/core/engine-factory.ts';+import { addSource } from '../../src/core/sources-ops.ts';++const REPO_ROOT = resolve(import.meta.dir, '..', '..');++const SAVED_ENV: Record<string, string | undefined> = {};+const ENV_KEYS = [+ 'GBRAIN_HOME', 'GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID',+ 'GBRAIN_SOURCE', 'GBRAIN_HOOKS', 'GBRAIN_SWEEP', 'GBRAIN_SYNC_NO_DELEGATE',+];++// Short prefix — the IPC unix socket lives under database_path and socket+// paths cap out around 104 bytes on macOS.+let tmpParent: string;+let home: string;+let dbDir: string;+let repo: string;+let serveProc: ReturnType<typeof Bun.spawn> | null = null;+const serveStderr: string[] = [];++function childEnv(): Record<string, string> {+ return {+ ...process.env,+ GBRAIN_HOME: tmpParent,+ HOME: tmpParent,+ GBRAIN_SOURCE: 'workspace',+ GBRAIN_SWEEP: '0',+ } as Record<string, string>;+}++async function runSyncChild(+ args: string[],+ opts: { onStderrLine?: (line: string, kill: () => void) => void; timeoutMs?: number } = {},+): Promise<{ code: number; out: string; err: string }> {+ const proc = Bun.spawn(['bun', 'run', join(REPO_ROOT, 'src', 'cli.ts'), 'sync', ...args], {+ cwd: REPO_ROOT,+ env: childEnv(),+ stdin: 'ignore',+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const decoder = new TextDecoder();+ let out = '';+ let err = '';+ const kill = () => { try { serveProc?.kill('SIGKILL'); } catch { /* dead */ } };+ const outDone = (async () => {+ const r = (proc.stdout as ReadableStream<Uint8Array>).getReader();+ for (;;) { const { value, done } = await r.read(); if (done) break; out += decoder.decode(value, { stream: true }); }+ })();+ const errDone = (async () => {+ const r = (proc.stderr as ReadableStream<Uint8Array>).getReader();+ for (;;) {+ const { value, done } = await r.read();+ if (done) break;+ const chunk = decoder.decode(value, { stream: true });+ err += chunk;+ if (opts.onStderrLine) for (const line of chunk.split('\n')) opts.onStderrLine(line, kill);+ }+ })();+ const timeout = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* dead */ } }, opts.timeoutMs ?? 120_000);+ const code = await proc.exited;+ clearTimeout(timeout);+ await Promise.all([outDone, errDone]);+ return { code, out, err };+}++function gitCommitAll(msg: string): void {+ execSync(`git add -A && git commit -m "${msg}"`, { cwd: repo, stdio: 'pipe', shell: '/bin/bash' as never });+}++function writeNotes(from: number, to: number): void {+ for (let i = from; i < to; i++) {+ writeFileSync(+ join(repo, 'topics', `note-${String(i).padStart(4, '0')}.md`),+ `---\ntype: concept\ntitle: Note ${i} Example\n---\n\nBody for note ${i}.\n`,+ );+ }+}++async function pollFor(pred: () => boolean, deadlineMs: number, label: string): Promise<void> {+ const deadline = Date.now() + deadlineMs;+ while (Date.now() < deadline) {+ if (pred()) return;+ if (serveProc && serveProc.exitCode !== null) {+ throw new Error(`serve exited early (code ${serveProc.exitCode}) while waiting for ${label}\nstderr:\n${serveStderr.join('')}`);+ }+ await new Promise((r) => setTimeout(r, 150));+ }+ throw new Error(`timed out waiting for ${label}\nserve stderr:\n${serveStderr.join('')}`);+}++beforeAll(async () => {+ for (const k of ENV_KEYS) SAVED_ENV[k] = process.env[k];+ // A dev/CI DATABASE_URL must not flip the sandboxed brain to Postgres.+ delete process.env.GBRAIN_DATABASE_URL;+ delete process.env.DATABASE_URL;+ delete process.env.GBRAIN_BRAIN_ID;+ delete process.env.GBRAIN_HOOKS;+ delete process.env.GBRAIN_SYNC_NO_DELEGATE;++ tmpParent = mkdtempSync(join(tmpdir(), 'gb-sds-'));+ home = join(tmpParent, '.gbrain');+ mkdirSync(home, { recursive: true });+ dbDir = join(tmpParent, 'db');+ process.env.GBRAIN_HOME = tmpParent;+ process.env.GBRAIN_SOURCE = 'workspace';++ writeFileSync(+ join(home, 'config.json'),+ JSON.stringify({ engine: 'pglite', database_path: dbDir, embedding_dimensions: 1536 }, null, 2),+ );++ // Real git repo the source syncs from.+ repo = mkdtempSync(join(tmpdir(), 'gb-sds-repo-'));+ execSync('git init && git config user.email [email protected] && git config user.name T', {+ cwd: repo, stdio: 'pipe', shell: '/bin/bash' as never,+ });+ mkdirSync(join(repo, 'topics'), { recursive: true });+ writeNotes(0, 2);+ gitCommitAll('initial');++ // Pre-init the brain in-process (schema + source) so the serve boots fast.+ const engineConfig = { engine: 'pglite' as const, database_path: dbDir };+ const engine = await createEngine(engineConfig);+ await engine.connect(engineConfig);+ await engine.initSchema();+ await addSource(engine, { id: 'workspace', localPath: repo, force: true });+ await engine.disconnect();++ serveProc = Bun.spawn(['bun', 'run', join(REPO_ROOT, 'src', 'cli.ts'), 'serve'], {+ cwd: REPO_ROOT,+ env: {+ ...childEnv(),+ GBRAIN_SKIP_STARTUP_HOOKS: '1',+ GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300',+ },+ stdin: 'pipe',+ stdout: 'pipe',+ stderr: 'pipe',+ });+ void (async () => {+ const reader = (serveProc!.stderr as ReadableStream<Uint8Array>).getReader();+ const decoder = new TextDecoder();+ try {+ for (;;) { const { value, done } = await reader.read(); if (done) break; serveStderr.push(decoder.decode(value, { stream: true })); }+ } catch { /* child gone */ }+ })();++ await pollFor(+ () => existsSync(resolveSocketPath(dbDir)) && existsSync(ipcSecretPath(dbDir)),+ 120_000,+ 'IPC socket + secret',+ );+}, 240_000);++afterAll(async () => {+ if (serveProc && serveProc.exitCode === null) {+ try { serveProc.kill('SIGKILL'); await serveProc.exited; } catch { /* dead */ }+ }+ for (const k of ENV_KEYS) {+ if (SAVED_ENV[k] === undefined) delete process.env[k];+ else process.env[k] = SAVED_ENV[k];+ }+ for (const dir of [tmpParent, repo]) {+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }+ }+});++describe('serve-delegated sync (real serve + real sync subprocesses)', () => {+ test('Pin 1 — sync under a live serve delegates and completes', async () => {+ const r = await runSyncChild(['--no-pull', '--yes']);+ expect(r.err).toContain('delegating the sync through it (job ');+ expect(r.code).toBe(0);++ // The job's result is queryable over the real socket with the real secret.+ const jobId = /\(job ([0-9a-f-]+)/.exec(r.err)?.[1];+ expect(jobId).toBeTruthy();+ const secret = readIpcSecret(dbDir)!;+ const s = await requestSyncStatus(resolveSocketPath(dbDir), { secret, jobId: jobId! });+ const status = s as SyncStatusResponse;+ expect(status.ok).toBe(true);+ expect(status.state).toBe('done');+ expect(status.result!.added).toBe(2);+ // Embeds are deferred, never claimed.+ expect(status.result!.embedded).toBe(0);+ expect(r.err).toContain('embeds deferred');+ // Serve survived the whole thing.+ expect(serveProc!.exitCode).toBeNull();+ }, 120_000);++ test('Pin 2 — unsupported flag refuses by name with remediation, exit 1, no stack', async () => {+ const r = await runSyncChild(['--repo', repo]);+ expect(r.code).toBe(1);+ expect(r.err).toContain('`--repo` isn\'t supported through serve-delegated sync');+ expect(r.err).toContain('--no-delegate');+ expect(r.err).not.toContain('LiveServeLockError');+ expect(serveProc!.exitCode).toBeNull();+ }, 60_000);++ test('Pin 3 — SIGKILL the serve mid-delegated-sync → resume hint, exit 1', async () => {+ // Enough new files that the job is still importing when the kill lands.+ writeNotes(2, 302);+ gitCommitAll('bulk notes');+ let killed = false;+ const r = await runSyncChild(['--no-pull', '--yes'], {+ timeoutMs: 180_000,+ onStderrLine: (line, kill) => {+ if (!killed && line.includes('delegating the sync through it')) {+ killed = true;+ kill();+ }+ },+ });+ expect(killed).toBe(true);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/died mid-sync|stopped answering|restarted mid-sync/);+ expect(r.err).toContain('progress is checkpointed');+ expect(r.err).toContain('--break-lock');+ }, 200_000);++ test('Pin 4 — dead serve: row lock force-broken, DIRECT sync resumes from checkpoint', async () => {+ // The dead serve's PGLite data-dir lock is reaped by acquireLock (dead+ // PID), so the delegation ladder returns false and sync runs directly —+ // the rung-2 regression pin. The gbrain-sync ROW lock is dead-held for+ // the 60s takeover grace, so break it explicitly first.+ const br = await runSyncChild(['--force-break-lock', '--yes'], { timeoutMs: 120_000 });+ expect(br.code).toBe(0);++ const r = await runSyncChild(['--no-pull', '--yes', '--no-embed'], { timeoutMs: 180_000 });+ expect(r.err).not.toContain('delegating the sync');+ expect(r.code).toBe(0);++ // The pages are really in the brain (direct engine open works now).+ const engineConfig = { engine: 'pglite' as const, database_path: dbDir };+ const engine = await createEngine(engineConfig);+ await engine.connect(engineConfig);+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages WHERE source_id = 'workspace' AND deleted_at IS NULL`,+ );+ await engine.disconnect();+ expect(rows[0].n).toBeGreaterThanOrEqual(302);+ }, 240_000);+});diff --git a/test/pglite-lock.test.ts b/test/pglite-lock.test.tsindex 6d2782003a..4dff5c9b0e 100644--- a/test/pglite-lock.test.ts+++ b/test/pglite-lock.test.ts@@ -139,7 +139,7 @@ describe('pglite-lock #2058 heartbeat + steal-grace', () => {const startedAt = Date.now();await expect(acquireLock(TEST_DIR, { timeoutMs: 5_000 })).rejects.toThrow(- /already open through `gbrain serve`.*Stop `gbrain serve`, then retry this CLI command.*use its MCP tools instead.*will not remove/s,+ /already open through `gbrain serve`.*`gbrain sync` runs through the live serve automatically.*stop `gbrain serve` and retry.*use its MCP tools instead.*will not remove/s,);expect(Date.now() - startedAt).toBeLessThan(1_000);diff --git a/test/serve-sync-runner.serial.test.ts b/test/serve-sync-runner.serial.test.tsnew file mode 100644index 0000000000..3bf7e2c12a--- /dev/null+++ b/test/serve-sync-runner.serial.test.ts@@ -0,0 +1,230 @@+/**+ * Serve-delegated sync job runner pins (core/serve-sync-runner.ts).+ *+ * What these tests protect:+ * - single-flight: a second start while a job runs answers `busy` fast;+ * correctness still rests on the gbrain-sync row lock inside performSync.+ * - clientToken attach: a lost-ack retry finds its OWN job (running → same+ * jobId; retained terminal → completed:true) instead of duplicate-running.+ * - abort → typed partial → checkpoint resume: the abort/resume story the+ * delegation UX promises ("progress is checkpointed — re-run to resume").+ * - shutdownDelegatedSync is an idempotent shared promise (both serve+ * shutdown paths race here on every signal).+ * - delegated jobs always defer embeds and flag the drain backlog.+ *+ * Marked .serial.test.ts: spawns git subprocesses and shares one PGLite+ * engine across tests.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import {+ __deferredEmbedsPendingForTests,+ __resetDelegatedSyncForTests,+ abortDelegatedSync,+ delegatedSyncSettleMs,+ getDelegatedSyncStatus,+ isDelegatedSyncRunning,+ shutdownDelegatedSync,+ startDelegatedSync,+} from '../src/core/serve-sync-runner.ts';++let engine: PGLiteEngine;+let repoPath: string;++function gitInit(repo: string): void {+ execSync('git init', { cwd: repo, stdio: 'pipe' });+ execSync('git config user.email "[email protected]"', { cwd: repo, stdio: 'pipe' });+ execSync('git config user.name "Test"', { cwd: repo, stdio: 'pipe' });+}++function writeNote(name: string, title: string): void {+ writeFileSync(join(repoPath, `topics/${name}.md`), [+ '---',+ 'type: concept',+ `title: ${title}`,+ '---',+ '',+ `Content for ${title}.`,+ ].join('\n'));+}++/** Poll the job until it reaches a terminal state (bounded). */+async function waitForTerminal(jobId: string, timeoutMs = 30_000): Promise<ReturnType<typeof getDelegatedSyncStatus>> {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const s = getDelegatedSyncStatus(jobId);+ if (!s.ok) return s;+ if (s.state === 'done' || s.state === 'error') return s;+ if (Date.now() > deadline) throw new Error(`job ${jobId} did not settle within ${timeoutMs}ms (state=${s.state})`);+ await new Promise((r) => setTimeout(r, 25));+ }+}++describe('serve-sync-runner delegated jobs', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);++ afterAll(async () => {+ if (engine) await engine.disconnect();+ }, 60_000);++ beforeEach(async () => {+ __resetDelegatedSyncForTests();+ await resetPgliteState(engine);+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-ssr-'));+ gitInit(repoPath);+ mkdirSync(join(repoPath, 'topics'), { recursive: true });+ writeNote('alpha', 'Alpha Example');+ writeNote('beta', 'Beta Example');+ execSync('git add -A && git commit -m "initial"', { cwd: repoPath, stdio: 'pipe' });+ // Delegated jobs never carry repoPath on the wire — performSync reads the+ // source row's local_path (a fresh initSchema seeds 'default' with null).+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [repoPath]);+ });++ afterEach(() => {+ if (repoPath) rmSync(repoPath, { recursive: true, force: true });+ });++ test('start → status polls → done with a real WireSyncResult; embeds deferred', async () => {+ const start = startDelegatedSync(+ engine,+ { sourceId: 'default', noPull: true, timeoutSeconds: 120 },+ 'token-happy',+ );+ expect(start.ok).toBe(true);+ expect(start.jobId).toBeTruthy();+ expect(isDelegatedSyncRunning()).toBe(true);++ const s = await waitForTerminal(start.jobId!);+ expect(s.ok).toBe(true);+ expect(s.state).toBe('done');+ expect(s.sourceId).toBe('default');+ expect(s.result).toBeDefined();+ expect(s.result!.added).toBe(2);+ // first_sync's full-import path reports pagesAffected: [] by design;+ // the truncation invariant (total === untruncated length) is what the+ // wire must preserve here.+ expect(s.result!.pagesAffectedTotal).toBe(s.result!.pagesAffected.length);+ // The wire result must never claim embeds happened — they are deferred.+ expect(s.result!.embedded).toBe(0);+ expect(__deferredEmbedsPendingForTests()).toBe(true);+ expect(isDelegatedSyncRunning()).toBe(false);+ // The imported pages are really in the brain.+ expect(await engine.getPage('topics/alpha')).not.toBeNull();+ }, 60_000);++ test('single-flight: a different token while running answers busy with the jobId', () => {+ const first = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-a');+ expect(first.ok).toBe(true);+ // Same tick — the async job body has not settled, so the guard must hold.+ const second = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-b');+ expect(second.ok).toBe(false);+ expect(second.error).toBe('busy');+ expect(second.jobId).toBe(first.jobId);+ });++ test('clientToken attach: running retry returns the SAME job; terminal retry returns completed', async () => {+ const first = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-attach');+ const retry = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-attach');+ expect(retry.ok).toBe(true);+ expect(retry.jobId).toBe(first.jobId);+ expect(retry.completed).toBeUndefined();++ await waitForTerminal(first.jobId!);+ const afterDone = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-attach');+ expect(afterDone.ok).toBe(true);+ expect(afterDone.jobId).toBe(first.jobId);+ expect(afterDone.completed).toBe(true);+ // A DIFFERENT token after terminal starts a fresh run (the retained job is replaced).+ const fresh = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60, sourceId: 'default' }, 'token-next');+ expect(fresh.ok).toBe(true);+ expect(fresh.jobId).not.toBe(first.jobId);+ await waitForTerminal(fresh.jobId!);+ }, 60_000);++ test('abort → typed partial; a second delegated sync resumes from the checkpoint', async () => {+ const first = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 120, sourceId: 'default' }, 'token-abort');+ expect(first.ok).toBe(true);+ // Abort before the job body reaches the import loop — the pre-bookmark+ // signal checks turn this into a typed partial, never a throw.+ const ab = abortDelegatedSync(first.jobId!);+ expect(ab.ok).toBe(true);+ const s = await waitForTerminal(first.jobId!);+ expect(s.state).toBe('done');+ expect(s.result!.status).toBe('partial');+ expect(['timeout', 'pull_timeout', 'stall_timeout']).toContain(s.result!.reason!);++ // Resume: a fresh delegated run completes the remainder.+ const second = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 120, sourceId: 'default' }, 'token-resume');+ const s2 = await waitForTerminal(second.jobId!);+ expect(s2.state).toBe('done');+ expect(['first_sync', 'synced', 'up_to_date']).toContain(s2.result!.status);+ expect(await engine.getPage('topics/alpha')).not.toBeNull();+ expect(await engine.getPage('topics/beta')).not.toBeNull();+ }, 60_000);++ test('unknown jobId: status and abort answer unknown_job (serve restarted mid-sync)', () => {+ expect(getDelegatedSyncStatus('nope')).toEqual({ ok: false, protocol: 2, error: 'unknown_job' });+ expect(abortDelegatedSync('nope')).toEqual({ ok: false, protocol: 2, error: 'unknown_job' });+ });++ test('options are validated at the runner boundary (smuggled keys refuse)', () => {+ const r = startDelegatedSync(engine, { repoPath: '/tmp/evil', timeoutSeconds: 60 }, 'token-x');+ expect(r.ok).toBe(false);+ expect(r.error).toBe('invalid_options:repoPath');+ expect(isDelegatedSyncRunning()).toBe(false);+ });++ test('bound-source mismatch refuses before any work starts', () => {+ const r = startDelegatedSync(+ engine,+ { sourceId: 'other', timeoutSeconds: 60 },+ 'token-y',+ { boundSourceId: 'default' },+ );+ expect(r).toEqual({ ok: false, protocol: 2, error: 'source_mismatch' });+ });++ test('shutdownDelegatedSync aborts the job, settles bounded, is idempotent, and refuses new starts', async () => {+ const first = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 120, sourceId: 'default' }, 'token-shutdown');+ expect(first.ok).toBe(true);+ const p1 = shutdownDelegatedSync(5_000);+ const p2 = shutdownDelegatedSync(5_000);+ // Idempotent shared promise: both racing shutdown paths await the SAME settle.+ expect(p1).toBe(p2);+ await p1;+ const s = getDelegatedSyncStatus(first.jobId!);+ expect(s.ok).toBe(true);+ expect(['done', 'error']).toContain(s.state!);+ const refused = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 60 }, 'token-late');+ expect(refused).toEqual({ ok: false, protocol: 2, error: 'shutting_down' });+ }, 60_000);++ test('dry runs never flag the deferred-embed backlog', async () => {+ const start = startDelegatedSync(+ engine,+ { sourceId: 'default', noPull: true, dryRun: true, timeoutSeconds: 60 },+ 'token-dry',+ );+ await waitForTerminal(start.jobId!);+ expect(__deferredEmbedsPendingForTests()).toBe(false);+ }, 60_000);++ test('settle bound resolver clamps and defaults sanely', () => {+ expect(delegatedSyncSettleMs({})).toBe(3000);+ expect(delegatedSyncSettleMs({ GBRAIN_SERVE_SYNC_SETTLE_MS: '8000' })).toBe(8000);+ expect(delegatedSyncSettleMs({ GBRAIN_SERVE_SYNC_SETTLE_MS: '-5' })).toBe(3000);+ expect(delegatedSyncSettleMs({ GBRAIN_SERVE_SYNC_SETTLE_MS: 'junk' })).toBe(3000);+ expect(delegatedSyncSettleMs({ GBRAIN_SERVE_SYNC_SETTLE_MS: '999999' })).toBe(60_000);+ });+});diff --git a/test/sync-delegate-ladder.test.ts b/test/sync-delegate-ladder.test.tsnew file mode 100644index 0000000000..b7f75662fc--- /dev/null+++ b/test/sync-delegate-ladder.test.ts@@ -0,0 +1,146 @@+/**+ * Serve-delegated sync — CLI ladder pins (commands/sync-delegate.ts).+ *+ * The load-bearing property is DEFAULT-DENY: any sync argv token outside the+ * explicit allowlist refuses by name. A silently-dropped `--exclude` or+ * `--src-subpath` would perform the WRONG sync (whole repo instead of the+ * scoped subset) — refusing is the only safe default, and it means every+ * FUTURE sync flag is delegation-safe until someone classifies it.+ *+ * Parallel-safe: pure functions + hermetic tmpdir lock fixtures; no env+ * mutation (deriveDelegatedTimeoutSeconds takes injected env/tty).+ */++import { describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ IGNORED_FLAGS,+ VALUE_FLAGS,+ WIRE_BOOL_FLAGS,+ deriveDelegatedTimeoutSeconds,+ maybeDelegateSyncToServe,+ parseDelegatedSyncArgs,+} from '../src/commands/sync-delegate.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';++describe('parseDelegatedSyncArgs (default-deny)', () => {+ test('bare sync → empty options, no explicit source', () => {+ expect(parseDelegatedSyncArgs([])).toEqual({ ok: true, options: {}, explicitSource: null });+ });++ test('the full wire-forwardable set maps field-for-field', () => {+ const r = parseDelegatedSyncArgs([+ '--full', '--dry-run', '--no-pull', '--no-embed', '--no-extract',+ '--no-schema-pack', '--skip-failed', '--retry-failed', '--include-gitignored',+ '--source', 'notes',+ ]);+ expect(r.ok).toBe(true);+ if (!r.ok) throw new Error('unreachable');+ expect(r.options).toEqual({+ full: true, dryRun: true, noPull: true, noEmbed: true, noExtract: true,+ noSchemaPack: true, skipFailed: true, retryFailed: true, includeGitignored: true,+ });+ expect(r.explicitSource).toBe('notes');+ });++ test('deadline/prompt flags are consumed or ignored, never refused', () => {+ expect(parseDelegatedSyncArgs(['--timeout', '60', '--yes', '--no-hard-deadline', '--no-delegate']).ok).toBe(true);+ expect(parseDelegatedSyncArgs(['--hard-deadline', '2h']).ok).toBe(true);+ });++ test.each([+ ['--repo'], ['--watch'], ['--all'], ['--workers'], ['--concurrency'],+ ['--json'], ['--exclude'], ['--src-subpath'], ['--break-lock'],+ ['--force-break-lock'], ['--max-age'], ['--missing-path'], ['--parallel'],+ ['--interval'], ['--serial'], ['--strategy'], ['trigger'],+ ['--some-flag-added-in-2027'],+ ])('refuses %s by name (default-deny)', (tok) => {+ expect(parseDelegatedSyncArgs([tok])).toEqual({ ok: false, refused: tok });+ });++ test('a value flag with a missing/flag-shaped value refuses loudly', () => {+ expect(parseDelegatedSyncArgs(['--source'])).toEqual({ ok: false, refused: '--source (missing value)' });+ expect(parseDelegatedSyncArgs(['--source', '--full'])).toEqual({ ok: false, refused: '--source (missing value)' });+ });++ test('every allowlisted flag exists in the generated sync flag registry', () => {+ // Drift pin (eng-review F5): the pre-dispatch validator rejects flags the+ // registry doesn't know — an allowlist entry missing from the registry+ // would be dead on arrival. (The reverse direction is covered by+ // default-deny: unclassified registry flags refuse at runtime.)+ const registry = new Set(CLI_FLAG_REGISTRY['sync']);+ for (const flag of [...Object.keys(WIRE_BOOL_FLAGS), ...VALUE_FLAGS, ...IGNORED_FLAGS]) {+ expect(registry.has(flag)).toBe(true);+ }+ });+});++describe('deriveDelegatedTimeoutSeconds', () => {+ const noEnv = {};+ test('--no-hard-deadline is the ONLY unbounded encoding (0 = no server timer)', async () => {+ expect(await deriveDelegatedTimeoutSeconds(['--no-hard-deadline'], { isTty: true, env: noEnv })).toBe(0);+ });+ test('interactive TTY default maps to the same 3600s the non-TTY default uses', async () => {+ expect(await deriveDelegatedTimeoutSeconds([], { isTty: true, env: noEnv })).toBe(3600);+ expect(await deriveDelegatedTimeoutSeconds([], { isTty: false, env: noEnv })).toBe(3600);+ });+ test('explicit flags win: --hard-deadline then --timeout', async () => {+ expect(await deriveDelegatedTimeoutSeconds(['--hard-deadline', '120'], { isTty: true, env: noEnv })).toBe(120);+ expect(await deriveDelegatedTimeoutSeconds(['--timeout', '60'], { isTty: true, env: noEnv })).toBe(60);+ });+ test('env knob applies when set', async () => {+ expect(+ await deriveDelegatedTimeoutSeconds([], { isTty: true, env: { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '900' } }),+ ).toBe(900);+ });+});++describe('maybeDelegateSyncToServe short-circuits (no socket I/O)', () => {+ function dirWithLiveServeLock(): string {+ const dir = mkdtempSync(join(tmpdir(), 'sdl-'));+ mkdirSync(join(dir, '.gbrain-lock'), { recursive: true });+ writeFileSync(+ join(dir, '.gbrain-lock', 'lock'),+ JSON.stringify({+ pid: process.pid, // provably alive: it is us+ acquired_at: new Date().toISOString(),+ refreshed_at: new Date().toISOString(),+ command: '/x/gbrain/src/cli.ts serve',+ subcommand: 'serve',+ }),+ );+ return dir;+ }++ test('no holder → false (normal connect path, REGRESSION pin)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'sdl-empty-'));+ expect(await maybeDelegateSyncToServe(dir, [])).toBe(false);+ });++ test('--no-delegate opts out even under a live serve', async () => {+ const dir = dirWithLiveServeLock();+ expect(await maybeDelegateSyncToServe(dir, ['--no-delegate'])).toBe(false);+ });++ test('live NON-serve holder → false (existing bounded-wait behavior)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'sdl-cli-'));+ mkdirSync(join(dir, '.gbrain-lock'), { recursive: true });+ writeFileSync(+ join(dir, '.gbrain-lock', 'lock'),+ JSON.stringify({ pid: process.pid, subcommand: 'embed', command: 'cli.ts embed' }),+ );+ expect(await maybeDelegateSyncToServe(dir, [])).toBe(false);+ });++ test('live serve + unsupported flag → handled (named refusal, no socket needed)', async () => {+ const dir = dirWithLiveServeLock();+ expect(await maybeDelegateSyncToServe(dir, ['--repo', '/tmp/x'])).toBe(true);+ });++ test('live serve + no IPC socket → handled (polite refusal)', async () => {+ const dir = dirWithLiveServeLock();+ expect(await maybeDelegateSyncToServe(dir, [])).toBe(true);+ });+});