Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(sync): hand-off authorization, skew fallbacks and the Postgres delegated drain with a spawned serve (#6317 T-07, T1c)

garrytanfbec5602cd81
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index f1b85780bb..ec34078a9b 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -23,7 +23,7 @@
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
- `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; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
-- `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 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/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 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 never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) keeps the CLI's own consumer with one actionable line. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).
- `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/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 614d92f937..4a2712584a 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; native Bun terminal (`Bun.spawn({ terminal })`, skipped on win32) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).
-- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
+- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 1e792d463a..e147f0e8ef 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -320,6 +320,7 @@ test/serve-idle-sweep-source.serial.test.ts R2 R2: mock.module(../src/core/sweep
test/serve-source-guard.serial.test.ts R1 R1: mutates process.env (GBRAIN_SOURCE)
test/serve-status-mode.serial.test.ts global-state global-state: binds local servers/ports
test/serve-sync-embed-drain.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; process-wide test seams __setEmbedTransportForTests, __resetDelegatedSyncForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
+test/serve-sync-handoff.serial.test.ts global-state global-state: process-wide test seams __resetDelegatedSyncForTests; binds local servers/ports; patches process stdout/stderr/console
test/serve-sync-ipc-killswitch.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; patches process stdout/stderr/console
test/serve-sync-runner.serial.test.ts global-state global-state: process-wide test seams __resetDelegatedSyncForTests
test/session-seat-capture.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SEAT)
diff --git a/test/e2e/serve-delegated-managed-sync.serial.test.ts b/test/e2e/serve-delegated-managed-sync.serial.test.ts
new file mode 100644
index 0000000000..b56bbba6f0
--- /dev/null
+++ b/test/e2e/serve-delegated-managed-sync.serial.test.ts
@@ -0,0 +1,222 @@
+/**
+ * #6317 (D1 a′) on real Postgres: a spawned `gbrain serve` owns the host (its
+ * B3 heartbeat row says so), and `gbrain sync --source <id> --no-pull --no-embed
+ * --json` from a second process hands the managed catch-up to it over the
+ * resolve-IPC socket as the CLI's verified writer. Asserts the CLI's exit code
+ * and JSON envelope are the in-process ones, the drain's own lines reached the
+ * CLI, the serve (not the CLI) published every page, and `--no-delegate` keeps
+ * the CLI's own consumer beside the same serve.
+ *
+ * Measurement (the plan asks for it before rejecting the approach): while the
+ * delegated drain runs, the test sends MCP `tools/call` requests to the serve's
+ * stdio session every 250 ms and prints the request-latency percentiles. Set
+ * GBRAIN_E2E_DELEGATION_PAGES=1000 for the 1k-page fixture (the default keeps
+ * CI short); the numbers are printed, never asserted.
+ *
+ * Lane 1 owns the `persistence_consumers` migration and the serve's heartbeat;
+ * until they land this test creates the agreed table when absent and renews
+ * the spawned serve's row itself.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { hookResolveSocketForConfig, socketHasLiveListener } from '../../src/core/context/resolve-ipc.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..', '..');
+const PAGES = Number(process.env.GBRAIN_E2E_DELEGATION_PAGES ?? '60');
+const SOURCE = 'workspace';
+const describeWithDb = process.env.DATABASE_URL ? describe : describe.skip;
+
+let home: string, repo: string, databaseUrl: string;
+let engine: Awaited<ReturnType<typeof isolatedPersistencePostgres>>['engine'];
+let closeDb: (() => Promise<void>) | undefined;
+let serve: StdioServe | undefined;
+let heartbeat: ReturnType<typeof setInterval> | undefined;
+
+function git(...args: string[]): string { return execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+
+function childEnv(extra: Record<string, string | undefined> = {}): Record<string, string> {
+ return keylessBrainEnv(process.env, home, {
+ DATABASE_URL: databaseUrl, GBRAIN_DATABASE_URL: undefined, GBRAIN_DIRECT_DATABASE_URL: undefined,
+ GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: SOURCE, GBRAIN_SWEEP: '0', GBRAIN_HOOKS: undefined,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_SKILL_NAG: '1', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300', GBRAIN_SYNC_NO_DELEGATE: undefined,
+ ...extra,
+ });
+}
+
+/** One stdio MCP session against the spawned `gbrain serve` (ndjson JSON-RPC). */
+class StdioServe {
+ readonly child: ChildProcess;
+ stderr = '';
+ private buf = '';
+ private nextId = 1;
+ private pending = new Map<number, (msg: Record<string, unknown>) => void>();
+ constructor(env: Record<string, string>) {
+ this.child = spawn(process.execPath, [join(REPO_ROOT, 'src/cli.ts'), 'serve'], { cwd: REPO_ROOT, env, stdio: ['pipe', 'pipe', 'pipe'] });
+ this.child.stderr!.on('data', (d: Buffer) => { this.stderr += d.toString('utf8'); });
+ this.child.stdout!.on('data', (d: Buffer) => {
+ this.buf += d.toString('utf8');
+ let idx: number;
+ while ((idx = this.buf.indexOf('\n')) !== -1) {
+ const line = this.buf.slice(0, idx).trim(); this.buf = this.buf.slice(idx + 1);
+ if (!line) continue;
+ try {
+ const msg = JSON.parse(line) as Record<string, unknown>;
+ const id = msg.id as number | undefined;
+ if (id !== undefined && this.pending.has(id)) { this.pending.get(id)!(msg); this.pending.delete(id); }
+ } catch { /* serve chatter */ }
+ }
+ });
+ }
+ get pid(): number { return this.child.pid!; }
+ request(method: string, params: Record<string, unknown>, timeoutMs = 60_000): Promise<Record<string, unknown>> {
+ const id = this.nextId++;
+ return new Promise((resolvePromise, reject) => {
+ const t = setTimeout(() => { this.pending.delete(id); reject(new Error(`rpc ${id} (${method}) timed out`)); }, timeoutMs);
+ this.pending.set(id, (msg) => { clearTimeout(t); resolvePromise(msg); });
+ this.child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
+ });
+ }
+ async start(): Promise<void> {
+ await this.request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'delegation-e2e', version: '1' } }, 240_000);
+ this.child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ }
+ async call(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ return this.request('tools/call', { name, arguments: args });
+ }
+ async stop(): Promise<void> {
+ this.child.kill('SIGTERM');
+ await new Promise<void>((done) => { const t = setTimeout(() => { this.child.kill('SIGKILL'); done(); }, 8000); this.child.once('exit', () => { clearTimeout(t); done(); }); });
+ }
+}
+
+async function runSync(args: string[], env: Record<string, string | undefined> = {}, timeoutMs = 600_000): Promise<{ code: number; out: string; err: string }> {
+ const proc = Bun.spawn([process.execPath, join(REPO_ROOT, 'src/cli.ts'), 'sync', ...args], { cwd: REPO_ROOT, env: childEnv(env), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const timer = setTimeout(() => proc.kill('SIGKILL'), timeoutMs);
+ try {
+ const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { code, out, err };
+ } finally { clearTimeout(timer); }
+}
+
+async function until(check: () => boolean | Promise<boolean>, label: string, timeoutMs = 240_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (await check()) return;
+ if (serve && serve.child.exitCode !== null) throw new Error(`serve exited while waiting for ${label}: ${serve.stderr}`);
+ await Bun.sleep(100);
+ }
+ throw new Error(`timed out waiting for ${label}: ${serve?.stderr}`);
+}
+
+const percentile = (sorted: number[], p: number): number => sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] : NaN;
+
+describeWithDb('serve-delegated managed sync on Postgres (#6317 D1 a′)', () => {
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gb-sdm-'));
+ mkdirSync(join(home, '.gbrain'));
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine; databaseUrl = pg.databaseUrl; closeDb = pg.close;
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: databaseUrl, embedding_disabled: true }));
+ repo = mkdtempSync(join(tmpdir(), 'gb-sdm-repo-'));
+ git('init', '-q'); git('config', 'user.email', '[email protected]'); git('config', 'user.name', 'Example');
+ mkdirSync(join(repo, 'notes'));
+ for (let i = 0; i < PAGES; i++) writeFileSync(join(repo, 'notes', `note-${String(i).padStart(4, '0')}.md`), `---\ntype: concept\ntitle: Note ${i} Example\n---\n\nBody for note ${i}, an observation about acme-example.\n`);
+ git('add', '-A'); git('commit', '-qm', 'notes');
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, repo]);
+ // A second, unclaimed source for the source_mismatch case (the managed-writer guard refuses topology writes once enabled).
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', ['other', repo]);
+ await claimWorktree(engine, SOURCE, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ // Lane 1's table, by the agreed columns, when the migration is not in this tree yet.
+ await engine.executeRaw(`CREATE TABLE IF NOT EXISTS persistence_consumers (
+ host_id uuid NOT NULL, pid integer NOT NULL, nonce text NOT NULL, pid_ns text, kind text NOT NULL, mode text NOT NULL,
+ started_at timestamptz NOT NULL DEFAULT now(), renewed_at timestamptz NOT NULL DEFAULT now(), restart_required boolean NOT NULL DEFAULT false,
+ root_barrier_age_ms integer, pool jsonb, host_json_path text, persistence_home text, minted_under jsonb, version text,
+ PRIMARY KEY (host_id, pid, nonce))`);
+ serve = new StdioServe(childEnv());
+ await serve.start();
+ // The serve keys its socket under GBRAIN_HOME; resolve the same path here.
+ const sock = await withEnv({ GBRAIN_HOME: home }, () => hookResolveSocketForConfig({ engine: 'postgres', database_url: databaseUrl }, SOURCE));
+ await until(async () => !!sock && await socketHasLiveListener(sock), 'the serve\'s resolve-IPC socket');
+ const { localHostId } = await import('../../src/core/persistence/identity.ts');
+ const hostId = await withEnv({ GBRAIN_HOME: home }, async () => localHostId());
+ const renew = () => engine.executeRaw(`INSERT INTO persistence_consumers(host_id,pid,nonce,kind,mode,version) VALUES($1::uuid,$2,'e2e','serve','full','e2e')
+ ON CONFLICT (host_id,pid,nonce) DO UPDATE SET renewed_at=now()`, [hostId, serve!.pid]).catch(() => undefined);
+ await renew();
+ heartbeat = setInterval(() => { void renew(); }, 5_000);
+ heartbeat.unref?.();
+ }, 400_000);
+
+ afterAll(async () => {
+ if (heartbeat) clearInterval(heartbeat);
+ await serve?.stop();
+ try { await engine?.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); } catch { /* noop */ }
+ await closeDb?.();
+ rmSync(home, { recursive: true, force: true });
+ rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('the CLI hands the managed catch-up to the resident serve and prints the in-process result; MCP latency under the drain is measured', async () => {
+ const latencies: number[] = [];
+ let stopProbing = false;
+ const probing = (async () => {
+ while (!stopProbing) {
+ const at = performance.now();
+ try { await serve!.call('get_stats', {}); latencies.push(performance.now() - at); } catch { latencies.push(Number.POSITIVE_INFINITY); }
+ await Bun.sleep(250);
+ }
+ })();
+ const started = performance.now();
+ const result = await runSync(['--source', SOURCE, '--no-pull', '--no-embed', '--json']);
+ const elapsedMs = performance.now() - started;
+ stopProbing = true; await probing;
+ if (result.code !== 0) throw new Error(`sync exited ${result.code}\nstdout:\n${result.out}\nstderr:\n${result.err}\nserve stderr:\n${serve!.stderr}`);
+ expect(result.err).toMatch(new RegExp(`a live gbrain serve \\(PID ${serve!.pid}\\) owns this host's writes — running the managed catch-up inside it as this CLI's writer`));
+ expect(result.err).toMatch(new RegExp(`\\[sync\\] managed catch-up: ${PAGES} entries frozen`));
+ expect(serve!.stderr).toMatch(/\[serve-sync\] start job=.* managed=true/);
+ expect(serve!.stderr).toMatch(/\[serve-sync\] done job=.* drain=synced/);
+ const envelope = JSON.parse(result.out.trim().split('\n').pop()!) as Record<string, unknown>;
+ expect(envelope).toMatchObject({ schema_version: 1, source_id: SOURCE, sync_status: 'first_sync', added: PAGES, outcome: 'synced' });
+ expect(envelope.drain).toMatchObject({ outcome: 'synced', written: PAGES, remaining: 0 });
+ expect(envelope.next).toBeUndefined();
+ // The serve, never this CLI, held every claim: the owner stamps on the committed requests name its pid only.
+ const owners = await engine.executeRaw<{ pid: string | null; n: number }>(
+ `SELECT claim_phase->'owner'->>'pid' AS pid, count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state='committed' GROUP BY 1`, [SOURCE]);
+ const stamped = owners.filter(o => o.pid !== null);
+ expect(stamped.length).toBeGreaterThan(0);
+ expect(stamped.map(o => Number(o.pid))).toEqual([serve!.pid]);
+ const finite = latencies.filter(Number.isFinite).sort((a, b) => a - b);
+ const line = `[measure] serve-delegated drain of ${PAGES} pages in ${Math.round(elapsedMs / 1000)}s: ${latencies.length} MCP get_stats calls during it, ` +
+ `p50 ${percentile(finite, 0.5).toFixed(0)}ms p95 ${percentile(finite, 0.95).toFixed(0)}ms max ${(finite.at(-1) ?? NaN).toFixed(0)}ms, ${latencies.length - finite.length} timed out`;
+ console.error(line);
+ expect(latencies.length).toBeGreaterThan(0);
+ }, 900_000);
+
+ test('--no-delegate keeps this process\'s own consumer beside the same serve and still converges', async () => {
+ writeFileSync(join(repo, 'notes', 'late-note.md'), '---\ntype: concept\ntitle: Late Note Example\n---\n\nA page added after the first catch-up.\n');
+ git('add', '-A'); git('commit', '-qm', 'late');
+ const result = await runSync(['--source', SOURCE, '--no-pull', '--no-embed', '--no-delegate', '--json']);
+ if (result.code !== 0) throw new Error(`sync exited ${result.code}\nstdout:\n${result.out}\nstderr:\n${result.err}`);
+ expect(result.err).not.toMatch(/running the managed catch-up inside it/);
+ const envelope = JSON.parse(result.out.trim().split('\n').pop()!) as Record<string, unknown>;
+ expect(envelope).toMatchObject({ source_id: SOURCE, outcome: 'synced', added: 1 });
+ }, 600_000);
+
+ test('a serve bound to another source keeps this process\'s own consumer with one line (source_mismatch)', async () => {
+ const result = await runSync(['--source', 'other', '--no-pull', '--no-embed', '--json'], { GBRAIN_SOURCE: 'other' }, 120_000);
+ // The ladder reached the serve (through the legacy URL-keyed socket), was told source_mismatch, and kept the own consumer;
+ // what the unclaimed source does after that is the in-process path's business.
+ expect(result.err).toMatch(/\[sync\] the serve is bound to a different source than this sync targets.*this run uses its own consumer beside the serve \(PID \d+\)/);
+ expect(result.err).not.toMatch(/running the managed catch-up inside it/);
+ }, 300_000);
+});
diff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.ts
new file mode 100644
index 0000000000..f9eaf98d9d
--- /dev/null
+++ b/test/serve-sync-handoff.serial.test.ts
@@ -0,0 +1,349 @@
+/**
+ * #6317 (D1 a′): serve-delegated managed sync with a verified CLI-registration
+ * hand-off — the runner's authorization seam and the Postgres ladder's client
+ * half, hermetic on PGLite (the ladder takes its brain config, heartbeat probe
+ * and socket through seams; the serve half is the real resolve-IPC server
+ * bound to the real runner).
+ *
+ * What these tests protect:
+ * - the gate is NOT lifted: a shared-secret sync_start on a managed brain
+ * still fails `writer_coordinator_required` (assertDurableSyncCaller /
+ * assertUnmanagedCanonicalWriter by design);
+ * - the hand-off refuses a denied, revoked or stdio registration at
+ * sync_start with `permission_denied` and the OperationError envelope;
+ * - a verified `cli` registration runs the managed drain inside the serve:
+ * sync_status carries the drain's own lines (the `[sync] managed catch-up`
+ * start line), the DrainReport and `next`; the line cursor never resends;
+ * - the Postgres ladder: `--no-delegate` bypasses it before the classifier,
+ * an unsupported flag / a non-serve owner / no socket / GBRAIN_SERVE_SYNC_IPC=0
+ * / an older serve (`unknown_kind`, `stale_serve`) each keep the CLI's own
+ * consumer with ONE actionable line, and a live serve runs the drain and
+ * hands back the SyncResult the in-process printers take, with
+ * `gbrain sync --source <id> --no-pull --json` admitted unchanged.
+ *
+ * Marked .serial.test.ts: the runner is a module singleton
+ * (__resetDelegatedSyncForTests) and the tests bind local sockets.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type net from 'node:net';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { registerLocalWriter, revokeLocalWriter } from '../src/core/persistence/identity.ts';
+import { startResolveIpcServer, type IpcHandlers } from '../src/core/context/resolve-ipc.ts';
+import { localIpcSocketPath } from '../src/core/context/ipc-path.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import {
+ __resetDelegatedSyncForTests,
+ getDelegatedSyncStatus,
+ startDelegatedSync,
+} from '../src/core/serve-sync-runner.ts';
+import { maybeDelegateManagedSyncToServe, type ManagedDelegationDeps } from '../src/commands/sync-delegate.ts';
+import type { ConsumerRow } from '../src/core/persistence/consumer-heartbeat.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-handoff-'));
+const sources: string[] = [];
+let engine: BrainEngine;
+const SECRET = randomBytes(32).toString('hex');
+const servers: net.Server[] = [];
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+
+/** A managed source: a claimed git worktree of `count` notes on an activated brain (the managed-sync-drain fixture). */
+async function fixture(count: number): Promise<{ id: string; root: string }> {
+ const id = `handoff-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+
+async function waitTerminal(jobId: string, timeoutMs = 120_000): Promise<ReturnType<typeof getDelegatedSyncStatus>> {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const s = getDelegatedSyncStatus(jobId);
+ if (!s.ok || s.state === 'done' || s.state === 'error') return s;
+ if (Date.now() > deadline) throw new Error(`job ${jobId} did not settle: ${JSON.stringify(s)}`);
+ await Bun.sleep(50);
+ }
+}
+
+/** The serve half: the real resolve-IPC server with the real runner's sync handlers (the binding's wiring). */
+async function serveSocket(handlers?: Partial<IpcHandlers>, secret = SECRET): Promise<string> {
+ const sock = localIpcSocketPath(join(mkdtempSync(join(tmpdir(), 'handoff-sock-')), 'resolve.sock'));
+ const base: IpcHandlers = {
+ resolve: async () => null,
+ sync_start: (req) => startDelegatedSync(engine, req.options, req.clientToken, { registration: req.registration }),
+ sync_status: (req) => getDelegatedSyncStatus(req.jobId, typeof req.afterLine === 'number' ? req.afterLine : 0),
+ sync_abort: () => ({ ok: true, protocol: 2 as const }),
+ };
+ const server = await startResolveIpcServer(sock, { ...base, ...handlers }, { secret });
+ if (!server) throw new Error('could not bind the test IPC socket');
+ servers.push(server);
+ return sock;
+}
+
+/** Drop a revoked cli registration (row + private file) so the next test registers a fresh principal; host.json stays (the consumer's host identity). */
+async function forgetCliRegistration(id: string): Promise<void> {
+ await engine.executeRaw('DELETE FROM persistence_local_writers WHERE id=$1::uuid', [id]);
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ rmSync(join(home, '.gbrain', 'persistence', `${brain.brain_id}.cli.json`), { force: true });
+}
+
+const serveRow = (over: Partial<ConsumerRow> = {}): ConsumerRow => ({
+ host_id: 'host', pid: 4242, nonce: 'n1', pid_ns: null, kind: 'serve', mode: 'full', started_at: new Date().toISOString(),
+ renewed_at: new Date().toISOString(), restart_required: false, root_barrier_age_ms: null, pool: null,
+ host_json_path: null, persistence_home: null, minted_under: null, version: 'test', ...over,
+});
+
+const captured: string[] = [];
+const origError = console.error;
+const origWrite = process.stderr.write.bind(process.stderr);
+function captureStderr(): void {
+ captured.length = 0;
+ console.error = (...a: unknown[]) => { captured.push(a.map(String).join(' ')); };
+ process.stderr.write = ((chunk: string | Uint8Array) => { captured.push(String(chunk).replace(/\n$/, '')); return true; }) as typeof process.stderr.write;
+}
+function releaseStderr(): void { console.error = origError; process.stderr.write = origWrite; }
+
+function deps(over: Partial<ManagedDelegationDeps> & { sock?: string | null; secret?: string | null; row?: ConsumerRow | null }): ManagedDelegationDeps {
+ return {
+ config: { engine: 'postgres', database_url: 'postgresql://example.invalid/brain' },
+ probe: async () => over.row === undefined ? serveRow() : over.row,
+ socket: async () => ({ sock: over.sock ?? null, secret: over.secret === undefined ? SECRET : over.secret }),
+ env: over.env ?? {},
+ ...(over.config !== undefined ? { config: over.config } : {}),
+ };
+}
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite;
+}, 120_000);
+afterEach(() => { __resetDelegatedSyncForTests(); releaseStderr(); });
+afterAll(async () => {
+ for (const server of servers) { try { server.close(); } catch { /* noop */ } }
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ await engine.disconnect();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('sync_start authorization hand-off (serve half)', () => {
+ test('the shared-secret lane still refuses a managed brain: the gate is a hand-off, not a lift', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const start = startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 60 }, randomUUID());
+ expect(start.ok).toBe(true);
+ const done = await waitTerminal(start.jobId!);
+ expect(done.state).toBe('error');
+ expect(done.jobErrorEnvelope).toMatchObject({ error: 'writer_coordinator_required' });
+ expect(done.managed).toBeUndefined();
+ }), 120_000);
+
+ test('a registration that never existed is refused at sync_start with permission_denied and the envelope', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 60 }, randomUUID(),
+ { registration: { id: randomUUID(), credential: randomBytes(32).toString('hex'), lane: 'cli' } });
+ expect(start.ok).toBe(false);
+ expect(start.error).toBe('permission_denied');
+ expect(start.refusal).toMatchObject({ error: 'permission_denied', code: 'permission_denied' });
+ expect(typeof start.refusal!.message).toBe('string');
+ expect((start.refusal!.fix as { argv: string[] }).argv).toEqual(['gbrain', 'auth', 'local-writer', 'list', '--json']);
+ // The slot is retained terminal (a token retry attaches to the refusal, never a duplicate run), and the status says error.
+ const status = getDelegatedSyncStatus(start.jobId!);
+ expect(status.state).toBe('error');
+ expect(status.jobErrorEnvelope).toMatchObject({ error: 'permission_denied' });
+ }), 120_000);
+
+ test('a revoked cli registration is refused with permission_denied', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const local = await registerLocalWriter(engine, 'cli');
+ expect(await revokeLocalWriter(engine, local.id)).toBe(true);
+ try {
+ const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 60 }, randomUUID(),
+ { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ expect(start.ok).toBe(false);
+ expect(start.error).toBe('permission_denied');
+ expect(start.refusal).toMatchObject({ error: 'permission_denied' });
+ expect(String(start.refusal!.message)).toMatch(/revoked/);
+ } finally {
+ // The revocation persists in the row; re-register a fresh cli principal for the tests that follow.
+ await forgetCliRegistration(local.id);
+ }
+ }), 120_000);
+
+ test('a stdio-principal registration is refused: by shape (lane stdio) and by lane mismatch (a stdio row presented as cli)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const stdio = await registerLocalWriter(engine, 'stdio');
+ const shaped = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 60 }, randomUUID(),
+ { registration: { id: stdio.id, credential: stdio.credential, lane: 'stdio' } });
+ expect(shaped).toEqual({ ok: false, protocol: 2, error: 'invalid_options:registration' });
+ const forged = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 60 }, randomUUID(),
+ { registration: { id: stdio.id, credential: stdio.credential, lane: 'cli' } });
+ expect(forged.ok).toBe(false);
+ expect(forged.error).toBe('permission_denied');
+ expect(forged.refusal).toMatchObject({ error: 'permission_denied' });
+ }), 120_000);
+
+ test('a verified cli registration runs the managed drain inside the serve; sync_status carries its lines, the DrainReport and next', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(4);
+ const local = await registerLocalWriter(engine, 'cli');
+ const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, explicitProcessing: ['noEmbed'], timeoutSeconds: 120 }, randomUUID(),
+ { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ expect(start.ok).toBe(true);
+ const done = await waitTerminal(start.jobId!);
+ expect(done.state).toBe('done');
+ expect(done.managed).toBe(true);
+ expect(done.result).toMatchObject({ status: 'first_sync', added: 4 });
+ expect(done.drain).toMatchObject({ outcome: 'synced', written: 4, remaining: 0 });
+ expect(done.next).toBeNull();
+ const lines = (done.lines ?? []).map(l => l.text);
+ expect(lines.some(l => l.startsWith('[sync] managed catch-up: 4 entries frozen'))).toBe(true);
+ expect(done.lineSeq).toBe(lines.length);
+ // The line cursor: a poll after the newest sequence resends nothing; one before it resends the tail only.
+ expect(getDelegatedSyncStatus(start.jobId!, done.lineSeq!).lines).toEqual([]);
+ expect(getDelegatedSyncStatus(start.jobId!, done.lineSeq! - 1).lines).toHaveLength(1);
+ // The writer is this CLI principal: the committed requests carry it, not a shared-secret lane.
+ const rows = await engine.executeRaw<{ principal_id: string; n: number }>(
+ 'SELECT principal_id, count(*)::int AS n FROM persistence_requests WHERE source_id=$1 GROUP BY principal_id', [f.id]);
+ expect(rows.map(r => r.principal_id)).toEqual([local.id]);
+ }), 180_000);
+});
+
+describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', () => {
+ const baseOpts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, explicitProcessing: ['noEmbed'], drain: true });
+
+ test('--no-delegate and GBRAIN_SYNC_NO_DELEGATE=1 bypass the ladder before anything is probed', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ let probed = 0;
+ const d = { ...deps({}), probe: async () => { probed++; return serveRow(); } };
+ expect(await maybeDelegateManagedSyncToServe(engine, ['--no-delegate', '--repo', '/x'], baseOpts(f.id), d)).toEqual({ kind: 'own_consumer', reason: 'opted_out', line: null });
+ expect(await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), { ...d, env: { GBRAIN_SYNC_NO_DELEGATE: '1' } })).toEqual({ kind: 'own_consumer', reason: 'opted_out', line: null });
+ expect(probed).toBe(0);
+ }), 120_000);
+
+ test('no live owner, or a non-serve owner, keeps the CLI\'s own consumer (one line names a non-serve owner)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ captureStderr();
+ expect(await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ row: null }))).toEqual({ kind: 'own_consumer', reason: 'no_owner', line: null });
+ const jobs = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ row: serveRow({ kind: 'jobs', pid: 777 }) }));
+ releaseStderr();
+ expect(jobs).toMatchObject({ kind: 'own_consumer', reason: 'owner_not_serve' });
+ expect(jobs.kind === 'own_consumer' && jobs.line).toMatch(/jobs process \(PID 777\).*own consumer/);
+ expect(captured.filter(l => l.includes('PID 777'))).toHaveLength(1);
+ }), 120_000);
+
+ test('an unsupported flag, the kill switch and a missing socket each fall back with one actionable line, never a refusal', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ captureStderr();
+ const flag = await maybeDelegateManagedSyncToServe(engine, ['--exclude', 'x'], baseOpts(f.id), deps({ sock: await serveSocket() }));
+ const kill = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), { ...deps({ sock: await serveSocket() }), env: { GBRAIN_SERVE_SYNC_IPC: '0' } });
+ const noSock = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: null }));
+ releaseStderr();
+ expect(flag).toMatchObject({ kind: 'own_consumer', reason: 'unsupported_flag' });
+ expect(flag.kind === 'own_consumer' && flag.line).toMatch(/`--exclude` isn't supported through serve-delegated sync; this run uses its own consumer beside the serve \(PID 4242\)/);
+ expect(kill).toMatchObject({ kind: 'own_consumer', reason: 'kill_switch' });
+ expect(kill.kind === 'own_consumer' && kill.line).toMatch(/GBRAIN_SERVE_SYNC_IPC=0.*own consumer beside the serve \(PID 4242\)/);
+ expect(noSock).toMatchObject({ kind: 'own_consumer', reason: 'no_socket' });
+ expect(noSock.kind === 'own_consumer' && noSock.line).toMatch(/exposes no sync IPC socket.*Restart that serve on this gbrain version/);
+ expect(captured).toHaveLength(3);
+ }), 120_000);
+
+ test('skew (T1c): an older serve answering unknown_kind, a stale serve without the protocol echo, and unsupported_kind each fall back with one line', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ // An older base server has no sync handlers at all: `unknown_kind:sync_start` without a protocol echo → stale_serve on the client.
+ const older = await serveSocket({ sync_start: undefined, sync_status: undefined, sync_abort: undefined });
+ // A serve of this family with the kinds disabled (GBRAIN_SERVE_SYNC_IPC=0 on the serve) → `unsupported_kind` with the echo.
+ const disabled = await serveSocket({ sync_start: () => ({ ok: false, protocol: 2, error: 'unsupported_kind' }) });
+ captureStderr();
+ const stale = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: older }));
+ const unsupported = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: disabled }));
+ releaseStderr();
+ expect(stale).toMatchObject({ kind: 'own_consumer', reason: 'older_serve' });
+ expect(stale.kind === 'own_consumer' && stale.line).toMatch(/predates serve-delegated managed sync.*own consumer beside the serve \(PID 4242\).*Restart that serve/);
+ expect(unsupported).toMatchObject({ kind: 'own_consumer', reason: 'older_serve' });
+ expect(captured).toHaveLength(2);
+ // Nothing was admitted by the serve: the source's cursor is untouched.
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [f.id]);
+ expect(n).toBe(0);
+ }), 120_000);
+
+ test('a wrong IPC secret (unauthorized) falls back; the serve bound to another source (source_mismatch) falls back', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ captureStderr();
+ const unauthorized = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: await serveSocket(), secret: randomBytes(32).toString('hex') }));
+ const mismatch = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id),
+ deps({ sock: await serveSocket({ sync_start: (req) => startDelegatedSync(engine, req.options, req.clientToken, { boundSourceId: 'other', registration: req.registration }) }) }));
+ releaseStderr();
+ expect(unauthorized).toMatchObject({ kind: 'own_consumer', reason: 'serve_refused' });
+ expect(mismatch).toMatchObject({ kind: 'own_consumer', reason: 'serve_refused' });
+ expect(mismatch.kind === 'own_consumer' && mismatch.line).toMatch(/bound to a different source/);
+ }), 120_000);
+
+ test('the hand-off refusal is terminal: a revoked CLI registration throws the permission_denied OperationError the in-process path throws', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const local = await registerLocalWriter(engine, 'cli');
+ await revokeLocalWriter(engine, local.id);
+ try {
+ captureStderr();
+ const thrown = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock: await serveSocket() })).catch(e => e);
+ releaseStderr();
+ // The CLI reads its own registration before the hand-off, so a revoked one fails here exactly as the in-process path does.
+ expect(thrown).toBeInstanceOf(OperationError);
+ expect((thrown as OperationError).code).toBe('permission_denied');
+ expect((thrown as OperationError).message).toMatch(/revoked/);
+ } finally {
+ await forgetCliRegistration(local.id);
+ }
+ }), 120_000);
+
+ test('a refusal the serve answers (its verification lost the race with a revocation) is rethrown with the envelope\'s code, reason and fix', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(1);
+ const refusal = { error: 'permission_denied', code: 'permission_denied', message: 'Local writer registration is unavailable or revoked.', suggestion: 'Review it.',
+ reason: 'trusted_cli_required', why: 'The row was revoked.', fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists registrations.' }, contract_version: 1 };
+ const sock = await serveSocket({ sync_start: () => ({ ok: false, protocol: 2, error: 'permission_denied', refusal }) });
+ captureStderr();
+ const thrown = await maybeDelegateManagedSyncToServe(engine, [], baseOpts(f.id), deps({ sock })).catch(e => e);
+ releaseStderr();
+ expect(thrown).toBeInstanceOf(OperationError);
+ expect((thrown as OperationError).toJSON()).toMatchObject({ error: 'permission_denied', message: refusal.message, suggestion: 'Review it.', reason: 'trusted_cli_required', why: 'The row was revoked.', contract_version: 1 });
+ expect((thrown as OperationError).fix?.argv).toEqual(refusal.fix.argv);
+ }), 120_000);
+
+ test('`gbrain sync --source <id> --no-pull --json` delegates unchanged: the serve drains, the CLI prints the drain\'s lines and gets the SyncResult back', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await fixture(5);
+ const sock = await serveSocket();
+ captureStderr();
+ const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull', '--json'], { ...baseOpts(f.id), noEmbed: undefined, explicitProcessing: [] }, deps({ sock }));
+ releaseStderr();
+ expect(outcome.kind).toBe('delegated');
+ if (outcome.kind !== 'delegated') throw new Error('unreachable');
+ expect(outcome.pid).toBe(4242);
+ expect(outcome.result).toMatchObject({ status: 'first_sync', added: 5, pagesAffected: expect.any(Array) });
+ expect(outcome.result.drain).toMatchObject({ outcome: 'synced', written: 5, remaining: 0 });
+ expect(outcome.result.managedCursor).toMatchObject({ index: 5, total: 5 });
+ expect(captured.some(l => l.includes('running the managed catch-up inside it as this CLI\'s writer'))).toBe(true);
+ expect(captured.some(l => l.startsWith('[sync] managed catch-up: 5 entries frozen'))).toBe(true);
+ // Every request the drain admitted carries this CLI's registration, so the in-process grant and revocation checks applied.
+ const local = await registerLocalWriter(engine, 'cli');
+ const rows = await engine.executeRaw<{ principal_id: string }>('SELECT DISTINCT principal_id FROM persistence_requests WHERE source_id=$1', [f.id]);
+ expect(rows.map(r => r.principal_id)).toEqual([local.id]);
+ }), 180_000);
+});