Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli-socket): compare identity part by part; pooler lanes and sizing vars match (GBRA-156)
garrytandc090e666b0e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b28fa15ca..59db2a1242 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.348.0] - 2026-10-21++**The warm CLI socket now works when serve and the CLI connect through different pooler lanes.** A serve on a Supabase pooler's session lane (port 5432, prepared statements on, a larger pool) refused every CLI call made on the transaction lane (port 6543, `?prepare=false`), because the identity it compared included the port, the URL's query string and every `GBRAIN_*` value, pool sizes included. Each call then took the cold path, so with the socket on nothing got faster. The identity now leaves out what cannot change an answer, and a refusal says which part differed.++### What changed++| Situation | Before | Now |+|---|---|---|+| Serve on the session lane (5432), CLI on the transaction lane (6543) of the same Supavisor host, user and database | refused (`identity_mismatch`) | answered warm |+| `GBRAIN_POOL_SIZE`, `GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_PREPARE` or the database URL variables differ | refused | answered warm |+| Driver-only URL parameters (`prepare=`, `sslmode`, `application_name`, timeouts) differ | refused | answered warm |+| Another port on plain Postgres, another host, user or database, or a different `options` parameter | refused | still refused |+| A read-behavior setting (model, embeddings, search tuning, visibility, timeouts, schema pack, AI call log, contributor capture) differs | refused | still refused |+| A refusal | `refused (identity_mismatch)` with no detail | names the part, never its value: `database port`, `env GBRAIN_MODEL`, `provider key VOYAGE_API_KEY`, `config contents`; the serve logs each distinct one once |++### What to watch for after you upgrade++- Restart the serve after upgrading. A serve and a CLI on different gbrain versions never match, so until the restart every CLI call takes its cold path (`refused (identity_mismatch): version`).+- Nothing changes for a serve without `--cli-socket` or `serve.cli_socket`; the socket stays off by default.+- With `GBRAIN_DEBUG=1`, a CLI call that still falls back prints the part that differed. Align that setting between the serve's environment and the CLI's, or restart the serve with it.++### Itemized changes++- `src/core/cli-socket/identity.ts`: the identity is now structured: brain, version, engine, config home, file and content, `databaseTarget` (host, port, database, user, `options`) and `behaviorEnv` (SHA-256 values of the explicit `READ_BEHAVIOR_ENV` list and the provider routing variables, plus the names of the provider keys that are set). `cliSocketIdentityMismatch` compares it part by part, and lets the port differ only on a `*.pooler.supabase.com` host.+- The handshake refusal carries `mismatch`, and the CLI's debug line prints it. An older CLI sends the old token and is refused as `malformed_request`, so it takes its cold path.+- `test/cli-socket.test.ts` classifies every `GBRAIN_*` name in `src` as read behavior or not, so a new setting can't skip the decision.+## [0.60.347.0] - 2026-10-21**A model or dimension swap now finishes re-embedding on a large brain, and one overlong fact no longer stops the fact backfill.** After a swap, `gbrain embed --stale`, the background backfill and `gbrain migrate embeddings` mark every chunk from the old model for re-embedding. That marking was one statement over the whole brain, so on a large brain the statement timeout cancelled it, nothing was marked, and the next run hit the same timeout. Separately, before probing the embedder, every embed run counted drifted chunks with two full joins over every chunk. On a large drifted brain those counts timed out too, and the timeout was read as "no drift", so the swap was silently skipped.diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex fe96221aba..65604ff27c 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`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; 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/serve-cli-socket-off.test.ts` (a socket-off serve boot loads no cli-socket module and makes no engine call for it, each boot in its own process), `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, on from `serve.cli_socket`).+- `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`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; 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` with the differing part in `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`: the resolved brain id, `databaseTarget` (host, port, database, user and the `options` parameter; password and driver-only parameters dropped; 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 `behaviorEnv` (SHA-256 values of the explicit `READ_BEHAVIOR_ENV` list, which test/cli-socket.test.ts checks against every `GBRAIN_*` name in src, the names, never values, of the recipe registry's provider credentials that are set, and SHA-256 values of its other provider variables: base URLs, endpoints, deployments, API versions, org/project/group ids); `cliSocketIdentityMismatch` compares serve and CLI part by part and returns the first differing part's name (sent as the refusal's `mismatch` and logged once per part by the serve), and a port may differ only on a Supavisor pooler host. `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/serve-cli-socket-off.test.ts` (a socket-off serve boot loads no cli-socket module and makes no engine call for it, each boot in its own process), `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, on from `serve.cli_socket`).- `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 5e53a508bf..c10acf9fc7 100644--- a/docs/guides/cli-socket.md+++ b/docs/guides/cli-socket.md@@ -75,20 +75,32 @@ The CLI falls back to its normal path, silently, when: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 (nothingis printed from it);-- the serve was started for a different brain or environment: the CLI sends a- token built from the brain (host or mount), the database target (without- the password), the config home, the config file (path and content), the- gbrain version and a digest of the environment that changes answers 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 serve- runs sends CLI calls to the normal path until the serve restarts with the- same settings;+- the serve was started for a different brain or environment. The CLI sends+ its identity and the serve compares it part by part with its own: the brain+ (host or mount), the gbrain version, the config home, the config file (path+ and content), the database target and the read-behavior environment. The+ database target is the host, database, user and `options` parameter, never+ the password or driver-only parameters such as `prepare=`, `sslmode` or+ `application_name`. The port must match too, except on a Supabase Supavisor+ pooler host (`*.pooler.supabase.com`), where the same host and user name the+ same database, so a serve on the session lane (5432) answers CLI calls made+ on the transaction lane (6543). On any other host another port is another+ server and is refused. The read-behavior environment is an explicit list of+ the `GBRAIN_*` settings that can change an answer or where query text goes+ (`READ_BEHAVIOR_ENV` in `src/core/cli-socket/identity.ts`: models,+ embeddings, search tuning, visibility, timeouts, schema pack, AI call log,+ contributor capture and the like), 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).+ Connection sizing and driver settings (`GBRAIN_POOL_SIZE`,+ `GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_PREPARE`, ...), the database URL+ variables and `GBRAIN_SOURCE` (which every request carries and the serve+ resolves for that call) may differ. Editing `config.json`, changing a listed+ variable or upgrading gbrain while a serve runs sends CLI calls to the normal+ path until the serve restarts with the same settings. The refusal names the+ part that differed, never its value: `refused (identity_mismatch): database+ port`, `env GBRAIN_MODEL`, `provider key VOYAGE_API_KEY`, `config+ contents`, and the serve logs each distinct one once;- the CLI targets a mount brain (`--brain <mount>` and the other mount tiers).`GBRAIN_DEBUG=1` prints one `[cli-socket] cold path: <reason>` line on stderrdiff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.tsindex 64a9e0c0b0..f6f6e4cf85 100644--- a/src/cli/cli-socket-client.ts+++ b/src/cli/cli-socket-client.ts@@ -74,7 +74,7 @@ export function exchangeCliSocket(path: string, request: CliSocketRequest, totaltry { value = JSON.parse(text); } catch { finish({ reason: 'malformed_response' }); return; }if (!accepted) {if (!isHandshakeFrame(value)) { finish({ reason: 'malformed_response' }); return; }- if (!value.accepted) { finish({ reason: `refused (${value.reason})` }); return; }+ if (!value.accepted) { finish({ reason: `refused (${value.reason})${value.mismatch ? `: ${value.mismatch}` : ''}` }); return; }accepted = true;arm(Number.POSITIVE_INFINITY, 'round_trip_timeout');continue;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d94e084dae..f5e2d235e7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1073,6 +1073,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.347.0', text: 'After a model or dimension swap, `gbrain embed --stale`, the embed backfill and `gbrain migrate embeddings` now mark old-model chunks for re-embedding in windows of 1,000 pages (all committed together) instead of one statement over the whole brain, which a large brain cancelled at the statement timeout on every run. The drift check before the embedder probe is one page-first lookup instead of two counts over every chunk, so a count that timed out can no longer skip the swap silently; the "embedder probe failed" warning no longer names a chunk count.' },// #7211 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.347.0', text: '`gbrain embed --facts` no longer fails a whole batch, and every later run, on one fact longer than the embedding input limit: that fact is skipped (never truncated), keeps its text and stays stale, and the result reports it (`refused_oversized`, `refused_samples` with fact ids, `refused_fix`) without counting it in `remaining` or against `--max-facts`. Doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them. Shorten or split the fact, or withdraw it with `gbrain forget <fact-id>`, and the next run embeds it once it fits.' },+ // GBRA-156 (warm CLI socket identity fix). `since` is restamped at the merge slot.+ { since: 'TBD', text: 'The warm CLI socket now answers CLI calls whose connection setup differs from the serve\'s only in ways that cannot change an answer: connection sizing and driver settings (`GBRAIN_POOL_SIZE`, `GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_PREPARE` and the like), the database URL variables, driver-only URL parameters (`prepare=`, `sslmode`, `application_name`), and, on a Supabase Supavisor pooler host, the port, so a serve on the session lane (5432) answers CLI calls made on the transaction lane (6543). Only an explicit list of read-behavior `GBRAIN_*` settings must still match; on any other host another port is still refused. A refusal now names the part that differed (`refused (identity_mismatch): database port`, `env GBRAIN_MODEL`), never its value, and the serve logs each distinct one once. 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/identity.ts b/src/core/cli-socket/identity.tsindex ec329695d7..2ef6927823 100644--- a/src/core/cli-socket/identity.ts+++ b/src/core/cli-socket/identity.ts@@ -1,10 +1,12 @@/*** 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, another brain (mount), an edited config file, a- * different behavior-relevant environment or another gbrain release always- * takes its own cold path. The socket path alone never decides.+ * serve answers only a CLI whose identity matches its own part by part+ * (`cliSocketIdentityMismatch`), so a CLI aimed at another database, another+ * GBRAIN_HOME, another brain (mount), an edited config file, a different+ * read-behavior environment or another gbrain release always takes its own+ * cold path, and the refusal names the part that differed. The socket path+ * alone never decides.*/import { createHash } from 'node:crypto';import { readFileSync, realpathSync } from 'node:fs';@@ -12,15 +14,50 @@ import type { GBrainConfig } from '../config.ts';import { listRecipes } from '../ai/recipes/index.ts';/**- * 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.+ * The GBRAIN_* variables that can change what a socket read (search, query,+ * get, recall) answers or where its text goes. An explicit allow-list:+ * connection sizing and driver tuning (GBRAIN_POOL_SIZE, GBRAIN_PREPARE, ...)+ * never change an answer, so a serve and a CLI may differ there. The database+ * URL variables are compared as a database target instead (`DatabaseTarget`),+ * and GBRAIN_SOURCE travels in every request and is resolved per call.+ * test/cli-socket.test.ts classifies every GBRAIN_* name in src, so a new one+ * cannot skip this decision.*/-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. */+export const READ_BEHAVIOR_ENV: readonly string[] = [+ 'GBRAIN_HOME', 'GBRAIN_BRAIN_ID', 'GBRAIN_MOUNTS_PATH', 'GBRAIN_CWD_ENV_QUARANTINED',+ 'GBRAIN_SEARCH_EXCLUDE', 'GBRAIN_SEARCH_SALVAGE', 'GBRAIN_SEARCH_DEBUG', 'GBRAIN_SOURCE_BOOST', 'GBRAIN_RECENCY_DECAY',+ 'GBRAIN_FTS_LANGUAGE', 'GBRAIN_HNSW_ITERATIVE_SCAN', 'GBRAIN_VECTOR_LEGACY_GUARD', 'GBRAIN_PROJECTION_READINESS_CACHE',+ 'GBRAIN_REMOTE_PRIVATE_PAGES', 'GBRAIN_RLS_SCOPE_BINDING', 'GBRAIN_STALENESS_CEILING_HOURS', 'GBRAIN_SERVE_DEGRADED',+ 'GBRAIN_STATEMENT_TIMEOUT', 'GBRAIN_MAX_REGEX_INPUT_CHARS', 'GBRAIN_SCHEMA_PACK',+ 'GBRAIN_CONTENT_SANITY_DISABLED', 'GBRAIN_NO_SANITY', 'GBRAIN_MAX_MARKUP_RATIO',+ 'GBRAIN_RETRIEVAL_REFLEX', 'GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS', 'GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER', 'GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS',+ 'GBRAIN_DECIDE_SLOTS', 'GBRAIN_MEMORABLE', 'GBRAIN_MEMORABLE_CONFIG', 'GBRAIN_SYNOPSIS_DOC_MAX_CHARS',+ 'GBRAIN_MODEL', 'GBRAIN_MODEL_DISCOVERY', 'GBRAIN_CHAT_MODEL', 'GBRAIN_CHAT_FALLBACK_CHAIN', 'GBRAIN_CHAT_FALLBACK_ON_REFUSAL',+ 'GBRAIN_EXPANSION_MODEL', 'GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL',+ 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'GBRAIN_EMBEDDING_MULTIMODAL', 'GBRAIN_EMBEDDING_MULTIMODAL_MODEL',+ 'GBRAIN_EMBEDDING_IMAGE_OCR', 'GBRAIN_EMBEDDING_IMAGE_OCR_MODEL', 'GBRAIN_MAX_CHUNK_TOKENS',+ 'GBRAIN_QUERY_EMBED_TIMEOUT_MS', 'GBRAIN_AI_EMBED_TIMEOUT_MS', 'GBRAIN_AI_CHAT_TIMEOUT_MS', 'GBRAIN_AI_MULTIMODAL_TIMEOUT_MS',+ 'GBRAIN_RECIPES_DIR', 'GBRAIN_PLUGIN_PATH', 'GBRAIN_GUARDRAILS_MODULE', 'GBRAIN_AI_CALL_LOG', 'GBRAIN_CONTRIBUTOR_MODE',+];+/** Provider credentials: only whether each is set enters the identity. 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'];+/**+ * Connection-string parameters that can change what a statement sees+ * (`options` carries `-c search_path=...`, roles and the like). Every other+ * parameter (prepare, sslmode, application_name, timeouts, pooler flags) only+ * tunes the driver or the transport.+ */+const BEHAVIOR_URL_PARAMS = new Set(['options']);+/**+ * Supavisor pooler hosts (the same patterns as connection-manager.ts). One+ * pooler host serves the session lane (5432) and the transaction lane (6543)+ * of every project, and the project is part of the user name, so the same host+ * and user on another port is the same database. On any other host a port is+ * another server.+ */+const POOLER_HOST = /(^|\.)pooler\.supabase\.com$/i;let providerEnvNames: string[] | undefined;function providerEnv(): string[] {@@ -31,36 +68,49 @@ function providerEnv(): string[] {return providerEnvNames;}-/**- * 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 sha256 = (text: string): string => createHash('sha256').update(text).digest('hex');++/** The parts of the environment that change what a read answers or where its text goes, each value as a SHA-256 and credentials as names only. */+export interface BehaviorEnv {+ /** READ_BEHAVIOR_ENV names that are set, with the SHA-256 of each value; provider routing variables (base URLs, endpoints, deployments, ids) likewise. */+ values: Record<string, string>;+ /** The provider credentials that are set, by name (never the value). */+ credentials: string[];+}++export function behaviorEnv(env: Record<string, string | undefined>): BehaviorEnv {+ const values: Record<string, string> = {};+ for (const name of READ_BEHAVIOR_ENV) if (env[name] !== undefined) values[name] = sha256(env[name]!);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');+ for (const name of set) if (!SECRET_PROVIDER_ENV.test(name)) values[name] = sha256(env[name]!);+ return { values, credentials: set.filter(name => SECRET_PROVIDER_ENV.test(name)) };+}++/** A database URL reduced to what decides which database a read sees: never the password, and query parameters only when they change what a statement sees. */+export interface DatabaseTarget {+ protocol: string;+ host: string;+ port: string;+ database: string;+ user: string;+ params: string;}-/** Database URL without its password, with the host, port and query parameters in one canonical spelling. */-export function canonicalDatabaseTarget(databaseUrl: string): string {+export function databaseTarget(databaseUrl: string): DatabaseTarget {let url: URL;try { url = new URL(databaseUrl); }- catch { return `unparsed:${createHash('sha256').update(databaseUrl).digest('hex')}`; }+ catch { return { protocol: 'unparsed', host: sha256(databaseUrl), port: '', database: '', user: '', params: '' }; }const params = [...url.searchParams.entries()]- .filter(([key]) => !/pass/i.test(key))+ .filter(([key]) => BEHAVIOR_URL_PARAMS.has(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()}` : ''}`;+ return {+ protocol: url.protocol === 'postgres:' ? 'postgresql:' : url.protocol,+ host: url.hostname.toLowerCase(),+ port: url.port || '5432',+ database: decodeURIComponent(url.pathname) || '/',+ user: decodeURIComponent(url.username),+ params: new URLSearchParams(params).toString(),+ };}function realpathOr(path: string): string {@@ -68,7 +118,7 @@ function realpathOr(path: string): string {}function fileDigest(path: string): string {- try { return createHash('sha256').update(readFileSync(path)).digest('hex'); } catch { return 'absent'; }+ try { return sha256(readFileSync(path, 'utf8')); } catch { return 'absent'; }}export interface CliSocketIdentityInput {@@ -82,18 +132,64 @@ export interface CliSocketIdentityInput {env: Record<string, string | undefined>;}-/** SHA-256 over the brain id, the canonical database target, the config home and file (realpath and content), the behavior env and the gbrain version. */-export function cliSocketIdentity(input: CliSocketIdentityInput): string {- const fields = {- v: 2,+export interface CliSocketIdentity {+ version: string;+ brain: string;+ engine: string;+ database: DatabaseTarget | null;+ config_dir: string;+ config_file: string;+ config_sha256: string;+ env: BehaviorEnv;+}++/** The brain id, the database target, the config home and file (realpath and content), the read-behavior env and the gbrain version. */+export function cliSocketIdentity(input: CliSocketIdentityInput): CliSocketIdentity {+ return {version: input.version,brain: input.brainId,- env: behaviorEnvDigest(input.env),engine: input.config.engine,- database: input.config.database_url ? canonicalDatabaseTarget(input.config.database_url) : null,+ database: input.config.database_url ? databaseTarget(input.config.database_url) : null,config_dir: realpathOr(input.configDir),config_file: realpathOr(input.configFile),config_sha256: fileDigest(input.configFile),+ env: behaviorEnv(input.env),};- return createHash('sha256').update(JSON.stringify(fields)).digest('hex');+}++/**+ * Null when `cli` may be answered by the serve bound to `serve`; otherwise the+ * first part that differs (`version`, `database port`, `env GBRAIN_MODEL`,+ * `provider key VOYAGE_API_KEY`, ...), named without its value. The database+ * port may differ only on a Supavisor pooler host (POOLER_HOST), where host and+ * user already name the database.+ */+export function cliSocketIdentityMismatch(serve: CliSocketIdentity, cli: CliSocketIdentity): string | null {+ for (const part of ['version', 'brain', 'engine'] as const) if (serve[part] !== cli[part]) return part;+ if (!serve.database || !cli.database) {+ if (serve.database !== cli.database) return 'database';+ } else {+ for (const part of ['protocol', 'host', 'database', 'user', 'params'] as const) {+ if (serve.database[part] !== cli.database[part]) return `database ${part}`;+ }+ if (serve.database.port !== cli.database.port && !POOLER_HOST.test(serve.database.host)) return 'database port';+ }+ if (serve.config_dir !== cli.config_dir) return 'config home';+ if (serve.config_file !== cli.config_file) return 'config file';+ if (serve.config_sha256 !== cli.config_sha256) return 'config contents';+ const names = [...new Set([...Object.keys(serve.env.values), ...Object.keys(cli.env.values)])].sort();+ for (const name of names) if (serve.env.values[name] !== cli.env.values[name]) return `env ${name}`;+ const keys = [...new Set([...serve.env.credentials, ...cli.env.credentials])].sort();+ for (const name of keys) if (serve.env.credentials.includes(name) !== cli.env.credentials.includes(name)) return `provider key ${name}`;+ return null;+}++/** True when `value` has the shape of a CliSocketIdentity (the request validator's check). */+export function isCliSocketIdentity(value: unknown): value is CliSocketIdentity {+ const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);+ if (!record(value) || !record(value.env) || !record(value.env.values) || !Array.isArray(value.env.credentials)) return false;+ if (!['version', 'brain', 'engine', 'config_dir', 'config_file', 'config_sha256'].every(key => typeof value[key] === 'string')) return false;+ if (!Object.values(value.env.values).every(v => typeof v === 'string') || !value.env.credentials.every(v => typeof v === 'string')) return false;+ const db = value.database;+ return db === null || (record(db) && ['protocol', 'host', 'port', 'database', 'user', 'params'].every(key => typeof db[key] === 'string'));}diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.tsindex 6933d3f874..099cc10df8 100644--- a/src/core/cli-socket/protocol.ts+++ b/src/core/cli-socket/protocol.ts@@ -6,6 +6,7 @@*/import type { Notice } from '../agent-output.ts';import { OperationError } from '../ops/contract.ts';+import { isCliSocketIdentity, type CliSocketIdentity } from './identity.ts';export const CLI_SOCKET_PROTOCOL = 1;export const MAX_REQUEST_BYTES = 256 * 1024;@@ -32,14 +33,15 @@ export interface CliSocketRouting {export type CliSocketRequest = {v: 1;- identity: string;+ identity: CliSocketIdentity;/** 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 };+/** A refusal for `identity_mismatch` names the identity part that differed in `mismatch` (cliSocketIdentityMismatch), never its value. */+export type HandshakeFrame = { v: 1; accepted: true } | { v: 1; accepted: false; reason: string; mismatch?: string };export type OutputChunk = ['stdout' | 'stderr', string];@@ -58,7 +60,8 @@ function record(value: unknown): value is Record<string, unknown> {/** Shape check for the serve's handshake line. */export function isHandshakeFrame(value: unknown): value is HandshakeFrame {if (!record(value) || value.v !== CLI_SOCKET_PROTOCOL) return false;- return value.accepted === true || (value.accepted === false && typeof value.reason === 'string');+ return value.accepted === true+ || (value.accepted === false && typeof value.reason === 'string' && (value.mismatch === undefined || typeof value.mismatch === 'string'));}function isAnswered(value: Record<string, unknown>): boolean {@@ -86,7 +89,7 @@ export function isResultFrame(value: unknown): value is ResultFrame {/** 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;+ if (!record(value) || value.v !== CLI_SOCKET_PROTOCOL || !isCliSocketIdentity(value.identity) || 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;diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.tsindex 1661ea9765..ca19b9d04b 100644--- a/src/core/cli-socket/server.ts+++ b/src/core/cli-socket/server.ts@@ -5,7 +5,6 @@* 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 { lstatSync, unlinkSync } from 'node:fs';import net, { type Socket } from 'node:net';import type { BrainEngine } from '../engine.ts';@@ -16,7 +15,7 @@ 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, verifyBoundSocket } from './fs-guard.ts';-import { cliSocketIdentity } from './identity.ts';+import { cliSocketIdentity, cliSocketIdentityMismatch, type 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, MAX_ROUND_TRIP_MS, REQUEST_READ_TIMEOUT_MS,@@ -33,7 +32,7 @@ export interface CliSocketServerOptions {/** Test seams; production derives each from this process. */peerCred?: PeerCredSupport;home?: string;- identity?: string;+ identity?: CliSocketIdentity;uid?: () => number | undefined;brainId?: () => string;execute?: (request: CliSocketRequest) => Promise<ExecutedRequest>;@@ -50,12 +49,6 @@ export async function startCliSocket(engine: BrainEngine, log: (line: string) =>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;@@ -139,6 +132,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promislet active = 0;let closing = false;const rejectedUids = new Set<number | null>();+ const loggedMismatches = new Set<string>();const server = net.createServer(socket => {socket.on('error', () => {});if (closing || sockets.size >= MAX_CONNECTIONS) { socket.destroy(); return; }@@ -165,7 +159,12 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promislet 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; }+ const mismatch = cliSocketIdentityMismatch(identity, request.identity);+ if (mismatch) {+ if (!loggedMismatches.has(mismatch)) { loggedMismatches.add(mismatch); log(`refused a CLI call: identity_mismatch (${mismatch} differs from this serve's); that CLI takes its cold path.`); }+ socket.end(frame({ v: 1, accepted: false, reason: 'identity_mismatch', mismatch }));+ return;+ }if (active >= MAX_ACTIVE_REQUESTS) { socket.end(frame({ v: 1, accepted: false, reason: 'busy' })); return; }// Active until the request's own work settles, not until it answered: a timed-out handler still holds its slot.active++;diff --git a/test/cli-socket-context.test.ts b/test/cli-socket-context.test.tsindex 06cff9eae8..448c12248d 100644--- a/test/cli-socket-context.test.ts+++ b/test/cli-socket-context.test.ts@@ -16,6 +16,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:tesimport { makeContext } from '../src/cli/main.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { cliRequestContext, executeCliSocketRequest, mergedRequestConfig } from '../src/core/cli-socket/execute.ts';+import { cliSocketIdentity } from '../src/core/cli-socket/identity.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';@@ -81,7 +82,7 @@ describe('cliRequestContext mirrors makeContext', () => {return typeof value === 'function' ? value.bind(target) : value;},});- const { frame, settled } = await executeCliSocketRequest(gated, { v: 1, identity: 'x', command: 'search', kind: 'op', op: 'search', params: { query: 'alpha' },+ const { frame, settled } = await executeCliSocketRequest(gated, { v: 1, identity: cliSocketIdentity({ config: { engine: 'postgres' }, brainId: 'host', configDir: '/nonexistent', configFile: '/nonexistent/config.json', version: 'x', env: {} }), command: 'search', kind: 'op', op: 'search', params: { query: 'alpha' },routing: { cwd: process.cwd(), source_env: null }, cli: { quiet: false, timeout_ms: 5 } });let done = false;void settled.then(() => { done = true; });diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.tsindex 4726589e60..281f9a536d 100644--- a/test/cli-socket.test.ts+++ b/test/cli-socket.test.ts@@ -1,9 +1,10 @@/*** Warm CLI socket: the guards that decide whether a CLI may talk to a serve.*- * 1. Protects: the identity token changes with the brain, database target,- * config home, config bytes, behavior env and version (never with the- * password or a provider key's value); the run directory, the directories+ * 1. Protects: the identity refuses, and names, a different brain, database+ * (a port only off a Supavisor pooler host), config home, config bytes,+ * read-behavior env or version (never the password, a provider key's value,+ * connection sizing or driver-only URL parameters); the run directory, the directories* above it and the socket checks refuse symlinks, foreign owners, open* permissions and a socket swapped after bind; the serve rejects a peer* whose kernel-reported uid differs, refuses to start when peer credentials@@ -20,12 +21,12 @@* options, exchangeCliSocket's peerCred argument, FsGuardDeps.*/import { afterEach, beforeEach, describe, expect, test } from 'bun:test';-import { chmodSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, 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 { behaviorEnvDigest, canonicalDatabaseTarget, cliSocketIdentity } from '../src/core/cli-socket/identity.ts';+import { cliSocketIdentity, cliSocketIdentityMismatch, databaseTarget, READ_BEHAVIOR_ENV, type CliSocketIdentity } from '../src/core/cli-socket/identity.ts';import {ancestorProblem, cliSocketPath, connectProblem, ensurePrivateDir, privateDirProblem, privateSocketProblem, trustedAncestorProblem, verifyBoundSocket, type FsGuardDeps,} from '../src/core/cli-socket/fs-guard.ts';@@ -61,71 +62,140 @@ function homeWithConfig(name: string, body = '{"engine":"postgres"}'): { dir: streturn { dir, file: join(dir, 'config.json') };}-describe('identity token', () => {+/**+ * GBRAIN_* names in src that cannot change what a socket read answers or where+ * its text goes: writes, sync, jobs, workers, locks, doctor, setup and hooks,+ * other transports (HTTP, MCP surface, thin client), the database URL variables+ * (compared as a database target), connection sizing and driver tuning,+ * diagnostics, and constants that only share the prefix. Families are listed+ * by prefix only where no member reads; anything else is named.+ */+const NOT_READ_BEHAVIOR_PREFIXES = [+ 'GBRAIN_ALLOW', 'GBRAIN_AUTOPILOT_', 'GBRAIN_BACKUP_', 'GBRAIN_BULK', 'GBRAIN_CLAUDE_CLI_', 'GBRAIN_CLAW_', 'GBRAIN_CONNECTOR',+ 'GBRAIN_CYCLE_', 'GBRAIN_DOCTOR_', 'GBRAIN_DREAM', 'GBRAIN_DRIFT_', 'GBRAIN_EMBED_', 'GBRAIN_EXTRACT', 'GBRAIN_FENCE_', 'GBRAIN_FORCE_',+ 'GBRAIN_GIT', 'GBRAIN_GRADUATION_', 'GBRAIN_HOOK', 'GBRAIN_HTTP_', 'GBRAIN_JOB_', 'GBRAIN_LINK_RESOLUTION_', 'GBRAIN_LOCK_', 'GBRAIN_MIGRATE_',+ 'GBRAIN_MINION', 'GBRAIN_NO_', 'GBRAIN_NOTIFIER', 'GBRAIN_NTB_', 'GBRAIN_OAUTH_', 'GBRAIN_PACE', 'GBRAIN_PG_', 'GBRAIN_PGLITE_', 'GBRAIN_POOL_',+ 'GBRAIN_PROGRESSIVE_BATCH_', 'GBRAIN_QUEUE_', 'GBRAIN_SETUP_', 'GBRAIN_STOP_PUSH', 'GBRAIN_SUPERVIS', 'GBRAIN_SWEEP', 'GBRAIN_SYNC', 'GBRAIN_WORKER_',+];+const NOT_READ_BEHAVIOR = new Set([+ 'GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE', 'GBRAIN_SQL_TRACE_LABEL', 'GBRAIN_LME_DEBUG', 'GBRAIN_SOURCE',+ 'GBRAIN_DATABASE_URL', 'GBRAIN_DIRECT_DATABASE_URL', 'GBRAIN_DIRECT_POOL_SIZE', 'GBRAIN_DISABLE_DIRECT_POOL', 'GBRAIN_PREPARE',+ 'GBRAIN_IDLE_TX_TIMEOUT', 'GBRAIN_MAX_CONNECTIONS', 'GBRAIN_NO_RETRY_CONNECT', 'GBRAIN_DB_ACCESS',+ 'GBRAIN_ACCEPT_PENDING', 'GBRAIN_ACCEPT_SILENT_WIDEN', 'GBRAIN_WRITE_WAIT_MS', 'GBRAIN_PREADMIT_CACHE', 'GBRAIN_PREPARATION_DEADLINES',+ 'GBRAIN_SINGLE_CONSUMER', 'GBRAIN_SINGLE_WRITE_GROUP', 'GBRAIN_CONSUMER_DIRECT_LANE', 'GBRAIN_COMMIT_LOCK_WAIT_SECONDS',+ 'GBRAIN_PUBLISH_LOCK_WAIT_SECONDS', 'GBRAIN_PUSH_LOCK_WAIT_SECONDS', 'GBRAIN_PAGE_BLOCK_BYTES', 'GBRAIN_PAGE_WARN_BYTES', 'GBRAIN_INGEST_MAX_BYTES',+ 'GBRAIN_BELIEF_PREIMAGE_CHECK', 'GBRAIN_BLOCK_MARKERS', 'GBRAIN_CANCEL_SETTLE_MS', 'GBRAIN_CHUNKER_TIMEOUT_MS', 'GBRAIN_CONTENT_REPAIR_CALL_TIMEOUT_MS',+ 'GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY', 'GBRAIN_CONTEXTUAL_HAIKU_RPM', 'GBRAIN_CONTEXTUAL_SYNOPSIS_RPM', 'GBRAIN_CONTRADICTIONS_JUDGE_MODEL',+ 'GBRAIN_CORPUS_WINDOWS_PER_SWEEP', 'GBRAIN_DEFERRED_EMBED_RETRY_MS', 'GBRAIN_DRAIN_TIMEOUT_MS', 'GBRAIN_FLUSH_GRACE_MS', 'GBRAIN_GITHUB_PAT',+ 'GBRAIN_GITHUB_REPO', 'GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS', 'GBRAIN_LLM_HALT_COOLDOWN', 'GBRAIN_MAX_FENCES_PER_PAGE', 'GBRAIN_MAX_SKILL_MD_BYTES',+ 'GBRAIN_MAX_WALK_DEPTH', 'GBRAIN_ORPHANED_PRIVATE_QUEUE_MINUTES', 'GBRAIN_PHANTOM_REDIRECT_LIMIT', 'GBRAIN_PLANNER_AUTO_ANALYZE',+ 'GBRAIN_REFRESH_DRAIN_WAIT_MS', 'GBRAIN_REFRESH_FETCH_TIMEOUT_MS', 'GBRAIN_SKIP_REFERENCE_SWEEP', 'GBRAIN_SKIP_STARTUP_HOOKS', 'GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD',+ 'GBRAIN_WEDGED_QUEUE_WARN_MINUTES', 'GBRAIN_ANTHROPIC_MAX_INFLIGHT',+ 'GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS', 'GBRAIN_SERVE_EOF_DRAIN_MS', 'GBRAIN_SERVE_FAIL_FAST', 'GBRAIN_SERVE_HEAD_DEBOUNCE_MS', 'GBRAIN_SERVE_HEAD_POLL_MS',+ 'GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS', 'GBRAIN_SERVE_STALL_WATCHDOG_MS', 'GBRAIN_SERVE_SYNC_IPC', 'GBRAIN_SERVE_SYNC_SETTLE_MS',+ 'GBRAIN_SURFACE', 'GBRAIN_MCP_FORCE_SURFACE', 'GBRAIN_MCP_INSTRUCTIONS', 'GBRAIN_SOCKET_KINDS', 'GBRAIN_HEALTH_CACHE_TTL_MS', 'GBRAIN_CLIENT_CHECK_INTERVAL',+ 'GBRAIN_CLIENT_HEADER', 'GBRAIN_STDIN_TIMEOUT_MS', 'GBRAIN_STDOUT_DRAIN_DEADLINE_MS', 'GBRAIN_TEARDOWN_DEADLINE_MS', 'GBRAIN_PID1_REAP', 'GBRAIN_NICE',+ 'GBRAIN_REMOTE_CLIENT_ID', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_REMOTE_ISSUER_URL', 'GBRAIN_REMOTE_MCP_URL', 'GBRAIN_REMOTE_TOKEN', 'GBRAIN_REMOTE_TOKEN_ENV',+ 'GBRAIN_THIN_CLIENT_NAME', 'GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS', 'GBRAIN_ADMIN_BOOTSTRAP_TOKEN',+ 'GBRAIN_SCHEMA_AUDIT_VERBOSE', 'GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS', 'GBRAIN_SCHEMA_PACK_MAX_BYTES', 'GBRAIN_SCHEMA_PACK_WARN_BYTES',+ 'GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS', 'GBRAIN_INIT_SKIP_EMBED_CHECK', 'GBRAIN_IN_AGENT_SETUP', 'GBRAIN_INTERACTIVE', 'GBRAIN_NON_INTERACTIVE',+ 'GBRAIN_BOOTSTRAP_ABORT_AFTER', 'GBRAIN_SEAT', 'GBRAIN_CORE', 'GBRAIN_PRESSURE', 'GBRAIN_PAYLOAD', 'GBRAIN_DESCRIPTION', 'GBRAIN_HARNESS_MARKER_VALUE',+ 'GBRAIN_ENV_TEMPLATE', 'GBRAIN_SKILLS_DIR', 'GBRAIN_COORDINATION_HOME', 'GBRAIN_AUDIT_DIR', 'GBRAIN_TARGET_URL', 'GBRAIN_UPGRADE_OWNS_MIGRATIONS',+ 'GBRAIN_SELF_UPGRADE_MODE', 'GBRAIN_SWAP_RECEIPT', 'GBRAIN_POST_UPGRADE_TIMEOUT_MS', 'GBRAIN_PROBE_PROMPT_GRACE_SECONDS', 'GBRAIN_BANNER',+ 'GBRAIN_BIN', 'GBRAIN_BIN_OVERRIDE', 'GBRAIN_BINARY_VERSION', 'GBRAIN_ROOT', 'GBRAIN_VERIFY', 'GBRAIN_FRICTION_RUN_ID', 'GBRAIN_NOTABILITY_EVAL_REAL',+ 'GBRAIN_WHOKNOWS_FIXTURE_PATH', 'GBRAIN_PACK_STAT_TTL_MS', 'GBRAIN_EMBEDDING', 'GBRAIN_BASE_PATH_PREFIXES', 'GBRAIN_RECOVERED_RETRY',+]);++describe('identity', () => {const url = 'postgresql://alice-example:[email protected]:6543/brain?sslmode=require&application_name=x';- const token = (overrides: Partial<Parameters<typeof cliSocketIdentity>[0]> = {}) => {+ const pooler = 'postgresql://postgres.project-a:[email protected]';+ const identity = (overrides: Partial<Parameters<typeof cliSocketIdentity>[0]> = {}) => {const dir = join(root, 'a', '.gbrain');return cliSocketIdentity({ config: { engine: 'postgres', database_url: url }, brainId: 'host', configDir: dir, configFile: join(dir, 'config.json'), version: '1.0.0', env: {}, ...overrides });};+ const at = (databaseUrl: string, env: Record<string, string> = {}) => identity({ config: { engine: 'postgres', database_url: databaseUrl }, env });- 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('the database target drops the password and driver-only parameters, keeps options', () => {+ expect(databaseTarget(url)).toEqual(databaseTarget('postgres://alice-example:[email protected]:6543/brain?prepare=false&connect_timeout=5'));+ expect(JSON.stringify(databaseTarget(url))).not.toContain('secret-one');+ expect(databaseTarget(`${url}&options=-c%20search_path%3Dother`)).not.toEqual(databaseTarget(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);+ test('a session-lane serve answers a transaction-lane CLI on the same Supavisor host, user and database (prepare=, pool sizing and the URL variables differ)', () => {+ homeWithConfig('a');+ const serve = at(`${pooler}:5432/postgres`, { GBRAIN_POOL_SIZE: '10', GBRAIN_DATABASE_URL: `${pooler}:5432/postgres`, GBRAIN_HOME: '/home/alice-example' });+ const cli = at(`${pooler}:6543/postgres?prepare=false`, { GBRAIN_POOL_SIZE: '2', GBRAIN_DIRECT_POOL_SIZE: '1', GBRAIN_PREPARE: 'false',+ GBRAIN_DATABASE_URL: `${pooler}:6543/postgres?prepare=false`, GBRAIN_HOME: '/home/alice-example' });+ expect(cliSocketIdentityMismatch(serve, cli)).toBeNull();+ });++ test('on the pooler a different user or database is refused, and named', () => {+ homeWithConfig('a');+ const serve = at(`${pooler}:5432/postgres`);+ expect(cliSocketIdentityMismatch(serve, at(`${pooler.replace('project-a', 'project-b')}:6543/postgres`))).toBe('database user');+ expect(cliSocketIdentityMismatch(serve, at(`${pooler}:6543/other`))).toBe('database database');+ expect(cliSocketIdentityMismatch(serve, at(`${pooler.replace('region-a', 'region-b')}:6543/postgres`))).toBe('database host');});- test('changes with the resolved brain id (a mount serve never matches a host CLI)', () => {+ test('on plain Postgres another port is another server: refused, and named', () => {homeWithConfig('a');- expect(token({ brainId: 'mnt-example' })).not.toBe(token());+ expect(cliSocketIdentityMismatch(at(url), at(url.replace(':6543', ':5432')))).toBe('database port');+ expect(cliSocketIdentityMismatch(at(url), at(url.replace(':6543', ':6543')))).toBeNull();+ expect(cliSocketIdentityMismatch(at(url), at(url.replace('db.acme', 'db2.acme')))).toBe('database host');+ expect(cliSocketIdentityMismatch(at(url), identity({ config: { engine: 'postgres', database_url: undefined } }))).toBe('database');+ });++ test('names the config home, config bytes, version and brain id (a mount serve never matches a host CLI); a rotated password still matches', () => {+ const home = homeWithConfig('a');+ const base = identity();+ expect(cliSocketIdentityMismatch(base, identity())).toBeNull();+ expect(cliSocketIdentityMismatch(base, at(url.replace('secret-one', 'rotated')))).toBeNull();+ expect(cliSocketIdentityMismatch(base, identity({ version: '1.0.1' }))).toBe('version');+ expect(cliSocketIdentityMismatch(base, identity({ brainId: 'mnt-example' }))).toBe('brain');+ const other = homeWithConfig('b');+ expect(cliSocketIdentityMismatch(base, identity({ configDir: other.dir, configFile: other.file }))).toBe('config home');+ writeFileSync(home.file, '{"engine":"postgres","edited":true}');+ expect(cliSocketIdentityMismatch(base, identity())).toBe('config contents');});- test('changes with GBRAIN_* settings and which provider keys are set, never with a key value or the socket/debug switches', () => {+ test('a sizing or driver variable may differ; a read-behavior variable may not, and is named without its value', () => {homeWithConfig('a');- const base = token({ env: { HOME: '/home/alice-example', GBRAIN_HOME: '/home/alice-example' } });- expect(token({ env: { HOME: '/elsewhere', GBRAIN_HOME: '/home/alice-example' } })).toBe(base);- expect(token({ env: { GBRAIN_HOME: '/home/alice-example', GBRAIN_CONTRIBUTOR_MODE: '1' } })).not.toBe(base);- expect(token({ env: { GBRAIN_HOME: '/home/alice-example', GBRAIN_CLI_SOCKET: '1', GBRAIN_DEBUG: '1', GBRAIN_SQL_TRACE: '/tmp/t.jsonl' } })).toBe(base);- const keyed = behaviorEnvDigest({ VOYAGE_API_KEY: 'value-one' });- expect(behaviorEnvDigest({ VOYAGE_API_KEY: 'value-two' })).toBe(keyed);- expect(behaviorEnvDigest({})).not.toBe(keyed);- expect(behaviorEnvDigest({ VOYAGE_API_KEY: '' })).toBe(behaviorEnvDigest({}));- expect(behaviorEnvDigest({ OPENAI_BASE_URL: 'http://localhost:1' })).not.toBe(behaviorEnvDigest({}));- expect(JSON.stringify(behaviorEnvDigest({ VOYAGE_API_KEY: 'value-one' }))).not.toContain('value-one');+ const base = identity({ env: { HOME: '/home/alice-example', GBRAIN_HOME: '/home/alice-example' } });+ for (const env of [{ GBRAIN_POOL_SIZE: '10' }, { GBRAIN_DIRECT_POOL_SIZE: '4' }, { GBRAIN_PREPARE: 'true' }, { GBRAIN_POOL_MAX_LIFETIME_S: '60' },+ { GBRAIN_CLI_SOCKET: '1', GBRAIN_DEBUG: '1', GBRAIN_SQL_TRACE: '/tmp/t.jsonl' }, { GBRAIN_SOURCE: 'source-a' }, { HOME: '/elsewhere' }]) {+ expect(cliSocketIdentityMismatch(base, identity({ env: { HOME: '/home/alice-example', GBRAIN_HOME: '/home/alice-example', ...env } })), JSON.stringify(env)).toBeNull();+ }+ const contributor = identity({ env: { GBRAIN_HOME: '/home/alice-example', GBRAIN_CONTRIBUTOR_MODE: '1' } });+ expect(cliSocketIdentityMismatch(base, contributor)).toBe('env GBRAIN_CONTRIBUTOR_MODE');+ expect(cliSocketIdentityMismatch(base, identity({ env: { GBRAIN_HOME: '/home/bob-example' } }))).toBe('env GBRAIN_HOME');+ expect(JSON.stringify(identity({ env: { GBRAIN_MODEL: 'model-secretish' } }))).not.toContain('model-secretish');});- test('provider routing values enter the digest (a local and a remote endpoint never match); credentials stay set-or-not', () => {+ test('provider routing values enter with their value (a local and a remote endpoint never match); credentials only as 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 }));+ const env = (extra: Record<string, string>) => identity({ env: { GBRAIN_HOME: '/home/alice-example', ...extra } });+ expect(cliSocketIdentityMismatch(env({ OPENAI_BASE_URL: 'http://127.0.0.1:11434/v1' }), env({ OPENAI_BASE_URL: 'https://api.openai.com/v1' }))).toBe('env OPENAI_BASE_URL');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' }));+ expect(cliSocketIdentityMismatch(env({ [name]: 'value-one' }), env({ [name]: 'value-two' })), name).toBe(`env ${name}`);}- 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' }));+ for (const name of ['OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'LLAMA_SERVER_API_KEY', 'VOYAGE_API_KEY']) {+ expect(cliSocketIdentityMismatch(env({ [name]: 'value-one' }), env({ [name]: 'value-two' })), name).toBeNull();+ expect(cliSocketIdentityMismatch(env({}), env({ [name]: 'value-one' })), name).toBe(`provider key ${name}`);}+ expect(cliSocketIdentityMismatch(env({}), env({ VOYAGE_API_KEY: '' }))).toBeNull();+ expect(JSON.stringify(env({ VOYAGE_API_KEY: 'value-one' }))).not.toContain('value-one');});- 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' }));+ test('every GBRAIN_* name in src is classified: read behavior (READ_BEHAVIOR_ENV) or listed here as unable to change a socket read', () => {+ const names = new Set<string>();+ for (const file of new Bun.Glob('src/**/*.ts').scanSync('.')) {+ for (const match of readFileSync(file, 'utf8').matchAll(/GBRAIN_[A-Z0-9_]*[A-Z0-9]/g)) names.add(match[0]);+ }+ const unclassified = [...names].filter(name => !READ_BEHAVIOR_ENV.includes(name)+ && !NOT_READ_BEHAVIOR.has(name) && !NOT_READ_BEHAVIOR_PREFIXES.some(prefix => name.startsWith(prefix))).sort();+ expect(unclassified).toEqual([]);+ for (const name of READ_BEHAVIOR_ENV) expect(names.has(name), name).toBe(true);});});@@ -222,13 +292,15 @@ 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' },+ const serveIdentity = (databaseUrl = 'postgresql://[email protected]/brain'): CliSocketIdentity => (mkdirSync(join(root, 'home', '.gbrain'), { recursive: true, mode: 0o700 }), cliSocketIdentity({+ config: { engine: 'postgres', database_url: databaseUrl }, brainId: 'host', configDir: join(root, 'home', '.gbrain'), configFile: join(root, 'home', '.gbrain', 'config.json'), version: '1.0.0', env: {} }));+ const request = (identity: CliSocketIdentity): 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', brainId: () => 'host',+ const binding = await startCliSocketServer({ engine, log: line => lines.push(line), home, identity: serveIdentity(), brainId: () => 'host',execute: async () => ({ frame: okFrame, settled: Promise.resolve() }), ...overrides });if (binding) bindings.push(binding);return { binding, lines, path: cliSocketPath(home) };@@ -245,8 +317,15 @@ describe('serve listener', () => {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 });- expect(await exchangeCliSocket(path, request('token-b'), 5_000)).toEqual({ reason: 'refused (identity_mismatch)' });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ frame: okFrame });+ expect(await exchangeCliSocket(path, request({ ...serveIdentity(), version: '1.0.1' }), 5_000)).toEqual({ reason: 'refused (identity_mismatch): version' });+ expect(await exchangeCliSocket(path, request(serveIdentity('postgresql://[email protected]:6543/brain')), 5_000)).toEqual({ reason: 'refused (identity_mismatch): database port' });+ expect(started.lines.filter(line => line.includes('identity_mismatch'))).toEqual([+ "[gbrain serve] cli-socket: refused a CLI call: identity_mismatch (version differs from this serve's); that CLI takes its cold path.",+ "[gbrain serve] cli-socket: refused a CLI call: identity_mismatch (database port differs from this serve's); that CLI takes its cold path.",+ ]);+ await exchangeCliSocket(path, request({ ...serveIdentity(), version: '1.0.1' }), 5_000);+ expect(started.lines.filter(line => line.includes('identity_mismatch')).length).toBe(2);});test('rejects a peer whose kernel uid differs, and one whose uid cannot be read', async () => {@@ -254,14 +333,14 @@ describe('serve listener', () => {// 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);+ const outcome = await exchangeCliSocket(path, request(serveIdentity()), 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(await exchangeCliSocket(second.path, request(serveIdentity()), 5_000)).toHaveProperty('reason');expect(second.lines.join('\n')).toContain('rejected a connection from an unverifiable peer');});@@ -300,25 +379,25 @@ describe('serve listener', () => {let release!: () => void;const pending = new Promise<void>(resolve => { release = resolve; });const { path } = await start({ execute: async () => ({ frame: { v: 1, kind: 'fallback', reason: 'timeout' }, settled: pending }) });- for (let i = 0; i < 8; i++) expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: { v: 1, kind: 'fallback', reason: 'timeout' } });- expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ reason: 'refused (busy)' });+ for (let i = 0; i < 8; i++) expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ frame: { v: 1, kind: 'fallback', reason: 'timeout' } });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ reason: 'refused (busy)' });release();await Bun.sleep(20);- expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toHaveProperty('frame');+ expect(await exchangeCliSocket(path, request(serveIdentity()), 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 exchangeCliSocket(path, request(serveIdentity()), 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 exchangeCliSocket(second, request(serveIdentity()), 5_000);await Bun.sleep(150);expect(quiet.filter(line => line.includes('is still running'))).toEqual([]);});@@ -330,11 +409,11 @@ describe('serve listener', () => {const probe = join(runDir(), 'probe.sock');await new Promise<void>(resolve => counter.listen(probe, resolve));try {- expect(await exchangeCliSocket(probe, request('token-a'), 5_000, { ok: false, reason: 'no peer-credential call is wired for testos' }))+ expect(await exchangeCliSocket(probe, request(serveIdentity()), 5_000, { ok: false, reason: 'no peer-credential call is wired for testos' })).toEqual({ reason: 'peer_credentials_unsupported (no peer-credential call is wired for testos)' });await Bun.sleep(20);expect(connections).toBe(0);- expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ frame: okFrame });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ frame: okFrame });} finally {counter.close();}@@ -364,7 +443,7 @@ describe('serve listener', () => {const server = net.createServer(socket => socket.once('data', () => socket.write(`${handshake}\n${result}${result ? '\n' : ''}`)));await new Promise<void>(resolve => server.listen(path, resolve));try {- expect(await exchangeCliSocket(path, request('token-a'), 5_000)).toEqual({ reason: 'malformed_response' });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ reason: 'malformed_response' });} finally {await new Promise<void>(resolve => server.close(() => resolve()));}@@ -380,7 +459,7 @@ describe('serve listener', () => {await new Promise<void>(resolve => server.listen(path, resolve));try {const started = performance.now();- expect(await exchangeCliSocket(path, request('token-a'), 300)).toEqual({ reason: 'round_trip_timeout' });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 300)).toEqual({ reason: 'round_trip_timeout' });expect(performance.now() - started).toBeLessThan(2_000);} finally {server.close();@@ -392,7 +471,7 @@ describe('serve listener', () => {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' });+ expect(await exchangeCliSocket(path, request(serveIdentity()), 5_000)).toEqual({ reason: 'serve_closed_mid_request' });} finally {server.close();}@@ -404,7 +483,7 @@ describe('serve listener', () => {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(await exchangeCliSocket(path, request(serveIdentity()), 60_000)).toEqual({ reason: 'handshake_timeout' });expect(performance.now() - started).toBeLessThan(3_000);} finally {server.close();diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.tsindex 5e018e381d..5fe3b298f8 100644--- a/test/e2e/cli-socket-postgres.test.ts+++ b/test/e2e/cli-socket-postgres.test.ts@@ -204,7 +204,7 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {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.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch): config contents');expect(run.stdout).toBe(cold.get('search')!.stdout);expect(run.exitCode).toBe(0);} finally {@@ -216,19 +216,29 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {const identity = cliSocketIdentity({ config: { engine: 'postgres', database_url: databaseUrl }, brainId: 'host', configDir: join(otherHome, '.gbrain'), configFile: join(otherHome, '.gbrain', 'config.json'), version: VERSION, env });const outcome = await exchangeCliSocket(socketPath, { v: 1, identity, command: 'search', kind: 'op', op: 'search', params: { query: WORD },routing: { cwd: process.cwd(), source_env: null }, cli: { quiet: false, timeout_ms: null } }, 30_000);- expect(outcome).toEqual({ reason: 'refused (identity_mismatch)' });+ expect(outcome).toEqual({ reason: 'refused (identity_mismatch): config home' });rmSync(otherHome, { recursive: true, force: true });}, 90_000);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 extras: Array<[Record<string, string>, string]> = [[{ GBRAIN_CONTRIBUTOR_MODE: '1' }, 'env GBRAIN_CONTRIBUTOR_MODE'], [{ VOYAGE_API_KEY: 'synthetic-fixture-value' }, 'provider key VOYAGE_API_KEY'],+ [{ LMSTUDIO_BASE_URL: 'https://lmstudio.acme-example.test/v1' }, 'env LMSTUDIO_BASE_URL']];+ for (const [extra, part] of extras) {const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', ...extra });- expect(run.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch)');+ expect(run.stderr).toContain(`[cli-socket] cold path: refused (identity_mismatch): ${part}`);expect(run.stdout).toBe(cold.get('search')!.stdout);}}, 90_000);+ test('a CLI that differs only in connection sizing and driver-only URL parameters is answered warm', async () => {+ const lane = `${databaseUrl}${databaseUrl.includes('?') ? '&' : '?'}prepare=false&application_name=cli-lane-example`;+ const trace = traceFile();+ const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', GBRAIN_SQL_TRACE: trace, GBRAIN_POOL_SIZE: '3', GBRAIN_DIRECT_POOL_SIZE: '1', GBRAIN_DATABASE_URL: lane });+ expect(run.stderr).not.toContain('[cli-socket] cold path');+ expect(roundTrips(trace)).toBe(0);+ expect({ stdout: run.stdout, exitCode: run.exitCode }).toEqual({ stdout: cold.get('search')!.stdout, exitCode: 0 });+ }, 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');