Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(serve): opt-in warm CLI socket for Postgres reads (GBRA-156)

garrytanb609cb1e97d2
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index a5064579c5..27790f544d 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -17,6 +17,8 @@ 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/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
diff --git a/docs/guides/cli-socket.md b/docs/guides/cli-socket.md
new file mode 100644
index 0000000000..3c810d400f
--- /dev/null
+++ b/docs/guides/cli-socket.md
@@ -0,0 +1,96 @@
+# Warm CLI socket (Postgres)
+
+Agents usually call gbrain by running the CLI once per question. On a Postgres
+brain each of those calls opens its own database connection, reads config and
+runs schema checks before it answers, and behind a transaction-mode pooler
+every one of those steps is a network round trip. A long-running
+`gbrain serve` already has all of that warm. The warm CLI socket lets that
+serve answer this user's CLI reads directly, so `gbrain search` costs about
+what the same search costs over MCP.
+
+It is **off by default**. Nothing listens until you turn it on.
+
+**Say to your agent:** *"Turn on gbrain's warm CLI socket for my running
+serve so CLI searches stop paying a cold database connection each time."*
+
+**Say to your agent:** *"Check whether my gbrain CLI reads are going through
+the warm serve socket or the cold path."*
+
+## Turn it on
+
+Start the serve with the flag:
+
+```bash
+gbrain serve --cli-socket
+```
+
+or set the config key once and restart the serve:
+
+```bash
+gbrain config set serve.cli_socket true
+```
+
+The 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.
+Turn it off by removing the flag or running
+`gbrain config set serve.cli_socket false`, then restarting the serve.
+
+## What goes through it
+
+Only reads: `gbrain search`, `gbrain query` (and `ask`), `gbrain get`, and the
+`gbrain recall` forms that run the recall operation (`--query`,
+`--budget-tokens`, `--question`, `--budget-policy`). The serve runs them
+through the same operation handlers with the same trusted local-CLI context,
+using your CLI's working directory and `GBRAIN_SOURCE` for source resolution,
+and the CLI prints the result with its usual renderer: the same stdout, stderr
+notices, `--json` documents and exit codes. Everything else, every write
+included, keeps the normal path.
+
+Some calls take the normal path even with the socket on: `--explain`,
+`--brain <mount>`, `query --image`, input piped on stdin, the briefing,
+watch, cursor and rollup forms of `recall`, and a page large enough that
+`get` streams it.
+
+## When it is not used
+
+The 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.
+
+`GBRAIN_DEBUG=1` prints one `[cli-socket] cold path: <reason>` line on stderr
+whenever a call falls back. `GBRAIN_CLI_SOCKET=0` makes a CLI call skip the
+socket entirely, for comparisons and benchmarks.
+
+## Security
+
+- **Unix domain socket only**, at `$GBRAIN_HOME/.gbrain/run/cli.sock`; never TCP.
+- The `run` directory is created `0700` and must be owned by your uid; the
+ socket is `0600`. Both the serve (before binding) and the CLI (before
+ connecting) refuse a symlink, a directory or socket owned by another uid, or
+ open permissions.
+- On every connection the serve reads the peer's uid from the kernel
+ (`SO_PEERCRED` on Linux, `getpeereid` on macOS) and drops any other uid
+ before reading the request. The CLI checks the serve's uid the same way.
+ Where peer credentials cannot be read (another operating system, or a
+ runtime that hides the socket descriptor), the serve refuses to open the
+ socket and says why.
+- One serve per `GBRAIN_HOME` holds the socket; requests and responses are
+ size-bounded and each connection carries exactly one request.
+- Postgres brains only. A PGLite brain's CLI calls already reach its running
+ serve through the persistence socket.
+
+## Differences from a cold call
+
+A warm call skips the cold path's connect-time work, so one-time startup
+notices (pending-migration warnings, upgrade disclosures) appear only on cold
+calls. Each warm request reads the DB-plane config once, in one statement, and
+answers every later config read in that request from it; nothing carries over
+to the next request, so a `gbrain config set` reaches the next warm call.
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index ae78e812fb..eaca4d8c4d 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -71,6 +71,12 @@ catalog, `--surface verbs` exposes exactly the seven-verb memory protocol
`delta` — [MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) and `--surface
starter` sits between (40 ops: the verbs plus the daily-driver set).
+On a Postgres brain, `gbrain serve --cli-socket` (off by default; or
+`gbrain config set serve.cli_socket true`) also lets this serve answer the
+same user's CLI `search`, `query`, `get` and op-backed `recall` over a
+private Unix socket, so agents that shell out to the CLI skip a cold database
+connection per call ([warm CLI socket](../guides/cli-socket.md)).
+
`--surface` is the callable ceiling. To keep every operation callable while
listing fewer tools to the agent, set `mcp.advertised_surface`:
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 196022ad73..86ac3a717d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3016 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row
+src/cli/main.ts 3017 ratchet +1 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.ts
new file mode 100644
index 0000000000..06c9c42544
--- /dev/null
+++ b/src/cli/cli-socket-client.ts
@@ -0,0 +1,186 @@
+/**
+ * CLI half of the warm CLI socket. Before a read (search, query, get, recall)
+ * opens its own database connection, the CLI looks for a serve's socket in
+ * `$GBRAIN_HOME/.gbrain/run/`; when a serve bound to the same brain identity
+ * answers, the CLI prints that answer with the cold path's own renderer and
+ * exit codes. A missing, unsafe, stale, busy, refusing or dying socket returns
+ * false and the cold path runs as if the socket did not exist (a note goes to
+ * stderr only with GBRAIN_DEBUG=1). GBRAIN_CLI_SOCKET=0 skips the socket.
+ */
+import net from 'node:net';
+import { loadConfig, configDir, configPath, isThinClient } from '../core/config.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+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 {
+ 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,
+} 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`);
+}
+
+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> {
+ return new Promise(resolve => {
+ 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);
+ const finish = (outcome: Exchange) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(outcome);
+ };
+ const arm = (ms: number, reason: string) => { clearTimeout(timer); timer = setTimeout(() => finish({ reason }), ms); };
+ 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; }
+ arm(HANDSHAKE_TIMEOUT_MS, 'handshake_timeout');
+ socket.write(JSON.stringify(request) + '\n');
+ });
+ socket.on('data', data => {
+ const frames = reader.push(typeof data === 'string' ? Buffer.from(data) : data);
+ if (frames === 'overflow') { finish({ reason: 'response_too_large' }); return; }
+ for (const text of frames) {
+ let 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; }
+ accepted = true;
+ arm(resultTimeoutMs, 'result_timeout');
+ continue;
+ }
+ const result = value as ResultFrame;
+ finish(result?.v === 1 && typeof result.kind === 'string' ? { frame: result } : { reason: 'malformed_response' });
+ return;
+ }
+ });
+ });
+}
+
+/** 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);
+ for (const [stream, text] of frame.output) {
+ if (stream === 'stdout') process.stdout.write(text);
+ else process.stderr.write(text);
+ }
+}
+
+async function opRequest(command: string, args: string[]): Promise<{ op: import('../core/operations.ts').Operation; params: Record<string, unknown> } | string> {
+ const { cliOps } = await import('./op-manifest.ts');
+ const { cliAliases, parseOpArgs } = await import('./main.ts');
+ const meta = cliOps.get(command) ?? cliAliases.get(command);
+ if (!meta || !SOCKET_OPS[meta.name]) return 'not_a_socket_op';
+ const { loadOperation } = await import('../core/operation-load.ts');
+ const op = (await loadOperation(meta.name))!;
+ const params = parseOpArgs(op, args);
+ if (op.cliHints?.stdin && !params[op.cliHints.stdin]) return 'stdin_input';
+ if (typeof params.image === 'string' && params.image.length > 0) return 'image_query';
+ if (Object.entries(op.params).some(([key, def]) => def.required && params[key] === undefined)) return 'missing_param';
+ if (typeof params.source === 'string' && params.source.length > 0 && (params.source_id !== undefined || params.all_sources === true)) return 'conflicting_scope';
+ return { op, params };
+}
+
+async function renderOp(command: string, op: import('../core/operations.ts').Operation, params: Record<string, unknown>, frame: Exclude<ResultFrame, { kind: 'fallback' }>): Promise<void> {
+ const { formatResult, captureRetrievalMeta, maybePrintConceptNudge } = await import('./main.ts');
+ const { 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');
+ const e = reviveOperationError(frame.error);
+ if (!e.writeRequest || !await reportPersistenceCliError(e, params.json === true || !!e.writeRequest)) setCliExitVerdict(writeCliError(e, command));
+ return;
+ }
+ if (frame.meta) captureRetrievalMeta('retrieval', frame.meta);
+ for (const notice of frame.notices) captureOpNotice(notice);
+ const { result, stderr: noticeText } = applyCliOpNotices(frame.result, params.json === true);
+ const output = formatResult(op.name, result, params);
+ if (output) await writeStdoutFinal(output);
+ if (noticeText) process.stderr.write(noticeText);
+ if (typeof result === 'object' && result !== null && !Array.isArray(result) && (result as { status?: unknown }).status === 'error') {
+ const detail = (result as { error?: unknown }).error;
+ console.error(`gbrain ${command}: operation reported status 'error'` + (typeof detail === 'string' && detail ? ` — ${detail}` : '') + '.');
+ setCliExitVerdict(1);
+ }
+ maybePrintConceptNudge(op.name, params);
+}
+
+/**
+ * Serves `command` from a warm serve when one is bound to this CLI's brain.
+ * True means the output was printed and the exit verdict set; false means the
+ * caller runs the normal cold path.
+ */
+export async function maybeServeFromCliSocket(command: string, args: string[]): Promise<boolean> {
+ if (!CLI_SOCKET_COMMANDS.includes(command) || process.env.GBRAIN_CLI_SOCKET === '0') return false;
+ const config = loadConfig();
+ if (!config || config.engine !== 'postgres' || !config.database_url || isThinClient(config)) return false;
+ const cliOpts = getCliOptions();
+ if (cliOpts.explain) return false;
+ const home = configDir();
+ 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; }
+
+ const base = {
+ v: 1 as const,
+ identity: cliSocketIdentity({ config, configDir: home, configFile: configPath(), version: VERSION }),
+ 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;
+
+ if (command === 'recall') {
+ const recall = await import('../commands/recall.ts');
+ if (args.includes('--help') || args.includes('-h')) return false;
+ let flags: ReturnType<typeof recall.parseFlags>;
+ try { flags = recall.parseFlags(args); } catch { return false; }
+ if (!recall.isRecallVerbForm(flags)) return false;
+ 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; }
+ await replay(outcome.frame);
+ if (outcome.frame.kind === 'result') { recall.renderRecallVerbResult(flags, outcome.frame.result as Parameters<typeof recall.renderRecallVerbResult>[1]); return true; }
+ const error = reviveOperationError(outcome.frame.error);
+ if (recall.isOneShotRecall(flags)) await recall.reportOneShotRecallError(error, flags);
+ else throw error;
+ return true;
+ }
+
+ const prepared = await opRequest(command, args);
+ if (typeof prepared === 'string') { debug(prepared); return false; }
+ const outcome = await exchangeCliSocket(path, { ...base, kind: 'op', op: SOCKET_OPS[prepared.op.name]!, params: prepared.params }, resultTimeoutMs);
+ if ('reason' in outcome) { debug(outcome.reason); return false; }
+ if (outcome.frame.kind === 'fallback') { debug(outcome.frame.reason); return false; }
+ await renderOp(command, prepared.op, prepared.params, outcome.frame);
+ return true;
+}
diff --git a/src/cli/help/serve.ts b/src/cli/help/serve.ts
index bd4b17c6d5..3282834200 100644
--- a/src/cli/help/serve.ts
+++ b/src/cli/help/serve.ts
@@ -4,7 +4,7 @@ import type { CliHelpSpec } from '../command-table.ts';
export const help: CliHelpSpec = {
summary: 'Run the MCP server: stdio by default, or OAuth 2.1 HTTP with --http.',
usage: [
- 'gbrain serve [--surface verbs|starter|full] [--access full|read-only] [--source-guard] [--stdio-idle-timeout <s>] [--fail-fast]',
+ 'gbrain serve [--surface verbs|starter|full] [--access full|read-only] [--source-guard] [--stdio-idle-timeout <s>] [--fail-fast] [--cli-socket]',
'gbrain serve --http [--port <n>] [--bind <host>] [--public-url <url>] [--token-ttl <s>] [--enable-dcr] [--surface …]',
].join('\n'),
flags: [
@@ -14,6 +14,7 @@ export const help: CliHelpSpec = {
{ name: '--source-guard', type: 'boolean', desc: 'stdio only: refuse writes unless the source binding is deliberate or unambiguous.' },
{ name: '--stdio-idle-timeout', type: 'number', desc: 'stdio only: exit after this many idle seconds (0 = never).' },
{ name: '--fail-fast', type: 'boolean', desc: 'Exit non-zero with the classified error when the database is unreachable (no degraded mode).' },
+ { name: '--cli-socket', type: 'boolean', desc: 'Postgres only, off by default (or config serve.cli_socket): answer this user\'s CLI search, query, get and recall over a private Unix socket in $GBRAIN_HOME/.gbrain/run/ instead of a cold connection per call.' },
{ name: '--port', type: 'number', desc: 'HTTP port (default 3131).' },
{ name: '--bind', type: 'string', desc: 'HTTP interface to listen on (default 127.0.0.1; 0.0.0.0 for remote access).' },
{ name: '--public-url', type: 'string', desc: 'The externally reachable base URL (OAuth issuer and redirect checks).' },
@@ -27,6 +28,7 @@ export const help: CliHelpSpec = {
examples: [
'gbrain serve',
'gbrain serve --surface starter --access read-only',
+ 'gbrain serve --cli-socket',
'gbrain serve --http --port 3131 --public-url https://brain.example.com',
],
};
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 4e5c06ecab..76556e3323 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -506,6 +506,7 @@ async function main() {
return;
}
+ if (['search', 'query', 'get', 'recall'].includes(command) && await (await import('./cli-socket-client.ts')).maybeServeFromCliSocket(command, subArgs)) return; // warm serve socket (opt-in)
// CLI-only commands
if (CLI_ONLY.has(command)) {
await handleCliOnly(command, subArgs);
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 58c0e4e9fb..e893c74127 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -60,7 +60,7 @@ const KIND_ICON: Record<FactKind, string> = {
idea: '💡',
};
-interface ParsedFlags {
+export interface ParsedFlags {
entity: string | null;
since: Date | null;
sessionId: string | null;
@@ -94,7 +94,7 @@ const WATCH_THIN_CLIENT_WARN_THRESHOLD = 30;
const WATCH_MAX_CONSECUTIVE_FAILURES = 5;
const DEFAULT_FALLBACK_HOURS = 24;
-function parseFlags(args: string[]): ParsedFlags {
+export function parseFlags(args: string[]): ParsedFlags {
const out: ParsedFlags = {
entity: null,
since: null,
@@ -216,7 +216,7 @@ export function recallNeedsLocalEngine(args: string[]): boolean {
return flags.budgetPolicy === null && flags.question === null && (flags.query !== null || flags.budgetTokens !== null);
}
-function validateAndNormalizeFlags(flags: ParsedFlags): void {
+export function validateAndNormalizeFlags(flags: ParsedFlags): void {
if (flags.sinceLastRun && flags.since) {
process.stderr.write('Error: --since-last-run and --since are mutually exclusive.\n');
process.exit(2);
@@ -249,6 +249,7 @@ async function resolveSourceForRecall(
// cannot distinguish "user asked for the default source" from "user
// passed no source flag".
sourceExplicit: boolean,
+ routing: RecallRouting = callerRouting(),
): Promise<string> {
if (thinClient) {
// #5535: an explicit `--source default` is a real selector, not an
@@ -270,7 +271,7 @@ async function resolveSourceForRecall(
// #5535: pass the flag's literal value (including 'default') when it
// was explicit so tier 1 of the resolver wins; null only when the flag
// was omitted, which keeps the env/dotfile/config-default chain.
- return await resolveSourceId(engine, sourceExplicit || flagValue !== 'default' ? flagValue : null);
+ return await resolveSourceId(engine, sourceExplicit || flagValue !== 'default' ? flagValue : null, routing.cwd, { env: routing.env });
} catch (e) {
process.stderr.write(
`[recall] source not registered: ${flagValue}. Falling back to literal value.\n`,
@@ -308,42 +309,11 @@ Withdraw a fact with gbrain forget <fact-id>.
export async function runRecall(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { process.stdout.write(RECALL_HELP); return; }
const flags = parseFlags(args);
- if (flags.budgetPolicy !== null || flags.question !== null) {
- const { MEMORY_VERBS_VERSION, operationsByName, verbError } = await import('../core/operations.ts');
- const { validateParams } = await import('../mcp/validate-params.ts');
- const { reportPersistenceCliError } = await import('./persistence-delegate.ts');
- const option = flags.budgetPolicy !== null ? '--budget-policy' : '--question';
+ if (isOneShotRecall(flags)) {
try {
- const error = (flags.budgetPolicy !== null ? validateParams(operationsByName.recall, { budget_policy: flags.budgetPolicy }) : null)
- ?? (flags.watchSeconds !== null || flags.sinceLastRun || flags.rollup || flags.asContext
- ? `${option} cannot be combined with --watch, --since-last-run, --rollup, or --as-context.` : null);
- if (error) throw verbError('invalid_params', error, flags.budgetPolicy !== null
- ? 'Use --budget-policy facts_first or query_first on a one-shot recall, or omit the policy for CLI-only behavior.'
- : 'Use --question on a one-shot recall, or drop it for the watch, cursor, rollup and context renders.');
- const selector = flags.sourceExplicit ? flags.source : process.env.GBRAIN_SOURCE || undefined;
- if (selector !== undefined && !SOURCE_ID_RE.test(selector)) {
- throw verbError('invalid_params', 'recall requires a concrete source id matching [a-z0-9-]{1,32}.',
- 'Choose a registered source id, or omit the source selector to use your existing scope.', 'source_id');
- }
- const thinClient = isThinClient(loadConfig());
- const sourceId = resolveSourceIdEngineFree(flags.sourceExplicit ? flags.source : null)
- ?? (thinClient ? undefined : await resolveSourceId(engine, null));
- await runRecallVerb(engine, flags, sourceId);
+ renderRecallVerbResult(flags, await oneShotRecallResult(engine, flags));
} catch (error) {
- if (error instanceof RemoteMcpError) {
- const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');
- const detail = { protocol_version: MEMORY_VERBS_VERSION, ...error.toJSON() };
- if (flags.json) await writeStdoutFinal(JSON.stringify(detail, null, 2) + '\n');
- console.error(`Error [${detail.error}]: ${detail.message}`);
- if (detail.suggestion) console.error(`Fix: ${detail.suggestion}`);
- setCliExitVerdict(1);
- return;
- }
- if (error instanceof SourceTargetError) {
- error = verbError('not_found', error.message,
- 'Choose an active source with the source selector, or repair your local source configuration.', 'unknown_source');
- }
- if (!await reportPersistenceCliError(error, flags.json)) throw error;
+ await reportOneShotRecallError(error, flags);
}
return;
}
@@ -364,7 +334,7 @@ export async function runRecall(engine: BrainEngine, args: string[]): Promise<vo
// MEMORY_VERBS v1 [c4]: the verb params route through the recall OP so the
// CLI and MCP exercise the same arm (query/budget packing/superset envelope).
if (flags.query !== null || flags.budgetTokens !== null || flags.question !== null) {
- await runRecallVerb(engine, flags, sourceId);
+ renderRecallVerbResult(flags, await recallVerbResult(engine, flags, sourceId));
return;
}
@@ -375,12 +345,95 @@ export async function runRecall(engine: BrainEngine, args: string[]): Promise<vo
await runRecallOnce(engine, flags, sourceId, thinClient, 'briefing');
}
+/** The caller's GBRAIN_SOURCE and cwd for source resolution; the warm CLI socket passes the CLI's, never the serve's. */
+export interface RecallRouting { cwd: string; env: string | undefined }
+
+function callerRouting(): RecallRouting {
+ return { cwd: process.cwd(), env: process.env.GBRAIN_SOURCE };
+}
+
+/** MEMORY_VERBS v1 one-shot recall (`--budget-policy` or `--question`). */
+export function isOneShotRecall(flags: ParsedFlags): boolean {
+ return flags.budgetPolicy !== null || flags.question !== null;
+}
+
+/** The recall forms that run the recall op (and only it) before rendering: one-shot, `--query`, `--budget-tokens`. */
+export function isRecallVerbForm(flags: ParsedFlags): boolean {
+ return isOneShotRecall(flags) || flags.query !== null || flags.budgetTokens !== null;
+}
+
+/** One-shot recall: validates the combination, resolves the source and runs the recall op. */
+export async function oneShotRecallResult(engine: BrainEngine, flags: ParsedFlags, routing: RecallRouting = callerRouting()): Promise<RecallVerbResult> {
+ const { operationsByName, verbError } = await import('../core/operations.ts');
+ const { validateParams } = await import('../mcp/validate-params.ts');
+ const option = flags.budgetPolicy !== null ? '--budget-policy' : '--question';
+ const error = (flags.budgetPolicy !== null ? validateParams(operationsByName.recall, { budget_policy: flags.budgetPolicy }) : null)
+ ?? (flags.watchSeconds !== null || flags.sinceLastRun || flags.rollup || flags.asContext
+ ? `${option} cannot be combined with --watch, --since-last-run, --rollup, or --as-context.` : null);
+ if (error) throw verbError('invalid_params', error, flags.budgetPolicy !== null
+ ? 'Use --budget-policy facts_first or query_first on a one-shot recall, or omit the policy for CLI-only behavior.'
+ : 'Use --question on a one-shot recall, or drop it for the watch, cursor, rollup and context renders.');
+ const selector = flags.sourceExplicit ? flags.source : routing.env || undefined;
+ if (selector !== undefined && !SOURCE_ID_RE.test(selector)) {
+ throw verbError('invalid_params', 'recall requires a concrete source id matching [a-z0-9-]{1,32}.',
+ 'Choose a registered source id, or omit the source selector to use your existing scope.', 'source_id');
+ }
+ const thinClient = isThinClient(loadConfig());
+ const sourceId = resolveSourceIdEngineFree(flags.sourceExplicit ? flags.source : null, routing.cwd, { env: routing.env })
+ ?? (thinClient ? undefined : await resolveSourceId(engine, null, routing.cwd, { env: routing.env }));
+ return recallVerbResult(engine, flags, sourceId);
+}
+
+/** How a one-shot recall failure is reported (exit code and envelope); rethrows what it does not own. */
+export async function reportOneShotRecallError(error: unknown, flags: ParsedFlags): Promise<void> {
+ const { MEMORY_VERBS_VERSION, verbError } = await import('../core/operations.ts');
+ const { reportPersistenceCliError } = await import('./persistence-delegate.ts');
+ if (error instanceof RemoteMcpError) {
+ const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');
+ const detail = { protocol_version: MEMORY_VERBS_VERSION, ...error.toJSON() };
+ if (flags.json) await writeStdoutFinal(JSON.stringify(detail, null, 2) + '\n');
+ console.error(`Error [${detail.error}]: ${detail.message}`);
+ if (detail.suggestion) console.error(`Fix: ${detail.suggestion}`);
+ setCliExitVerdict(1);
+ return;
+ }
+ if (error instanceof SourceTargetError) {
+ error = verbError('not_found', error.message,
+ 'Choose an active source with the source selector, or repair your local source configuration.', 'unknown_source');
+ }
+ if (!await reportPersistenceCliError(error, flags.json)) throw error;
+}
+
+/**
+ * The recall op result for a verb form, without printing: the source a
+ * non-one-shot form resolves (with its stderr fallback notice) and the op.
+ * The warm CLI socket's serve-side half; the CLI renders what it returns.
+ */
+export async function recallVerbForCaller(engine: BrainEngine, args: string[], routing: RecallRouting): Promise<RecallVerbResult | null> {
+ const flags = parseFlags(args);
+ if (!isRecallVerbForm(flags)) return null;
+ if (isOneShotRecall(flags)) return oneShotRecallResult(engine, flags, routing);
+ return recallVerbResult(engine, flags, await resolveSourceForRecall(engine, flags.source, false, flags.sourceExplicit, routing));
+}
+
+export type RecallVerbResult = {
+ facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string; relevance?: number }>;
+ facts_order?: 'relevance' | 'newest';
+ facts_degraded?: { reason?: string; unembedded?: number };
+ results?: Array<{ slug: string; title: string | null; evidence: string; chunk: string | null }>;
+ search_degraded?: string;
+ budget_tokens?: number;
+ budget_used?: number;
+ dropped_count?: number;
+};
+
/**
* MEMORY_VERBS v1 — `gbrain recall --query ... [--budget-tokens N]` routes
- * through the recall OP (same code path MCP exercises) and renders facts +
- * search results with the budget footer. `--json` prints the raw envelope.
+ * through the recall OP (same code path MCP exercises); renderRecallVerbResult
+ * prints facts + search results with the budget footer. `--json` prints the
+ * raw envelope.
*/
-async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?: string): Promise<void> {
+async function recallVerbResult(engine: BrainEngine, flags: ParsedFlags, sourceId?: string): Promise<RecallVerbResult> {
const { operationsByName } = await import('../core/operations.ts');
const op = operationsByName['recall'];
const ctx = {
@@ -413,19 +466,12 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?:
...(flags.pending ? { include_pending: true } : {}),
} : {}),
};
- const result = (oneShot && isThinClient(ctx.config)
+ return (oneShot && isThinClient(ctx.config)
? unpackToolResult(await callRemoteTool(ctx.config, 'recall', params, { timeoutMs: 30_000 }))
- : await op.handler(ctx, params)) as {
- facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string; relevance?: number }>;
- facts_order?: 'relevance' | 'newest';
- facts_degraded?: { reason?: string; unembedded?: number };
- results?: Array<{ slug: string; title: string | null; evidence: string; chunk: string | null }>;
- search_degraded?: string;
- budget_tokens?: number;
- budget_used?: number;
- dropped_count?: number;
- };
+ : await op.handler(ctx, params)) as RecallVerbResult;
+}
+export function renderRecallVerbResult(flags: ParsedFlags, result: RecallVerbResult): void {
// An older server ignores `question` (warn-mode params) and answers without facts_order.
const unranked = flags.question !== null && result.facts_order !== 'relevance'
? 'note: this brain did not rank facts by the question (its server predates question ranking); facts are newest first.' : null;
@@ -496,7 +542,8 @@ async function keylessQuestionFallback(engine: BrainEngine, flags: ParsedFlags,
return false;
}
process.stderr.write(`[recall] no entity or fact text matched '${question}'; ranked facts by relevance to it as a question (keyword-only: this brain has no embeddings).\n`);
- await runRecallVerb(engine, { ...flags, entity: null, question }, sourceId);
+ const questionFlags = { ...flags, entity: null, question };
+ renderRecallVerbResult(questionFlags, await recallVerbResult(engine, questionFlags, sourceId));
return true;
}
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 37b7cd8412..380d4b3633 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -278,6 +278,7 @@ export async function runServe(
// binding is deliberate or unambiguous — sole-source brains are a pure
// no-op. Stdio-only: the OAuth HTTP path scopes writes per token instead.
const sourceGuard = args.includes('--source-guard');
+ const cliSocketFlag = args.includes('--cli-socket'); // opt-in warm CLI socket (core/cli-socket/server.ts)
if (sourceGuard && isHttp) {
// Loud posture warning (the --log-full-params precedent): the guard is a
// stdio-lane mechanism; HTTP writes are scoped per token instead. An
@@ -368,11 +369,13 @@ export async function runServe(
const { armCorpusDrain } = await import('../core/sweep.ts');
const corpusDrain = (opts.armCorpusDrain ?? armCorpusDrain)(engine, { sourceId: process.env.GBRAIN_SOURCE || undefined });
+ const cliSocket = await (await import('../core/cli-socket/server.ts')).maybeStartCliSocket(engine, cliSocketFlag, httpLog);
try {
await runHttp(engine, { port, tokenTtl, enableDcr, enableDcrInsecure, publicUrl, logFullParams, bind, suppressBootstrapToken, printAdminToken, surface, adoptServer: opts.adoptServer });
} finally {
stallWatchdog?.dispose();
corpusDrain?.cancel();
+ cliSocket?.close();
}
await finishHttpServe(engine, opts);
@@ -453,6 +456,8 @@ export async function runServe(
// earlier flips stdin into flowing mode and can consume a fast client's
// initialize frame before the SDK sees it.
activateStdioIdleActivityTracking();
+ // Opt-in warm CLI socket; bound after the stdout redirect so a request's captured console output keeps its stream.
+ void import('../core/cli-socket/server.ts').then(m => m.maybeStartCliSocket(engine, cliSocketFlag, opts.log ?? ((msg: string) => console.error(msg))));
} finally {
if (bootDeadline) clearTimeout(bootDeadline);
stopProgressWatch();
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 601d3dc65e..921b39ae83 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1028,6 +1028,7 @@ 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.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 58dab7b14e..fa0c6c800e 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -119,7 +119,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--request-id', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
diff --git a/src/core/cli-socket/execute.ts b/src/core/cli-socket/execute.ts
new file mode 100644
index 0000000000..fc0c1e6054
--- /dev/null
+++ b/src/core/cli-socket/execute.ts
@@ -0,0 +1,134 @@
+/**
+ * Serve-side execution of one warm CLI request. Shared ops run through the
+ * operation's own handler with the trusted local CLI context (remote: false),
+ * built the way src/cli/main.ts makeContext builds it but with the CLI's cwd
+ * and GBRAIN_SOURCE instead of the serve's. The result goes back as data and
+ * the CLI renders it with the cold path's renderer, so the printed bytes come
+ * from the same code. `recall` runs its op-backed forms the same way.
+ */
+import type { Notice } from '../agent-output.ts';
+import { takeChatFallbackHopNotices } from '../ai/fallback-hop-queue.ts';
+import { DEFAULT_CLI_OPTIONS } from '../cli-options.ts';
+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';
+import { withRequestConfigSnapshot } from '../config-snapshot.ts';
+import type { BrainEngine } from '../engine.ts';
+import { operationsByName } from '../operations.ts';
+import { OperationError, opOwnsSource, type Operation, type OperationContext } from '../ops/contract.ts';
+import { currentCliWriteWait } from '../persistence/write-wait.ts';
+import { localFederatedSourceIds, resolveSourceWithTier, SourceTargetError } from '../source-resolver.ts';
+import { 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';
+
+/** 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> {
+ const fileConfig = loadConfig() || { engine: 'postgres' as const };
+ try {
+ return (await loadConfigWithEngine(engine, fileConfig)) ?? fileConfig;
+ } catch (err) {
+ console.warn(
+ `[config] DB-plane merge failed; using file/env config only. ` +
+ `Values set via \`gbrain config set\` will not apply to this command: ` +
+ `${(err as Error).message}`,
+ );
+ return fileConfig;
+ }
+}
+
+/** The CLI's OperationContext for one request: makeContext's fields, with the caller's routing. */
+export async function cliRequestContext(engine: BrainEngine, params: Record<string, unknown>, op: Pick<Operation, 'params'>,
+ request: Pick<CliSocketRequest, 'routing' | 'cli'>, config: GBrainConfig,
+ sinks: { emitResponseMeta: (key: string, value: unknown) => void; emitNotice: (notice: Notice) => void }): Promise<OperationContext> {
+ let sourceId: string | undefined;
+ let localFederated: string[] | undefined;
+ let sourceImplicit = true;
+ const explicit = opOwnsSource(op) ? null : (params.source as string | undefined) ?? null;
+ const env = request.routing.source_env ?? undefined;
+ try {
+ const resolved = await resolveSourceWithTier(engine, explicit, request.routing.cwd, { env });
+ sourceId = resolved.source_id;
+ sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';
+ localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ } catch (err) {
+ if (explicit || err instanceof SourceTargetError) throw err;
+ sourceId = undefined;
+ }
+ return {
+ engine,
+ config,
+ logger: { info: (...args: unknown[]) => console.log(...args), warn: (...args: unknown[]) => console.warn(...args), error: (...args: unknown[]) => console.error(...args) },
+ dryRun: (params.dry_run as boolean) || false,
+ remote: false, admissionOrigin: 'interactive',
+ cliOpts: { ...DEFAULT_CLI_OPTIONS, quiet: request.cli.quiet, timeoutMs: request.cli.timeout_ms },
+ writeWaitMs: currentCliWriteWait().waitMs,
+ sourceId: sourceId ?? 'default',
+ brainId: 'host',
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
+ ...(sourceImplicit ? { localSourceImplicit: true } : {}),
+ emitResponseMeta: sinks.emitResponseMeta,
+ emitNotice: sinks.emitNotice,
+ } as OperationContext;
+}
+
+/** Only a plain OperationError round-trips exactly; subclasses and driver errors send the CLI to its cold path. */
+function errorFrame(error: unknown, capture: OutputCapture): ResultFrame {
+ if (error instanceof OperationError && error.constructor === OperationError && !('consent' in error)) {
+ return { v: 1, kind: 'error', error: serializeOperationError(error), output: capture.chunks };
+ }
+ return { v: 1, kind: 'fallback', reason: 'unportable_error' };
+}
+
+async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'op' }>, capture: OutputCapture): 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;
+ let meta: Record<string, unknown> | null = null;
+ const notices: Notice[] = [];
+ const sinks = {
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval' && value !== null && typeof value === 'object') meta = value as Record<string, unknown>; },
+ emitNotice: (notice: Notice) => { notices.push(notice); },
+ };
+ let stage = `gbrain ${request.command}: context`;
+ try {
+ const ctx = await withTimeout(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 result = JSON.parse(JSON.stringify(raw, bigintToStringReplacer) ?? 'null');
+ return { v: 1, kind: 'result', result, meta, notices: [...notices, ...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 (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> {
+ 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 });
+ 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 };
+ } catch (error) {
+ return errorFrame(error, capture);
+ }
+}
+
+/**
+ * Runs one accepted request inside its own output capture and its own config
+ * snapshot (config-snapshot.ts, the one MCP read ops use): the first config
+ * read takes the table in one statement, every later read in the request
+ * 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> {
+ 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 };
+}
diff --git a/src/core/cli-socket/fs-guard.ts b/src/core/cli-socket/fs-guard.ts
new file mode 100644
index 0000000000..9a5059d908
--- /dev/null
+++ b/src/core/cli-socket/fs-guard.ts
@@ -0,0 +1,92 @@
+/**
+ * Where the warm CLI socket lives and the filesystem checks around it. The
+ * socket is `$GBRAIN_HOME/.gbrain/run/cli.sock`: a Unix domain socket (never
+ * 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.
+ */
+import { chmodSync, lstatSync, mkdirSync, type Stats } from 'node:fs';
+import { 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;
+}
+
+const realDeps: FsGuardDeps = { lstat: path => lstatSync(path), uid: () => process.getuid?.() };
+
+export type UnsafeReason = 'missing' | 'symlink' | 'not_directory' | 'not_socket' | 'foreign_owner' | 'open_permissions' | 'no_uid';
+
+export function cliSocketDir(home: string = configDir()): string {
+ return join(home, 'run');
+}
+
+export function cliSocketPath(home: string = configDir()): string {
+ return join(cliSocketDir(home), 'cli.sock');
+}
+
+/** AF_UNIX addresses are capped (104 bytes on darwin, the stricter of the two); a longer GBRAIN_HOME cannot host the socket. */
+export function socketPathFits(path: string): boolean {
+ return Buffer.byteLength(path) <= UNIX_SOCKET_PATH_MAX_BYTES;
+}
+
+function lstatOrNull(path: string, deps: FsGuardDeps): Stats | null {
+ try { return deps.lstat(path); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
+}
+
+/** null when `dir` is a real directory owned by this uid with no group or other access. */
+export function privateDirProblem(dir: string, deps: FsGuardDeps = realDeps): UnsafeReason | null {
+ const uid = deps.uid();
+ if (uid === undefined) return 'no_uid';
+ const st = lstatOrNull(dir, deps);
+ if (!st) return 'missing';
+ if (st.isSymbolicLink()) return 'symlink';
+ if (!st.isDirectory()) return 'not_directory';
+ if (st.uid !== uid) return 'foreign_owner';
+ if ((st.mode & 0o077) !== 0) return 'open_permissions';
+ return null;
+}
+
+/** null when `path` is a socket (not a symlink) owned by this uid with no group or other access. */
+export function privateSocketProblem(path: string, deps: FsGuardDeps = realDeps): UnsafeReason | null {
+ const uid = deps.uid();
+ if (uid === undefined) return 'no_uid';
+ const st = lstatOrNull(path, deps);
+ if (!st) return 'missing';
+ if (st.isSymbolicLink()) return 'symlink';
+ if (!st.isSocket()) return 'not_socket';
+ if (st.uid !== uid) return 'foreign_owner';
+ if ((st.mode & 0o077) !== 0) return 'open_permissions';
+ return null;
+}
+
+/** The CLI's pre-connect check: both the 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);
+}
+
+export class CliSocketUnsafeError extends Error {
+ constructor(public readonly reason: UnsafeReason, public readonly path: string) {
+ super(`refusing the CLI socket: ${path} is unsafe (${reason})`);
+ this.name = 'CliSocketUnsafeError';
+ }
+}
+
+/**
+ * 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.
+ */
+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 {
+ 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.ts
new file mode 100644
index 0000000000..9a00bbb2f0
--- /dev/null
+++ b/src/core/cli-socket/identity.ts
@@ -0,0 +1,54 @@
+/**
+ * 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
+ * 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';
+
+/** Database URL without its password, with the host, port and query parameters in one canonical spelling. */
+export function canonicalDatabaseTarget(databaseUrl: string): string {
+ let url: URL;
+ try { url = new URL(databaseUrl); }
+ catch { return `unparsed:${createHash('sha256').update(databaseUrl).digest('hex')}`; }
+ const params = [...url.searchParams.entries()]
+ .filter(([key]) => !/pass/i.test(key))
+ .sort(([a, av], [b, bv]) => a === b ? av.localeCompare(bv) : a.localeCompare(b));
+ const protocol = url.protocol === 'postgres:' ? 'postgresql:' : url.protocol;
+ const user = decodeURIComponent(url.username);
+ return `${protocol}//${user ? `${user}@` : ''}${url.hostname.toLowerCase()}:${url.port || '5432'}`
+ + `${decodeURIComponent(url.pathname) || '/'}${params.length ? `?${new URLSearchParams(params).toString()}` : ''}`;
+}
+
+function realpathOr(path: string): string {
+ try { return realpathSync(path); } catch { return `absent:${path}`; }
+}
+
+function fileDigest(path: string): string {
+ try { return createHash('sha256').update(readFileSync(path)).digest('hex'); } catch { return 'absent'; }
+}
+
+export interface CliSocketIdentityInput {
+ config: Pick<GBrainConfig, 'engine' | 'database_url'>;
+ configDir: string;
+ configFile: string;
+ version: string;
+}
+
+/** SHA-256 over the canonical database target, the config home and file (realpath and content) and the gbrain version. */
+export function cliSocketIdentity(input: CliSocketIdentityInput): string {
+ const fields = {
+ v: 1,
+ version: input.version,
+ brain: 'host',
+ engine: input.config.engine,
+ database: input.config.database_url ? canonicalDatabaseTarget(input.config.database_url) : null,
+ config_dir: realpathOr(input.configDir),
+ config_file: realpathOr(input.configFile),
+ config_sha256: fileDigest(input.configFile),
+ };
+ return createHash('sha256').update(JSON.stringify(fields)).digest('hex');
+}
diff --git a/src/core/cli-socket/output-capture.ts b/src/core/cli-socket/output-capture.ts
new file mode 100644
index 0000000000..b87e10dea4
--- /dev/null
+++ b/src/core/cli-socket/output-capture.ts
@@ -0,0 +1,65 @@
+/**
+ * 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
+ * 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 { setSourceNoteScope } from '../fix-routing.ts';
+import { setWarnOnceScope } from '../utils.ts';
+import { MAX_CAPTURED_OUTPUT_BYTES, type OutputChunk } from './protocol.ts';
+
+export class OutputCapture {
+ readonly chunks: OutputChunk[] = [];
+ /** This request's warnOncePerProcess keys: a cold CLI process starts with none. */
+ readonly warned = new Set<string>();
+ /** The first source this request resolved, which the CLI pins in its fix commands. */
+ resolvedSource?: string;
+ private bytes = 0;
+ overflow = false;
+
+ push(stream: OutputChunk[0], text: string): void {
+ this.bytes += Buffer.byteLength(text);
+ if (this.bytes > MAX_CAPTURED_OUTPUT_BYTES) { this.overflow = true; return; }
+ const last = this.chunks[this.chunks.length - 1];
+ if (last && last[0] === stream) last[1] += text;
+ else this.chunks.push([stream, text]);
+ }
+}
+
+const store = new AsyncLocalStorage<OutputCapture>();
+let installed = false;
+
+/** Route console and stderr writes made inside a capture scope into it; outside a scope nothing changes. Idempotent. */
+export function installOutputCapture(): void {
+ if (installed) return;
+ installed = true;
+ setWarnOnceScope(() => store.getStore()?.warned);
+ setSourceNoteScope(() => store.getStore());
+ const methods = [['log', 'stdout'], ['info', 'stdout'], ['debug', 'stdout'], ['warn', 'stderr'], ['error', 'stderr']] as const;
+ for (const [method, stream] of methods) {
+ const original = console[method];
+ console[method] = (...args: unknown[]): void => {
+ const capture = store.getStore();
+ if (!capture) { original.apply(console, args); return; }
+ capture.push(stream, format(...args) + '\n');
+ };
+ }
+ const originalWrite = process.stderr.write;
+ process.stderr.write = function (this: NodeJS.WriteStream, chunk: unknown, ...rest: unknown[]): boolean {
+ const capture = store.getStore();
+ if (!capture) return (originalWrite as (...args: unknown[]) => boolean).call(this, chunk, ...rest);
+ const encoding = typeof rest[0] === 'string' ? rest[0] as BufferEncoding : 'utf8';
+ capture.push('stderr', typeof chunk === 'string' ? chunk : Buffer.from(chunk as Uint8Array).toString(encoding));
+ const callback = rest.find(arg => typeof arg === 'function') as (() => void) | undefined;
+ if (callback) queueMicrotask(callback);
+ return true;
+ } as typeof process.stderr.write;
+}
+
+export function withOutputCapture<T>(capture: OutputCapture, fn: () => Promise<T>): Promise<T> {
+ return store.run(capture, fn);
+}
diff --git a/src/core/cli-socket/peer-cred.ts b/src/core/cli-socket/peer-cred.ts
new file mode 100644
index 0000000000..aeeed0a0d2
--- /dev/null
+++ b/src/core/cli-socket/peer-cred.ts
@@ -0,0 +1,77 @@
+/**
+ * The uid of the process on the other end of a connected Unix socket, read
+ * from the kernel: getsockopt(SO_PEERCRED) on Linux, getpeereid() on macOS,
+ * both through bun:ffi on the socket's file descriptor. Other platforms (and
+ * Linux architectures whose SO_PEERCRED constant differs) report unsupported,
+ * and the serve then refuses to open the CLI socket at all (fail closed).
+ */
+import type { Socket } from 'node:net';
+
+export type PeerUidReader = (fd: number) => number | null;
+
+export type PeerCredSupport = { ok: true; read: PeerUidReader } | { ok: false; reason: string };
+
+let cached: PeerCredSupport | undefined;
+
+function linuxReader(): PeerCredSupport {
+ if (process.arch !== 'x64' && process.arch !== 'arm64') {
+ return { ok: false, reason: `SO_PEERCRED is not wired for linux/${process.arch}` };
+ }
+ const { dlopen, FFIType, ptr } = require('bun:ffi') as typeof import('bun:ffi');
+ const SOL_SOCKET = 1;
+ const SO_PEERCRED = 17;
+ for (const lib of ['libc.so.6', 'libc.so', `libc.musl-${process.arch === 'x64' ? 'x86_64' : 'aarch64'}.so.1`]) {
+ try {
+ const { symbols } = dlopen(lib, { getsockopt: { args: [FFIType.i32, FFIType.i32, FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 } });
+ return { ok: true, read: (fd) => {
+ const ucred = new Int32Array(3);
+ const length = new Uint32Array([12]);
+ if (symbols.getsockopt(fd, SOL_SOCKET, SO_PEERCRED, ptr(ucred), ptr(length)) !== 0 || length[0] !== 12) return null;
+ return ucred[1]! >>> 0;
+ } };
+ } catch { /* try the next libc spelling */ }
+ }
+ return { ok: false, reason: 'libc could not be loaded through bun:ffi' };
+}
+
+function darwinReader(): PeerCredSupport {
+ const { dlopen, FFIType, ptr } = require('bun:ffi') as typeof import('bun:ffi');
+ try {
+ const { symbols } = dlopen('libSystem.B.dylib', { getpeereid: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 } });
+ return { ok: true, read: (fd) => {
+ const uid = new Uint32Array(1);
+ const gid = new Uint32Array(1);
+ return symbols.getpeereid(fd, ptr(uid), ptr(gid)) === 0 ? uid[0]! : null;
+ } };
+ } catch {
+ return { ok: false, reason: 'libSystem could not be loaded through bun:ffi' };
+ }
+}
+
+/** The platform's peer-credential reader, resolved once per process. */
+export function peerCredSupport(): PeerCredSupport {
+ if (cached) return cached;
+ try {
+ if (typeof Bun === 'undefined') cached = { ok: false, reason: 'peer credentials need the Bun runtime (bun:ffi)' };
+ else if (process.getuid === undefined) cached = { ok: false, reason: 'this platform has no POSIX uid' };
+ else if (process.platform === 'linux') cached = linuxReader();
+ else if (process.platform === 'darwin') cached = darwinReader();
+ else cached = { ok: false, reason: `no peer-credential call is wired for ${process.platform}` };
+ } catch (error) {
+ cached = { ok: false, reason: `peer credentials unavailable: ${(error as Error).message}` };
+ }
+ return cached;
+}
+
+/** The connected socket's file descriptor, or null when the runtime does not expose one. */
+export function socketFd(socket: Socket): number | null {
+ const fd = (socket as unknown as { _handle?: { fd?: unknown } })._handle?.fd;
+ return typeof fd === 'number' && Number.isInteger(fd) && fd >= 0 ? fd : null;
+}
+
+/** The peer's uid, or null when it cannot be read (the caller treats that as a rejection). */
+export function peerUid(socket: Socket, read: PeerUidReader): number | null {
+ const fd = socketFd(socket);
+ if (fd === null) return null;
+ try { return read(fd); } catch { return null; }
+}
diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.ts
new file mode 100644
index 0000000000..0435114d8b
--- /dev/null
+++ b/src/core/cli-socket/protocol.ts
@@ -0,0 +1,113 @@
+/**
+ * The warm CLI socket's wire format: newline-delimited JSON on a Unix socket,
+ * one exchange per connection. The CLI sends one request; the serve answers a
+ * handshake line (accepted, or refused with a reason) and then, when accepted,
+ * one result line. Both directions are size-bounded.
+ */
+import type { Notice } from '../agent-output.ts';
+import { OperationError } from '../ops/contract.ts';
+
+export const CLI_SOCKET_PROTOCOL = 1;
+export const MAX_REQUEST_BYTES = 256 * 1024;
+export const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
+export const MAX_CAPTURED_OUTPUT_BYTES = 1024 * 1024;
+export const CONNECT_TIMEOUT_MS = 150;
+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 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;
+export type CliSocketOp = typeof CLI_SOCKET_OPS[number];
+
+export interface CliSocketRouting {
+ /** The CLI's working directory (dotfile walk and registered-path tiers). */
+ cwd: string;
+ /** The CLI's GBRAIN_SOURCE; null when unset. */
+ source_env: string | null;
+}
+
+export type CliSocketRequest = {
+ v: 1;
+ identity: string;
+ /** The command word the cold path would print in its timeout line. */
+ command: string;
+ routing: CliSocketRouting;
+ cli: { quiet: boolean; timeout_ms: number | null };
+} & ({ kind: 'op'; op: CliSocketOp; params: Record<string, unknown> } | { kind: 'recall'; args: string[] });
+
+export type HandshakeFrame = { v: 1; accepted: true } | { v: 1; accepted: false; reason: string };
+
+export type OutputChunk = ['stdout' | 'stderr', string];
+
+/** What every answered frame carries: the output to replay and the first source resolved (pinned in fix commands). */
+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 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;
+ const routing = value.routing;
+ if (!record(routing) || typeof routing.cwd !== 'string' || !routing.cwd.startsWith('/')
+ || !(routing.source_env === null || typeof routing.source_env === 'string')) return false;
+ const cli = value.cli;
+ if (!record(cli) || typeof cli.quiet !== 'boolean'
+ || !(cli.timeout_ms === null || typeof cli.timeout_ms === 'number' && Number.isFinite(cli.timeout_ms) && cli.timeout_ms > 0)) return false;
+ if (value.kind === 'op') return (CLI_SOCKET_OPS as readonly unknown[]).includes(value.op) && record(value.params);
+ if (value.kind === 'recall') return Array.isArray(value.args) && value.args.every(arg => typeof arg === 'string');
+ return false;
+}
+
+/** An OperationError's own fields, so the CLI can rebuild the same error and render it with the cold path's renderer. */
+export function serializeOperationError(error: OperationError): Record<string, unknown> {
+ const { stack: _stack, ...own } = Object.assign({}, error) as unknown as Record<string, unknown>;
+ return JSON.parse(JSON.stringify({ ...own, message: error.message }));
+}
+
+export function reviveOperationError(fields: Record<string, unknown>): OperationError {
+ const { code, message, suggestion, docs, name: _name, ...rest } = fields;
+ const error = new OperationError(code as OperationError['code'], String(message),
+ typeof suggestion === 'string' ? suggestion : undefined, typeof docs === 'string' ? docs : undefined);
+ return Object.assign(error, rest);
+}
+
+/** Accumulates one newline-terminated frame from a stream, refusing past `max` bytes. */
+export class FrameReader {
+ private chunks: Buffer[] = [];
+ private bytes = 0;
+ private rest: Buffer = Buffer.alloc(0);
+ constructor(private readonly max: number) {}
+
+ /** Feeds data; returns the completed frames' text, or 'overflow'. */
+ push(data: Buffer): string[] | 'overflow' {
+ let buffer = this.rest.length ? Buffer.concat([this.rest, data]) : data;
+ this.rest = Buffer.alloc(0);
+ const frames: string[] = [];
+ for (;;) {
+ const newline = buffer.indexOf(10);
+ if (newline === -1) break;
+ const piece = buffer.subarray(0, newline);
+ this.bytes += piece.length;
+ if (this.bytes > this.max) return 'overflow';
+ this.chunks.push(piece);
+ frames.push(Buffer.concat(this.chunks).toString('utf8'));
+ this.chunks = [];
+ this.bytes = 0;
+ buffer = buffer.subarray(newline + 1);
+ }
+ this.bytes += buffer.length;
+ if (this.bytes > this.max) return 'overflow';
+ if (buffer.length) this.chunks.push(Buffer.from(buffer));
+ return frames;
+ }
+}
diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.ts
new file mode 100644
index 0000000000..56f42efcbf
--- /dev/null
+++ b/src/core/cli-socket/server.ts
@@ -0,0 +1,198 @@
+/**
+ * The serve side of the warm CLI socket (opt-in: `gbrain serve --cli-socket`
+ * or config `serve.cli_socket`). Postgres brains only; PGLite already
+ * delegates through the persistence owner socket. Every connection's peer uid
+ * is read from the kernel and compared with this process's uid before a byte
+ * 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 net, { type Socket } from 'node:net';
+import type { BrainEngine } from '../engine.ts';
+import { configDir, configPath, loadConfig } 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 { cliSocketIdentity } from './identity.ts';
+import { installOutputCapture } from './output-capture.ts';
+import { peerCredSupport, peerUid, type PeerCredSupport } from './peer-cred.ts';
+import { FrameReader, isCliSocketRequest, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, REQUEST_READ_TIMEOUT_MS,
+ type CliSocketRequest, type HandshakeFrame, type ResultFrame } from './protocol.ts';
+
+export const CLI_SOCKET_CONFIG_KEY = 'serve.cli_socket';
+const MAX_CONNECTIONS = 32;
+const MAX_ACTIVE_REQUESTS = 8;
+
+export interface CliSocketBinding { path: string; close(): void }
+
+export interface CliSocketServerOptions {
+ engine: BrainEngine;
+ log: (line: string) => void;
+ /** Test seams; production derives each from this process. */
+ peerCred?: PeerCredSupport;
+ home?: string;
+ identity?: string;
+ uid?: () => number | undefined;
+ execute?: (request: CliSocketRequest) => Promise<ResultFrame>;
+}
+
+/** Whether this serve should open the socket: the flag, or the DB-plane config key set to a true value. */
+export async function cliSocketRequested(engine: BrainEngine, flag: boolean): Promise<boolean> {
+ if (flag) return true;
+ try { return /^(1|true|on|yes)$/i.test((await engine.getConfig(CLI_SOCKET_CONFIG_KEY))?.trim() ?? ''); }
+ catch { return false; }
+}
+
+/** serve's entry (`flag` is `--cli-socket`): opens the socket only when asked; logs (never throws) when it cannot. */
+export async function maybeStartCliSocket(engine: BrainEngine, flag: boolean, log: (line: string) => void): Promise<CliSocketBinding | null> {
+ if (!await cliSocketRequested(engine, flag)) return null;
+ try { return await startCliSocketServer({ engine, log }); }
+ catch (error) { log(`[gbrain serve] cli-socket: not started: ${(error as Error).message}`); return null; }
+}
+
+function sameToken(a: string, b: string): boolean {
+ const left = Buffer.from(a);
+ const right = Buffer.from(b);
+ return left.length === right.length && timingSafeEqual(left, right);
+}
+
+function frame(value: HandshakeFrame | ResultFrame): string {
+ const text = JSON.stringify(value) + '\n';
+ return Buffer.byteLength(text) > MAX_RESPONSE_BYTES ? JSON.stringify({ v: 1, kind: 'fallback', reason: 'response_too_large' }) + '\n' : text;
+}
+
+/** True when `path` answers a connect, i.e. another serve owns it. */
+function socketAnswers(path: string): Promise<boolean> {
+ return new Promise(resolve => {
+ const probe = net.createConnection(path);
+ const done = (live: boolean) => { clearTimeout(timer); probe.destroy(); resolve(live); };
+ const timer = setTimeout(() => done(false), 200);
+ probe.once('connect', () => done(true));
+ probe.once('error', () => done(false));
+ });
+}
+
+/** Proves the platform reader returns this process's uid on a real accepted socket before any real listener exists. */
+async function peerCredSelfTest(dir: string, support: Extract<PeerCredSupport, { ok: true }>, uid: number): Promise<boolean> {
+ const path = `${dir}/p${process.pid}`;
+ try { unlinkSync(path); } catch { /* absent */ }
+ return new Promise(resolve => {
+ let settled = false;
+ const finish = (ok: boolean) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ server.close();
+ try { unlinkSync(path); } catch { /* already gone */ }
+ resolve(ok);
+ };
+ const server = net.createServer(socket => { const seen = peerUid(socket, support.read); socket.destroy(); finish(seen === uid); });
+ const timer = setTimeout(() => finish(false), 2_000);
+ server.once('error', () => finish(false));
+ server.listen(path, () => { const client = net.createConnection(path); client.once('error', () => finish(false)); });
+ });
+}
+
+/**
+ * Binds the socket when it is safe to: peer credentials verified on this
+ * platform, a private run directory, no live owner. Returns null (with one log
+ * line saying why) when it does not bind; never throws into the serve.
+ */
+export async function startCliSocketServer(opts: CliSocketServerOptions): Promise<CliSocketBinding | null> {
+ const 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; }
+ 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();
+ const dir = cliSocketDir(home);
+ const path = cliSocketPath(home);
+ if (!socketPathFits(path) || !socketPathFits(`${dir}/p${process.pid}`)) { log(`not started: ${path} is longer than a Unix socket address allows.`); return null; }
+ try { ensurePrivateDir(dir); }
+ catch (error) { log(`not started: ${(error as Error).message}`); return null; }
+ if (!await peerCredSelfTest(dir, support, uid)) { log('not started: the peer-credential self-test did not return this process\'s uid.'); return null; }
+
+ let lock: Awaited<ReturnType<typeof tryAcquireNativeLock>>;
+ try { lock = await tryAcquireNativeLock(`${path}.bind.lock`); }
+ catch (error) { log(`not started: the bind lock is unavailable (${(error as Error).message}).`); return null; }
+ if (!lock) { log('not started: another serve holds the CLI socket for this GBRAIN_HOME.'); return null; }
+ const problem = privateSocketProblem(path);
+ if (problem !== 'missing') {
+ if (problem && problem !== 'open_permissions') { await lock.release(); log(`not started: ${new CliSocketUnsafeError(problem, path).message}`); return null; }
+ if (await socketAnswers(path)) { await lock.release(); log('not started: another serve already answers the CLI socket.'); return null; }
+ unlinkSync(path);
+ }
+
+ const config = loadConfig();
+ const identity = opts.identity ?? cliSocketIdentity({ config: config ?? { engine: 'postgres' }, configDir: home, configFile: configPath(), version: VERSION });
+ const execute = opts.execute ?? ((request: CliSocketRequest) => executeCliSocketRequest(opts.engine, request));
+ installOutputCapture();
+
+ const sockets = new Set<Socket>();
+ let active = 0;
+ let closing = false;
+ const rejectedUids = new Set<number | null>();
+ const server = net.createServer(socket => {
+ socket.on('error', () => {});
+ if (closing || sockets.size >= MAX_CONNECTIONS) { socket.destroy(); return; }
+ const peer = peerUid(socket, support.read);
+ if (peer !== uid) {
+ if (!rejectedUids.has(peer)) { rejectedUids.add(peer); log(`rejected a connection from ${peer === null ? 'an unverifiable peer' : `uid ${peer}`}.`); }
+ socket.destroy();
+ return;
+ }
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ const reader = new FrameReader(MAX_REQUEST_BYTES);
+ const readTimer = setTimeout(() => socket.destroy(), REQUEST_READ_TIMEOUT_MS);
+ readTimer.unref();
+ let handled = false;
+ socket.on('data', data => {
+ if (handled) return;
+ const frames = reader.push(typeof data === 'string' ? Buffer.from(data) : data);
+ if (frames === 'overflow') { handled = true; socket.destroy(); return; }
+ if (frames.length === 0) return;
+ handled = true;
+ clearTimeout(readTimer);
+ void (async () => {
+ let request: unknown;
+ try { request = JSON.parse(frames[0]!); } catch { request = null; }
+ if (!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++;
+ try {
+ socket.write(frame({ v: 1, accepted: true }));
+ let result: ResultFrame;
+ try { result = await execute(request); }
+ catch { result = { v: 1, kind: 'fallback', reason: 'serve_error' }; }
+ if (!socket.destroyed) socket.end(frame(result));
+ } finally {
+ active--;
+ }
+ })();
+ });
+ });
+
+ const bound = await new Promise<boolean>(resolve => {
+ server.once('error', () => resolve(false));
+ server.listen(path, () => resolve(true));
+ });
+ 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;
+ const close = () => {
+ if (closing) return;
+ closing = true;
+ server.close();
+ for (const socket of sockets) socket.destroy();
+ try { if (lstatSync(path).ino === inode) unlinkSync(path); } catch { /* already gone */ }
+ void lock!.release();
+ };
+ process.once('exit', close);
+ log(`listening on ${path} (read ops: search, query, get, recall).`);
+ return { path, close };
+}
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index 8d6d5235e4..080e903db6 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -16,4 +16,5 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'skillopt.capture_enabled', // skillopt/held-out.ts production rollout capture, default off
'entity_identity.union', // entity-identity.ts: links/backlinks union across identity co-members, default off
'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off
+ 'serve.cli_socket', // cli-socket/server.ts: a Postgres serve answers CLI reads over a private Unix socket, default off
];
diff --git a/src/core/fix-routing.ts b/src/core/fix-routing.ts
index 80b6f4dd76..89b3d59b34 100644
--- a/src/core/fix-routing.ts
+++ b/src/core/fix-routing.ts
@@ -107,8 +107,20 @@ export function installCliRouting(provider: () => FixRouting | undefined): void
recording = true;
}
+let sourceNoteScope: (() => { resolvedSource?: string } | undefined) | null = null;
+
+/** A resident serve answering for a one-shot CLI (the warm CLI socket) records each request's first source for that CLI, not for itself. */
+export function setSourceNoteScope(scope: () => { resolvedSource?: string } | undefined): void {
+ sourceNoteScope = scope;
+}
+
/** Called by the source resolver: the first source an invocation resolves is the one its fixes pin. */
export function noteResolvedSource(sourceId: string): void {
+ const scoped = sourceNoteScope?.();
+ if (scoped) {
+ if (scoped.resolvedSource === undefined && pinnableSource(sourceId)) scoped.resolvedSource = sourceId;
+ return;
+ }
if (recording && resolvedSource === undefined && pinnableSource(sourceId)) resolvedSource = sourceId;
}
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index b3b5c2a880..2c0ea25448 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -45,6 +45,11 @@ const DOTFILE = '.gbrain-source';
// Tier-specific messages are clearer than the generic assertValidSourceId
// error, so the throws stay inline.
+/** GBRAIN_SOURCE for this resolution: a caller-supplied value (even unset) wins over this process's env. */
+function ambientSourceEnv(opts: { env?: string }): string | undefined {
+ return Object.hasOwn(opts, 'env') ? opts.env : process.env.GBRAIN_SOURCE;
+}
+
function readDotfileWalk(startDir: string): string | null {
let dir = resolve(startDir);
// Guard against infinite loops on malformed paths.
@@ -151,7 +156,9 @@ export async function resolveSourceId(
cwd: string = process.cwd(),
// Local IPC already evaluated the client's flag/env/dotfile tiers. The
// owner's environment must never redirect that client's unscoped request.
- opts: { skipLocalSignals?: boolean } = {},
+ // `env` stands in for GBRAIN_SOURCE when a resident serve resolves for a
+ // CLI caller (the warm CLI socket): the caller's value, never the serve's.
+ opts: { skipLocalSignals?: boolean; env?: string } = {},
): Promise<string> {
const id = await resolveSourceIdChain(engine, explicit, cwd, opts);
if (!opts.skipLocalSignals) noteResolvedSource(id);
@@ -162,7 +169,7 @@ async function resolveSourceIdChain(
engine: BrainEngine,
explicit: string | null | undefined,
cwd: string,
- opts: { skipLocalSignals?: boolean },
+ opts: { skipLocalSignals?: boolean; env?: string },
): Promise<string> {
// 1. Explicit flag wins. The __all__ sentinel passes through verbatim
// (#1712) — it is not a source id, so it skips both the regex and
@@ -177,7 +184,7 @@ async function resolveSourceIdChain(
}
// 2. Env var. Same __all__ pass-through (#2140).
- const env = opts.skipLocalSignals ? undefined : process.env.GBRAIN_SOURCE;
+ const env = opts.skipLocalSignals ? undefined : ambientSourceEnv(opts);
if (env && env.length > 0) {
if (env === ALL_SOURCES) return ALL_SOURCES;
if (!SOURCE_ID_RE.test(env)) {
@@ -248,6 +255,7 @@ async function resolveSourceIdChain(
export function resolveSourceIdEngineFree(
explicit: string | null | undefined,
cwd: string = process.cwd(),
+ opts: { env?: string } = {},
): string | null {
if (explicit) {
if (explicit === ALL_SOURCES) return ALL_SOURCES; // #1712 sentinel pass-through
@@ -256,7 +264,7 @@ export function resolveSourceIdEngineFree(
}
return explicit;
}
- const env = process.env.GBRAIN_SOURCE;
+ const env = ambientSourceEnv(opts);
if (env && env.length > 0) {
if (env === ALL_SOURCES) return ALL_SOURCES; // #2140 sentinel pass-through
if (!SOURCE_ID_RE.test(env)) {
@@ -770,8 +778,9 @@ export async function resolveSourceWithTier(
engine: BrainEngine,
explicit: string | null | undefined,
cwd: string = process.cwd(),
+ opts: { env?: string } = {},
): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
- const resolved = await resolveSourceWithTierChain(engine, explicit, cwd);
+ const resolved = await resolveSourceWithTierChain(engine, explicit, cwd, opts);
noteResolvedSource(resolved.source_id);
return resolved;
}
@@ -780,6 +789,7 @@ async function resolveSourceWithTierChain(
engine: BrainEngine,
explicit: string | null | undefined,
cwd: string,
+ opts: { env?: string },
): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
// 1. Explicit flag wins. __all__ sentinel passes through verbatim (#1712).
if (explicit) {
@@ -794,7 +804,7 @@ async function resolveSourceWithTierChain(
}
// 2. Env var. Same __all__ pass-through (#2140).
- const env = process.env.GBRAIN_SOURCE;
+ const env = ambientSourceEnv(opts);
if (env && env.length > 0) {
if (env === ALL_SOURCES) {
return { source_id: ALL_SOURCES, tier: 'env', detail: `GBRAIN_SOURCE=${ALL_SOURCES} (spans all sources)` };
diff --git a/src/core/utils.ts b/src/core/utils.ts
index c0c9ad6120..4db33796a0 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -448,9 +448,21 @@ const _warnedKeys = new Set<string>();
* Test seam: `_resetWarnOnceForTests()` clears the set so per-process
* warn-once contracts can be reasserted across test cases.
*/
+let warnOnceScope: (() => Set<string> | undefined) | null = null;
+
+/**
+ * A resident serve answering for a one-shot CLI (the warm CLI socket) gives
+ * each request its own once-set, so the CLI sees the warnings its own process
+ * would have printed.
+ */
+export function setWarnOnceScope(scope: () => Set<string> | undefined): void {
+ warnOnceScope = scope;
+}
+
export function warnOncePerProcess(key: string, message: string): void {
- if (_warnedKeys.has(key)) return;
- _warnedKeys.add(key);
+ const warned = warnOnceScope?.() ?? _warnedKeys;
+ if (warned.has(key)) return;
+ warned.add(key);
console.warn(message);
}
diff --git a/test/cli-socket-context.test.ts b/test/cli-socket-context.test.ts
new file mode 100644
index 0000000000..fcc311a5bd
--- /dev/null
+++ b/test/cli-socket-context.test.ts
@@ -0,0 +1,76 @@
+/**
+ * Warm CLI socket context parity: the serve builds the CLI's OperationContext
+ * (src/core/cli-socket/execute.ts cliRequestContext) from the caller's
+ * GBRAIN_SOURCE and cwd, mirroring makeContext in src/cli/main.ts.
+ *
+ * 1. Protects: a warm search/query/get resolves the same source, tier-derived
+ * scope (implicit flag, federated set) and trust (remote: false) as the cold
+ * 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.
+ * 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 { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const op = { params: {} };
+const noop = { emitResponseMeta: () => {}, emitNotice: () => {} };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES
+ ('source-a', 'source-a', $1, '{"federated": true}'::jsonb),
+ ('source-b', 'source-b', NULL, '{"federated": true}'::jsonb)`, [process.cwd()]);
+});
+
+function comparable(ctx: Record<string, unknown>): Record<string, unknown> {
+ const { engine: _e, logger: _l, emitResponseMeta: _m, emitNotice: _n, cliOpts: _c, brainId: _b, writeWaitMs: _w, ...rest } = ctx;
+ return { keys: Object.keys(ctx).sort(), ...rest };
+}
+
+async function both(callerEnv: string | undefined, params: Record<string, unknown> = {}) {
+ const cold = await withEnv({ GBRAIN_SOURCE: callerEnv }, () => makeContext(engine, params, op));
+ // The serve runs with its own (different) GBRAIN_SOURCE; the caller's must win.
+ const warm = await withEnv({ GBRAIN_SOURCE: 'source-b' }, async () => cliRequestContext(engine, params, op,
+ { routing: { cwd: process.cwd(), source_env: callerEnv ?? null }, cli: { quiet: false, timeout_ms: null } },
+ await mergedRequestConfig(engine), noop));
+ return { cold: comparable(cold as unknown as Record<string, unknown>), warm: comparable(warm as unknown as Record<string, unknown>) };
+}
+
+describe('cliRequestContext mirrors makeContext', () => {
+ test('registered-path tier (implicit, federated set)', async () => {
+ const { cold, warm } = await both(undefined);
+ expect(cold.sourceId).toBe('source-a');
+ expect(cold.localSourceImplicit).toBe(true);
+ expect(cold.localFederatedSourceIds).toEqual(expect.arrayContaining(['source-a', 'source-b']));
+ expect(warm).toEqual(cold);
+ });
+
+ test('caller GBRAIN_SOURCE tier, not the serve\'s', async () => {
+ const { cold, warm } = await both('default');
+ expect(cold.sourceId).toBe('default');
+ expect(cold.localSourceImplicit).toBeUndefined();
+ expect(warm).toEqual(cold);
+ });
+
+ test('explicit --source', async () => {
+ const { cold, warm } = await both(undefined, { source: 'source-b' });
+ expect(cold.sourceId).toBe('source-b');
+ expect(warm).toEqual(cold);
+ });
+});
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
new file mode 100644
index 0000000000..4a2382701f
--- /dev/null
+++ b/test/cli-socket.test.ts
@@ -0,0 +1,225 @@
+/**
+ * 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.
+ * 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.
+ * 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.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+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 { 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 { opError, OperationError } from '../src/core/ops/contract.ts';
+
+const uid = process.getuid!();
+const engine = { kind: 'postgres' } as BrainEngine;
+let root: string;
+
+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-cli-sock-')); });
+afterEach(() => { rmSync(root, { recursive: true, force: true }); });
+
+function homeWithConfig(name: string, body = '{"engine":"postgres"}'): { dir: string; file: string } {
+ const dir = join(root, name, '.gbrain');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'config.json'), body);
+ return { dir, file: join(dir, 'config.json') };
+}
+
+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 });
+ };
+
+ test('ignores the password and query-parameter order, keeps host, port, database and user', () => {
+ expect(canonicalDatabaseTarget(url)).toBe(canonicalDatabaseTarget('postgres://alice-example:[email protected]:6543/brain?application_name=x&sslmode=require'));
+ expect(canonicalDatabaseTarget(url)).not.toContain('secret-one');
+ for (const other of [
+ url.replace(':6543', ':5432'), url.replace('/brain', '/brain2'), url.replace('db.acme', 'db2.acme'), url.replace('alice-example', 'bob-example'),
+ ]) expect(canonicalDatabaseTarget(other)).not.toBe(canonicalDatabaseTarget(url));
+ });
+
+ test('changes with the database, config home, config bytes and version', () => {
+ const home = homeWithConfig('a');
+ const base = token();
+ expect(token()).toBe(base);
+ expect(token({ config: { engine: 'postgres', database_url: url.replace('secret-one', 'rotated') } })).toBe(base);
+ expect(token({ config: { engine: 'postgres', database_url: url.replace('/brain', '/other') } })).not.toBe(base);
+ expect(token({ version: '1.0.1' })).not.toBe(base);
+ const other = homeWithConfig('b');
+ expect(token({ configDir: other.dir, configFile: other.file })).not.toBe(base);
+ writeFileSync(home.file, '{"engine":"postgres","edited":true}');
+ expect(token()).not.toBe(base);
+ });
+});
+
+describe('run directory and socket checks', () => {
+ test('ensurePrivateDir creates 0700, tightens an open directory this uid owns, refuses a symlink', () => {
+ const dir = join(root, 'home', '.gbrain', 'run');
+ ensurePrivateDir(dir);
+ expect(statSync(dir).mode & 0o777).toBe(0o700);
+ chmodSync(dir, 0o755);
+ expect(privateDirProblem(dir)).toBe('open_permissions');
+ ensurePrivateDir(dir);
+ expect(privateDirProblem(dir)).toBeNull();
+ const link = join(root, 'link-run');
+ symlinkSync(dir, link);
+ expect(privateDirProblem(link)).toBe('symlink');
+ expect(() => ensurePrivateDir(link)).toThrow(/symlink/);
+ });
+
+ 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 };
+ 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 path = join(dir, 'cli.sock');
+ expect(connectProblem(path, dir)).toBe('missing');
+ writeFileSync(path, 'x');
+ expect(privateSocketProblem(path)).toBe('not_socket');
+ rmSync(path);
+ const real = join(root, 'real.sock');
+ const server = net.createServer();
+ await new Promise<void>(resolve => server.listen(real, resolve));
+ try {
+ symlinkSync(real, path);
+ expect(connectProblem(path, dir)).toBe('symlink');
+ rmSync(path);
+ chmodSync(real, 0o666);
+ expect(privateSocketProblem(real)).toBe('open_permissions');
+ chmodSync(real, 0o600);
+ expect(privateSocketProblem(real)).toBeNull();
+ expect(privateSocketProblem(real, { lstat: p => lstatSync(p), uid: () => uid + 1 })).toBe('foreign_owner');
+ } finally {
+ server.close();
+ }
+ });
+});
+
+describe('serve listener', () => {
+ const bindings: CliSocketBinding[] = [];
+ afterEach(() => { for (const b of bindings.splice(0)) b.close(); });
+
+ const request = (identity: string): CliSocketRequest => ({ v: 1, identity, command: 'search', kind: 'op', op: 'search', params: { query: 'q' },
+ routing: { cwd: '/', source_env: null }, cli: { quiet: false, timeout_ms: null } });
+
+ 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 });
+ if (binding) bindings.push(binding);
+ return { binding, lines, path: cliSocketPath(home) };
+ }
+
+ test('this platform reads peer credentials (otherwise the serve would refuse to start)', () => {
+ if (process.platform === 'linux' || process.platform === 'darwin') expect(peerCredSupport().ok).toBe(true);
+ });
+
+ test('binds 0600 and answers a matching identity; refuses a mismatched one', async () => {
+ 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-b'), 5_000)).toEqual({ reason: 'refused (identity_mismatch)' });
+ });
+
+ test('rejects a peer whose kernel uid differs, and one whose uid cannot be read', async () => {
+ let calls = 0;
+ // The first read is the start-up self-test on this process's own connection.
+ const { binding, path, lines } = await start({ peerCred: { ok: true, read: () => (calls++ === 0 ? uid : uid + 1) } });
+ expect(binding).not.toBeNull();
+ const outcome = await exchangeCliSocket(path, request('token-a'), 5_000);
+ expect('reason' in outcome && outcome.reason).toMatch(/^serve_closed|connect_failed|lost/);
+ expect(lines.join('\n')).toContain(`rejected a connection from uid ${uid + 1}`);
+ binding!.close();
+ bindings.length = 0;
+ calls = 0;
+ const second = await start({ peerCred: { ok: true, read: () => (calls++ === 0 ? uid : null) } });
+ expect(await exchangeCliSocket(second.path, request('token-a'), 5_000)).toHaveProperty('reason');
+ expect(second.lines.join('\n')).toContain('rejected a connection from an unverifiable peer');
+ });
+
+ test('fails closed when peer credentials are unsupported or the self-test sees another uid', async () => {
+ const unsupported = await start({ peerCred: { ok: false, reason: 'no peer-credential call is wired for testos' } });
+ expect(unsupported.binding).toBeNull();
+ expect(unsupported.lines.join('\n')).toContain('peer credentials cannot be verified on this platform (no peer-credential call is wired for testos)');
+ expect(() => lstatSync(unsupported.path)).toThrow();
+ const wrong = await start({ peerCred: { ok: true, read: () => uid + 1 } });
+ expect(wrong.binding).toBeNull();
+ expect(wrong.lines.join('\n')).toContain('self-test');
+ });
+
+ test('refuses PGLite brains and a symlinked run directory', async () => {
+ expect((await start({ engine: { kind: 'pglite' } as BrainEngine })).binding).toBeNull();
+ const elsewhere = join(root, 'elsewhere');
+ mkdirSync(elsewhere, { mode: 0o700 });
+ mkdirSync(join(root, 'home', '.gbrain'), { recursive: true });
+ symlinkSync(elsewhere, join(root, 'home', '.gbrain', 'run'));
+ const { binding, lines } = await start();
+ expect(binding).toBeNull();
+ 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);
+ const path = join(dir, '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 {
+ expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ reason: 'serve_closed_mid_request' });
+ } finally {
+ server.close();
+ }
+ });
+
+ 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 server = net.createServer(() => { /* never answers */ });
+ await new Promise<void>(resolve => server.listen(path, resolve));
+ try {
+ const started = performance.now();
+ expect(await exchangeCliSocket(path, request('token-a'), 60_000)).toEqual({ reason: 'handshake_timeout' });
+ expect(performance.now() - started).toBeLessThan(3_000);
+ } finally {
+ server.close();
+ }
+ });
+});
+
+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.' },
+ });
+ const revived = reviveOperationError(JSON.parse(JSON.stringify(serializeOperationError(original))));
+ expect(revived).toBeInstanceOf(OperationError);
+ expect(revived.toJSON()).toEqual(original.toJSON());
+ expect({ ...revived }).toEqual({ ...original });
+});
diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.ts
new file mode 100644
index 0000000000..61df23a77c
--- /dev/null
+++ b/test/e2e/cli-socket-postgres.test.ts
@@ -0,0 +1,205 @@
+/**
+ * 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.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { cliSocketIdentity } from '../../src/core/cli-socket/identity.ts';
+import { exchangeCliSocket } from '../../src/cli/cli-socket-client.ts';
+import { VERSION } from '../../src/version.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+const WORD = 'zephyrquartz';
+
+interface Run { stdout: string; stderr: string; exitCode: number }
+
+describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {
+ let home: string;
+ let env: Record<string, string>;
+ let socketPath: string;
+ let configFile: string;
+ let databaseUrl: string;
+ let close: (() => Promise<void>) | undefined;
+ let serve: ChildProcess | null = null;
+ let serveLog = '';
+ let traceSeq = 0;
+ let serveTrace = '';
+ const cold = new Map<string, Run>();
+
+ const READS: Record<string, string[]> = {
+ search: ['search', WORD],
+ 'search --json': ['search', WORD, '--json'],
+ query: ['query', WORD],
+ 'query --json': ['query', WORD, '--json'],
+ get: ['get', 'notes/alpha-example'],
+ 'get --json': ['get', 'notes/alpha-example', '--json'],
+ 'get missing': ['get', 'notes/missing-example'],
+ 'recall --query': ['recall', '--query', WORD],
+ 'recall --query --json': ['recall', '--query', WORD, '--json'],
+ };
+
+ async function cli(args: string[], extra: Record<string, string> = {}): Promise<Run> {
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', ...args], {
+ cwd: process.cwd(), env: { ...env, ...extra }, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ }
+
+ function traceFile(): string { return join(home, `trace-${traceSeq++}.jsonl`); }
+ function roundTrips(file: string): number {
+ if (!existsSync(file)) return 0;
+ return readFileSync(file, 'utf8').split('\n').filter(line => line && !line.includes('"kind":"connect"')).length;
+ }
+
+ async function startServe(args: string[], extra: Record<string, string> = {}): Promise<ChildProcess> {
+ serveLog = '';
+ const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', ...args], { cwd: process.cwd(), env: { ...env, ...extra }, stdio: ['pipe', 'ignore', 'pipe'] });
+ child.stderr!.on('data', data => { serveLog += String(data); });
+ for (let i = 0; i < 240 && !serveLog.includes('Starting GBrain MCP server'); i++) await Bun.sleep(250);
+ expect(serveLog).toContain('Starting GBrain MCP server');
+ return child;
+ }
+
+ async function stopServe(signal: NodeJS.Signals = 'SIGTERM'): Promise<void> {
+ const child = serve;
+ serve = null;
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
+ await new Promise<void>(resolve => {
+ const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);
+ child.once('exit', () => { clearTimeout(deadline); resolve(); });
+ child.kill(signal);
+ });
+ }
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-cli-socket-'));
+ const isolated = await isolatedPersistencePostgres(DATABASE_URL!);
+ close = isolated.close;
+ databaseUrl = isolated.databaseUrl;
+ for (const [slug, body] of [['notes/alpha-example', `${WORD} alpha synthetic page for the warm socket.`], ['notes/beta-example', `Beta page mentions ${WORD} twice: ${WORD}.`]] as const) {
+ await importFromContent(isolated.engine, slug, `---\ntitle: ${slug}\ntype: note\n---\n\n${body}\n`, {
+ sourceId: 'default', noEmbed: true,
+ prepare: async prepared => { await withManagedFixtureWrite(isolated.engine, ['default'], tx => prepared.apply(tx)); return prepared.result; },
+ });
+ }
+ await isolated.engine.disconnect();
+ mkdirSync(join(home, '.gbrain'));
+ configFile = join(home, '.gbrain', 'config.json');
+ writeFileSync(configFile, JSON.stringify({ engine: 'postgres', database_url: databaseUrl }));
+ socketPath = join(home, '.gbrain', 'run', 'cli.sock');
+ env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined, GBRAIN_SOURCE: undefined,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_NO_RETRY_CONNECT: '1', GBRAIN_DEBUG: undefined,
+ });
+ // Two warm-up calls absorb one-time notices so the cold baseline is steady state.
+ await cli(['search', 'warmup']);
+ await cli(['search', 'warmup']);
+ for (const [name, args] of Object.entries(READS)) cold.set(name, await cli(args));
+ }, 180_000);
+
+ afterAll(async () => {
+ await stopServe('SIGKILL');
+ await close?.();
+ if (home) rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+
+ test('off by default: a serve without --cli-socket or serve.cli_socket binds no socket', async () => {
+ serve = await startServe([]);
+ await Bun.sleep(3_000);
+ expect(existsSync(socketPath)).toBe(false);
+ expect(serveLog).not.toContain('cli-socket');
+ await stopServe();
+ }, 90_000);
+
+ test('serve --cli-socket binds a 0600 socket in a 0700 run directory', async () => {
+ serveTrace = join(home, 'serve-trace.jsonl');
+ serve = await startServe(['--cli-socket'], { GBRAIN_SQL_TRACE: serveTrace });
+ for (let i = 0; i < 120 && !serveLog.includes('cli-socket: listening'); i++) await Bun.sleep(250);
+ expect(serveLog).toContain('cli-socket: listening');
+ const { statSync, lstatSync } = await import('node:fs');
+ expect(lstatSync(socketPath).isSocket()).toBe(true);
+ expect(lstatSync(socketPath).mode & 0o777).toBe(0o600);
+ expect(statSync(join(home, '.gbrain', 'run')).mode & 0o777).toBe(0o700);
+ }, 90_000);
+
+ test('search, query, get and recall print the cold path\'s exact bytes and exit code through the socket', async () => {
+ expect(existsSync(socketPath)).toBe(true);
+ for (const [name, args] of Object.entries(READS)) {
+ const warm = await cli(args, { GBRAIN_DEBUG: '1' });
+ expect(warm.stderr, `${name} took the cold path`).not.toContain('[cli-socket] cold path');
+ const expected = cold.get(name)!;
+ expect({ name, ...warm }).toEqual({ name, ...expected });
+ }
+ expect(cold.get('get missing')!.exitCode).not.toBe(0);
+ }, 180_000);
+
+ test('a warm read opens no database connection in the CLI and costs the serve at least 30 fewer round trips than a cold call', async () => {
+ const coldTrace = traceFile();
+ const coldStarted = performance.now();
+ const coldRun = await cli(['search', WORD], { GBRAIN_SQL_TRACE: coldTrace, GBRAIN_CLI_SOCKET: '0' });
+ const coldMs = performance.now() - coldStarted;
+ const warmCli = traceFile();
+ await Bun.sleep(1_500);
+ const serveBefore = roundTrips(serveTrace);
+ const started = performance.now();
+ const warmRun = await cli(['search', WORD], { GBRAIN_SQL_TRACE: warmCli });
+ const warmMs = performance.now() - started;
+ await Bun.sleep(1_500);
+ const serveTrips = roundTrips(serveTrace) - serveBefore;
+ expect(warmRun.stdout).toBe(coldRun.stdout);
+ expect(roundTrips(warmCli)).toBe(0);
+ const coldTrips = roundTrips(coldTrace);
+ console.error(`[cli-socket e2e] search round trips: cold CLI ${coldTrips}; warm CLI ${roundTrips(warmCli)} + serve ${serveTrips} (${Math.round(warmMs)} ms wall; cold ${Math.round(coldMs)} ms)`);
+ expect(coldTrips).toBeGreaterThan(10);
+ expect(serveTrips).toBeLessThanOrEqual(coldTrips - 30);
+ }, 90_000);
+
+ test('a write never goes through the socket', async () => {
+ const trace = traceFile();
+ const run = await cli(['tag', 'notes/alpha-example', 'tag-example'], { GBRAIN_SQL_TRACE: trace, GBRAIN_DEBUG: '1' });
+ expect(run.stderr).not.toContain('[cli-socket]');
+ expect(roundTrips(trace)).toBeGreaterThan(0);
+ }, 90_000);
+
+ test('a CLI bound to a different config or GBRAIN_HOME is refused by the handshake and falls back', async () => {
+ const original = readFileSync(configFile, 'utf8');
+ writeFileSync(configFile, JSON.stringify({ ...JSON.parse(original), search_mode_note: 'edited-after-bind' }));
+ try {
+ const run = await cli(READS.search!, { GBRAIN_DEBUG: '1' });
+ expect(run.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch)');
+ expect(run.stdout).toBe(cold.get('search')!.stdout);
+ expect(run.exitCode).toBe(0);
+ } finally {
+ writeFileSync(configFile, original);
+ }
+ 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 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 killed serve leaves a stale socket that falls back silently', async () => {
+ await stopServe('SIGKILL');
+ expect(existsSync(socketPath)).toBe(true);
+ const quiet = await cli(READS.search!);
+ expect(quiet).toEqual(cold.get('search')!);
+ const noisy = await cli(READS.search!, { GBRAIN_DEBUG: '1' });
+ expect(noisy.stderr).toContain('[cli-socket] cold path: connect_failed');
+ expect(noisy.stdout).toBe(cold.get('search')!.stdout);
+ }, 90_000);
+});