Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli-socket): review findings for #7218 — host brain only, behavior env in the identity, bounded round trip with timeout fallback, slots held until work settles, full frame validation, per-request hop queue, no connect without peer creds, ancestor dir and post-bind checks
garrytanc4b9cbf6c768
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex 27790f544d..eed02ae1b2 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/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`. `server.ts` `maybeStartCliSocket` (called from both serve lanes; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine, after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; the socket is chmod 0600 and re-verified, and unlinked on exit only while its inode is still ours. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, `timeout`, or `fallback`). `identity.ts` `cliSocketIdentity`: SHA-256 over the canonical database target (password and query order dropped, user kept), config dir and file realpaths, the config file's SHA-256 and VERSION. `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a refusal, a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity, directory/socket checks, foreign and unreadable peer uids, unsupported platform, wedged and dying serves), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal, stale socket, off by default).+- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`. `server.ts` `maybeStartCliSocket` (called from both serve lanes; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `tightenBoundSocket` lstats the bound path (our socket, never followed) before chmod 0600 and requires the same inode, private, after; it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: SHA-256 over the resolved brain id, the canonical database target (password and query order dropped, user kept; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnvDigest` (every `GBRAIN_*` name and value except `GBRAIN_CLI_SOCKET`/`GBRAIN_DEBUG`/`GBRAIN_SQL_TRACE`, plus the names, never values, of the recipe registry's provider credentials and endpoints that are set). `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default).- `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).diff --git a/docs/guides/cli-socket.md b/docs/guides/cli-socket.mdindex 3c810d400f..52bf97844c 100644--- a/docs/guides/cli-socket.md+++ b/docs/guides/cli-socket.md@@ -32,6 +32,9 @@ gbrain config set serve.cli_socket trueThe serve logs one line on stderr: `cli-socket: listening on …/run/cli.sock`,or `cli-socket: not started: <reason>` when it cannot open the socket safely.+A serve on a mount brain (`gbrain serve --brain <mount>`, `GBRAIN_BRAIN_ID`, a+`.gbrain-mount` file or a mount path) never opens it: the socket serves the+host brain only.Turn it off by removing the flag or running`gbrain config set serve.cli_socket false`, then restarting the serve.@@ -56,14 +59,25 @@ watch, cursor and rollup forms of `recall`, and a page large enough thatThe CLI falls back to its normal path, silently, when:- no serve has the socket open, or the serve died and left a stale socket;-- the serve does not answer within about a second (a wedged serve never- stalls the CLI), or dies in the middle of the request (the CLI then runs- the call itself, once);-- the serve was started for a different brain: the CLI sends a token built- from the database target (without the password), the config home and the- config file (path and content) and the gbrain version, and the serve answers- only an identical one. Editing `config.json` or upgrading gbrain while a serve- runs sends CLI calls to the normal path until the serve restarts.+- the serve does not accept the request within about a second (a wedged serve+ never stalls the CLI);+- the answer takes longer than 30 seconds, or than the call's `--timeout` when+ that is shorter, the serve's own read deadline passes, or the serve dies in+ the middle of the request: the CLI then runs the call itself, once, with its+ usual timeout and exit codes (it can only be a read, so running it again is+ safe);+- the serve answers with a frame the CLI cannot fully read;+- the serve was started for a different brain or environment: the CLI sends a+ token built from the brain (host or mount), the database target (without+ the password), the config home, the config file (path and content), the+ gbrain version and a digest of the environment that changes answers (every+ `GBRAIN_*` setting except `GBRAIN_CLI_SOCKET`, `GBRAIN_DEBUG` and+ `GBRAIN_SQL_TRACE`, plus which provider API keys and endpoints are set,+ never their values), and the serve answers only an identical one. Editing+ `config.json`, changing those variables or upgrading gbrain while a serve+ runs sends CLI calls to the normal path until the serve restarts with the+ same settings;+- the CLI targets a mount brain (`--brain <mount>` and the other mount tiers).`GBRAIN_DEBUG=1` prints one `[cli-socket] cold path: <reason>` line on stderrwhenever a call falls back. `GBRAIN_CLI_SOCKET=0` makes a CLI call skip the@@ -75,15 +89,21 @@ socket entirely, for comparisons and benchmarks.- The `run` directory is created `0700` and must be owned by your uid; thesocket is `0600`. Both the serve (before binding) and the CLI (beforeconnecting) refuse a symlink, a directory or socket owned by another uid, or- open permissions.+ open permissions. `GBRAIN_HOME` and `.gbrain` above it must be yours too and+ writable by no one else (a sticky directory excepted); the serve refuses+ otherwise and never repairs them. Right after binding, the serve checks the+ path is still its own socket before making it `0600`, and the same inode+ after.- On every connection the serve reads the peer's uid from the kernel(`SO_PEERCRED` on Linux, `getpeereid` on macOS) and drops any other uidbefore reading the request. The CLI checks the serve's uid the same way.Where peer credentials cannot be read (another operating system, or aruntime that hides the socket descriptor), the serve refuses to open the- socket and says why.+ socket and says why, and the CLI never connects.- One serve per `GBRAIN_HOME` holds the socket; requests and responses are- size-bounded and each connection carries exactly one request.+ size-bounded and each connection carries exactly one request. At most 8+ requests run at once; a request that timed out keeps its slot until its work+ actually finishes, so slow requests cannot pile up.- Postgres brains only. A PGLite brain's CLI calls already reach its runningserve through the persistence socket.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9455a91d43..c4b934d7a8 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,7 +21,7 @@ src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is asrc/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 242 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)src/core/pglite-engine.ts 3085 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)-src/core/postgres-engine.ts 3107 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)+src/core/postgres-engine.ts 3109 ratchet +2 warm CLI socket: connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.tssrc/core/types.ts 2339 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts)src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.tsindex 06c9c42544..250326f7cc 100644--- a/src/cli/cli-socket-client.ts+++ b/src/cli/cli-socket-client.ts@@ -14,16 +14,14 @@ import { resolveBrainId } from '../core/brain-resolver.ts';import { VERSION } from '../version.ts';import { cliSocketDir, cliSocketPath, connectProblem } from '../core/cli-socket/fs-guard.ts';import { cliSocketIdentity } from '../core/cli-socket/identity.ts';-import { peerCredSupport, peerUid } from '../core/cli-socket/peer-cred.ts';+import { peerCredSupport, peerUid, type PeerCredSupport } from '../core/cli-socket/peer-cred.ts';import {- CONNECT_TIMEOUT_MS, DEFAULT_READ_WALLCLOCK_MS, FrameReader, HANDSHAKE_TIMEOUT_MS, MAX_RESPONSE_BYTES, reviveOperationError,- type CliSocketOp, type CliSocketRequest, type HandshakeFrame, type OutputChunk, type ResultFrame,+ CONNECT_TIMEOUT_MS, DEFAULT_READ_WALLCLOCK_MS, FrameReader, HANDSHAKE_TIMEOUT_MS, isHandshakeFrame, isResultFrame, MAX_RESPONSE_BYTES,+ MAX_ROUND_TRIP_MS, reviveOperationError, type CliSocketOp, type CliSocketRequest, type OutputChunk, type ResultFrame,} from '../core/cli-socket/protocol.ts';export const CLI_SOCKET_COMMANDS: readonly string[] = ['search', 'query', 'get', 'recall'];const SOCKET_OPS: Record<string, CliSocketOp> = { search: 'search', query: 'query', get_page: 'get_page' };-/** How long past the read wallclock the CLI waits before treating the serve as wedged. */-const RESULT_GRACE_MS = 10_000;function debug(reason: string): void {if (process.env.GBRAIN_DEBUG === '1') process.stderr.write(`[cli-socket] cold path: ${reason}\n`);@@ -31,14 +29,22 @@ function debug(reason: string): void {type Exchange = { frame: ResultFrame } | { reason: string };-/** One request on one connection: connect, verify the serve's uid, send, read the handshake, then the result. */-export function exchangeCliSocket(path: string, request: CliSocketRequest, resultTimeoutMs: number): Promise<Exchange> {+/**+ * One request on one connection: connect, verify the serve's uid, send, read+ * the handshake, then the result. `totalTimeoutMs` bounds the whole exchange;+ * the connect and handshake keep their own shorter bounds inside it. Without a+ * peer-credential reader on this platform the CLI never connects.+ */+export function exchangeCliSocket(path: string, request: CliSocketRequest, totalTimeoutMs: number, peerCred: PeerCredSupport = peerCredSupport()): Promise<Exchange> {+ if (!peerCred.ok) return Promise.resolve({ reason: `peer_credentials_unsupported (${peerCred.reason})` });+ const support = peerCred;return new Promise(resolve => {+ const deadline = performance.now() + totalTimeoutMs;const socket = net.createConnection(path);const reader = new FrameReader(MAX_RESPONSE_BYTES);let accepted = false;let settled = false;- let timer = setTimeout(() => finish({ reason: 'connect_timeout' }), CONNECT_TIMEOUT_MS);+ let timer: ReturnType<typeof setTimeout> | undefined;const finish = (outcome: Exchange) => {if (settled) return;settled = true;@@ -46,12 +52,16 @@ export function exchangeCliSocket(path: string, request: CliSocketRequest, resulsocket.destroy();resolve(outcome);};- const arm = (ms: number, reason: string) => { clearTimeout(timer); timer = setTimeout(() => finish({ reason }), ms); };+ const arm = (ms: number, reason: string) => {+ clearTimeout(timer);+ const remaining = deadline - performance.now();+ timer = setTimeout(() => finish({ reason: remaining <= ms ? 'round_trip_timeout' : reason }), Math.max(0, Math.min(ms, remaining)));+ };+ arm(CONNECT_TIMEOUT_MS, 'connect_timeout');socket.once('error', error => finish({ reason: `${accepted ? 'lost' : 'connect_failed'} (${(error as NodeJS.ErrnoException).code ?? error.message})` }));socket.once('close', () => finish({ reason: accepted ? 'serve_closed_mid_request' : 'serve_closed' }));socket.once('connect', () => {- const support = peerCredSupport();- if (support.ok && peerUid(socket, support.read) !== process.getuid?.()) { finish({ reason: 'serve_uid_mismatch' }); return; }+ if (peerUid(socket, support.read) !== process.getuid?.()) { finish({ reason: 'serve_uid_mismatch' }); return; }arm(HANDSHAKE_TIMEOUT_MS, 'handshake_timeout');socket.write(JSON.stringify(request) + '\n');});@@ -62,20 +72,24 @@ export function exchangeCliSocket(path: string, request: CliSocketRequest, resullet value: unknown;try { value = JSON.parse(text); } catch { finish({ reason: 'malformed_response' }); return; }if (!accepted) {- const handshake = value as HandshakeFrame;- if (handshake?.v !== 1 || handshake.accepted !== true) { finish({ reason: `refused (${(handshake as { reason?: string })?.reason ?? 'unknown'})` }); return; }+ if (!isHandshakeFrame(value)) { finish({ reason: 'malformed_response' }); return; }+ if (!value.accepted) { finish({ reason: `refused (${value.reason})` }); return; }accepted = true;- arm(resultTimeoutMs, 'result_timeout');+ arm(Number.POSITIVE_INFINITY, 'round_trip_timeout');continue;}- const result = value as ResultFrame;- finish(result?.v === 1 && typeof result.kind === 'string' ? { frame: result } : { reason: 'malformed_response' });+ finish(isResultFrame(value) ? { frame: value } : { reason: 'malformed_response' });return;}});});}+/** The longest the CLI waits on one whole exchange: MAX_ROUND_TRIP_MS, or the call's --timeout when shorter. */+export function cliSocketRoundTripMs(timeoutMs: number | null): number {+ return Math.min(MAX_ROUND_TRIP_MS, timeoutMs ?? DEFAULT_READ_WALLCLOCK_MS);+}+/** Restores what the cold process would have by now: the pinned fix source and the operation's own output. */async function replay(frame: { output: OutputChunk[]; source?: string | null }): Promise<void> {if (frame.source) (await import('../core/fix-routing.ts')).noteResolvedSource(frame.source);@@ -105,12 +119,6 @@ async function renderOp(command: string, op: import('../core/operations.ts').Opeconst { applyCliOpNotices, captureOpNotice } = await import('./op-notices.ts');const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');await replay(frame);- if (frame.kind === 'timeout') {- const hint = getCliOptions().timeoutMs ? '' : ` (default ${frame.ms}ms; pass --timeout=Ns to override)`;- console.error(`${frame.label} timed out${hint}.`);- setCliExitVerdict(124);- return;- }if (frame.kind === 'error') {const { writeCliError } = await import('./cli-error.ts');const { reportPersistenceCliError } = await import('../commands/persistence-delegate.ts');@@ -147,16 +155,18 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):const path = cliSocketPath(home);const problem = connectProblem(path, cliSocketDir(home));if (problem) { if (problem !== 'missing') debug(`socket refused before connect (${problem})`); return false; }- try { if (resolveBrainId(cliOpts.brain) !== 'host') return false; } catch { return false; }+ let brainId: string;+ try { brainId = resolveBrainId(cliOpts.brain); } catch { return false; }+ if (brainId !== 'host') { debug(`mount brain ${brainId}`); return false; }const base = {v: 1 as const,- identity: cliSocketIdentity({ config, configDir: home, configFile: configPath(), version: VERSION }),+ identity: cliSocketIdentity({ config, brainId, configDir: home, configFile: configPath(), version: VERSION, env: process.env }),command,routing: { cwd: process.cwd(), source_env: process.env.GBRAIN_SOURCE ?? null },cli: { quiet: cliOpts.quiet, timeout_ms: cliOpts.timeoutMs },};- const resultTimeoutMs = (cliOpts.timeoutMs ?? DEFAULT_READ_WALLCLOCK_MS) + RESULT_GRACE_MS;+ const resultTimeoutMs = cliSocketRoundTripMs(cliOpts.timeoutMs);if (command === 'recall') {const recall = await import('../commands/recall.ts');@@ -167,9 +177,13 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):if (!recall.isOneShotRecall(flags)) recall.validateAndNormalizeFlags(flags);const outcome = await exchangeCliSocket(path, { ...base, kind: 'recall', args }, resultTimeoutMs);if ('reason' in outcome) { debug(outcome.reason); return false; }- if (outcome.frame.kind === 'fallback' || outcome.frame.kind === 'timeout') { debug(outcome.frame.kind === 'fallback' ? outcome.frame.reason : 'timeout'); return false; }+ if (outcome.frame.kind === 'fallback') { debug(outcome.frame.reason); return false; }await replay(outcome.frame);- if (outcome.frame.kind === 'result') { recall.renderRecallVerbResult(flags, outcome.frame.result as Parameters<typeof recall.renderRecallVerbResult>[1]); return true; }+ if (outcome.frame.kind === 'result') {+ recall.renderRecallVerbResult(flags, outcome.frame.result as Parameters<typeof recall.renderRecallVerbResult>[1]);+ if (outcome.frame.notices.length > 0) (await import('../core/interop-notices.ts')).writeCliNotices(outcome.frame.notices);+ return true;+ }const error = reviveOperationError(outcome.frame.error);if (recall.isOneShotRecall(flags)) await recall.reportOneShotRecallError(error, flags);else throw error;diff --git a/src/core/ai/fallback-hop-queue.ts b/src/core/ai/fallback-hop-queue.tsindex 0f3407bc2c..8e5ddcbea7 100644--- a/src/core/ai/fallback-hop-queue.ts+++ b/src/core/ai/fallback-hop-queue.ts@@ -7,24 +7,41 @@*/import type { Notice } from '../agent-output.ts';-let queued = false;-const pending: Notice[] = [];+/** One process's (or one warm CLI request's) first-hop state. */+export interface FallbackHopQueue { queued: boolean; pending: Notice[] }++const processQueue: FallbackHopQueue = { queued: false, pending: [] };+let hopScope: (() => FallbackHopQueue | undefined) | undefined;++/**+ * A serve answering warm CLI requests (src/core/cli-socket/output-capture.ts)+ * gives each request its own queue, as a one-shot CLI process starts with one;+ * outside a scope the process queue applies.+ */+export function setFallbackHopScope(scope: () => FallbackHopQueue | undefined): void {+ hopScope = scope;+}++function activeQueue(): FallbackHopQueue {+ return hopScope?.() ?? processQueue;+}/** Queue the first hop's notice; every later call in this process is a no-op. Returns whether it queued. */export function queueFirstFallbackHop(build: () => Notice): boolean {- if (queued) return false;- queued = true;- pending.push(build());+ const queue = activeQueue();+ if (queue.queued) return false;+ queue.queued = true;+ queue.pending.push(build());return true;}/** Drain the queued first-hop notice (at most one per process). */export function takeChatFallbackHopNotices(): Notice[] {- return pending.splice(0);+ return activeQueue().pending.splice(0);}/** Test seam: re-arm the once-per-process first-hop notice. */export function __resetChatFallbackHopNoticeForTests(): void {- queued = false;- pending.splice(0);+ processQueue.queued = false;+ processQueue.pending.splice(0);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9f16ad5099..e36837c87c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1028,7 +1028,6 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.330.0', text: 'Sync now caps how many pages one run deletes (#7130): new settings `sync.max_deletes` (default 500) and `sync.max_delete_ratio` (default 0.01, applied above 50 deletes), each with a per-source override `<key>.source.<id>`, on top of the 50% valve. A managed pass over a cap withholds its deletes through the existing `deletes_withheld` record (it names the cap that tripped), the dry run lists them, and `gbrain sync status` asks the user (`ask_user`) before anything raises the cap; a classic full reconcile and a working-tree sync (on a detached HEAD too) skip the deletes with a warning naming the cap. Adds and edits still import. `GBRAIN_ALLOW_MASS_RECONCILE=1` lets a deletion through as before, and `gbrain config set` refuses a cap that is not a whole number of 0 or more (ratio: a number from 0 to 1).' },{ since: '0.60.330.0', text: 'Classic `gbrain sync --full` no longer deletes pages it cannot prove were removed (#7130): when Git cannot list the history that shows their files were committed (a dangling ref fails `git log --all`), it keeps every stale page with a warning, where before it skipped the never-committed check and deleted them all. With readable history it deletes as before.' },{ since: '0.60.330.0', text: 'The autopilot purge phase and the `purge` job no longer hard-delete a page that a managed sync soft-deleted unless another live page of the same source has identical content (#7130). Each sync deletion now leaves a durable record (op_checkpoints `sync-delete-tombstone`; a tombstone from before this release is recognized by its uncompacted `managed_sync_delete` receipt, and one whose receipt was compacted is not). Held pages are reported as `sync_delete_unreviewed` in the phase\'s `purged_pages_blocked` and counted in `held`, and the phase reports warn. `gbrain pages purge-deleted` still purges them after consent: its dry run reports `sync_unreviewed` and its consent text names how many of the set are sync deletions with no live twin and that a purged page can only come back from a backup. The purge phase\'s recovery window (pages and orphan clone temp dirs), and the `purge` job\'s default, now follow `purge.retention_hours` instead of a fixed 72 hours. It can only lengthen the window (default and minimum 72, so a 72-hour restore promise always holds); `gbrain config set` refuses a smaller value.' },- { since: '0.60.330.0', text: 'New opt-in warm CLI socket for Postgres brains, off by default: `gbrain serve --cli-socket` (or `gbrain config set serve.cli_socket true`) lets that serve answer this user\'s CLI `search`, `query`, `get` and op-backed `recall` (`--query`, `--budget-tokens`, `--question`, `--budget-policy`) over a private Unix socket in `$GBRAIN_HOME/.gbrain/run/` (directory 0700, socket 0600, peer uid checked by the kernel on every connection, never TCP), so those calls skip a cold database connection. The CLI is served only when its brain identity (database target, config home and file, gbrain version) matches the serve\'s; otherwise, and whenever the socket is missing, stale or busy, the CLI takes its usual path. Without the option nothing listens. Guide: docs/guides/cli-socket.md.' },{ since: '0.60.330.0', text: 'New doctor check `uncommitted_sync_deletions` and explicit-only repair kind `gbrain repair uncommitted-deletions --source <id>` (#7130): on each managed source\'s owner host, doctor warns about soft-deleted pages a sync removed although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), bounded to 20,000 tombstones per source and 2,000 Git evidence reads per run. The repair previews each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) with a hash; `--apply --expect <hash> --yes` restores exactly that set, each page live and database-only (detached: it forgets its recorded file and no file is written), so the next sync keeps it. Pages another writer deleted join only with `--include-ambiguous`; a sync deletion is recognized by its record or receipt for the page\'s current tombstone. A preview reads one bounded window, newest page id first, and `--after <page-id>` (named in the preview\'s `next_after` and in the doctor message) continues past it. It refuses off the owner host (`not_owner_host`) and a changed plan (`preview_changed`); without `--yes` a non-interactive run exits 3 and changes nothing. Pages already purged cannot be restored by this command; only a backup (pg_dump, or `gbrain backup create`) can bring them back. It never runs on upgrade or automatically.' },// Wave B follow-ups lane F2 (#7106: a managed import or sync of a new page over 4 MiB replies at commit). `since` is stamped at the merge slot.{ since: '0.60.331.0', text: 'A managed `gbrain import` or `gbrain sync` of a new page over 4 MiB stored in segments now replies when the write commits, before its search index is built, instead of waiting for that build (which on a loaded host outlasted the 30 s import wait and replied `write_pending`). The import result and the write\'s receipt say `searchable: "pending"` and `projection: "pending"`; the import result also carries the `request_id`, `searchable_retry_after_ms` and `searchable_fix`. Read the receipt again (`gbrain write-request -- <request_id>`, `get_write_request`) at that interval until it says `searchable: true`; search finds the page from then on. The build no longer holds up the source\'s next write either. A new page up to 4 MiB, and an edit of a page stored in segments, is still searchable when its import replies (`searchable: true`). A `put_page` of a new page over 4 MiB, whose receipt already said `searchable: "pending"`, now also replies at commit instead of after the build.' },@@ -1041,6 +1040,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.332.0', text: 'The `score` that search and query return now never increases down the list: in a reranked list it is the rerank score (times any rank prior), and a pinned or unreranked row takes its neighbour\'s value. The fused score it replaced stays on the row as `fused_score`.' },{ since: '0.60.332.0', text: 'One search or query chunk row returns at most 8,000 characters of chunk text by default, ending with the marker that names the read for the rest (an old oversized chunk could return tens of thousands). Pass `snippet_chars: 0` for the full chunk. Evidence blocks (conversations, long-page units) keep their own budget and cap.' },{ since: '0.60.332.0', text: '`gbrain search --explain` and `gbrain query --explain` now pass explain to the search, so `score_details` reports the arms, RRF and blend that ran; before, every row said `single_arm_path` / `no_query_embedding` even when both arms ran. A CLI search or query whose keyword or vector arm failed or timed out now prints the `degraded_recall` notice on stderr (the `--json` array stays bare), as MCP already did.' },+ { since: '0.60.332.0', text: 'New opt-in warm CLI socket for Postgres brains, off by default: `gbrain serve --cli-socket` (or `gbrain config set serve.cli_socket true`) lets that serve answer this user\'s CLI `search`, `query`, `get` and op-backed `recall` (`--query`, `--budget-tokens`, `--question`, `--budget-policy`) over a private Unix socket in `$GBRAIN_HOME/.gbrain/run/` (directory 0700, socket 0600, peer uid checked by the kernel on every connection, never TCP), so those calls skip a cold database connection. Only the host brain is served (a serve on a mount brain never opens the socket), and only when the CLI\'s identity (database target, config home and file, gbrain version, every `GBRAIN_*` setting but the socket, debug and SQL-trace switches, and which provider keys are set) matches the serve\'s; otherwise, and whenever the socket is missing, stale or busy, the answer is malformed, or it takes over 30 s (or the call\'s shorter `--timeout`), the CLI takes its usual path. Without the option nothing listens. Guide: docs/guides/cli-socket.md.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-socket/execute.ts b/src/core/cli-socket/execute.tsindex fc0c1e6054..ba7113ad3f 100644--- a/src/core/cli-socket/execute.ts+++ b/src/core/cli-socket/execute.ts@@ -8,6 +8,7 @@*/import type { Notice } from '../agent-output.ts';import { takeChatFallbackHopNotices } from '../ai/fallback-hop-queue.ts';+import { recallInteropNotices } from '../interop-notices.ts';import { DEFAULT_CLI_OPTIONS } from '../cli-options.ts';import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';import { withRequestConfigSnapshot } from '../config-snapshot.ts';@@ -19,7 +20,7 @@ import { localFederatedSourceIds, resolveSourceWithTier, SourceTargetError } froimport { OperationTimeoutError, withTimeout } from '../timeout.ts';import { bigintToStringReplacer } from '../utils.ts';import { OutputCapture, withOutputCapture } from './output-capture.ts';-import { DEFAULT_READ_WALLCLOCK_MS, serializeOperationError, type CliSocketRequest, type ResultFrame } from './protocol.ts';+import { DEFAULT_READ_WALLCLOCK_MS, MAX_ROUND_TRIP_MS, serializeOperationError, type CliSocketRequest, type ResultFrame } from './protocol.ts';/** File config merged with the DB plane, read fresh for every request (inside its config snapshot), as a cold CLI reads it at connect. */export async function mergedRequestConfig(engine: BrainEngine): Promise<GBrainConfig> {@@ -79,11 +80,19 @@ function errorFrame(error: unknown, capture: OutputCapture): ResultFrame {return { v: 1, kind: 'fallback', reason: 'unportable_error' };}-async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'op' }>, capture: OutputCapture): Promise<ResultFrame> {+/** The promises a request started; the serve counts the request as active until every one settles, even after a timeout answered it. */+type Work = Promise<unknown>[];++function track<T>(work: Work, promise: Promise<T>): Promise<T> {+ work.push(promise);+ return promise;+}++async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'op' }>, capture: OutputCapture, work: Work): Promise<ResultFrame> {const op = operationsByName[request.op];if (!op || op.scope !== 'read' || op.mutating) return { v: 1, kind: 'fallback', reason: 'not_a_read_op' };const params = request.params;- const wallclockMs = request.cli.timeout_ms ?? DEFAULT_READ_WALLCLOCK_MS;+ const wallclockMs = Math.min(MAX_ROUND_TRIP_MS, request.cli.timeout_ms ?? DEFAULT_READ_WALLCLOCK_MS);let meta: Record<string, unknown> | null = null;const notices: Notice[] = [];const sinks = {@@ -92,25 +101,30 @@ async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { k};let stage = `gbrain ${request.command}: context`;try {- const ctx = await withTimeout(cliRequestContext(engine, params, op, request, await mergedRequestConfig(engine), sinks), wallclockMs, stage);+ const ctx = await withTimeout(track(work, (async () => cliRequestContext(engine, params, op, request, await mergedRequestConfig(engine), sinks))()), wallclockMs, stage);stage = `gbrain ${request.command}`;- const raw = await withTimeout(op.handler(ctx, params), wallclockMs, stage);+ const raw = await withTimeout(track(work, op.handler(ctx, params)), wallclockMs, stage);+ // src/cli/main.ts runSharedOperation: captureRetrievalNotices after the handler, before the JSON round trip.+ const retrieval = op.name === 'search' || op.name === 'query'+ ? recallInteropNotices(op.name, raw, { retrieval: meta ?? {} }, params, { config: ctx.config, transport: 'cli' })+ : [];const result = JSON.parse(JSON.stringify(raw, bigintToStringReplacer) ?? 'null');- return { v: 1, kind: 'result', result, meta, notices: [...notices, ...takeChatFallbackHopNotices()], output: capture.chunks };+ return { v: 1, kind: 'result', result, meta, notices: [...notices, ...retrieval, ...takeChatFallbackHopNotices()], output: capture.chunks };} catch (error) {- if (error instanceof OperationTimeoutError) return { v: 1, kind: 'timeout', label: error.label, ms: error.ms, output: capture.chunks };+ if (error instanceof OperationTimeoutError) return { v: 1, kind: 'fallback', reason: 'timeout' };if (op.name === 'get_page' && (error as { code?: unknown })?.code === 'page_body_segmented') return { v: 1, kind: 'fallback', reason: 'segmented_page' };return errorFrame(error, capture);}}-async function runRecall(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'recall' }>, capture: OutputCapture): Promise<ResultFrame> {+async function runRecall(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'recall' }>, capture: OutputCapture, work: Work): Promise<ResultFrame> {const { recallVerbForCaller } = await import('../../commands/recall.ts');try {- const raw = await recallVerbForCaller(engine, request.args, { cwd: request.routing.cwd, env: request.routing.source_env ?? undefined });+ const raw = await track(work, recallVerbForCaller(engine, request.args, { cwd: request.routing.cwd, env: request.routing.source_env ?? undefined }));if (raw === null) return { v: 1, kind: 'fallback', reason: 'not_a_recall_verb' };const result = JSON.parse(JSON.stringify(raw, bigintToStringReplacer) ?? 'null');- return { v: 1, kind: 'result', result, meta: null, notices: [], output: capture.chunks };+ // A cold recall prints the first chat-fallback hop at teardown (src/core/cli-force-exit.ts); the CLI does the same with these.+ return { v: 1, kind: 'result', result, meta: null, notices: takeChatFallbackHopNotices(), output: capture.chunks };} catch (error) {return errorFrame(error, capture);}@@ -123,12 +137,20 @@ async function runRecall(engine: BrainEngine, request: Extract<CliSocketRequest,* answers from it, and the snapshot closes when the request settles, so* nothing is cached across requests. Every op served here is non-mutating.*/-export async function executeCliSocketRequest(engine: BrainEngine, request: CliSocketRequest): Promise<ResultFrame> {+export interface ExecutedRequest {+ frame: ResultFrame;+ /** Settles when every promise the request started has settled (never rejects); a timed-out handler keeps it pending. */+ settled: Promise<unknown>;+}++export async function executeCliSocketRequest(engine: BrainEngine, request: CliSocketRequest): Promise<ExecutedRequest> {const capture = new OutputCapture();- const frame = await withOutputCapture(capture, () => withRequestConfigSnapshot(engine, () => request.kind === 'op'- ? runOp(engine, request, capture)- : runRecall(engine, request, capture)));- if (frame.kind === 'fallback') return frame;- if (capture.overflow) return { v: 1, kind: 'fallback', reason: 'output_too_large' };- return { ...frame, source: capture.resolvedSource ?? null };+ const work: Work = [];+ const answered = await withOutputCapture(capture, () => withRequestConfigSnapshot(engine, () => request.kind === 'op'+ ? runOp(engine, request, capture, work)+ : runRecall(engine, request, capture, work)));+ const settled = Promise.allSettled(work);+ if (answered.kind === 'fallback') return { frame: answered, settled };+ if (capture.overflow) return { frame: { v: 1, kind: 'fallback', reason: 'output_too_large' }, settled };+ return { frame: { ...answered, source: capture.resolvedSource ?? null }, settled };}diff --git a/src/core/cli-socket/fs-guard.ts b/src/core/cli-socket/fs-guard.tsindex 9a5059d908..c2aa4b331f 100644--- a/src/core/cli-socket/fs-guard.ts+++ b/src/core/cli-socket/fs-guard.ts@@ -4,21 +4,26 @@* TCP) in a directory that is 0700 and owned by the current user, the socket* itself 0600. Both the serve (before bind) and the CLI (before connect)* lstat the directory and the socket path, so a symlink, a foreign owner or- * open permissions refuse instead of being followed or repaired.+ * open permissions refuse instead of being followed or repaired. The+ * directories above it, GBRAIN_HOME and `.gbrain`, must be this user's and+ * writable by no one else (a sticky directory excepted), so nobody else can+ * swap a path component.*/-import { chmodSync, lstatSync, mkdirSync, type Stats } from 'node:fs';-import { join } from 'node:path';+import { chmodSync, lstatSync, mkdirSync, statSync, type Stats } from 'node:fs';+import { dirname, join } from 'node:path';import { configDir } from '../config.ts';import { UNIX_SOCKET_PATH_MAX_BYTES } from '../context/ipc-path.ts';export interface FsGuardDeps {lstat: (path: string) => Stats;uid: () => number | undefined;+ /** Follows symlinks; used for GBRAIN_HOME and `.gbrain`. Defaults to the real stat. */+ stat?: (path: string) => Stats;}-const realDeps: FsGuardDeps = { lstat: path => lstatSync(path), uid: () => process.getuid?.() };+const realDeps: FsGuardDeps = { lstat: path => lstatSync(path), stat: path => statSync(path), uid: () => process.getuid?.() };-export type UnsafeReason = 'missing' | 'symlink' | 'not_directory' | 'not_socket' | 'foreign_owner' | 'open_permissions' | 'no_uid';+export type UnsafeReason = 'missing' | 'symlink' | 'not_directory' | 'not_socket' | 'foreign_owner' | 'open_permissions' | 'no_uid' | 'replaced';export function cliSocketDir(home: string = configDir()): string {return join(home, 'run');@@ -64,9 +69,48 @@ export function privateSocketProblem(path: string, deps: FsGuardDeps = realDeps)return null;}-/** The CLI's pre-connect check: both the directory and the socket must pass, or the CLI never connects. */+/** null when `dir` (symlinks followed) is a directory this uid owns with no group or other write bit, unless sticky. */+export function trustedAncestorProblem(dir: string, deps: FsGuardDeps = realDeps): UnsafeReason | null {+ const uid = deps.uid();+ if (uid === undefined) return 'no_uid';+ let st: Stats;+ try { st = (deps.stat ?? statSync)(dir); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing'; throw error; }+ if (!st.isDirectory()) return 'not_directory';+ if (st.uid !== uid) return 'foreign_owner';+ if ((st.mode & 0o022) !== 0 && (st.mode & 0o1000) === 0) return 'open_permissions';+ return null;+}++/** GBRAIN_HOME and `.gbrain` above the run directory, outermost first, with the first that fails its check. */+export function ancestorProblem(dir: string, deps: FsGuardDeps = realDeps): { path: string; reason: UnsafeReason } | null {+ for (const ancestor of [dirname(dirname(dir)), dirname(dir)]) {+ const reason = trustedAncestorProblem(ancestor, deps);+ if (reason) return { path: ancestor, reason };+ }+ return null;+}++/** The CLI's pre-connect check: the directories above, the run directory and the socket must pass, or the CLI never connects. */export function connectProblem(path: string, dir: string, deps: FsGuardDeps = realDeps): UnsafeReason | null {- return privateDirProblem(dir, deps) ?? privateSocketProblem(path, deps);+ return ancestorProblem(dir, deps)?.reason ?? privateDirProblem(dir, deps) ?? privateSocketProblem(path, deps);+}++/**+ * Right after bind: the path must be a socket this uid owns (lstat, never+ * followed) before it is chmod 0600, and the same inode, private, after.+ * Returns that inode; throws when the path changed or is not ours.+ */+export function tightenBoundSocket(path: string, deps: FsGuardDeps = realDeps, chmod: (path: string) => void = target => chmodSync(target, 0o600)): number {+ const uid = deps.uid();+ const before = deps.lstat(path);+ if (before.isSymbolicLink() || !before.isSocket()) throw new CliSocketUnsafeError(before.isSymbolicLink() ? 'symlink' : 'not_socket', path);+ if (before.uid !== uid) throw new CliSocketUnsafeError('foreign_owner', path);+ chmod(path);+ const problem = privateSocketProblem(path, deps);+ if (problem) throw new CliSocketUnsafeError(problem, path);+ if (deps.lstat(path).ino !== before.ino) throw new CliSocketUnsafeError('replaced', path);+ return before.ino;}export class CliSocketUnsafeError extends Error {@@ -78,15 +122,20 @@ export class CliSocketUnsafeError extends Error {/*** The serve's pre-bind step: create the run directory 0700 when it is missing,- * tighten one this uid already owns, and refuse a symlink, a non-directory or- * a directory another uid owns.+ * tighten one this uid already owns, and refuse a symlink, a non-directory, a+ * directory another uid owns, or a GBRAIN_HOME / `.gbrain` above it that is+ * not this user's or that others can write to (never repaired).*/export function ensurePrivateDir(dir: string, deps: FsGuardDeps = realDeps, fs: { mkdir: (path: string) => void; chmod: (path: string) => void } = {mkdir: path => mkdirSync(path, { recursive: true, mode: 0o700 }),chmod: path => chmodSync(path, 0o700),}): void {+ const initial = privateDirProblem(dir, deps);+ if (initial && initial !== 'missing' && initial !== 'open_permissions') throw new CliSocketUnsafeError(initial, dir);+ if (initial === 'missing') fs.mkdir(dir);+ const above = ancestorProblem(dir, deps);+ if (above) throw new CliSocketUnsafeError(above.reason, above.path);let problem = privateDirProblem(dir, deps);- if (problem === 'missing') { fs.mkdir(dir); problem = privateDirProblem(dir, deps); }if (problem === 'open_permissions') { fs.chmod(dir); problem = privateDirProblem(dir, deps); }if (problem) throw new CliSocketUnsafeError(problem, dir);}diff --git a/src/core/cli-socket/identity.ts b/src/core/cli-socket/identity.tsindex 9a00bbb2f0..df288a3463 100644--- a/src/core/cli-socket/identity.ts+++ b/src/core/cli-socket/identity.ts@@ -2,12 +2,43 @@* The brain identity the warm CLI socket is bound to. A serve computes it once* when it binds; the CLI computes it per call and sends it in the request. The* serve answers only an identical token, so a CLI aimed at another database,- * another GBRAIN_HOME, an edited config file or another gbrain release always+ * another GBRAIN_HOME, another brain (mount), an edited config file, a+ * different behavior-relevant environment or another gbrain release always* takes its own cold path. The socket path alone never decides.*/import { createHash } from 'node:crypto';import { readFileSync, realpathSync } from 'node:fs';import type { GBrainConfig } from '../config.ts';+import { listRecipes } from '../ai/recipes/index.ts';++/** GBRAIN_* switches that only steer the socket itself or diagnostics, never an operation's answer. */+const NON_BEHAVIOR_GBRAIN_ENV = new Set(['GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE']);+/** Provider env names read outside the recipe registry: the Google alias and the compatibility endpoints. */+const EXTRA_PROVIDER_ENV = ['GEMINI_API_KEY', 'OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL'];++let providerEnvNames: string[] | undefined;+function providerEnv(): string[] {+ providerEnvNames ??= [...new Set([+ ...listRecipes().flatMap(recipe => [...(recipe.auth_env?.required ?? []), ...(recipe.auth_env?.optional ?? [])]),+ ...EXTRA_PROVIDER_ENV,+ ])].sort();+ return providerEnvNames;+}++/**+ * SHA-256 over the environment that changes what a read answers: every+ * GBRAIN_* name and value except the socket switch, debug and SQL trace, and+ * the names (never the values) of the provider credentials and endpoints that+ * are set to a non-empty value.+ */+export function behaviorEnvDigest(env: Record<string, string | undefined>): string {+ const gbrain = Object.keys(env)+ .filter(key => key.startsWith('GBRAIN_') && !NON_BEHAVIOR_GBRAIN_ENV.has(key) && env[key] !== undefined)+ .sort()+ .map(key => [key, env[key]]);+ const providers = providerEnv().filter(name => env[name] !== undefined && env[name] !== '');+ return createHash('sha256').update(JSON.stringify({ gbrain, providers })).digest('hex');+}/** Database URL without its password, with the host, port and query parameters in one canonical spelling. */export function canonicalDatabaseTarget(databaseUrl: string): string {@@ -32,18 +63,23 @@ function fileDigest(path: string): string {}export interface CliSocketIdentityInput {+ /** The serve's: the config its engine connected with. The CLI's: the config it would connect with. */config: Pick<GBrainConfig, 'engine' | 'database_url'>;+ /** The resolved brain id (src/core/brain-resolver.ts resolveBrainId). */+ brainId: string;configDir: string;configFile: string;version: string;+ env: Record<string, string | undefined>;}-/** SHA-256 over the canonical database target, the config home and file (realpath and content) and the gbrain version. */+/** SHA-256 over the brain id, the canonical database target, the config home and file (realpath and content), the behavior env and the gbrain version. */export function cliSocketIdentity(input: CliSocketIdentityInput): string {const fields = {- v: 1,+ v: 2,version: input.version,- brain: 'host',+ brain: input.brainId,+ env: behaviorEnvDigest(input.env),engine: input.config.engine,database: input.config.database_url ? canonicalDatabaseTarget(input.config.database_url) : null,config_dir: realpathOr(input.configDir),diff --git a/src/core/cli-socket/output-capture.ts b/src/core/cli-socket/output-capture.tsindex b87e10dea4..50da4d3897 100644--- a/src/core/cli-socket/output-capture.ts+++ b/src/core/cli-socket/output-capture.ts@@ -1,13 +1,15 @@/*** Serve-side capture of what an operation prints (and the per-process state a- * one-shot CLI would start fresh: once-only warnings, the pinned fix source)- * while it answers a warm CLI request. A cold CLI prints a handler's console and stderr lines itself; the+ * one-shot CLI would start fresh: once-only warnings, the pinned fix source,+ * the first chat-fallback hop notice) while it answers a warm CLI request.+ * A cold CLI prints a handler's console and stderr lines itself; the* serve records them per request (AsyncLocalStorage, so concurrent MCP work* and other requests are untouched) and the CLI replays them in order before* rendering the result.*/import { AsyncLocalStorage } from 'node:async_hooks';import { format } from 'node:util';+import { setFallbackHopScope, type FallbackHopQueue } from '../ai/fallback-hop-queue.ts';import { setSourceNoteScope } from '../fix-routing.ts';import { setWarnOnceScope } from '../utils.ts';import { MAX_CAPTURED_OUTPUT_BYTES, type OutputChunk } from './protocol.ts';@@ -16,6 +18,8 @@ export class OutputCapture {readonly chunks: OutputChunk[] = [];/** This request's warnOncePerProcess keys: a cold CLI process starts with none. */readonly warned = new Set<string>();+ /** This request's chat_fallback_hop queue: a cold CLI process starts with an empty, unarmed one. */+ readonly fallbackHops: FallbackHopQueue = { queued: false, pending: [] };/** The first source this request resolved, which the CLI pins in its fix commands. */resolvedSource?: string;private bytes = 0;@@ -39,6 +43,7 @@ export function installOutputCapture(): void {installed = true;setWarnOnceScope(() => store.getStore()?.warned);setSourceNoteScope(() => store.getStore());+ setFallbackHopScope(() => store.getStore()?.fallbackHops);const methods = [['log', 'stdout'], ['info', 'stdout'], ['debug', 'stdout'], ['warn', 'stderr'], ['error', 'stderr']] as const;for (const [method, stream] of methods) {const original = console[method];diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.tsindex 0435114d8b..a5ec8f793c 100644--- a/src/core/cli-socket/protocol.ts+++ b/src/core/cli-socket/protocol.ts@@ -16,6 +16,8 @@ export const HANDSHAKE_TIMEOUT_MS = 1_000;export const REQUEST_READ_TIMEOUT_MS = 2_000;/** The cold path's read wallclock (src/cli/main.ts READ_OP_TIMEOUT_MS) when --timeout is not given. */export const DEFAULT_READ_WALLCLOCK_MS = 180_000;+/** The longest a CLI waits on one whole exchange (or its --timeout, when shorter) before running the call itself. */+export const MAX_ROUND_TRIP_MS = 30_000;/** The read operations a serve answers over the socket. Everything else keeps the cold path. */export const CLI_SOCKET_OPS = ['search', 'query', 'get_page'] as const;@@ -47,13 +49,41 @@ interface Answered { output: OutputChunk[]; source?: string | null }export type ResultFrame =| { v: 1; kind: 'result'; result: unknown; meta: Record<string, unknown> | null; notices: Notice[] } & Answered| { v: 1; kind: 'error'; error: Record<string, unknown> } & Answered- | { v: 1; kind: 'timeout'; label: string; ms: number } & Answered| { v: 1; kind: 'fallback'; reason: string };function record(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}+/** Shape check for the serve's handshake line. */+export function isHandshakeFrame(value: unknown): value is HandshakeFrame {+ if (!record(value) || value.v !== CLI_SOCKET_PROTOCOL) return false;+ return value.accepted === true || (value.accepted === false && typeof value.reason === 'string');+}++function isAnswered(value: Record<string, unknown>): boolean {+ return Array.isArray(value.output)+ && value.output.every(chunk => Array.isArray(chunk) && chunk.length === 2 && (chunk[0] === 'stdout' || chunk[0] === 'stderr') && typeof chunk[1] === 'string')+ && (value.source === undefined || value.source === null || typeof value.source === 'string');+}++/** Shape check for the serve's result line: every field the CLI reads, per kind; anything else is malformed. */+export function isResultFrame(value: unknown): value is ResultFrame {+ if (!record(value) || value.v !== CLI_SOCKET_PROTOCOL) return false;+ switch (value.kind) {+ case 'result':+ return 'result' in value && (value.meta === null || record(value.meta))+ && Array.isArray(value.notices) && value.notices.every(notice => record(notice) && typeof notice.code === 'string')+ && isAnswered(value);+ case 'error':+ return record(value.error) && typeof value.error.code === 'string' && typeof value.error.message === 'string' && isAnswered(value);+ case 'fallback':+ return typeof value.reason === 'string';+ default:+ return false;+ }+}+/** Shape check for an inbound request; anything else is refused before it reaches the engine. */export function isCliSocketRequest(value: unknown): value is CliSocketRequest {if (!record(value) || value.v !== CLI_SOCKET_PROTOCOL || typeof value.identity !== 'string' || typeof value.command !== 'string') return false;diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.tsindex 56f42efcbf..cee841a202 100644--- a/src/core/cli-socket/server.ts+++ b/src/core/cli-socket/server.ts@@ -6,14 +6,16 @@* is parsed; a platform where that cannot be read never opens the listener.*/import { timingSafeEqual } from 'node:crypto';-import { chmodSync, lstatSync, unlinkSync } from 'node:fs';+import { lstatSync, unlinkSync } from 'node:fs';import net, { type Socket } from 'node:net';import type { BrainEngine } from '../engine.ts';-import { configDir, configPath, loadConfig } from '../config.ts';+import { resolveBrainId } from '../brain-resolver.ts';+import { getCliOptions } from '../cli-options.ts';+import { configDir, configPath } from '../config.ts';import { tryAcquireNativeLock } from '../persistence/native-lock.ts';import { VERSION } from '../../version.ts';-import { executeCliSocketRequest } from './execute.ts';-import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, privateSocketProblem, socketPathFits } from './fs-guard.ts';+import { executeCliSocketRequest, type ExecutedRequest } from './execute.ts';+import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, privateSocketProblem, socketPathFits, tightenBoundSocket } from './fs-guard.ts';import { cliSocketIdentity } from './identity.ts';import { installOutputCapture } from './output-capture.ts';import { peerCredSupport, peerUid, type PeerCredSupport } from './peer-cred.ts';@@ -34,7 +36,8 @@ export interface CliSocketServerOptions {home?: string;identity?: string;uid?: () => number | undefined;- execute?: (request: CliSocketRequest) => Promise<ResultFrame>;+ brainId?: () => string;+ execute?: (request: CliSocketRequest) => Promise<ExecutedRequest>;}/** Whether this serve should open the socket: the flag, or the DB-plane config key set to a true value. */@@ -103,6 +106,12 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promisconst log = (line: string) => opts.log(`[gbrain serve] cli-socket: ${line}`);const uid = (opts.uid ?? (() => process.getuid?.()))();if (opts.engine.kind !== 'postgres') { log('not started: the CLI socket serves Postgres brains only (PGLite CLI calls already reach a running serve).'); return null; }+ let brainId: string;+ try { brainId = (opts.brainId ?? (() => resolveBrainId(getCliOptions().brain)))(); }+ catch (error) { log(`not started: the serve's brain cannot be resolved (${(error as Error).message}).`); return null; }+ if (brainId !== 'host') { log(`not started: this serve is on mount brain "${brainId}"; the CLI socket serves the host brain only.`); return null; }+ const databaseUrl = (opts.engine as { connectedDatabaseUrl?: string }).connectedDatabaseUrl;+ if (!databaseUrl) { log('not started: the engine does not report the database it connected to.'); return null; }const support = opts.peerCred ?? peerCredSupport();if (!support.ok || uid === undefined) { log(`not started: peer credentials cannot be verified on this platform (${support.ok ? 'no POSIX uid' : support.reason}).`); return null; }const home = opts.home ?? configDir();@@ -124,8 +133,9 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): PromisunlinkSync(path);}- const config = loadConfig();- const identity = opts.identity ?? cliSocketIdentity({ config: config ?? { engine: 'postgres' }, configDir: home, configFile: configPath(), version: VERSION });+ const identity = opts.identity ?? cliSocketIdentity({+ config: { engine: 'postgres', database_url: databaseUrl }, brainId, configDir: home, configFile: configPath(), version: VERSION, env: process.env,+ });const execute = opts.execute ?? ((request: CliSocketRequest) => executeCliSocketRequest(opts.engine, request));installOutputCapture();@@ -161,15 +171,17 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promisif (!isCliSocketRequest(request)) { socket.end(frame({ v: 1, accepted: false, reason: 'malformed_request' })); return; }if (!sameToken(request.identity, identity)) { socket.end(frame({ v: 1, accepted: false, reason: 'identity_mismatch' })); return; }if (active >= MAX_ACTIVE_REQUESTS) { socket.end(frame({ v: 1, accepted: false, reason: 'busy' })); return; }+ // Active until the request's own work settles, not until it answered: a timed-out handler still holds its slot.active++;+ let settled: Promise<unknown> = Promise.resolve();try {socket.write(frame({ v: 1, accepted: true }));let result: ResultFrame;- try { result = await execute(request); }+ try { ({ frame: result, settled } = await execute(request)); }catch { result = { v: 1, kind: 'fallback', reason: 'serve_error' }; }if (!socket.destroyed) socket.end(frame(result));} finally {- active--;+ void settled.then(() => { active--; }, () => { active--; });}})();});@@ -181,9 +193,9 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis});if (!bound) { await lock.release(); log(`not started: could not bind ${path}.`); return null; }server.on('error', () => {});- try { chmodSync(path, 0o600); } catch { /* verified below */ }- if (privateSocketProblem(path) !== null) { server.close(); await lock.release(); log(`not started: ${path} did not become a private socket.`); return null; }- const inode = lstatSync(path).ino;+ let inode: number;+ try { inode = tightenBoundSocket(path); }+ catch (error) { server.close(); await lock.release(); log(`not started: ${path} did not become a private socket (${(error as Error).message}).`); return null; }const close = () => {if (closing) return;closing = true;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex af1b260aba..6c1f113b5d 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -267,6 +267,8 @@ export class PostgresEngine implements BrainEngine {connectionManager: ConnectionManager | null = null;// Instance connection (for workers) or fall back to module global (backward compat)+ /** The database URL this engine connected with; the warm CLI socket binds its identity to it (src/core/cli-socket/server.ts). */+ get connectedDatabaseUrl(): string | undefined { return this._savedConfig?.database_url; }get sql(): ReturnType<typeof postgres> {if (this._sql) return this._sql;// issue #1678: an instance-pool engine whose _sql went null (a mid-processdiff --git a/test/cli-socket-context.test.ts b/test/cli-socket-context.test.tsindex fcc311a5bd..b346554495 100644--- a/test/cli-socket-context.test.ts+++ b/test/cli-socket-context.test.ts@@ -8,13 +8,14 @@* CLI, and the serve's own GBRAIN_SOURCE never leaks into a CLI request.* 2. Fails when: makeContext gains or changes a field the mirror lacks, or the* mirror reads process.env instead of the caller's routing.- * 3. The E2E compares printed bytes for one routing; this pins every tier.+ * 3. The E2E compares printed bytes for one routing; this pins every tier,+ * plus the serve-side timeout answer.* 4. No production seam.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { makeContext } from '../src/cli/main.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { cliRequestContext, mergedRequestConfig } from '../src/core/cli-socket/execute.ts';+import { cliRequestContext, executeCliSocketRequest, mergedRequestConfig } from '../src/core/cli-socket/execute.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';@@ -68,6 +69,17 @@ describe('cliRequestContext mirrors makeContext', () => {expect(warm).toEqual(cold);});+ test('a serve-side timeout answers fallback (the CLI runs the call itself) while the work keeps the request active until it settles', async () => {+ const { frame, settled } = await executeCliSocketRequest(engine, { v: 1, identity: 'x', command: 'search', kind: 'op', op: 'search', params: { query: 'alpha' },+ routing: { cwd: process.cwd(), source_env: null }, cli: { quiet: false, timeout_ms: 1 } });+ let done = false;+ void settled.then(() => { done = true; });+ expect(frame).toEqual({ v: 1, kind: 'fallback', reason: 'timeout' });+ expect(done).toBe(false);+ await settled;+ expect(done).toBe(true);+ });+test('explicit --source', async () => {const { cold, warm } = await both(undefined, { source: 'source-b' });expect(cold.sourceId).toBe('source-b');diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.tsindex 4a2382701f..d7f045a95c 100644--- a/test/cli-socket.test.ts+++ b/test/cli-socket.test.ts@@ -1,17 +1,23 @@/*** Warm CLI socket: the guards that decide whether a CLI may talk to a serve.*- * 1. Protects: the identity token changes with the database target, config home,- * config bytes and version (never with the password); the run directory and- * socket checks refuse symlinks, foreign owners and open permissions; the- * serve rejects a peer whose kernel-reported uid differs, refuses to start- * when peer credentials cannot be read, refuses a mismatched identity, and a- * serve that dies mid-request sends the CLI to its cold path.+ * 1. Protects: the identity token changes with the brain, database target,+ * config home, config bytes, behavior env and version (never with the+ * password or a provider key's value); the run directory, the directories+ * above it and the socket checks refuse symlinks, foreign owners, open+ * permissions and a socket swapped after bind; the serve rejects a peer+ * whose kernel-reported uid differs, refuses to start when peer credentials+ * cannot be read or on a mount brain, refuses a mismatched identity, holds a+ * request's slot until its work settles, and the CLI never connects without+ * a peer-credential reader, bounds the whole exchange, and treats a dying+ * serve or a malformed frame as its cold path.* 2. Fails when: a token input is dropped, a check follows a symlink or skips- * the uid comparison, or the peer-credential branch is removed.+ * the uid comparison, the peer-credential branch is removed, or a frame+ * field the CLI reads goes unchecked.* 3. The Postgres E2E (test/e2e/cli-socket-postgres.test.ts) exercises the* happy path and fallbacks end to end; another uid cannot be produced there.- * 4. Seams: startCliSocketServer's peerCred/identity/execute/home options.+ * 4. Seams: startCliSocketServer's peerCred/identity/execute/home/brainId+ * options, exchangeCliSocket's peerCred argument, FsGuardDeps.*/import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { chmodSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';@@ -19,16 +25,28 @@ import net from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';-import { canonicalDatabaseTarget, cliSocketIdentity } from '../src/core/cli-socket/identity.ts';-import { cliSocketPath, connectProblem, ensurePrivateDir, privateDirProblem, privateSocketProblem, type FsGuardDeps } from '../src/core/cli-socket/fs-guard.ts';+import { behaviorEnvDigest, canonicalDatabaseTarget, cliSocketIdentity } from '../src/core/cli-socket/identity.ts';+import {+ ancestorProblem, cliSocketPath, connectProblem, ensurePrivateDir, privateDirProblem, privateSocketProblem, tightenBoundSocket, trustedAncestorProblem, type FsGuardDeps,+} from '../src/core/cli-socket/fs-guard.ts';import { peerCredSupport } from '../src/core/cli-socket/peer-cred.ts';import { startCliSocketServer, type CliSocketBinding } from '../src/core/cli-socket/server.ts';-import { exchangeCliSocket } from '../src/cli/cli-socket-client.ts';-import { reviveOperationError, serializeOperationError, type CliSocketRequest } from '../src/core/cli-socket/protocol.ts';+import { cliSocketRoundTripMs, exchangeCliSocket } from '../src/cli/cli-socket-client.ts';+import { isResultFrame, reviveOperationError, serializeOperationError, type CliSocketRequest, type ResultFrame } from '../src/core/cli-socket/protocol.ts';+import { queueFirstFallbackHop, takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';+import { installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';import { opError, OperationError } from '../src/core/ops/contract.ts';const uid = process.getuid!();-const engine = { kind: 'postgres' } as BrainEngine;+const engine = { kind: 'postgres', connectedDatabaseUrl: 'postgresql://[email protected]/brain' } as unknown as BrainEngine;+const okFrame: ResultFrame = { v: 1, kind: 'result', result: ['ok'], meta: null, notices: [], output: [], source: null };++/** A run directory under a private home, as the serve lays it out: <root>/home/.gbrain/run. */+function runDir(): string {+ const dir = join(root, 'home', '.gbrain', 'run');+ ensurePrivateDir(dir);+ return dir;+}let root: string;beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-cli-sock-')); });@@ -45,7 +63,7 @@ describe('identity token', () => {const url = 'postgresql://alice-example:[email protected]:6543/brain?sslmode=require&application_name=x';const token = (overrides: Partial<Parameters<typeof cliSocketIdentity>[0]> = {}) => {const dir = join(root, 'a', '.gbrain');- return cliSocketIdentity({ config: { engine: 'postgres', database_url: url }, configDir: dir, configFile: join(dir, 'config.json'), version: '1.0.0', ...overrides });+ return cliSocketIdentity({ config: { engine: 'postgres', database_url: url }, brainId: 'host', configDir: dir, configFile: join(dir, 'config.json'), version: '1.0.0', env: {}, ...overrides });};test('ignores the password and query-parameter order, keeps host, port, database and user', () => {@@ -68,6 +86,25 @@ describe('identity token', () => {writeFileSync(home.file, '{"engine":"postgres","edited":true}');expect(token()).not.toBe(base);});++ test('changes with the resolved brain id (a mount serve never matches a host CLI)', () => {+ homeWithConfig('a');+ expect(token({ brainId: 'mnt-example' })).not.toBe(token());+ });++ test('changes with GBRAIN_* settings and which provider keys are set, never with a key value or the socket/debug switches', () => {+ homeWithConfig('a');+ const base = token({ env: { HOME: '/home/alice-example', GBRAIN_HOME: '/home/alice-example' } });+ expect(token({ env: { HOME: '/elsewhere', GBRAIN_HOME: '/home/alice-example' } })).toBe(base);+ expect(token({ env: { GBRAIN_HOME: '/home/alice-example', GBRAIN_CONTRIBUTOR_MODE: '1' } })).not.toBe(base);+ expect(token({ env: { GBRAIN_HOME: '/home/alice-example', GBRAIN_CLI_SOCKET: '1', GBRAIN_DEBUG: '1', GBRAIN_SQL_TRACE: '/tmp/t.jsonl' } })).toBe(base);+ const keyed = behaviorEnvDigest({ VOYAGE_API_KEY: 'value-one' });+ expect(behaviorEnvDigest({ VOYAGE_API_KEY: 'value-two' })).toBe(keyed);+ expect(behaviorEnvDigest({})).not.toBe(keyed);+ expect(behaviorEnvDigest({ VOYAGE_API_KEY: '' })).toBe(behaviorEnvDigest({}));+ expect(behaviorEnvDigest({ OPENAI_BASE_URL: 'http://localhost:1' })).not.toBe(behaviorEnvDigest({}));+ expect(JSON.stringify(behaviorEnvDigest({ VOYAGE_API_KEY: 'value-one' }))).not.toContain('value-one');+ });});describe('run directory and socket checks', () => {@@ -86,17 +123,15 @@ describe('run directory and socket checks', () => {});test('a directory or socket owned by another uid is refused, never repaired', () => {- const dir = join(root, 'run');- ensurePrivateDir(dir);- const foreign: FsGuardDeps = { lstat: path => lstatSync(path), uid: () => uid + 1 };+ const dir = runDir();+ const foreign: FsGuardDeps = { lstat: path => lstatSync(path), stat: path => statSync(path), uid: () => uid + 1 };expect(privateDirProblem(dir, foreign)).toBe('foreign_owner');expect(() => ensurePrivateDir(dir, foreign)).toThrow(/foreign_owner/);expect(privateDirProblem(dir, { ...foreign, uid: () => undefined })).toBe('no_uid');});test('the CLI refuses a regular file, a symlinked socket and an open socket before connecting', async () => {- const dir = join(root, 'run');- ensurePrivateDir(dir);+ const dir = runDir();const path = join(dir, 'cli.sock');expect(connectProblem(path, dir)).toBe('missing');writeFileSync(path, 'x');@@ -118,6 +153,48 @@ describe('run directory and socket checks', () => {server.close();}});++ test('GBRAIN_HOME and .gbrain must be this user\'s and writable by no one else (sticky excepted), on both sides', () => {+ const dir = runDir();+ const home = join(root, 'home');+ const path = join(dir, 'cli.sock');+ expect(ancestorProblem(dir)).toBeNull();+ for (const [target, mode] of [[home, 0o775], [home, 0o757], [join(home, '.gbrain'), 0o770]] as const) {+ chmodSync(target, mode);+ expect(ancestorProblem(dir)).toEqual({ path: target, reason: 'open_permissions' });+ expect(connectProblem(path, dir)).toBe('open_permissions');+ expect(() => ensurePrivateDir(dir)).toThrow(/open_permissions/);+ chmodSync(target, 0o700);+ }+ chmodSync(home, 0o1777);+ expect(trustedAncestorProblem(home)).toBeNull();+ chmodSync(home, 0o700);+ const foreignHome: FsGuardDeps = { lstat: p => lstatSync(p), stat: p => p === home ? { ...statSync(p), isDirectory: () => true, uid: uid + 1 } as never : statSync(p), uid: () => uid };+ expect(ancestorProblem(dir, foreignHome)).toEqual({ path: home, reason: 'foreign_owner' });+ expect(() => ensurePrivateDir(dir, foreignHome)).toThrow(/foreign_owner/);+ });++ test('after bind the socket is chmod 0600 only while it is still our socket, and must keep its inode', async () => {+ const dir = runDir();+ const path = join(dir, 'cli.sock');+ const server = net.createServer();+ await new Promise<void>(resolve => server.listen(path, resolve));+ try {+ const real: FsGuardDeps = { lstat: p => lstatSync(p), uid: () => uid };+ expect(tightenBoundSocket(path, real)).toBe(lstatSync(path).ino);+ expect(lstatSync(path).mode & 0o777).toBe(0o600);+ let chmods = 0;+ const symlinked: FsGuardDeps = { ...real, lstat: p => ({ ...lstatSync(p), isSymbolicLink: () => true, isSocket: () => false }) as never };+ expect(() => tightenBoundSocket(path, symlinked, () => { chmods++; })).toThrow(/symlink/);+ expect(() => tightenBoundSocket(path, { ...real, uid: () => uid + 1 }, () => { chmods++; })).toThrow(/foreign_owner/);+ expect(chmods).toBe(0);+ let reads = 0;+ const swapped: FsGuardDeps = { ...real, lstat: p => { const st = lstatSync(p); return reads++ < 2 ? st : ({ ...st, isSocket: () => true, isSymbolicLink: () => false, ino: st.ino + 1 }) as never; } };+ expect(() => tightenBoundSocket(path, swapped, () => {})).toThrow(/replaced/);+ } finally {+ server.close();+ }+ });});describe('serve listener', () => {@@ -130,8 +207,8 @@ describe('serve listener', () => {async function start(overrides: Partial<Parameters<typeof startCliSocketServer>[0]> = {}) {const lines: string[] = [];const home = join(root, 'home', '.gbrain');- const binding = await startCliSocketServer({ engine, log: line => lines.push(line), home, identity: 'token-a',- execute: async () => ({ v: 1, kind: 'result', result: ['ok'], meta: null, notices: [], output: [], source: null }), ...overrides });+ const binding = await startCliSocketServer({ engine, log: line => lines.push(line), home, identity: 'token-a', brainId: () => 'host',+ execute: async () => ({ frame: okFrame, settled: Promise.resolve() }), ...overrides });if (binding) bindings.push(binding);return { binding, lines, path: cliSocketPath(home) };}@@ -144,7 +221,7 @@ describe('serve listener', () => {const { binding, path } = await start();expect(binding).not.toBeNull();expect(lstatSync(path).mode & 0o777).toBe(0o600);- expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: { v: 1, kind: 'result', result: ['ok'], meta: null, notices: [], output: [], source: null } });+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: okFrame });expect(await exchangeCliSocket(path, request('token-b'), 5_000)).toEqual({ reason: 'refused (identity_mismatch)' });});@@ -185,10 +262,92 @@ describe('serve listener', () => {expect(lines.join('\n')).toContain('(symlink)');});- test('a serve that dies after the handshake sends the CLI to its cold path', async () => {- const dir = join(root, 'run');- ensurePrivateDir(dir);+ test('refuses to start on a mount brain, or when the engine does not report the database it connected to', async () => {+ const mount = await start({ brainId: () => 'mnt-example' });+ expect(mount.binding).toBeNull();+ expect(mount.lines.join('\n')).toContain('this serve is on mount brain "mnt-example"');+ expect(() => lstatSync(mount.path)).toThrow();+ const unknown = await start({ engine: { kind: 'postgres' } as BrainEngine });+ expect(unknown.binding).toBeNull();+ expect(unknown.lines.join('\n')).toContain('does not report the database it connected to');+ });++ test('a request holds its slot until its work settles, not until it answered', async () => {+ let release!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ const { path } = await start({ execute: async () => ({ frame: { v: 1, kind: 'fallback', reason: 'timeout' }, settled: pending }) });+ for (let i = 0; i < 8; i++) expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: { v: 1, kind: 'fallback', reason: 'timeout' } });+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ reason: 'refused (busy)' });+ release();+ await Bun.sleep(20);+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toHaveProperty('frame');+ });++ test('without a peer-credential reader the CLI never connects', async () => {+ const { path } = await start();+ let connections = 0;+ const counter = net.createServer(socket => { connections++; socket.destroy(); });+ const probe = join(runDir(), 'probe.sock');+ await new Promise<void>(resolve => counter.listen(probe, resolve));+ try {+ expect(await exchangeCliSocket(probe, request('token-a'), 5_000, { ok: false, reason: 'no peer-credential call is wired for testos' }))+ .toEqual({ reason: 'peer_credentials_unsupported (no peer-credential call is wired for testos)' });+ await Bun.sleep(20);+ expect(connections).toBe(0);+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: okFrame });+ } finally {+ counter.close();+ }+ });++ test('a response frame missing a field the CLI reads, or of an unknown kind, is malformed', async () => {+ const valid: unknown[] = [okFrame, { v: 1, kind: 'error', error: { code: 'page_not_found', message: 'm' }, output: [['stderr', 'x']] }, { v: 1, kind: 'fallback', reason: 'r' }];+ for (const frame of valid) expect(isResultFrame(frame)).toBe(true);+ const malformed: unknown[] = [+ { v: 1, kind: 'result', result: 1, meta: null, notices: [] },+ { v: 1, kind: 'result', result: 1, meta: null, notices: [], output: [['stdout']] },+ { v: 1, kind: 'result', result: 1, meta: 'x', notices: [], output: [] },+ { v: 1, kind: 'result', result: 1, meta: null, notices: [{}], output: [] },+ { v: 1, kind: 'error', output: [] },+ { v: 1, kind: 'error', error: { message: 'no code' }, output: [] },+ { v: 1, kind: 'timeout', label: 'l', ms: 1, output: [] },+ { v: 1, kind: 'mystery' },+ { v: 1, kind: 'fallback' },+ { v: 2, kind: 'fallback', reason: 'r' },+ ];+ for (const frame of malformed) expect(isResultFrame(frame)).toBe(false);+ const dir = runDir();const path = join(dir, 'cli.sock');+ const lines = [JSON.stringify(malformed[0]), JSON.stringify({ v: 1, accepted: 'yes' })];+ for (const [handshake, result] of [['{"v":1,"accepted":true}', lines[0]], [lines[1], '']] as const) {+ const server = net.createServer(socket => socket.once('data', () => socket.write(`${handshake}\n${result}${result ? '\n' : ''}`)));+ await new Promise<void>(resolve => server.listen(path, resolve));+ try {+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ reason: 'malformed_response' });+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()));+ }+ }+ });++ test('the whole exchange is bounded: about 30 s, or the CLI\'s --timeout when shorter', async () => {+ expect(cliSocketRoundTripMs(null)).toBe(30_000);+ expect(cliSocketRoundTripMs(5_000)).toBe(5_000);+ expect(cliSocketRoundTripMs(600_000)).toBe(30_000);+ const path = join(runDir(), 'cli.sock');+ const server = net.createServer(socket => socket.once('data', () => socket.write('{"v":1,"accepted":true}\n')));+ await new Promise<void>(resolve => server.listen(path, resolve));+ try {+ const started = performance.now();+ expect(await exchangeCliSocket(path, request('token-a'), 300)).toEqual({ reason: 'round_trip_timeout' });+ expect(performance.now() - started).toBeLessThan(2_000);+ } finally {+ server.close();+ }+ });++ test('a serve that dies after the handshake sends the CLI to its cold path', async () => {+ const path = join(runDir(), 'cli.sock');const server = net.createServer(socket => socket.once('data', () => { socket.write('{"v":1,"accepted":true}\n'); setTimeout(() => socket.destroy(), 20); }));await new Promise<void>(resolve => server.listen(path, resolve));try {@@ -199,9 +358,7 @@ describe('serve listener', () => {});test('a wedged serve that never answers the handshake is abandoned within the handshake timeout', async () => {- const dir = join(root, 'run');- ensurePrivateDir(dir);- const path = join(dir, 'cli.sock');+ const path = join(runDir(), 'cli.sock');const server = net.createServer(() => { /* never answers */ });await new Promise<void>(resolve => server.listen(path, resolve));try {@@ -214,6 +371,24 @@ describe('serve listener', () => {});});+test('each warm request has its own first chat-fallback hop queue; the process queue is untouched', async () => {+ installOutputCapture();+ __resetChatFallbackHopNoticeForTests();+ const hop = (why: string) => () => ({ code: 'chat_fallback_hop', kind: 'safety', why }) as never;+ expect(queueFirstFallbackHop(hop('process'))).toBe(true);+ const seen: unknown[][] = [];+ for (const name of ['a', 'b']) {+ await withOutputCapture(new OutputCapture(), async () => {+ expect(queueFirstFallbackHop(hop(name))).toBe(true);+ expect(queueFirstFallbackHop(hop(`${name}-again`))).toBe(false);+ seen.push(takeChatFallbackHopNotices());+ });+ }+ expect(seen).toEqual([[{ code: 'chat_fallback_hop', kind: 'safety', why: 'a' }], [{ code: 'chat_fallback_hop', kind: 'safety', why: 'b' }]]);+ expect(takeChatFallbackHopNotices()).toEqual([{ code: 'chat_fallback_hop', kind: 'safety', why: 'process' }]);+ __resetChatFallbackHopNoticeForTests();+});+test('an OperationError round-trips with every field the CLI renderer reads', () => {const original = opError('page_not_found', 'Page not found: notes/alpha-example', 'Check the slug.', {fix: { argv: ['gbrain', 'get', 'notes/alpha-example', '--include-deleted'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows deleted pages too.' },diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.tsindex 61df23a77c..7119e7e25f 100644--- a/test/e2e/cli-socket-postgres.test.ts+++ b/test/e2e/cli-socket-postgres.test.ts@@ -1,9 +1,10 @@/*** The opt-in warm CLI socket against a real Postgres brain: a `gbrain serve* --cli-socket` answers CLI search/query/get/recall with the cold path's exact- * bytes and exit code in a handful of database round trips, writes never use- * it, a CLI bound to another config is refused by the identity handshake and a- * dead serve falls back to the cold path. Runs when DATABASE_URL is set.+ * bytes and exit code in far fewer database round trips, writes never use it,+ * a CLI bound to another config or another behavior env is refused by the+ * identity handshake, a serve on a mount brain never answers the host CLI and+ * a dead serve falls back to the cold path. Runs when DATABASE_URL is set.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { spawn, type ChildProcess } from 'node:child_process';@@ -186,13 +187,22 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {const otherHome = mkdtempSync(join(tmpdir(), 'gbrain-cli-socket-other-'));mkdirSync(join(otherHome, '.gbrain'));writeFileSync(join(otherHome, '.gbrain', 'config.json'), original);- const identity = cliSocketIdentity({ config: { engine: 'postgres', database_url: databaseUrl }, configDir: join(otherHome, '.gbrain'), configFile: join(otherHome, '.gbrain', 'config.json'), version: VERSION });+ const identity = cliSocketIdentity({ config: { engine: 'postgres', database_url: databaseUrl }, brainId: 'host', configDir: join(otherHome, '.gbrain'), configFile: join(otherHome, '.gbrain', 'config.json'), version: VERSION, env });const outcome = await exchangeCliSocket(socketPath, { v: 1, identity, command: 'search', kind: 'op', op: 'search', params: { query: WORD },routing: { cwd: process.cwd(), source_env: null }, cli: { quiet: false, timeout_ms: null } }, 30_000);expect(outcome).toEqual({ reason: 'refused (identity_mismatch)' });rmSync(otherHome, { recursive: true, force: true });}, 90_000);+ test('a CLI whose behavior env differs from the serve\'s (GBRAIN_* settings, provider keys present) is refused and falls back', async () => {+ const extras: Record<string, string>[] = [{ GBRAIN_CONTRIBUTOR_MODE: '1' }, { VOYAGE_API_KEY: 'synthetic-fixture-value' }];+ for (const extra of extras) {+ const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', ...extra });+ expect(run.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch)');+ expect(run.stdout).toBe(cold.get('search')!.stdout);+ }+ }, 90_000);+test('a killed serve leaves a stale socket that falls back silently', async () => {await stopServe('SIGKILL');expect(existsSync(socketPath)).toBe(true);@@ -202,4 +212,35 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {expect(noisy.stderr).toContain('[cli-socket] cold path: connect_failed');expect(noisy.stdout).toBe(cold.get('search')!.stdout);}, 90_000);++ test('a serve on a mount brain never answers the host CLI with the mount\'s data', async () => {+ const mountWord = 'quillmountword';+ const mount = await isolatedPersistencePostgres(DATABASE_URL!);+ const mountsFile = join(home, '.gbrain', 'mounts.json');+ try {+ await importFromContent(mount.engine, 'notes/mount-only-example', `---\ntitle: notes/mount-only-example\ntype: note\n---\n\n${mountWord} lives only in the mount.\n`, {+ sourceId: 'default', noEmbed: true,+ prepare: async prepared => { await withManagedFixtureWrite(mount.engine, ['default'], tx => prepared.apply(tx)); return prepared.result; },+ });+ await mount.engine.disconnect();+ const checkout = join(home, 'mnt-checkout');+ mkdirSync(checkout, { recursive: true });+ writeFileSync(mountsFile, JSON.stringify({ version: 1, mounts: [{ id: 'mnt', path: checkout, engine: 'postgres', database_url: mount.databaseUrl }] }));+ const coldHost = await cli(['search', mountWord], { GBRAIN_CLI_SOCKET: '0' });+ expect(coldHost.stdout).not.toContain('mount-only-example');+ const viaMount = await cli(['--brain', 'mnt', 'search', mountWord], { GBRAIN_CLI_SOCKET: '0' });+ expect(viaMount.stdout).toContain('notes/mount-only-example');+ serve = await startServe(['--brain', 'mnt', '--cli-socket']);+ for (let i = 0; i < 120 && !serveLog.includes('cli-socket: '); i++) await Bun.sleep(250);+ const warmHost = await cli(['search', mountWord], { GBRAIN_DEBUG: '1' });+ expect(warmHost.stdout).toBe(coldHost.stdout);+ expect(warmHost.exitCode).toBe(coldHost.exitCode);+ expect(warmHost.stderr).toContain('[cli-socket] cold path:');+ expect(serveLog).toContain('cli-socket: not started: this serve is on mount brain "mnt"');+ } finally {+ await stopServe();+ rmSync(mountsFile, { force: true });+ await mount.close();+ }+ }, 180_000);});