Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli-socket): re-review — provider routing values in the identity, GBRAIN_SOURCE forwarded not hashed, warm rendering buffered with cold fallback, socket created 0600 under umask (verify only), stuck-request log, slow-read note in the guide
garrytancfb38feb36a1
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex eed02ae1b2..eb64069bcf 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; native Bun terminal (`Bun.spawn({ terminal })`, skipped on win32) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).-- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`. `server.ts` `maybeStartCliSocket` (called from both serve lanes; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `tightenBoundSocket` lstats the bound path (our socket, never followed) before chmod 0600 and requires the same inode, private, after; it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: SHA-256 over the resolved brain id, the canonical database target (password and query order dropped, user kept; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnvDigest` (every `GBRAIN_*` name and value except `GBRAIN_CLI_SOCKET`/`GBRAIN_DEBUG`/`GBRAIN_SQL_TRACE`, plus the names, never values, of the recipe registry's provider credentials and endpoints that are set). `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default).+- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`. `server.ts` `maybeStartCliSocket` (called from both serve lanes; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `listen()` binds synchronously under `process.umask(0o177)` (restored right after), so the kernel creates the socket 0600, and `verifyBoundSocket` only checks it (lstat: our private socket; nothing is chmod'ed through the path); it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered; one still unsettled at the 30 s round-trip cap is logged once. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: SHA-256 over the resolved brain id, the canonical database target (password and query order dropped, user kept; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnvDigest` (every `GBRAIN_*` name and value except `GBRAIN_CLI_SOCKET`/`GBRAIN_DEBUG`/`GBRAIN_SQL_TRACE`/`GBRAIN_SOURCE` (forwarded per request), the names, never values, of the recipe registry's provider credentials that are set, and the names and values of its other provider variables: base URLs, endpoints, deployments, API versions, org/project/group ids). `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a frame its renderer throws on (rendered into a buffer first, so nothing prints), a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default).- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).diff --git a/docs/guides/cli-socket.md b/docs/guides/cli-socket.mdindex 52bf97844c..b2742f6100 100644--- a/docs/guides/cli-socket.md+++ b/docs/guides/cli-socket.md@@ -65,15 +65,22 @@ The CLI falls back to its normal path, silently, when:that is shorter, the serve's own read deadline passes, or the serve dies inthe middle of the request: the CLI then runs the call itself, once, with itsusual timeout and exit codes (it can only be a read, so running it again is- safe);-- the serve answers with a frame the CLI cannot fully read;+ safe). A warm read that runs past 30 seconds therefore runs a second time+ cold, so a slow LLM-backed query (`query`, `recall --question`) can cost+ twice; pass a shorter `--timeout` or set `GBRAIN_CLI_SOCKET=0` for those;+- the serve answers with a frame the CLI cannot fully read or render (nothing+ is printed from it);- the serve was started for a different brain or environment: the CLI sends atoken built from the brain (host or mount), the database target (withoutthe password), the config home, the config file (path and content), the- gbrain version and a digest of the environment that changes answers (every- `GBRAIN_*` setting except `GBRAIN_CLI_SOCKET`, `GBRAIN_DEBUG` and- `GBRAIN_SQL_TRACE`, plus which provider API keys and endpoints are set,- never their values), and the serve answers only an identical one. Editing+ gbrain version and a digest of the environment that changes answers or+ where query text is sent (every `GBRAIN_*` setting except+ `GBRAIN_CLI_SOCKET`, `GBRAIN_DEBUG`, `GBRAIN_SQL_TRACE` and+ `GBRAIN_SOURCE`, which every request carries and the serve resolves for that+ call; which provider API keys are set, never their values; and the values of+ the provider routing settings: base URLs, endpoints, deployments, API+ versions, org, project and group ids), and the serve answers only an+ identical one. Editing`config.json`, changing those variables or upgrading gbrain while a serveruns sends CLI calls to the normal path until the serve restarts with thesame settings;@@ -91,9 +98,9 @@ socket entirely, for comparisons and benchmarks.connecting) refuse a symlink, a directory or socket owned by another uid, oropen permissions. `GBRAIN_HOME` and `.gbrain` above it must be yours too andwritable by no one else (a sticky directory excepted); the serve refuses- otherwise and never repairs them. Right after binding, the serve checks the- path is still its own socket before making it `0600`, and the same inode- after.+ otherwise and never repairs them. The serve binds under umask `0177`, so the+ kernel creates the socket `0600`; it then checks the path is its own private+ socket and never changes permissions through it.- On every connection the serve reads the peer's uid from the kernel(`SO_PEERCRED` on Linux, `getpeereid` on macOS) and drops any other uidbefore reading the request. The CLI checks the serve's uid the same way.diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.tsindex 250326f7cc..64a9e0c0b0 100644--- a/src/cli/cli-socket-client.ts+++ b/src/cli/cli-socket-client.ts@@ -8,6 +8,7 @@* stderr only with GBRAIN_DEBUG=1). GBRAIN_CLI_SOCKET=0 skips the socket.*/import net from 'node:net';+import { format } from 'node:util';import { loadConfig, configDir, configPath, isThinClient } from '../core/config.ts';import { getCliOptions } from '../core/cli-options.ts';import { resolveBrainId } from '../core/brain-resolver.ts';@@ -90,9 +91,13 @@ export function cliSocketRoundTripMs(timeoutMs: number | null): number {return Math.min(MAX_ROUND_TRIP_MS, timeoutMs ?? DEFAULT_READ_WALLCLOCK_MS);}-/** Restores what the cold process would have by now: the pinned fix source and the operation's own output. */-async function replay(frame: { output: OutputChunk[]; source?: string | null }): Promise<void> {+/** The source the serve resolved for this call, pinned in fix commands exactly as the cold process would have noted it (before anything renders). */+async function noteSource(frame: { source?: string | null }): Promise<void> {if (frame.source) (await import('../core/fix-routing.ts')).noteResolvedSource(frame.source);+}++/** Prints the operation's own output, as the cold process would have by now. */+async function replay(frame: { output: OutputChunk[] }): Promise<void> {for (const [stream, text] of frame.output) {if (stream === 'stdout') process.stdout.write(text);else process.stderr.write(text);@@ -114,22 +119,72 @@ async function opRequest(command: string, args: string[]): Promise<{ op: import(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> {+type Buffered<T> = { value: T; flush: () => void } | { error: unknown };++/**+ * Runs a renderer with stdout, stderr and console held in memory, so a frame+ * the renderer cannot handle throws before anything reaches the terminal and+ * the caller can still take the cold path. `flush` writes what it printed.+ */+async function buffered<T>(render: () => T | Promise<T>): Promise<Buffered<T>> {+ const chunks: Array<['stdout' | 'stderr', string]> = [];+ const hold = (stream: 'stdout' | 'stderr') => (chunk: unknown, ...rest: unknown[]): boolean => {+ chunks.push([stream, typeof chunk === 'string' ? chunk : Buffer.from(chunk as Uint8Array).toString()]);+ const callback = rest.find(arg => typeof arg === 'function') as (() => void) | undefined;+ if (callback) queueMicrotask(callback);+ return true;+ };+ const saved = { out: process.stdout.write, err: process.stderr.write, log: console.log, info: console.info, warn: console.warn, error: console.error, debug: console.debug };+ process.stdout.write = hold('stdout') as typeof process.stdout.write;+ process.stderr.write = hold('stderr') as typeof process.stderr.write;+ for (const [method, stream] of [['log', 'stdout'], ['info', 'stdout'], ['debug', 'stdout'], ['warn', 'stderr'], ['error', 'stderr']] as const) {+ console[method] = (...args: unknown[]) => { chunks.push([stream, format(...args) + '\n']); };+ }+ try {+ const value = await render();+ return { value, flush: () => { for (const [stream, text] of chunks) (stream === 'stdout' ? process.stdout : process.stderr).write(text); } };+ } catch (error) {+ return { error };+ } finally {+ Object.assign(process.stdout, { write: saved.out });+ Object.assign(process.stderr, { write: saved.err });+ Object.assign(console, { log: saved.log, info: saved.info, warn: saved.warn, error: saved.error, debug: saved.debug });+ }+}++function renderFailed(error: unknown): false {+ debug(`render_failed (${error instanceof Error ? error.message : String(error)})`);+ return false;+}++/** Prints an answered op frame the way the cold path would; false (nothing printed) when the frame cannot be rendered. */+export async function renderOp(command: string, op: import('../core/operations.ts').Operation, params: Record<string, unknown>, frame: Exclude<ResultFrame, { kind: 'fallback' }>): Promise<boolean> {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);+ await noteSource(frame);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;+ const rendered = await buffered(() => writeCliError(reviveOperationError(frame.error), command));+ if ('error' in rendered) return renderFailed(rendered.error);+ await replay(frame);+ rendered.flush();+ setCliExitVerdict(rendered.value);+ return true;+ }+ const rendered = await buffered(() => {+ if (frame.meta) captureRetrievalMeta('retrieval', frame.meta);+ for (const notice of frame.notices) captureOpNotice(notice);+ const { result, stderr } = applyCliOpNotices(frame.result, params.json === true);+ return { result, noticeText: stderr, output: formatResult(op.name, result, params) };+ });+ if ('error' in rendered) {+ try { applyCliOpNotices(null, true); } catch { /* drains what the failed render captured */ }+ return renderFailed(rendered.error);}- 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);+ const { result, noticeText, output } = rendered.value;+ await replay(frame);+ rendered.flush();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') {@@ -138,6 +193,7 @@ async function renderOp(command: string, op: import('../core/operations.ts').OpesetCliExitVerdict(1);}maybePrintConceptNudge(op.name, params);+ return true;}/**@@ -178,15 +234,18 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):const outcome = await exchangeCliSocket(path, { ...base, kind: 'recall', args }, resultTimeoutMs);if ('reason' in outcome) { debug(outcome.reason); return false; }if (outcome.frame.kind === 'fallback') { debug(outcome.frame.reason); return false; }- await replay(outcome.frame);- if (outcome.frame.kind === 'result') {- recall.renderRecallVerbResult(flags, outcome.frame.result as Parameters<typeof recall.renderRecallVerbResult>[1]);- if (outcome.frame.notices.length > 0) (await import('../core/interop-notices.ts')).writeCliNotices(outcome.frame.notices);- return true;- }- const error = reviveOperationError(outcome.frame.error);- if (recall.isOneShotRecall(flags)) await recall.reportOneShotRecallError(error, flags);- else throw error;+ const frame = outcome.frame;+ await noteSource(frame);+ if (frame.kind === 'error' && !recall.isOneShotRecall(flags)) { await replay(frame); throw reviveOperationError(frame.error); }+ const { writeCliNotices } = await import('../core/interop-notices.ts');+ const rendered = await buffered(async () => {+ if (frame.kind === 'error') { await recall.reportOneShotRecallError(reviveOperationError(frame.error), flags); return; }+ recall.renderRecallVerbResult(flags, frame.result as Parameters<typeof recall.renderRecallVerbResult>[1]);+ if (frame.notices.length > 0) writeCliNotices(frame.notices);+ });+ if ('error' in rendered) return renderFailed(rendered.error);+ await replay(frame);+ rendered.flush();return true;}@@ -195,6 +254,5 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):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;+ return renderOp(command, prepared.op, prepared.params, outcome.frame);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 529efd6027..fdc96bf833 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1043,7 +1043,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.332.0', text: 'The `score` that search and query return now never increases down the list: in a reranked list it is the rerank score (times any rank prior), and a pinned or unreranked row takes its neighbour\'s value. The fused score it replaced stays on the row as `fused_score`.' },{ since: '0.60.332.0', text: 'One search or query chunk row returns at most 8,000 characters of chunk text by default, ending with the marker that names the read for the rest (an old oversized chunk could return tens of thousands). Pass `snippet_chars: 0` for the full chunk. Evidence blocks (conversations, long-page units) keep their own budget and cap.' },{ since: '0.60.332.0', text: '`gbrain search --explain` and `gbrain query --explain` now pass explain to the search, so `score_details` reports the arms, RRF and blend that ran; before, every row said `single_arm_path` / `no_query_embedding` even when both arms ran. A CLI search or query whose keyword or vector arm failed or timed out now prints the `degraded_recall` notice on stderr (the `--json` array stays bare), as MCP already did.' },- { since: '0.60.333.0', text: 'New opt-in warm CLI socket for Postgres brains, off by default: `gbrain serve --cli-socket` (or `gbrain config set serve.cli_socket true`) lets that serve answer this user\'s CLI `search`, `query`, `get` and op-backed `recall` (`--query`, `--budget-tokens`, `--question`, `--budget-policy`) over a private Unix socket in `$GBRAIN_HOME/.gbrain/run/` (directory 0700, socket 0600, peer uid checked by the kernel on every connection, never TCP), so those calls skip a cold database connection. Only the host brain is served (a serve on a mount brain never opens the socket), and only when the CLI\'s identity (database target, config home and file, gbrain version, every `GBRAIN_*` setting but the socket, debug and SQL-trace switches, and which provider keys are set) matches the serve\'s; otherwise, and whenever the socket is missing, stale or busy, the answer is malformed, or it takes over 30 s (or the call\'s shorter `--timeout`), the CLI takes its usual path. Without the option nothing listens. Guide: docs/guides/cli-socket.md.' },+ { since: '0.60.333.0', text: 'New opt-in warm CLI socket for Postgres brains, off by default: `gbrain serve --cli-socket` (or `gbrain config set serve.cli_socket true`) lets that serve answer this user\'s CLI `search`, `query`, `get` and op-backed `recall` (`--query`, `--budget-tokens`, `--question`, `--budget-policy`) over a private Unix socket in `$GBRAIN_HOME/.gbrain/run/` (directory 0700, socket 0600, peer uid checked by the kernel on every connection, never TCP), so those calls skip a cold database connection. Only the host brain is served (a serve on a mount brain never opens the socket), and only when the CLI\'s identity (database target, config home and file, gbrain version, every `GBRAIN_*` setting but the socket, debug and SQL-trace switches and `GBRAIN_SOURCE` (sent with each call), which provider keys are set, and the provider base URLs, endpoints, deployments and ids) matches the serve\'s; otherwise, and whenever the socket is missing, stale or busy, the answer is malformed, or it takes over 30 s (or the call\'s shorter `--timeout`), the CLI takes its usual path. Without the option nothing listens. Guide: docs/guides/cli-socket.md.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-socket/fs-guard.ts b/src/core/cli-socket/fs-guard.tsindex c2aa4b331f..d290532ea2 100644--- a/src/core/cli-socket/fs-guard.ts+++ b/src/core/cli-socket/fs-guard.ts@@ -23,7 +23,7 @@ export interface FsGuardDeps {const realDeps: FsGuardDeps = { lstat: path => lstatSync(path), stat: path => statSync(path), uid: () => process.getuid?.() };-export type UnsafeReason = 'missing' | 'symlink' | 'not_directory' | 'not_socket' | 'foreign_owner' | 'open_permissions' | 'no_uid' | 'replaced';+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');@@ -97,20 +97,15 @@ export function connectProblem(path: string, dir: string, deps: FsGuardDeps = re}/**- * Right after bind: the path must be a socket this uid owns (lstat, never- * followed) before it is chmod 0600, and the same inode, private, after.- * Returns that inode; throws when the path changed or is not ours.+ * Right after bind (the serve binds under umask 0177, so the kernel creates+ * the socket 0600): the path must already be a private socket this uid owns,+ * read with lstat and never repaired. Nothing is chmod'ed through a path that+ * could have been swapped. Returns its inode.*/-export function tightenBoundSocket(path: string, deps: FsGuardDeps = realDeps, chmod: (path: string) => void = target => chmodSync(target, 0o600)): number {- const uid = deps.uid();- const before = deps.lstat(path);- if (before.isSymbolicLink() || !before.isSocket()) throw new CliSocketUnsafeError(before.isSymbolicLink() ? 'symlink' : 'not_socket', path);- if (before.uid !== uid) throw new CliSocketUnsafeError('foreign_owner', path);- chmod(path);+export function verifyBoundSocket(path: string, deps: FsGuardDeps = realDeps): number {const problem = privateSocketProblem(path, deps);if (problem) throw new CliSocketUnsafeError(problem, path);- if (deps.lstat(path).ino !== before.ino) throw new CliSocketUnsafeError('replaced', path);- return before.ino;+ return deps.lstat(path).ino;}export class CliSocketUnsafeError extends Error {diff --git a/src/core/cli-socket/identity.ts b/src/core/cli-socket/identity.tsindex df288a3463..ec329695d7 100644--- a/src/core/cli-socket/identity.ts+++ b/src/core/cli-socket/identity.ts@@ -11,8 +11,14 @@ import { readFileSync, realpathSync } from 'node:fs';import type { GBrainConfig } from '../config.ts';import { listRecipes } from '../ai/recipes/index.ts';-/** GBRAIN_* switches that only steer the socket itself or diagnostics, never an operation's answer. */-const NON_BEHAVIOR_GBRAIN_ENV = new Set(['GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE']);+/**+ * GBRAIN_* variables left out of the digest: the socket switch and diagnostics+ * never change an answer, and GBRAIN_SOURCE travels in every request+ * (`routing.source_env`) and is resolved per request, as the cold CLI does.+ */+const NON_BEHAVIOR_GBRAIN_ENV = new Set(['GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE', 'GBRAIN_SOURCE']);+/** Provider credentials: only whether each is set enters the digest. Every other provider variable (endpoints, deployments, versions, org/project/group ids) enters with its value. */+const SECRET_PROVIDER_ENV = /(_API_KEY|_TOKEN|_SECRET)$/;/** Provider env names read outside the recipe registry: the Google alias and the compatibility endpoints. */const EXTRA_PROVIDER_ENV = ['GEMINI_API_KEY', 'OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL'];@@ -26,18 +32,21 @@ function providerEnv(): string[] {}/**- * SHA-256 over the environment that changes what a read answers: every- * GBRAIN_* name and value except the socket switch, debug and SQL trace, and- * the names (never the values) of the provider credentials and endpoints that- * are set to a non-empty value.+ * SHA-256 over the environment that changes what a read answers or where its+ * text goes: every GBRAIN_* name and value except NON_BEHAVIOR_GBRAIN_ENV, the+ * names (never the values) of the provider credentials that are set, and the+ * names and values of every other provider variable that is set (base URLs,+ * endpoints, deployments, API versions, org/project/group ids).*/export function behaviorEnvDigest(env: Record<string, string | undefined>): string {const gbrain = Object.keys(env).filter(key => key.startsWith('GBRAIN_') && !NON_BEHAVIOR_GBRAIN_ENV.has(key) && env[key] !== undefined).sort().map(key => [key, env[key]]);- const providers = providerEnv().filter(name => env[name] !== undefined && env[name] !== '');- return createHash('sha256').update(JSON.stringify({ gbrain, providers })).digest('hex');+ const set = providerEnv().filter(name => env[name] !== undefined && env[name] !== '');+ const credentials = set.filter(name => SECRET_PROVIDER_ENV.test(name));+ const routing = set.filter(name => !SECRET_PROVIDER_ENV.test(name)).map(name => [name, env[name]]);+ return createHash('sha256').update(JSON.stringify({ gbrain, credentials, routing })).digest('hex');}/** Database URL without its password, with the host, port and query parameters in one canonical spelling. */diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.tsindex a5ec8f793c..6933d3f874 100644--- a/src/core/cli-socket/protocol.ts+++ b/src/core/cli-socket/protocol.ts@@ -73,7 +73,7 @@ export function isResultFrame(value: unknown): value is ResultFrame {switch (value.kind) {case 'result':return 'result' in value && (value.meta === null || record(value.meta))- && Array.isArray(value.notices) && value.notices.every(notice => record(notice) && typeof notice.code === 'string')+ && Array.isArray(value.notices) && value.notices.every(notice => record(notice) && typeof notice.code === 'string' && typeof notice.kind === 'string' && typeof notice.why === 'string')&& isAnswered(value);case 'error':return record(value.error) && typeof value.error.code === 'string' && typeof value.error.message === 'string' && isAnswered(value);diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.tsindex cee841a202..293e28ba6d 100644--- a/src/core/cli-socket/server.ts+++ b/src/core/cli-socket/server.ts@@ -15,11 +15,11 @@ import { configDir, configPath } from '../config.ts';import { tryAcquireNativeLock } from '../persistence/native-lock.ts';import { VERSION } from '../../version.ts';import { executeCliSocketRequest, type ExecutedRequest } from './execute.ts';-import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, privateSocketProblem, socketPathFits, tightenBoundSocket } from './fs-guard.ts';+import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, privateSocketProblem, socketPathFits, verifyBoundSocket } 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,+import { FrameReader, isCliSocketRequest, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, MAX_ROUND_TRIP_MS, REQUEST_READ_TIMEOUT_MS,type CliSocketRequest, type HandshakeFrame, type ResultFrame } from './protocol.ts';export const CLI_SOCKET_CONFIG_KEY = 'serve.cli_socket';@@ -38,6 +38,8 @@ export interface CliSocketServerOptions {uid?: () => number | undefined;brainId?: () => string;execute?: (request: CliSocketRequest) => Promise<ExecutedRequest>;+ /** After this long a request whose work has not settled is logged once (its slot is still held). */+ stuckAfterMs?: number;}/** Whether this serve should open the socket: the flag, or the DB-plane config key set to a true value. */@@ -173,6 +175,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promisif (active >= MAX_ACTIVE_REQUESTS) { socket.end(frame({ v: 1, accepted: false, reason: 'busy' })); return; }// Active until the request's own work settles, not until it answered: a timed-out handler still holds its slot.active++;+ const started = performance.now();let settled: Promise<unknown> = Promise.resolve();try {socket.write(frame({ v: 1, accepted: true }));@@ -181,7 +184,12 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promiscatch { result = { v: 1, kind: 'fallback', reason: 'serve_error' }; }if (!socket.destroyed) socket.end(frame(result));} finally {- void settled.then(() => { active--; }, () => { active--; });+ let done = false;+ const stuck = setTimeout(() => {+ if (!done) log(`a ${request.command} request is still running ${Math.round((performance.now() - started) / 1000)} s after it started; its slot stays held until it finishes (${active} of ${MAX_ACTIVE_REQUESTS} in use).`);+ }, Math.max(0, (opts.stuckAfterMs ?? MAX_ROUND_TRIP_MS) - (performance.now() - started)));+ stuck.unref();+ void settled.then(() => { done = true; clearTimeout(stuck); active--; }, () => { done = true; clearTimeout(stuck); active--; });}})();});@@ -189,12 +197,15 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promisconst bound = await new Promise<boolean>(resolve => {server.once('error', () => resolve(false));- server.listen(path, () => resolve(true));+ // listen() binds synchronously; under umask 0177 the kernel creates the socket 0600, so nothing is chmod'ed afterwards.+ const umask = process.umask(0o177);+ try { server.listen(path, () => resolve(true)); }+ finally { process.umask(umask); }});if (!bound) { await lock.release(); log(`not started: could not bind ${path}.`); return null; }server.on('error', () => {});let inode: number;- try { inode = tightenBoundSocket(path); }+ try { inode = verifyBoundSocket(path); }catch (error) { server.close(); await lock.release(); log(`not started: ${path} did not become a private socket (${(error as Error).message}).`); return null; }const close = () => {if (closing) return;diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.tsindex d7f045a95c..1577b07a57 100644--- a/test/cli-socket.test.ts+++ b/test/cli-socket.test.ts@@ -27,11 +27,12 @@ import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { behaviorEnvDigest, canonicalDatabaseTarget, cliSocketIdentity } from '../src/core/cli-socket/identity.ts';import {- ancestorProblem, cliSocketPath, connectProblem, ensurePrivateDir, privateDirProblem, privateSocketProblem, tightenBoundSocket, trustedAncestorProblem, type FsGuardDeps,+ ancestorProblem, cliSocketPath, connectProblem, ensurePrivateDir, privateDirProblem, privateSocketProblem, trustedAncestorProblem, verifyBoundSocket, 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 { cliSocketRoundTripMs, exchangeCliSocket } from '../src/cli/cli-socket-client.ts';+import { cliSocketRoundTripMs, exchangeCliSocket, renderOp } from '../src/cli/cli-socket-client.ts';+import { loadOperation } from '../src/core/operation-load.ts';import { isResultFrame, reviveOperationError, serializeOperationError, type CliSocketRequest, type ResultFrame } from '../src/core/cli-socket/protocol.ts';import { queueFirstFallbackHop, takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';import { installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';@@ -105,6 +106,26 @@ describe('identity token', () => {expect(behaviorEnvDigest({ OPENAI_BASE_URL: 'http://localhost:1' })).not.toBe(behaviorEnvDigest({}));expect(JSON.stringify(behaviorEnvDigest({ VOYAGE_API_KEY: 'value-one' }))).not.toContain('value-one');});++ test('provider routing values enter the digest (a local and a remote endpoint never match); credentials stay set-or-not', () => {+ homeWithConfig('a');+ const local = { GBRAIN_HOME: '/home/alice-example', OPENAI_BASE_URL: 'http://127.0.0.1:11434/v1' };+ const remote = { GBRAIN_HOME: '/home/alice-example', OPENAI_BASE_URL: 'https://api.openai.com/v1' };+ expect(behaviorEnvDigest(local)).not.toBe(behaviorEnvDigest(remote));+ expect(token({ env: local })).not.toBe(token({ env: remote }));+ for (const name of ['OLLAMA_BASE_URL', 'LMSTUDIO_BASE_URL', 'LLAMA_SERVER_BASE_URL', 'LLAMA_SERVER_RERANKER_BASE_URL', 'LITELLM_BASE_URL', 'OPENROUTER_BASE_URL',+ 'ANTHROPIC_BASE_URL', 'AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_DEPLOYMENT', 'AZURE_OPENAI_API_VERSION', 'OPENAI_ORG_ID', 'OPENAI_PROJECT', 'MINIMAX_GROUP_ID']) {+ expect(behaviorEnvDigest({ [name]: 'value-one' }), name).not.toBe(behaviorEnvDigest({ [name]: 'value-two' }));+ }+ for (const name of ['OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'LLAMA_SERVER_API_KEY']) {+ expect(behaviorEnvDigest({ [name]: 'value-one' }), name).toBe(behaviorEnvDigest({ [name]: 'value-two' }));+ }+ });++ test('GBRAIN_SOURCE stays out of the digest: it travels with each request and is resolved per call', () => {+ expect(behaviorEnvDigest({ GBRAIN_SOURCE: 'source-a' })).toBe(behaviorEnvDigest({}));+ expect(behaviorEnvDigest({ GBRAIN_SOURCE: 'source-a' })).toBe(behaviorEnvDigest({ GBRAIN_SOURCE: 'source-b' }));+ });});describe('run directory and socket checks', () => {@@ -174,23 +195,22 @@ describe('run directory and socket checks', () => {expect(() => ensurePrivateDir(dir, foreignHome)).toThrow(/foreign_owner/);});- test('after bind the socket is chmod 0600 only while it is still our socket, and must keep its inode', async () => {+ test('a bound socket is only verified, never chmod\'ed: an open, symlinked or foreign one is refused as found', async () => {const dir = runDir();const path = join(dir, 'cli.sock');const server = net.createServer();- await new Promise<void>(resolve => server.listen(path, resolve));+ const umask = process.umask(0o022);+ try { await new Promise<void>(resolve => server.listen(path, resolve)); } finally { process.umask(umask); }try {const real: FsGuardDeps = { lstat: p => lstatSync(p), uid: () => uid };- expect(tightenBoundSocket(path, real)).toBe(lstatSync(path).ino);- expect(lstatSync(path).mode & 0o777).toBe(0o600);- let chmods = 0;- const symlinked: FsGuardDeps = { ...real, lstat: p => ({ ...lstatSync(p), isSymbolicLink: () => true, isSocket: () => false }) as never };- expect(() => tightenBoundSocket(path, symlinked, () => { chmods++; })).toThrow(/symlink/);- expect(() => tightenBoundSocket(path, { ...real, uid: () => uid + 1 }, () => { chmods++; })).toThrow(/foreign_owner/);- expect(chmods).toBe(0);- let reads = 0;- const swapped: FsGuardDeps = { ...real, lstat: p => { const st = lstatSync(p); return reads++ < 2 ? st : ({ ...st, isSocket: () => true, isSymbolicLink: () => false, ino: st.ino + 1 }) as never; } };- expect(() => tightenBoundSocket(path, swapped, () => {})).toThrow(/replaced/);+ const openMode = lstatSync(path).mode & 0o777;+ expect(openMode & 0o077).not.toBe(0);+ expect(() => verifyBoundSocket(path, real)).toThrow(/open_permissions/);+ expect(lstatSync(path).mode & 0o777).toBe(openMode);+ chmodSync(path, 0o600);+ expect(verifyBoundSocket(path, real)).toBe(lstatSync(path).ino);+ expect(() => verifyBoundSocket(path, { ...real, lstat: p => ({ ...lstatSync(p), isSymbolicLink: () => true, isSocket: () => false }) as never })).toThrow(/symlink/);+ expect(() => verifyBoundSocket(path, { ...real, uid: () => uid + 1 })).toThrow(/foreign_owner/);} finally {server.close();}@@ -217,8 +237,11 @@ describe('serve listener', () => {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();+ test('binds 0600 even under an open process umask (the kernel creates it so), restores the umask, and answers a matching identity; refuses a mismatched one', async () => {+ const umask = process.umask(0o000);+ let started: Awaited<ReturnType<typeof start>>;+ try { started = await start(); expect(process.umask()).toBe(0o000); } finally { process.umask(umask); }+ const { binding, path } = started;expect(binding).not.toBeNull();expect(lstatSync(path).mode & 0o777).toBe(0o600);expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: okFrame });@@ -283,6 +306,22 @@ describe('serve listener', () => {expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toHaveProperty('frame');});+ test('a request whose work is still unsettled at the round-trip cap is logged once', async () => {+ let release!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ const { path, lines } = await start({ stuckAfterMs: 50, execute: async () => ({ frame: { v: 1, kind: 'fallback', reason: 'timeout' }, settled: pending }) });+ await exchangeCliSocket(path, request('token-a'), 5_000);+ await Bun.sleep(150);+ expect(lines.filter(line => line.includes('is still running')).length).toBe(1);+ expect(lines.join('\n')).toContain('a search request is still running');+ release();+ await Bun.sleep(20);+ const { path: second, lines: quiet } = await start({ home: join(root, 'quiet', '.gbrain'), stuckAfterMs: 50 } as never);+ await exchangeCliSocket(second, request('token-a'), 5_000);+ await Bun.sleep(150);+ expect(quiet.filter(line => line.includes('is still running'))).toEqual([]);+ });+test('without a peer-credential reader the CLI never connects', async () => {const { path } = await start();let connections = 0;@@ -308,6 +347,7 @@ describe('serve listener', () => {{ v: 1, kind: 'result', result: 1, meta: null, notices: [], output: [['stdout']] },{ v: 1, kind: 'result', result: 1, meta: 'x', notices: [], output: [] },{ v: 1, kind: 'result', result: 1, meta: null, notices: [{}], output: [] },+ { v: 1, kind: 'result', result: 1, meta: null, notices: [{ code: 'x' }], output: [] },{ v: 1, kind: 'error', output: [] },{ v: 1, kind: 'error', error: { message: 'no code' }, output: [] },{ v: 1, kind: 'timeout', label: 'l', ms: 1, output: [] },@@ -371,6 +411,25 @@ describe('serve listener', () => {});});+test('a well-formed frame whose payload the renderer cannot handle prints nothing and sends the CLI to its cold path', async () => {+ const op = (await loadOperation('search'))!;+ const written: string[] = [];+ const saved = { out: process.stdout.write, err: process.stderr.write };+ const record = (chunk: unknown) => { written.push(String(chunk)); return true; };+ process.stdout.write = record as typeof process.stdout.write;+ process.stderr.write = record as typeof process.stderr.write;+ let outcome: boolean | Error;+ try {+ outcome = await renderOp('search', op, { query: 'q' }, { v: 1, kind: 'result', result: 5, meta: null, notices: [], output: [['stdout', 'handler line\n']], source: null })+ .catch((error: Error) => error);+ } finally {+ Object.assign(process.stdout, { write: saved.out });+ Object.assign(process.stderr, { write: saved.err });+ }+ expect(outcome).toBe(false);+ expect(written).toEqual([]);+});+test('each warm request has its own first chat-fallback hop queue; the process queue is untouched', async () => {installOutputCapture();__resetChatFallbackHopNoticeForTests();diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.tsindex e6f6655fc0..0b3265fa06 100644--- a/test/e2e/cli-socket-postgres.test.ts+++ b/test/e2e/cli-socket-postgres.test.ts@@ -95,6 +95,12 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {prepare: async prepared => { await withManagedFixtureWrite(isolated.engine, ['default'], tx => prepared.apply(tx)); return prepared.result; },});}+ // A second source, so a CLI's GBRAIN_SOURCE visibly changes what a search answers.+ await isolated.engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('source-b', 'source-b', '{}'::jsonb)`);+ await importFromContent(isolated.engine, 'notes/gamma-example', `---\ntitle: notes/gamma-example\ntype: note\n---\n\n${WORD} gamma page in source-b.\n`, {+ sourceId: 'source-b', noEmbed: true,+ prepare: async prepared => { await withManagedFixtureWrite(isolated.engine, ['source-b'], tx => prepared.apply(tx)); return prepared.result; },+ });await isolated.engine.disconnect();mkdirSync(join(home, '.gbrain'));configFile = join(home, '.gbrain', 'config.json');@@ -103,6 +109,8 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {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,+ // A provider endpoint no recipe here uses: the serve and every CLI share it, so a CLI pointing elsewhere must be refused.+ LMSTUDIO_BASE_URL: 'http://127.0.0.1:9/v1',});// Two warm-up calls absorb one-time notices so the cold baseline is steady state.await cli(['search', 'warmup']);@@ -199,8 +207,8 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {rmSync(otherHome, { recursive: true, force: true });}, 90_000);- test('a CLI whose behavior env differs from the serve\'s (GBRAIN_* settings, provider keys present) is refused and falls back', async () => {- const extras: Record<string, string>[] = [{ GBRAIN_CONTRIBUTOR_MODE: '1' }, { VOYAGE_API_KEY: 'synthetic-fixture-value' }];+ test('a CLI whose behavior env differs from the serve\'s (GBRAIN_* settings, provider keys present, a provider endpoint value) is refused and falls back', async () => {+ const extras: Record<string, string>[] = [{ GBRAIN_CONTRIBUTOR_MODE: '1' }, { VOYAGE_API_KEY: 'synthetic-fixture-value' }, { LMSTUDIO_BASE_URL: 'https://lmstudio.acme-example.test/v1' }];for (const extra of extras) {const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', ...extra });expect(run.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch)');@@ -208,6 +216,15 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {}}, 90_000);+ test('a CLI with its own GBRAIN_SOURCE is answered warm, with that source applied', async () => {+ const coldB = await cli(['search', WORD], { GBRAIN_CLI_SOCKET: '0', GBRAIN_SOURCE: 'source-b' });+ expect(coldB.stdout).toContain('notes/gamma-example');+ expect(coldB.stdout).not.toBe(cold.get('search')!.stdout);+ const warmB = await cli(['search', WORD], { GBRAIN_DEBUG: '1', GBRAIN_SOURCE: 'source-b' });+ expect(warmB.stderr).not.toContain('[cli-socket] cold path');+ expect({ stdout: warmB.stdout, exitCode: warmB.exitCode }).toEqual({ stdout: coldB.stdout, exitCode: coldB.exitCode });+ }, 90_000);+test('a killed serve leaves a stale socket that falls back silently', async () => {await stopServe('SIGKILL');expect(existsSync(socketPath)).toBe(true);