Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): a serve with the warm CLI socket off does no work for it

garrytand92d6cbf2240
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index eb64069bcf..fe96221aba 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; `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/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/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.md
index b2742f6100..5e53a508bf 100644
--- a/docs/guides/cli-socket.md
+++ b/docs/guides/cli-socket.md
@@ -37,6 +37,11 @@ A serve on a mount brain (`gbrain serve --brain <mount>`, `GBRAIN_BRAIN_ID`, a
host brain only.
Turn it off by removing the flag or running
`gbrain config set serve.cli_socket false`, then restarting the serve.
+The serve reads the key from the config it already loaded when it connected,
+so a serve with the socket off does no work for it: it loads none of the
+socket's code and sends the database nothing extra. A serve that started
+degraded (database unreachable at boot) does not see the key; pass
+`--cli-socket` there.
## What goes through it
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 988ebcc277..935ec327c2 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1995 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts)
+src/core/config.ts 1999 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts)
src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 0cb479d2f1..c0df1ba5a5 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -21,7 +21,7 @@ import {
resolveSelfUpgradeMode,
justUpgradedPath,
} from '../core/self-upgrade.ts';
-import { loadConfig, loadConfigFileOnly, loadConfigWithEngine, isThinClient, getDbUrlSource, envShadowDetected } from '../core/config.ts';
+import { loadConfig, loadConfigFileOnly, loadConfigWithEngine, isThinClient, getDbUrlSource, envShadowDetected, MERGED_CONFIG_BY_ENGINE } from '../core/config.ts';
import {
classifyPgAccessError as classifyDbAccessError,
diagnoseDbConfig as diagnoseDbConfigForMarker,
@@ -1382,16 +1382,6 @@ export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | n
return null;
}
-/**
- * #1475 — the DB-plane merge `connectEngine` performs after connect, published
- * for `makeContext` so the operation context carries it too.
- *
- * Why a map rather than a module-level variable: a process can hold more than
- * one engine (`--brain <mount>` connects a second one), and the host brain's
- * merged config must never be served for a mounted brain's context. Weak so a
- * disconnected engine does not pin its config for the life of the process.
- */
-const MERGED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
const SELECTED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
/**
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 380d4b3633..5698f51441 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -238,7 +238,7 @@ export async function runServe(
// 'verbs' exposes exactly the seven protocol verbs (the quickstart surface);
// 'starter' the ~20-op daily-driver set; 'full' keeps every operation.
const { parseSurfaceFlag, resolveSurfaceWithSource, resolveStdioSurface, parseAccessFlag, SURFACE_SOURCE_LABEL } = await import('../mcp/surface.ts');
- const { loadConfig } = await import('../core/config.ts');
+ const { loadConfig, MERGED_CONFIG_BY_ENGINE } = await import('../core/config.ts');
const surfaceFlag = parseSurfaceFlag(args);
const resolved = isHttp ? resolveSurfaceWithSource(surfaceFlag, loadConfig()) : resolveStdioSurface(surfaceFlag, loadConfig());
const surface = resolved.surface;
@@ -278,7 +278,8 @@ export async function runServe(
// binding is deliberate or unambiguous — sole-source brains are a pure
// no-op. Stdio-only: the OAuth HTTP path scopes writes per token instead.
const sourceGuard = args.includes('--source-guard');
- const cliSocketFlag = args.includes('--cli-socket'); // opt-in warm CLI socket (core/cli-socket/server.ts)
+ // Opt-in warm CLI socket (core/cli-socket/server.ts): off, the serve loads nothing and reads nothing for it.
+ const cliSocketOn = args.includes('--cli-socket') || MERGED_CONFIG_BY_ENGINE.get(engine)?.serve_cli_socket === true;
if (sourceGuard && isHttp) {
// Loud posture warning (the --log-full-params precedent): the guard is a
// stdio-lane mechanism; HTTP writes are scoped per token instead. An
@@ -369,7 +370,7 @@ export async function runServe(
const { armCorpusDrain } = await import('../core/sweep.ts');
const corpusDrain = (opts.armCorpusDrain ?? armCorpusDrain)(engine, { sourceId: process.env.GBRAIN_SOURCE || undefined });
- const cliSocket = await (await import('../core/cli-socket/server.ts')).maybeStartCliSocket(engine, cliSocketFlag, httpLog);
+ const cliSocket = cliSocketOn ? await (await import('../core/cli-socket/server.ts')).startCliSocket(engine, httpLog) : null;
try {
await runHttp(engine, { port, tokenTtl, enableDcr, enableDcrInsecure, publicUrl, logFullParams, bind, suppressBootstrapToken, printAdminToken, surface, adoptServer: opts.adoptServer });
} finally {
@@ -457,7 +458,7 @@ export async function runServe(
// initialize frame before the SDK sees it.
activateStdioIdleActivityTracking();
// Opt-in warm CLI socket; bound after the stdout redirect so a request's captured console output keeps its stream.
- void import('../core/cli-socket/server.ts').then(m => m.maybeStartCliSocket(engine, cliSocketFlag, opts.log ?? ((msg: string) => console.error(msg))));
+ if (cliSocketOn) void import('../core/cli-socket/server.ts').then(m => m.startCliSocket(engine, opts.log ?? ((msg: string) => console.error(msg))));
} finally {
if (bootDeadline) clearTimeout(bootDeadline);
stopProgressWatch();
diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.ts
index 293e28ba6d..1661ea9765 100644
--- a/src/core/cli-socket/server.ts
+++ b/src/core/cli-socket/server.ts
@@ -22,7 +22,6 @@ 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,
type CliSocketRequest, type HandshakeFrame, type ResultFrame } from './protocol.ts';
-export const CLI_SOCKET_CONFIG_KEY = 'serve.cli_socket';
const MAX_CONNECTIONS = 32;
const MAX_ACTIVE_REQUESTS = 8;
@@ -42,16 +41,11 @@ export interface CliSocketServerOptions {
stuckAfterMs?: number;
}
-/** Whether this serve should open the socket: the flag, or the DB-plane config key set to a true value. */
-export async function cliSocketRequested(engine: BrainEngine, flag: boolean): Promise<boolean> {
- if (flag) return true;
- try { return /^(1|true|on|yes)$/i.test((await engine.getConfig(CLI_SOCKET_CONFIG_KEY))?.trim() ?? ''); }
- catch { return false; }
-}
-
-/** serve's entry (`flag` is `--cli-socket`): opens the socket only when asked; logs (never throws) when it cannot. */
-export async function maybeStartCliSocket(engine: BrainEngine, flag: boolean, log: (line: string) => void): Promise<CliSocketBinding | null> {
- if (!await cliSocketRequested(engine, flag)) return null;
+/**
+ * serve's entry, called only when the socket was asked for (`--cli-socket`, or `serve.cli_socket` in the connect-time
+ * config merge): serve decides that without loading this module. Logs (never throws) when it cannot open the socket.
+ */
+export async function startCliSocket(engine: BrainEngine, log: (line: string) => void): Promise<CliSocketBinding | null> {
try { return await startCliSocketServer({ engine, log }); }
catch (error) { log(`[gbrain serve] cli-socket: not started: ${(error as Error).message}`); return null; }
}
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index 080e903db6..26eff6323c 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -16,5 +16,5 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'skillopt.capture_enabled', // skillopt/held-out.ts production rollout capture, default off
'entity_identity.union', // entity-identity.ts: links/backlinks union across identity co-members, default off
'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off
- 'serve.cli_socket', // cli-socket/server.ts: a Postgres serve answers CLI reads over a private Unix socket, default off
+ 'serve.cli_socket', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve answers CLI reads over a private Unix socket, default off
];
diff --git a/src/core/config.ts b/src/core/config.ts
index 36747deede..17d607c1ad 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -8,6 +8,8 @@ import { loadGbrainEnvFile } from './gbrain-env-file.ts';
import { dotenvValuesForKey } from './env-trust.ts';
import { REMOTE_PRIVATE_PAGES_KEY } from './search/private-visibility.ts';
import { RUNTIME_READER_CONFIG_KEYS } from './config-runtime-keys.ts';
+import { mergeServeCliSocket } from './published-config.ts';
+export { MERGED_CONFIG_BY_ENGINE } from './published-config.ts';
/**
* Where is the active DB URL coming from? Pure introspection, no connection
@@ -306,6 +308,8 @@ export interface GBrainConfig {
embedding_multimodal?: boolean;
/** Model override for multimodal embeddings (e.g. "voyage:voyage-multimodal-3"). */
embedding_multimodal_model?: string;
+ /** DB-plane `serve.cli_socket`: the serve opens the warm CLI socket without `--cli-socket` (see published-config.ts). */
+ serve_cli_socket?: boolean;
/**
* v0.42 (#1981) — Retrieval Reflex. The context engine's deterministic
@@ -1220,7 +1224,7 @@ export async function loadConfigWithEngine(
: engine,
);
- return merged;
+ return mergeServeCliSocket(merged, snapshot);
}
/**
diff --git a/src/core/published-config.ts b/src/core/published-config.ts
new file mode 100644
index 0000000000..453719ebe8
--- /dev/null
+++ b/src/core/published-config.ts
@@ -0,0 +1,23 @@
+/**
+ * The DB-plane config merge, as published after connect.
+ *
+ * #1475 — `connectEngine` merges the DB plane over file/env once after connect (`loadConfigWithEngine`) and
+ * publishes the result here for `makeContext` (ctx.config) and for `gbrain serve` (`serve_cli_socket`), so neither
+ * reads the config table again. Why a map rather than a module-level variable: a process can hold more than one
+ * engine (`--brain <mount>` connects a second one), and the host brain's merged config must never be served for a
+ * mounted brain. Weak so a disconnected engine does not pin its config for the life of the process.
+ */
+import type { GBrainConfig } from './config.ts';
+
+export const MERGED_CONFIG_BY_ENGINE = new WeakMap<object, GBrainConfig>();
+
+/**
+ * `serve.cli_socket` (docs/guides/cli-socket.md) joins the merge from the bulk config snapshot only, never a per-key
+ * read: a serve that leaves the warm CLI socket off then does no work for it at boot, and a brain whose config table
+ * cannot be read in one statement opens the socket only with `gbrain serve --cli-socket`.
+ */
+export function mergeServeCliSocket(merged: GBrainConfig, snapshot: Record<string, string> | null): GBrainConfig {
+ const value = snapshot?.['serve.cli_socket'];
+ if (merged.serve_cli_socket === undefined && value !== undefined) merged.serve_cli_socket = /^(1|true|on|yes)$/i.test(value.trim());
+ return merged;
+}
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
index 1577b07a57..4726589e60 100644
--- a/test/cli-socket.test.ts
+++ b/test/cli-socket.test.ts
@@ -37,6 +37,7 @@ import { isResultFrame, reviveOperationError, serializeOperationError, type CliS
import { queueFirstFallbackHop, takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';
import { installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';
import { opError, OperationError } from '../src/core/ops/contract.ts';
+import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
const uid = process.getuid!();
const engine = { kind: 'postgres', connectedDatabaseUrl: 'postgresql://[email protected]/brain' } as unknown as BrainEngine;
@@ -457,3 +458,20 @@ test('an OperationError round-trips with every field the CLI renderer reads', ()
expect(revived.toJSON()).toEqual(original.toJSON());
expect({ ...revived }).toEqual({ ...original });
});
+
+test('serve.cli_socket joins the connect-time config merge from its bulk snapshot only, never a read of its own', async () => {
+ const base: GBrainConfig = { engine: 'postgres' };
+ const reads: string[] = [];
+ const reader = (table: Record<string, string> | null) => ({
+ getConfig: async (key: string) => { reads.push(key); return table?.[key] ?? null; },
+ ...(table ? { getAllConfig: async () => ({ ...table }) } : {}),
+ });
+ expect((await loadConfigWithEngine(reader({ 'serve.cli_socket': ' Yes ' }), base))?.serve_cli_socket).toBe(true);
+ expect((await loadConfigWithEngine(reader({ 'serve.cli_socket': 'false' }), base))?.serve_cli_socket).toBe(false);
+ expect((await loadConfigWithEngine(reader({}), base))?.serve_cli_socket).toBeUndefined();
+ expect(reads).toEqual([]);
+ const perKey = await loadConfigWithEngine({ getConfig: async (key: string) => { reads.push(key); return key === 'serve.cli_socket' ? 'true' : null; } }, base);
+ expect(perKey?.serve_cli_socket).toBeUndefined();
+ expect(reads.length).toBeGreaterThan(0);
+ expect(reads).not.toContain('serve.cli_socket');
+});
diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.ts
index 0b3265fa06..5e018e381d 100644
--- a/test/e2e/cli-socket-postgres.test.ts
+++ b/test/e2e/cli-socket-postgres.test.ts
@@ -132,6 +132,19 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {
await stopServe();
}, 90_000);
+ test('serve.cli_socket true opens it without the flag (read from the connect-time config merge)', async () => {
+ expect((await cli(['config', 'set', 'serve.cli_socket', 'true'])).exitCode).toBe(0);
+ try {
+ serve = await startServe([]);
+ for (let i = 0; i < 120 && !serveLog.includes('cli-socket: listening'); i++) await Bun.sleep(250);
+ expect(serveLog).toContain('cli-socket: listening');
+ await stopServe();
+ expect(existsSync(socketPath)).toBe(false);
+ } finally {
+ expect((await cli(['config', 'set', 'serve.cli_socket', 'false'])).exitCode).toBe(0);
+ }
+ }, 90_000);
+
test('serve --cli-socket binds a 0600 socket in a 0700 run directory', async () => {
serveTrace = join(home, 'serve-trace.jsonl');
serve = await startServe(['--cli-socket'], { GBRAIN_SQL_TRACE: serveTrace });
diff --git a/test/eval-capture-db-plane.test.ts b/test/eval-capture-db-plane.test.ts
index ebc8b1379e..f64529a947 100644
--- a/test/eval-capture-db-plane.test.ts
+++ b/test/eval-capture-db-plane.test.ts
@@ -197,8 +197,16 @@ describe('eval.capture set on the DB plane reaches the runtime gate (#1475)', ()
const cli = surfaceSource('cli');
expect(cli).toContain('MERGED_CONFIG_BY_ENGINE.set(engine, merged)');
// Guard the guard: if the map is ever renamed, the assertion above must
- // not keep passing against a stale literal that no longer exists.
- expect(cli).toContain('const MERGED_CONFIG_BY_ENGINE = new WeakMap');
+ // not keep passing against a stale literal that no longer exists. The map
+ // lives in src/core/published-config.ts (serve reads it too); the CLI must
+ // import that one map, and the publish seam must write into it.
+ expect(cli).toContain("MERGED_CONFIG_BY_ENGINE } from '../core/config.ts'");
+ const { __testing } = await import('../src/cli/main.ts');
+ const { MERGED_CONFIG_BY_ENGINE } = await import('../src/core/published-config.ts');
+ const probe = {} as unknown as BrainEngine;
+ const published = { engine: 'pglite' as const };
+ __testing.publishMergedConfig(probe, published);
+ expect(MERGED_CONFIG_BY_ENGINE.get(probe)).toBe(published);
});
test('connectMountEngine still marks its engine as a mount engine', async () => {
diff --git a/test/serve-cli-socket-off.test.ts b/test/serve-cli-socket-off.test.ts
new file mode 100644
index 0000000000..6270753b4d
--- /dev/null
+++ b/test/serve-cli-socket-off.test.ts
@@ -0,0 +1,77 @@
+/**
+ * The warm CLI socket is opt-in (docs/guides/cli-socket.md). A serve that leaves it off must boot as it did before the
+ * socket existed: it loads nothing under src/core/cli-socket/ and makes no engine call for it. A serve that asks for it
+ * (`--cli-socket`, or `serve_cli_socket` in the config merge connectEngine published) loads it once its boot is done.
+ *
+ * Each boot runs in its own bun process, so a module another test file in this shard already loaded cannot hide an
+ * import, and the counting engine records every method the serve calls on it. The socket refuses a non-Postgres engine
+ * before touching it, so a boot with the socket off must make exactly the engine calls of a boot with `--cli-socket`.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+interface Boot { calls: string[]; modules: string[]; logs: string[] }
+
+const CHILD = `
+import { EventEmitter } from 'node:events';
+import { writeFileSync } from 'node:fs';
+import { runServe } from './src/commands/serve.ts';
+const { args, published, out } = JSON.parse(process.env.BOOT_SPEC);
+const calls = [];
+const engine = {
+ getConfig: async (key) => { calls.push('getConfig(' + key + ')'); return null; },
+ getAllConfig: async () => { calls.push('getAllConfig()'); return {}; },
+ disconnect: async () => { calls.push('disconnect()'); },
+};
+if (published) (await import('./src/core/config.ts')).MERGED_CONFIG_BY_ENGINE.set(engine, { engine: 'postgres', serve_cli_socket: true });
+const logs = [];
+await runServe(engine, args, {
+ stdin: new EventEmitter(), signals: { on() { return this; } }, exit: () => {}, log: line => { logs.push(line); },
+ startMcpServer: async () => {}, getParentPid: () => 1, setInterval: () => 0, clearInterval: () => {},
+ probeWatchdog: () => false, sweepEnabled: false,
+});
+await new Promise(resolve => setTimeout(resolve, 300));
+const modules = Object.keys(require.cache).filter(path => path.includes('/src/core/cli-socket/'));
+writeFileSync(out, JSON.stringify({ calls, modules, logs }));
+process.exit(0);
+`;
+
+async function boot(args: string[], published = false): Promise<Boot> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-serve-socket-off-'));
+ try {
+ const out = join(home, 'boot.json');
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home, GBRAIN_SWEEP: '0', BOOT_SPEC: JSON.stringify({ args, published, out }) };
+ const proc = Bun.spawn(['bun', '--no-env-file', '-e', CHILD], { cwd: process.cwd(), env, stdout: 'pipe', stderr: 'pipe' });
+ const [stderr, exitCode] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
+ expect({ exitCode, stderr: exitCode === 0 ? '' : stderr }).toEqual({ exitCode: 0, stderr: '' });
+ return JSON.parse(readFileSync(out, 'utf8')) as Boot;
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+describe('serve with the warm CLI socket off', () => {
+ test('loads no cli-socket module and makes no engine call for it', async () => {
+ const [off, on] = await Promise.all([boot([]), boot(['--cli-socket'])]);
+ expect(off.modules).toEqual([]);
+ expect(off.calls.toSorted()).toEqual(on.calls.toSorted());
+ expect(off.calls).not.toContain('getConfig(serve.cli_socket)');
+ expect(off.logs.filter(line => line.includes('cli-socket'))).toEqual([]);
+ }, 60_000);
+
+ test('--cli-socket loads it after the boot (the control: the probe sees an import)', async () => {
+ const on = await boot(['--cli-socket']);
+ expect(on.modules.some(path => path.endsWith('/cli-socket/server.ts'))).toBe(true);
+ expect(on.logs.some(line => line.includes('cli-socket: not started'))).toBe(true);
+ expect(on.calls).not.toContain('getConfig(serve.cli_socket)');
+ }, 60_000);
+
+ test('serve_cli_socket in the published config merge turns it on with no config read of its own', async () => {
+ const on = await boot([], true);
+ expect(on.modules.some(path => path.endsWith('/cli-socket/server.ts'))).toBe(true);
+ expect(on.logs.some(line => line.includes('cli-socket: not started'))).toBe(true);
+ expect(on.calls).not.toContain('getConfig(serve.cli_socket)');
+ }, 60_000);
+});