Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(embeddings): opt-in vector index prewarm (gbrain embeddings prewarm, serve.vector_prewarm) refuses when the HNSW indexes exceed half of shared_buffers (GBRA-156)

garrytanf8a937f0b212
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 22ee959bcf..210a8d09a0 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -205,6 +205,44 @@ took 103 s on 16 vCPU with 12 GB and 8 workers. Measured, not shipped:
(m 16, ef_construction 64, `vector`). Measurements and method:
[`docs/eval/hnsw-scale-bench.md`](eval/hnsw-scale-bench.md).
+### Vector index prewarm
+
+<a id="vector-index-prewarm"></a>
+
+After a Postgres restart or a cache eviction, the first searches walk HNSW
+pages nobody has read yet: on a brain whose index is bigger than the cache,
+an unseen query reads 2,000 to 4,500 index pages and spends 1.2 to 2.7 s in
+the vector stage. `gbrain embeddings prewarm` loads every HNSW index of the
+brain into `shared_buffers` once with `pg_prewarm(<index>, 'buffer')`, so
+those pages are already cached. It is opt-in and local to the brain host: a
+CLI-only command (no MCP tool, refused by thin clients), and
+`gbrain config set serve.vector_prewarm true` runs it once in the
+background each time `gbrain serve` starts (off by default; a refusal is
+logged and the serve carries on).
+
+`shared_buffers` decides whether it runs. The indexes must total at most
+half of it, read with `current_setting('shared_buffers')`; past that the
+prewarm would evict the heap and keyword-index pages every other read needs.
+`effective_cache_size` is printed but never decides: it is a planner hint
+the operator sets, not memory the server holds. The check reads only catalog
+rows and file sizes, so a refusal reads no index page.
+
+| Command | Does |
+|---|---|
+| `gbrain embeddings prewarm --dry-run --json` | Index sizes, `shared_buffers`, `effective_cache_size`, the budget and the fit; reads nothing |
+| `gbrain embeddings prewarm` | Prewarms when the indexes fit and `pg_prewarm` exists |
+| `gbrain config set serve.vector_prewarm true` | Prewarms at each serve start (restart the serve) |
+
+Refusals, each with a fix: `vector_prewarm_wont_fit` (raise
+`shared_buffers` to at least twice the index size and restart Postgres; a
+managed database sizes it with the instance), `vector_prewarm_extension_missing`
+(`CREATE EXTENSION IF NOT EXISTS pg_prewarm;` as a role that may create
+extensions) and `vector_prewarm_unsupported_engine` (PGLite has no server
+cache to fill). Prewarmed pages stay cached until Postgres restarts or other
+reads evict them; pg_prewarm's own `autoprewarm` worker
+(`shared_preload_libraries = 'pg_prewarm'`) can reload them after a restart
+without gbrain.
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 26aa590ff9..f51ce2d1fc 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (`cycle.ts:runPhaseEmbed`) convert it to a failure via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.
- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. `decorateEmbeddingDimError(err, slug)`: maps pgvector's bare "expected N dimensions, not M" write rejection to a named `OperationError('embedding_plane_split', …)` carrying the consequence (page NOT written, transaction rolled back) + recovery command; applied at `importFromContent`'s transaction boundary so `gbrain put` fails loudly instead of echoing an unexplained provider string; every other error passes through untouched. Pinned by `test/embedding-dim-check-facts.test.ts` + `test/put-page-embedding-plane-split.test.ts`. `embeddingMismatchMessage` on PGLite offers, in order, keeping the existing width when the requested model supports it (in-place `init --force … --path <active>`), a previewed `gbrain migrate embeddings --to … --dim … --dry-run` that keeps pages and DB-only facts, and `gbrain reinit-pglite` as the labelled last resort; it never prints a hand-run wipe.
-- `src/commands/embeddings.ts` — `gbrain embeddings enable --embedding-model <p:m> [--embedding-dimensions N] [--brain <id>] [--json]`: turns embeddings on in place for the selected brain, including a mount (where `init --force` would repoint the host config at the mount's datastore). Opens the datastore, reads the vector column width (default for `--embedding-dimensions`) and stored identity; refuses with `embedding_width_mismatch` or `embedding_model_mismatch` (fix Action, nothing changed); refuses a mount whose host already embeds with another model (the model is host-wide). Writes the host file-plane `embedding_model`/`embedding_dimensions`, clears `embedding_disabled`, and reports `queued_chunks`/`queued_facts` plus `gbrain embed --stale [--brain]`. The fix readiness emits for mounted brains; exercised by `test/readiness-embedding-enablement.serial.test.ts`.
+- `src/commands/embeddings.ts` — `gbrain embeddings enable --embedding-model <p:m> [--embedding-dimensions N] [--brain <id>] [--json]`: turns embeddings on in place for the selected brain, including a mount (where `init --force` would repoint the host config at the mount's datastore). Opens the datastore, reads the vector column width (default for `--embedding-dimensions`) and stored identity; refuses with `embedding_width_mismatch` or `embedding_model_mismatch` (fix Action, nothing changed); refuses a mount whose host already embeds with another model (the model is host-wide). Writes the host file-plane `embedding_model`/`embedding_dimensions`, clears `embedding_disabled`, and reports `queued_chunks`/`queued_facts` plus `gbrain embed --stale [--brain]`. The fix readiness emits for mounted brains; exercised by `test/readiness-embedding-enablement.serial.test.ts`. `gbrain embeddings prewarm [--dry-run] [--brain <id>] [--json]` refuses a thin client and a PGLite brain (`vector_prewarm_unsupported_engine`) before opening an engine, then runs `core/vector-prewarm.ts` `runVectorPrewarm` on the selected Postgres brain (it lives here, not under `search`, because `gbrain search` takes a free-text query); `test/vector-prewarm.test.ts` pins the CLI refusals.
- `src/core/embed-overlength-heal.ts` — [R13] (PR #5347): a chunk the embedder rejects as too long on a model with NO declared `max_input_tokens` is SPLIT, not parked and not retried identically forever. `isSingleInputOverLengthError` (lives in `src/core/embed-overlength-classify.ts`, re-exported here: status 400/413/422 with one of the field-seen message shapes, or #6772 a 5xx or statusless error whose message names a token or context limit, such as llama.cpp's "larger than the max context size" and Ollama's 500 "input length exceeds the context length"; never a batch-shaped message or the gateway's `isTokenLimitError`; `isEmbedRetriableError`, `isTransientNetworkEmbedError` and `embedPageTexts`' no-fan-out rule all exempt it, so the bad chunk is isolated instead of retried; tests `test/embed-overlength-classification.test.ts`, `test/embed-partial-failure-3037.serial.test.ts`), `overLengthLimitFromMessage`, `deriveOverLengthChunkCap` (named limit × `EMBED_INPUT_SAFETY`, else half the largest failed text's estimate; null when not below the current cap or below `MIN_USEFUL_CHUNK_TOKENS` = 128), `healPageAfterOverLength` (learns the cap for the model, heals the page at that cap at once; `skipped` with a reason — `not_overlength`, `unresolved_model`, `declared_cap` (recipe or `GBRAIN_MAX_CHUNK_TOKENS`: the declaration is what to fix), `attempts_exhausted` (`MAX_OVERLENGTH_HEAL_ATTEMPTS` = 3 per page per process), `cap_floor`, `nothing_to_split`, `heal_failed` — leaves the page untouched) and `describeOverLengthOutcome` (the operator line naming the fix). `healAndReportOverLength` is the one-liner every failure site calls: `src/commands/embed.ts` (embedPage total/partial failure, embedAll, embedAllStale) and `src/core/embed-stale.ts` (`embedStaleForSource` catch). `statusFromCause` moved here from embed.ts (one home). Pinned by `test/embed-overlength-heal.test.ts` and `test/embed-overlength-drain.serial.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 87f94f008b..bbc3cd8fbf 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -18,6 +18,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` 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`). GBRA-175: `probe.ts` `probeCliSocket` sends a `probe` frame, which `server.ts` answers with the handshake alone (no op runs), so `gbrain upgrade --restart-only` checks that serve accepts the installed build; it lives outside the client so the upgrade path never loads the CLI.
+- `src/core/vector-prewarm.ts` — opt-in HNSW prewarm for Postgres brains ([ENGINES](../../ENGINES.md#vector-index-prewarm)). `readVectorPrewarmPlan` reads only catalogs and file sizes: every valid `hnsw` index in `current_schema()` with `pg_relation_size`, `pg_size_bytes(current_setting('shared_buffers'))`, `effective_cache_size` (missing_ok, reported only) and the pg_prewarm extension state. `prewarmFits`: shared_buffers alone decides, the total must be at most `PREWARM_SHARED_BUFFERS_SHARE` (0.5) of it, because 'buffer' mode fills Postgres's own cache and a bigger prewarm would evict the heap and keyword-index pages other reads need; effective_cache_size is a planner hint the server never allocates, so it never decides. `runVectorPrewarm` refuses PGLite (`vector_prewarm_unsupported_engine`), a misfit (`vector_prewarm_wont_fit`, host_admin fix naming the shared_buffers needed) and a missing extension (`vector_prewarm_extension_missing`) before any `pg_prewarm` call, and a dry run reads nothing; otherwise one transaction per index, largest first, with `SET LOCAL statement_timeout = 0` and `pg_prewarm(<index>, 'buffer')`. Callers: `gbrain embeddings prewarm` (CLI-only, never an operation, so no MCP caller reaches it) and `prewarmAtServeStart`, which `runServe` starts in the background only when DB-plane `serve.vector_prewarm` is true (`mergeServeVectorPrewarm` in `published-config.ts`, snapshot only); it logs the load or the refusal and never stops the serve. Pinned by `test/vector-prewarm.test.ts`, `test/serve-vector-prewarm-off.test.ts` (off: no module load, no engine call, no log line) and `test/e2e/vector-prewarm-postgres.test.ts` (prewarm, refusal under a simulated 16 kB shared_buffers, missing extension).
- `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/error-codes.md b/docs/guides/error-codes.md
index a3ef6083a0..b3d113046e 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4465,6 +4465,36 @@ More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/trou
More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/troubleshooting.md#upstream-rewritten)
+### vector_prewarm_extension_missing
+
+<a id="vector_prewarm_extension_missing"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `gbrain embeddings prewarm` was refused before reading anything because the pg_prewarm extension is not created in the brain's database (or the server does not ship it). | Prewarm loads index pages into shared_buffers with pg_prewarm, the Postgres contrib function for exactly that; creating an extension needs a database owner or superuser, so gbrain never creates it itself. | Ask the database administrator to run CREATE EXTENSION IF NOT EXISTS pg_prewarm; (install the PostgreSQL contrib package first if the server lacks it), then rerun gbrain embeddings prewarm. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/ENGINES.md#vector-index-prewarm](../../docs/ENGINES.md#vector-index-prewarm)
+
+### vector_prewarm_unsupported_engine
+
+<a id="vector_prewarm_unsupported_engine"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `gbrain embeddings prewarm` was refused because the brain is PGLite; nothing was read. | Prewarm fills a Postgres server's shared_buffers so later processes find index pages cached; PGLite runs inside each gbrain process, with no server cache that outlives it. | Nothing to do on PGLite. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/ENGINES.md#vector-index-prewarm](../../docs/ENGINES.md#vector-index-prewarm)
+
+### vector_prewarm_wont_fit
+
+<a id="vector_prewarm_wont_fit"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `gbrain embeddings prewarm` was refused before reading anything because the brain's HNSW indexes are larger than half of shared_buffers. | Prewarm loads the indexes into shared_buffers, the cache Postgres sizes and keeps; past half of it the prewarm would evict heap and keyword-index pages other reads need, so the next searches would pay first-touch reads on those instead. effective_cache_size does not decide: it is a planner hint, not memory the server holds. | Raise shared_buffers on the database host to at least twice the index size the message names and restart Postgres, or leave the indexes cold; read the fit with gbrain embeddings prewarm --dry-run --json. Run: gbrain embeddings prewarm --dry-run --json | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/ENGINES.md#vector-index-prewarm](../../docs/ENGINES.md#vector-index-prewarm)
+
### verification_failed
<a id="verification_failed"></a>
diff --git a/llms-full.txt b/llms-full.txt
index 378bf168c1..92586fd90b 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5635,6 +5635,44 @@ took 103 s on 16 vCPU with 12 GB and 8 workers. Measured, not shipped:
(m 16, ef_construction 64, `vector`). Measurements and method:
[`docs/eval/hnsw-scale-bench.md`](eval/hnsw-scale-bench.md).
+### Vector index prewarm
+
+<a id="vector-index-prewarm"></a>
+
+After a Postgres restart or a cache eviction, the first searches walk HNSW
+pages nobody has read yet: on a brain whose index is bigger than the cache,
+an unseen query reads 2,000 to 4,500 index pages and spends 1.2 to 2.7 s in
+the vector stage. `gbrain embeddings prewarm` loads every HNSW index of the
+brain into `shared_buffers` once with `pg_prewarm(<index>, 'buffer')`, so
+those pages are already cached. It is opt-in and local to the brain host: a
+CLI-only command (no MCP tool, refused by thin clients), and
+`gbrain config set serve.vector_prewarm true` runs it once in the
+background each time `gbrain serve` starts (off by default; a refusal is
+logged and the serve carries on).
+
+`shared_buffers` decides whether it runs. The indexes must total at most
+half of it, read with `current_setting('shared_buffers')`; past that the
+prewarm would evict the heap and keyword-index pages every other read needs.
+`effective_cache_size` is printed but never decides: it is a planner hint
+the operator sets, not memory the server holds. The check reads only catalog
+rows and file sizes, so a refusal reads no index page.
+
+| Command | Does |
+|---|---|
+| `gbrain embeddings prewarm --dry-run --json` | Index sizes, `shared_buffers`, `effective_cache_size`, the budget and the fit; reads nothing |
+| `gbrain embeddings prewarm` | Prewarms when the indexes fit and `pg_prewarm` exists |
+| `gbrain config set serve.vector_prewarm true` | Prewarms at each serve start (restart the serve) |
+
+Refusals, each with a fix: `vector_prewarm_wont_fit` (raise
+`shared_buffers` to at least twice the index size and restart Postgres; a
+managed database sizes it with the instance), `vector_prewarm_extension_missing`
+(`CREATE EXTENSION IF NOT EXISTS pg_prewarm;` as a role that may create
+extensions) and `vector_prewarm_unsupported_engine` (PGLite has no server
+cache to fill). Prewarmed pages stay cached until Postgres restarts or other
+reads evict them; pg_prewarm's own `autoprewarm` worker
+(`shared_preload_libraries = 'pg_prewarm'`) can reload them after a restart
+without gbrain.
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4a4fcc1648..482200e009 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 2009 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); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.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); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured)
+src/core/config.ts 2011 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); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.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); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts)
src/core/persistence/sync-run.ts 1682 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); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)
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/top-help.ts b/src/cli/top-help.ts
index 336cb11dc5..6aa1429e00 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -26,6 +26,7 @@ SETUP
migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)
migrate embeddings --to <p:model> Re-embed onto another embedding provider
embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)
+ embeddings prewarm [--dry-run] Load the vector indexes into shared_buffers when they fit (Postgres)
upgrade Self-update
check-update [--json] Check for new versions
repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)
diff --git a/src/commands/embeddings.ts b/src/commands/embeddings.ts
index 1fc34a61cd..9a1abe2d01 100644
--- a/src/commands/embeddings.ts
+++ b/src/commands/embeddings.ts
@@ -9,6 +9,12 @@
* host file-plane embedding model and dimensions and clears the keyless
* marker. Pages, facts and keyword search are untouched; chunks and facts
* without vectors stay queued for `gbrain embed --stale`.
+ *
+ * `gbrain embeddings prewarm`: load a Postgres brain's HNSW indexes into
+ * shared_buffers when they fit (core/vector-prewarm.ts). It lives here because
+ * this is the command group for a brain's vector side that opens the selected
+ * brain's own engine and that thin clients already refuse; `gbrain search`
+ * takes a free-text query, so `search prewarm` would be a search.
*/
import { existsSync } from 'node:fs';
import { loadConfigFileOnly, saveConfig, toEngineConfig, type GBrainConfig } from '../core/config.ts';
@@ -24,8 +30,10 @@ import { opError, OperationError } from '../core/ops/contract.ts';
import { renderCliError, type Action } from '../core/agent-output.ts';
import { recordAgentContractEvent } from '../core/agent-contract-log.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { runVectorPrewarm, vectorPrewarmUnsupported } from '../core/vector-prewarm.ts';
const USAGE = `Usage: gbrain embeddings enable --embedding-model <provider:model> [--embedding-dimensions <N>] [--brain <id>] [--json]
+ gbrain embeddings prewarm [--dry-run] [--brain <id>] [--json]
Turn on embeddings for the selected brain in place. Pages, facts and keyword
search are kept; chunks and facts without vectors stay queued for
@@ -36,6 +44,13 @@ the brain holds vectors from another model.
Effects: writes ~/.gbrain/config.json; later embedding calls use the provider
key (paid). Needs the brain's single-writer lock (stop a running gbrain serve).
+
+prewarm (Postgres): load the brain's HNSW vector indexes into shared_buffers
+with pg_prewarm, so the first searches after a restart skip their cold index
+reads. Refuses before reading anything when the indexes exceed half of
+shared_buffers (effective_cache_size is reported, never used: it is a planner
+hint) or the pg_prewarm extension is missing. --dry-run prints the fit only.
+\`gbrain config set serve.vector_prewarm true\` runs it once at each serve start.
`;
interface EnableOpts { model: string; dims?: number; json: boolean }
@@ -142,6 +157,29 @@ async function enable(opts: EnableOpts): Promise<Record<string, unknown>> {
}
}
+async function writePrewarm(args: string[], json: boolean): Promise<void> {
+ const unknown = args.find(a => a !== '--json' && a !== '--dry-run');
+ if (unknown) throw opError('invalid_params', `Unknown option '${unknown}' for gbrain embeddings prewarm.`, 'Run `gbrain embeddings --help` for the accepted options.');
+ const host = loadConfigFileOnly();
+ if (!host) throw opError('config_error', 'No gbrain config file found.', 'Run `gbrain init` first.');
+ if (host.remote_mcp) throw opError('config_error', 'This is a thin-client install; prewarm runs on the brain host.', 'Run this command on the brain host.');
+ const target = targetConfig(host, resolveBrainId(getCliOptions().brain));
+ if (target.engine !== 'postgres') throw vectorPrewarmUnsupported();
+ const engine = await createEngine(toEngineConfig(target));
+ await engine.connect(toEngineConfig(target));
+ try {
+ const r = await runVectorPrewarm(engine, { dryRun: args.includes('--dry-run') });
+ const mb = (bytes: number) => `${Math.ceil(bytes / (1024 * 1024))} MB`;
+ const blocks = r.loaded.reduce((sum, l) => sum + l.blocks, 0);
+ await writeStdoutFinal(json ? `${JSON.stringify(r, null, 2)}\n`
+ : `Vector indexes: ${r.indexes.length}, ${mb(r.total_bytes)}; prewarm budget ${mb(r.budget_bytes)} (half of shared_buffers ${mb(r.shared_buffers_bytes)}${r.effective_cache_size_bytes === null ? '' : `; effective_cache_size ${mb(r.effective_cache_size_bytes)}, not used`}).\n` +
+ (r.dry_run ? `Fits. Dry run: nothing read${r.extension_version ? '' : '; pg_prewarm is not created yet (CREATE EXTENSION IF NOT EXISTS pg_prewarm)'}.\n`
+ : `Loaded ${mb(blocks * 8192)} into shared_buffers in ${(r.elapsed_ms / 1000).toFixed(1)} s.\n`));
+ } finally {
+ await engine.disconnect().catch(() => {});
+ }
+}
+
export async function runEmbeddings(args: string[]): Promise<void> {
const [sub, ...rest] = args;
if (!sub || sub === '--help' || sub === '-h' || sub === 'help' || rest.includes('--help')) {
@@ -150,7 +188,8 @@ export async function runEmbeddings(args: string[]): Promise<void> {
}
const json = args.includes('--json');
try {
- if (sub !== 'enable') throw opError('invalid_params', `Unknown embeddings subcommand '${sub}'.`, 'The only subcommand is enable: `gbrain embeddings enable --embedding-model <provider:model>`.');
+ if (sub === 'prewarm') return await writePrewarm(rest, json);
+ if (sub !== 'enable') throw opError('invalid_params', `Unknown embeddings subcommand '${sub}'.`, 'The subcommands are enable (`gbrain embeddings enable --embedding-model <provider:model>`) and prewarm.');
const result = await enable(parseEnableArgs(rest));
const next = (result.next_command as string[]).join(' ');
await writeStdoutFinal(json ? `${JSON.stringify(result, null, 2)}\n`
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 19b05451fb..3a191bd538 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -293,6 +293,10 @@ export async function runServe(
const sourceGuard = args.includes('--source-guard');
// 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;
+ // Opt-in vector index prewarm (core/vector-prewarm.ts): off, the serve loads nothing and reads nothing for it.
+ if (MERGED_CONFIG_BY_ENGINE.get(engine)?.serve_vector_prewarm === true) {
+ void import('../core/vector-prewarm.ts').then(m => m.prewarmAtServeStart(engine, opts.log ?? ((msg: string) => console.error(msg))));
+ }
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
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e06b2aabf9..446bfa3ba4 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -55,7 +55,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
- 'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
+ 'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index d218cccf6a..24cef0603d 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -18,4 +18,5 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off
'context.hot_memory.session_only', // facts/meta-hook.ts, read by the turn_context and context_pack IPC handlers: hot memory never falls back to other sessions' facts, 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
+ 'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off
];
diff --git a/src/core/config.ts b/src/core/config.ts
index 06a7ead68d..1da1609363 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -8,7 +8,7 @@ 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';
+import { mergeServeCliSocket, mergeServeVectorPrewarm } from './published-config.ts';
export { MERGED_CONFIG_BY_ENGINE } from './published-config.ts';
/**
@@ -313,6 +313,8 @@ export interface GBrainConfig {
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;
+ /** DB-plane `serve.vector_prewarm`: the serve prewarms the HNSW indexes into shared_buffers once at start (core/vector-prewarm.ts), default off. */
+ serve_vector_prewarm?: boolean;
/**
* v0.42 (#1981) — Retrieval Reflex. The context engine's deterministic
@@ -1227,7 +1229,7 @@ export async function loadConfigWithEngine(
: engine,
);
- return mergeServeCliSocket(merged, snapshot);
+ return mergeServeVectorPrewarm(mergeServeCliSocket(merged, snapshot), snapshot);
}
/**
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5a7fc69010..c064e55104 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -758,6 +758,9 @@ export const CODES = {
upstream_diverged: { class: 'caller', actor: 'agent', summary: "A classic source's pull cannot fast-forward: the checkout has commits that are not on the upstream and the upstream moved forward; local HEAD keeps syncing.", why: "The upstream still contains the commit this checkout last pulled, so nothing was force-pushed: bringing the upstream in beside the local commits loses nothing.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Run gbrain git commit-push --pull --path <checkout>, then gbrain sync --source <id>.' },
upstream_rewritten: { class: 'consent', actor: 'user', summary: "A classic source's upstream was force-pushed: the upstream commit the checkout last contained is not in the new upstream history, so the pull cannot fast-forward; local HEAD keeps syncing.", why: "Merging would bring back the commits the force-push removed, so the fix resets the checkout to the new upstream after the user agrees, keeping the old history under a backup ref.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then run the gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> command doctor sync_failures prints (preview with --dry-run), then gbrain sync --source <id>.' },
upstream_unknown: { class: 'consent', actor: 'user', summary: "A classic source's checkout and upstream diverged and gbrain has no record of the upstream before the fetch (first pull after an upgrade, or the recorded commit is gone), so it cannot tell a force-push from local commits; local HEAD keeps syncing.", why: "Merging could bring back commits a force-push removed; the reset preview names any local commit that was never on the upstream before anything moves.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then preview the gbrain sources reset-upstream command doctor sync_failures prints with --dry-run.' },
+ vector_prewarm_extension_missing: { class: 'host_only', actor: 'host_admin', summary: "`gbrain embeddings prewarm` was refused before reading anything because the pg_prewarm extension is not created in the brain's database (or the server does not ship it).", why: "Prewarm loads index pages into shared_buffers with pg_prewarm, the Postgres contrib function for exactly that; creating an extension needs a database owner or superuser, so gbrain never creates it itself.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Ask the database administrator to run CREATE EXTENSION IF NOT EXISTS pg_prewarm; (install the PostgreSQL contrib package first if the server lacks it), then rerun gbrain embeddings prewarm.' },
+ vector_prewarm_unsupported_engine: { class: 'caller', summary: "`gbrain embeddings prewarm` was refused because the brain is PGLite; nothing was read.", why: "Prewarm fills a Postgres server's shared_buffers so later processes find index pages cached; PGLite runs inside each gbrain process, with no server cache that outlives it.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Nothing to do on PGLite.' },
+ vector_prewarm_wont_fit: { class: 'host_only', actor: 'host_admin', summary: "`gbrain embeddings prewarm` was refused before reading anything because the brain's HNSW indexes are larger than half of shared_buffers.", why: "Prewarm loads the indexes into shared_buffers, the cache Postgres sizes and keeps; past half of it the prewarm would evict heap and keyword-index pages other reads need, so the next searches would pay first-touch reads on those instead. effective_cache_size does not decide: it is a planner hint, not memory the server holds.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Raise shared_buffers on the database host to at least twice the index size the message names and restart Postgres, or leave the indexes cold; read the fit with gbrain embeddings prewarm --dry-run --json.', fix: { argv: ['gbrain', 'embeddings', 'prewarm', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: prints the index sizes, shared_buffers, effective_cache_size and the fit, and reads no relation page.', requires_exclusive: false } },
verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },
withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },
withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },
diff --git a/src/core/published-config.ts b/src/core/published-config.ts
index 453719ebe8..ae3cf7372d 100644
--- a/src/core/published-config.ts
+++ b/src/core/published-config.ts
@@ -2,7 +2,7 @@
* 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
+ * publishes the result here for `makeContext` (ctx.config) and for `gbrain serve` (`serve_cli_socket`, `serve_vector_prewarm`), 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.
@@ -21,3 +21,13 @@ export function mergeServeCliSocket(merged: GBrainConfig, snapshot: Record<strin
if (merged.serve_cli_socket === undefined && value !== undefined) merged.serve_cli_socket = /^(1|true|on|yes)$/i.test(value.trim());
return merged;
}
+
+/**
+ * `serve.vector_prewarm` (core/vector-prewarm.ts) joins the merge the same way, from the bulk snapshot only: a serve that
+ * leaves the prewarm off does no work and no config read for it at boot.
+ */
+export function mergeServeVectorPrewarm(merged: GBrainConfig, snapshot: Record<string, string> | null): GBrainConfig {
+ const value = snapshot?.['serve.vector_prewarm'];
+ if (merged.serve_vector_prewarm === undefined && value !== undefined) merged.serve_vector_prewarm = /^(1|true|on|yes)$/i.test(value.trim());
+ return merged;
+}
diff --git a/src/core/vector-prewarm.ts b/src/core/vector-prewarm.ts
new file mode 100644
index 0000000000..8dcc76be2f
--- /dev/null
+++ b/src/core/vector-prewarm.ts
@@ -0,0 +1,173 @@
+/**
+ * Opt-in vector (HNSW) index prewarm for Postgres brains (GBRA-156).
+ *
+ * A search whose embedding has not been seen walks HNSW pages nobody has read
+ * since the last restart or eviction: on a brain whose index exceeds the cache
+ * that is 2-4.5k uncached index pages and 1.2-2.7 s of first-touch vector time.
+ * `gbrain embeddings prewarm` (and `serve.vector_prewarm` at serve start) loads
+ * every HNSW index of the brain's schema into shared_buffers with
+ * pg_prewarm(..., 'buffer') once, so later searches find those pages cached.
+ *
+ * Which cache decides: shared_buffers. pg_prewarm's 'buffer' mode loads pages
+ * into Postgres's own buffer cache, the one cache whose size the server knows
+ * (current_setting('shared_buffers')) and whose contents it keeps. The total
+ * HNSW size must fit in PREWARM_SHARED_BUFFERS_SHARE of it; past that the
+ * prewarm would evict the heap, keyword-index and catalog pages every other
+ * read needs, trading vector first touches for keyword ones. Nothing is read
+ * before this check passes: index sizes come from pg_relation_size (file
+ * sizes, no relation pages) and the settings from current_setting.
+ * effective_cache_size is read when it can be and reported, but it decides
+ * nothing: it is a planner hint the operator types in, the server never
+ * allocates it, and it says nothing about what the OS page cache holds or can
+ * keep, so a fit against it could not be honest.
+ *
+ * Local operator only: a CLI-only command (never an operation, so no MCP
+ * caller can reach it) that thin clients refuse, plus an opt-in serve-start
+ * hook that is off by default. PGLite has no server buffer cache that
+ * outlives the process, so it is refused.
+ */
+import type { BrainEngine } from './engine.ts';
+import type { Action } from './agent-output.ts';
+import { opError } from './ops/contract.ts';
+
+/** At most this share of shared_buffers may go to prewarmed HNSW pages; the rest stays for heap, keyword-index and catalog pages. */
+export const PREWARM_SHARED_BUFFERS_SHARE = 0.5;
+
+export interface VectorIndexSize { index: string; table: string; bytes: number }
+
+export interface VectorPrewarmPlan {
+ indexes: VectorIndexSize[];
+ total_bytes: number;
+ shared_buffers_bytes: number;
+ /** Reported for context only; null when the server would not say. */
+ effective_cache_size_bytes: number | null;
+ budget_bytes: number;
+ decided_by: 'shared_buffers';
+ fits: boolean;
+ /** Installed pg_prewarm version, null when the extension is not created in this database. */
+ extension_version: string | null;
+ extension_available: boolean;
+}
+
+export interface VectorPrewarmResult extends VectorPrewarmPlan {
+ dry_run: boolean;
+ mode: 'buffer';
+ /** Per index: blocks pg_prewarm loaded and how long it took (empty on a dry run). */
+ loaded: Array<{ index: string; blocks: number; ms: number }>;
+ elapsed_ms: number;
+}
+
+const MB = 1024 * 1024;
+const mb = (bytes: number) => `${Math.ceil(bytes / MB)} MB`;
+
+/** The fit decision: shared_buffers alone, against PREWARM_SHARED_BUFFERS_SHARE of it. */
+export function prewarmFits(totalBytes: number, sharedBuffersBytes: number): { fits: boolean; budget_bytes: number } {
+ const budget = Math.floor(sharedBuffersBytes * PREWARM_SHARED_BUFFERS_SHARE);
+ return { fits: totalBytes <= budget, budget_bytes: budget };
+}
+
+/** Index sizes, cache settings and extension state; reads catalogs and file sizes only, never a relation page. */
+export async function readVectorPrewarmPlan(engine: BrainEngine): Promise<VectorPrewarmPlan> {
+ const indexes = (await engine.executeRaw<{ index: string; table: string; bytes: string | number }>(
+ `SELECT c.relname AS index, t.relname AS "table", pg_relation_size(c.oid)::bigint AS bytes
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_class t ON t.oid = i.indrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_am am ON am.oid = c.relam
+ WHERE am.amname = 'hnsw' AND i.indisvalid AND n.nspname = current_schema()
+ ORDER BY 3 DESC, 1`)).map(r => ({ index: r.index, table: r.table, bytes: Number(r.bytes) }));
+ const [s] = await engine.executeRaw<{ shared_buffers: string | number; effective_cache_size: string | number | null; extension_version: string | null; extension_available: boolean }>(
+ `SELECT pg_size_bytes(current_setting('shared_buffers'))::bigint AS shared_buffers,
+ pg_size_bytes(current_setting('effective_cache_size', true))::bigint AS effective_cache_size,
+ (SELECT extversion FROM pg_extension WHERE extname = 'pg_prewarm') AS extension_version,
+ EXISTS (SELECT 1 FROM pg_available_extensions WHERE name = 'pg_prewarm') AS extension_available`);
+ const total = indexes.reduce((sum, i) => sum + i.bytes, 0);
+ const sharedBuffers = Number(s!.shared_buffers);
+ const { fits, budget_bytes } = prewarmFits(total, sharedBuffers);
+ return {
+ indexes, total_bytes: total, shared_buffers_bytes: sharedBuffers,
+ effective_cache_size_bytes: s!.effective_cache_size === null ? null : Number(s!.effective_cache_size),
+ budget_bytes, decided_by: 'shared_buffers', fits,
+ extension_version: s!.extension_version, extension_available: s!.extension_available === true,
+ };
+}
+
+const VERIFY: Action['verify'] = { argv: ['gbrain', 'embeddings', 'prewarm', '--dry-run', '--json'] };
+
+function tooLarge(plan: VectorPrewarmPlan) {
+ const needed = Math.ceil(plan.total_bytes / PREWARM_SHARED_BUFFERS_SHARE / MB);
+ return opError('vector_prewarm_wont_fit',
+ `The vector indexes total ${mb(plan.total_bytes)}, more than the ${mb(plan.budget_bytes)} prewarm budget (${PREWARM_SHARED_BUFFERS_SHARE * 100}% of shared_buffers ${mb(plan.shared_buffers_bytes)}); nothing was read.`,
+ `Raise shared_buffers to at least ${needed} MB on the database host and restart Postgres, or leave the indexes cold.`,
+ {
+ why: 'pg_prewarm loads the indexes into shared_buffers; past half of it the prewarm would evict the heap and keyword-index pages other reads need, so the next searches would pay first-touch reads on those instead. effective_cache_size is not used: it is a planner hint, not memory the server holds.',
+ fix: {
+ argv: ['psql', '-c', `ALTER SYSTEM SET shared_buffers = '${needed}MB'`], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: `shared_buffers takes effect only after a Postgres restart, and the host needs that much RAM to spare (a managed database sets it through its instance size).`,
+ user_message: `Prewarming the vector index needs shared_buffers of at least ${needed} MB on the database (it is ${mb(plan.shared_buffers_bytes)}). That is a database setting and a restart; search keeps working without it.`,
+ verify: VERIFY,
+ },
+ });
+}
+
+function extensionMissing(plan: VectorPrewarmPlan) {
+ return opError('vector_prewarm_extension_missing',
+ plan.extension_available
+ ? 'The pg_prewarm extension is not created in this database; nothing was read.'
+ : 'This Postgres server does not ship the pg_prewarm extension; nothing was read.',
+ plan.extension_available
+ ? 'Create it once as a role that may create extensions: CREATE EXTENSION IF NOT EXISTS pg_prewarm;'
+ : 'Install the PostgreSQL contrib package on the database host (pg_prewarm is part of it), then CREATE EXTENSION IF NOT EXISTS pg_prewarm;',
+ {
+ why: 'gbrain loads index pages with pg_prewarm, the Postgres contrib function that reads a relation into shared_buffers; without it there is no supported way to fill the buffer cache.',
+ fix: {
+ argv: ['psql', '-c', 'CREATE EXTENSION IF NOT EXISTS pg_prewarm'], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'Creating an extension needs a database owner or superuser (on a managed database, its extensions page).',
+ user_message: 'Prewarming the vector index needs the pg_prewarm extension in the database. Creating it is a one-time step for whoever administers the database.',
+ verify: VERIFY,
+ },
+ });
+}
+
+export function vectorPrewarmUnsupported() {
+ return opError('vector_prewarm_unsupported_engine',
+ 'Vector index prewarm runs on Postgres brains only; this brain is PGLite, and nothing was read.',
+ 'Nothing to do: PGLite runs inside this process, with no server buffer cache that outlives it.',
+ { why: 'Prewarm fills Postgres shared_buffers so later processes find index pages cached; PGLite has no shared server cache to fill.' });
+}
+
+/** Check the fit, then (unless a dry run) prewarm every HNSW index into shared_buffers, largest first. */
+export async function runVectorPrewarm(engine: BrainEngine, opts: { dryRun?: boolean } = {}): Promise<VectorPrewarmResult> {
+ if (engine.kind !== 'postgres') throw vectorPrewarmUnsupported();
+ const t0 = performance.now();
+ const plan = await readVectorPrewarmPlan(engine);
+ if (!plan.fits) throw tooLarge(plan);
+ if (!plan.extension_version && !opts.dryRun) throw extensionMissing(plan);
+ const loaded: VectorPrewarmResult['loaded'] = [];
+ if (!opts.dryRun) {
+ for (const ix of plan.indexes) {
+ const t = performance.now();
+ const blocks = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL statement_timeout = 0');
+ const [row] = await tx.executeRaw<{ blocks: string | number }>(`SELECT pg_prewarm(format('%I.%I', current_schema(), $1::text)::regclass, 'buffer')::bigint AS blocks`, [ix.index]);
+ return Number(row?.blocks ?? 0);
+ });
+ loaded.push({ index: ix.index, blocks, ms: Math.round(performance.now() - t) });
+ }
+ }
+ return { ...plan, dry_run: opts.dryRun === true, mode: 'buffer', loaded, elapsed_ms: Math.round(performance.now() - t0) };
+}
+
+/** serve.vector_prewarm: one prewarm after the serve boots, logged; a refusal or failure is logged and never stops the serve. */
+export async function prewarmAtServeStart(engine: BrainEngine, log: (line: string) => void): Promise<void> {
+ if (engine.kind !== 'postgres') { log('[gbrain serve] vector prewarm: skipped (Postgres only; this brain is PGLite)'); return; }
+ try {
+ const r = await runVectorPrewarm(engine);
+ const blocks = r.loaded.reduce((sum, l) => sum + l.blocks, 0);
+ log(`[gbrain serve] vector prewarm: loaded ${r.loaded.length} index(es), ${mb(blocks * 8192)}, into shared_buffers in ${(r.elapsed_ms / 1000).toFixed(1)} s`);
+ } catch (error) {
+ const e = error as { code?: string; message?: string };
+ log(`[gbrain serve] vector prewarm: skipped (${e.code ?? 'error'}): ${e.message ?? String(error)}`);
+ }
+}
diff --git a/test/e2e/vector-prewarm-postgres.test.ts b/test/e2e/vector-prewarm-postgres.test.ts
new file mode 100644
index 0000000000..de3e53af8c
--- /dev/null
+++ b/test/e2e/vector-prewarm-postgres.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Vector index prewarm on real Postgres (GBRA-156, core/vector-prewarm.ts):
+ * a small brain's HNSW indexes fit the test server's shared_buffers and are
+ * prewarmed block for block; the same brain under a simulated small
+ * shared_buffers (the settings statement reads a 16 kB literal in its place,
+ * everything else runs on the real server) is refused before any pg_prewarm
+ * call; without the extension the command refuses with its own code.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { readVectorPrewarmPlan, runVectorPrewarm } from '../../src/core/vector-prewarm.ts';
+
+const RUN = hasDatabase();
+let engine: PostgresEngine;
+
+/** The real engine, recording every statement; with `sharedBuffers` the settings statement reads that literal instead of the server's value. */
+function recording(sharedBuffers?: string): { engine: BrainEngine; statements: string[] } {
+ const statements: string[] = [];
+ const wrap = (target: BrainEngine): BrainEngine => new Proxy(target, {
+ get(t, prop, receiver) {
+ if (prop === 'executeRaw') {
+ return (sql: string, params?: unknown[]) => {
+ statements.push(sql);
+ const run = sharedBuffers ? sql.replace("current_setting('shared_buffers')", `'${sharedBuffers}'::text`) : sql;
+ return t.executeRaw(run, params);
+ };
+ }
+ if (prop === 'transaction') return (fn: (e: BrainEngine) => Promise<unknown>) => t.transaction(tx => fn(wrap(tx)));
+ const value = Reflect.get(t, prop, receiver);
+ return typeof value === 'function' ? value.bind(t) : value;
+ },
+ });
+ return { engine: wrap(engine), statements };
+}
+
+describe.skipIf(!RUN)('vector index prewarm on Postgres', () => {
+ beforeAll(async () => {
+ engine = await setupDB();
+ await engine.executeRaw('DROP EXTENSION IF EXISTS pg_prewarm');
+ });
+ afterAll(async () => {
+ await engine.executeRaw('DROP EXTENSION IF EXISTS pg_prewarm');
+ await teardownDB();
+ });
+
+ test('the plan reads the brain HNSW indexes, shared_buffers and effective_cache_size', async () => {
+ const plan = await readVectorPrewarmPlan(engine);
+ const [settings] = await engine.executeRaw<{ sb: string }>("SELECT pg_size_bytes(current_setting('shared_buffers'))::text AS sb");
+ expect(plan.indexes.map(i => i.index)).toContain('idx_chunks_embedding');
+ expect(plan.shared_buffers_bytes).toBe(Number(settings!.sb));
+ expect(plan.effective_cache_size_bytes).toBeGreaterThan(0);
+ expect(plan.fits).toBe(true);
+ expect(plan.extension_available).toBe(true);
+ });
+
+ test('without the extension it refuses and calls no pg_prewarm', async () => {
+ const r = recording();
+ let code: string | undefined;
+ try { await runVectorPrewarm(r.engine); } catch (e) { code = (e as { canonicalCode?: string }).canonicalCode; }
+ expect(code).toBe('vector_prewarm_extension_missing');
+ expect(r.statements.some(s => s.includes('pg_prewarm('))).toBe(false);
+ });
+
+ test('a small shared_buffers refuses before any pg_prewarm call', async () => {
+ await engine.executeRaw('CREATE EXTENSION IF NOT EXISTS pg_prewarm');
+ const r = recording('16kB');
+ let code: string | undefined;
+ try { await runVectorPrewarm(r.engine); } catch (e) { code = (e as { canonicalCode?: string }).canonicalCode; }
+ expect(code).toBe('vector_prewarm_wont_fit');
+ expect(r.statements.some(s => s.includes('pg_prewarm('))).toBe(false);
+ expect(r.statements).toHaveLength(2);
+ });
+
+ test('a fitting brain is prewarmed into shared_buffers, every block of every HNSW index', async () => {
+ await engine.executeRaw('CREATE EXTENSION IF NOT EXISTS pg_prewarm');
+ const r = recording();
+ const result = await runVectorPrewarm(r.engine);
+ expect(result.loaded.map(l => l.index)).toEqual(result.indexes.map(i => i.index));
+ for (const ix of result.indexes) expect(result.loaded.find(l => l.index === ix.index)!.blocks).toBe(ix.bytes / 8192);
+ expect(r.statements.filter(s => s.includes('pg_prewarm(')).length).toBe(result.indexes.length);
+ });
+
+ test('a dry run reads nothing', async () => {
+ const r = recording();
+ const result = await runVectorPrewarm(r.engine, { dryRun: true });
+ expect(result.loaded).toEqual([]);
+ expect(r.statements.some(s => s.includes('pg_prewarm('))).toBe(false);
+ });
+});
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 3fc491bd6d..761228b155 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -25,6 +25,7 @@
" migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
+ " embeddings prewarm [--dry-run] Load the vector indexes into shared_buffers when they fit (Postgres)",
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
@@ -250,6 +251,7 @@
" migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
+ " embeddings prewarm [--dry-run] Load the vector indexes into shared_buffers when they fit (Postgres)",
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
@@ -475,6 +477,7 @@
" migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)",
" migrate embeddings --to <p:model> Re-embed onto another embedding provider",
" embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)",
+ " embeddings prewarm [--dry-run] Load the vector indexes into shared_buffers when they fit (Postgres)",
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index d5fe25135d..599b771dbd 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -2801,6 +2801,7 @@
"search_embedding_column?: string | undefined",
"self_upgrade?: { mode?: \"auto\" | \"notify\" | \"off\"; channel?: \"latest\" | \"stable\"; mode_prompted?: boolean; quiet_hours?: { start?: number; end?: number; tz?: string; }; failed_versions?: string[]; attempting_version?: string; last_check_ts?: number; last_applied_version?: string; } | undefined",
"serve_cli_socket?: boolean | undefined",
+ "serve_vector_prewarm?: boolean | undefined",
"storage?: unknown",
"together_api_key?: string | undefined",
"voyage_api_key?: string | undefined"
@@ -6467,7 +6468,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/serve-vector-prewarm-off.test.ts b/test/serve-vector-prewarm-off.test.ts
new file mode 100644
index 0000000000..ee7944ca4c
--- /dev/null
+++ b/test/serve-vector-prewarm-off.test.ts
@@ -0,0 +1,71 @@
+/**
+ * serve.vector_prewarm is opt-in (core/vector-prewarm.ts). A serve that leaves it off loads nothing under
+ * src/core/vector-prewarm.ts and makes no engine call or log line for it; one whose published config merge turns it on
+ * loads it once the boot is done. Each boot runs in its own bun process, like test/serve-cli-socket-off.test.ts, so a
+ * module another test already loaded cannot hide an import.
+ */
+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 { published, out } = JSON.parse(process.env.BOOT_SPEC);
+const calls = [];
+const engine = {
+ kind: 'pglite',
+ getConfig: async (key) => { calls.push('getConfig(' + key + ')'); return null; },
+ getAllConfig: async () => { calls.push('getAllConfig()'); return {}; },
+ executeRaw: async (sql) => { calls.push('executeRaw(' + sql.slice(0, 40) + ')'); return []; },
+ disconnect: async () => { calls.push('disconnect()'); },
+};
+(await import('./src/core/config.ts')).MERGED_CONFIG_BY_ENGINE.set(engine, { engine: 'pglite', ...(published ? { serve_vector_prewarm: published === 'on' } : {}) });
+const logs = [];
+await runServe(engine, [], {
+ 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.endsWith('/src/core/vector-prewarm.ts'));
+writeFileSync(out, JSON.stringify({ calls, modules, logs }));
+process.exit(0);
+`;
+
+async function boot(published: '' | 'on' | 'off'): Promise<Boot> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-serve-prewarm-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({ 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 vector prewarm off', () => {
+ test('unset or false: loads no prewarm module, makes no extra engine call and logs nothing for it', async () => {
+ const [unset, off, on] = await Promise.all([boot(''), boot('off'), boot('on')]);
+ for (const b of [unset, off]) {
+ expect(b.modules).toEqual([]);
+ expect(b.logs.filter(line => line.includes('vector prewarm'))).toEqual([]);
+ expect(b.calls.toSorted()).toEqual(on.calls.toSorted());
+ }
+ expect(unset.calls).not.toContain('getConfig(serve.vector_prewarm)');
+ }, 60_000);
+
+ test('serve_vector_prewarm in the published merge runs it after the boot (the control: the probe sees it)', async () => {
+ const on = await boot('on');
+ expect(on.modules).toHaveLength(1);
+ expect(on.logs).toContain('[gbrain serve] vector prewarm: skipped (Postgres only; this brain is PGLite)');
+ expect(on.calls).not.toContain('getConfig(serve.vector_prewarm)');
+ }, 60_000);
+});
diff --git a/test/vector-prewarm.test.ts b/test/vector-prewarm.test.ts
new file mode 100644
index 0000000000..2418c130ac
--- /dev/null
+++ b/test/vector-prewarm.test.ts
@@ -0,0 +1,145 @@
+/**
+ * Opt-in vector index prewarm (GBRA-156, core/vector-prewarm.ts): the fit check
+ * decides on shared_buffers alone, a refusal reads nothing (no pg_prewarm call,
+ * no transaction), a missing extension refuses with its own code, PGLite is
+ * refused without a single statement, and the CLI wires it under
+ * `gbrain embeddings prewarm`. The real-Postgres path is
+ * test/e2e/vector-prewarm-postgres.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PREWARM_SHARED_BUFFERS_SHARE, prewarmFits, runVectorPrewarm } from '../src/core/vector-prewarm.ts';
+import { mergeServeVectorPrewarm } from '../src/core/published-config.ts';
+import { renderCliError } from '../src/core/agent-output.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const GB = 1024 ** 3;
+
+interface Fake { engine: BrainEngine; statements: string[]; transactions: () => number }
+
+function fake(o: { kind?: 'postgres' | 'pglite'; indexes?: Array<[string, number]>; sharedBuffers?: number; ecs?: number | null; ext?: string | null; available?: boolean }): Fake {
+ const statements: string[] = [];
+ let transactions = 0;
+ const indexes = o.indexes ?? [['idx_chunks_embedding', 11 * GB], ['idx_chunks_embedding_image', 16384]];
+ const engine = {
+ kind: o.kind ?? 'postgres',
+ async executeRaw(sql: string, params?: unknown[]) {
+ statements.push(sql);
+ if (sql.includes('pg_relation_size')) return indexes.map(([index, bytes]) => ({ index, table: 'content_chunks', bytes: String(bytes) }));
+ if (sql.includes("current_setting('shared_buffers')")) return [{ shared_buffers: String(o.sharedBuffers ?? 8 * GB), effective_cache_size: o.ecs === null ? null : String(o.ecs ?? 24 * GB), extension_version: o.ext === undefined ? '1.2' : o.ext, extension_available: o.available ?? true }];
+ if (sql.startsWith('SET LOCAL')) return [];
+ if (sql.includes('pg_prewarm(')) return [{ blocks: String(indexes.find(([name]) => name === params?.[0])![1] / 8192) }];
+ throw new Error('unexpected statement: ' + sql);
+ },
+ async transaction<T>(fn: (e: BrainEngine) => Promise<T>) { transactions++; return fn(engine as unknown as BrainEngine); },
+ };
+ return { engine: engine as unknown as BrainEngine, statements, transactions: () => transactions };
+}
+
+const prewarmCalls = (f: Fake) => f.statements.filter(s => s.includes('pg_prewarm('));
+const codeOf = async (p: Promise<unknown>) => { try { await p; return 'resolved'; } catch (e) { return (e as { canonicalCode?: string }).canonicalCode; } };
+
+describe('prewarm fit check', () => {
+ test('shared_buffers decides, at half of it', () => {
+ expect(PREWARM_SHARED_BUFFERS_SHARE).toBe(0.5);
+ expect(prewarmFits(11 * GB, 8 * GB)).toEqual({ fits: false, budget_bytes: 4 * GB });
+ expect(prewarmFits(11 * GB, 26 * GB)).toEqual({ fits: true, budget_bytes: 13 * GB });
+ expect(prewarmFits(4 * GB, 8 * GB).fits).toBe(true);
+ expect(prewarmFits(4 * GB + 1, 8 * GB).fits).toBe(false);
+ });
+
+ test('an index that does not fit is refused before any page is read, whatever effective_cache_size says', async () => {
+ const f = fake({ sharedBuffers: 8 * GB, ecs: 64 * GB });
+ expect(await codeOf(runVectorPrewarm(f.engine))).toBe('vector_prewarm_wont_fit');
+ expect(prewarmCalls(f)).toEqual([]);
+ expect(f.transactions()).toBe(0);
+ expect(f.statements).toHaveLength(2);
+ });
+
+ test('the refusal carries the agent-operator contract: why, a host_admin fix naming the needed size, a read-only verify', async () => {
+ const f = fake({ sharedBuffers: 8 * GB });
+ let error: unknown;
+ try { await runVectorPrewarm(f.engine); } catch (e) { error = e; }
+ const env = JSON.parse(renderCliError(error, { json: true, command: 'embeddings', tty: false }).stdout!);
+ expect(env.code).toBe('vector_prewarm_wont_fit');
+ expect(env.class).toBe('host_only');
+ expect(env.message).toContain('nothing was read');
+ expect(env.why).toContain('effective_cache_size');
+ expect(env.fix.next).toBe('tell_user_to_run');
+ expect(env.fix.argv).toEqual(['psql', '-c', "ALTER SYSTEM SET shared_buffers = '22529MB'"]);
+ expect(env.fix.verify.argv).toEqual(['gbrain', 'embeddings', 'prewarm', '--dry-run', '--json']);
+ });
+
+ test('a missing pg_prewarm extension is refused with its own code and reads nothing', async () => {
+ const f = fake({ sharedBuffers: 32 * GB, ext: null });
+ expect(await codeOf(runVectorPrewarm(f.engine))).toBe('vector_prewarm_extension_missing');
+ expect(prewarmCalls(f)).toEqual([]);
+ const g = fake({ sharedBuffers: 32 * GB, ext: null, available: false });
+ let error: unknown;
+ try { await runVectorPrewarm(g.engine); } catch (e) { error = e; }
+ expect((error as Error).message).toContain('does not ship');
+ });
+
+ test('a fitting index is prewarmed into shared_buffers, largest first, each without a statement timeout', async () => {
+ const f = fake({ sharedBuffers: 26 * GB });
+ const r = await runVectorPrewarm(f.engine);
+ expect(r.fits).toBe(true);
+ expect(r.decided_by).toBe('shared_buffers');
+ expect(r.mode).toBe('buffer');
+ expect(r.loaded.map(l => [l.index, l.blocks])).toEqual([['idx_chunks_embedding', 11 * GB / 8192], ['idx_chunks_embedding_image', 2]]);
+ expect(prewarmCalls(f).every(s => s.includes("'buffer'"))).toBe(true);
+ expect(f.transactions()).toBe(2);
+ expect(f.statements.filter(s => s === 'SET LOCAL statement_timeout = 0')).toHaveLength(2);
+ });
+
+ test('a dry run reports the fit and reads nothing, even before the extension exists', async () => {
+ const f = fake({ sharedBuffers: 26 * GB, ext: null });
+ const r = await runVectorPrewarm(f.engine, { dryRun: true });
+ expect(r).toMatchObject({ dry_run: true, fits: true, loaded: [], extension_version: null, effective_cache_size_bytes: 24 * GB });
+ expect(prewarmCalls(f)).toEqual([]);
+ });
+
+ test('PGLite is refused without a statement', async () => {
+ const f = fake({ kind: 'pglite' });
+ expect(await codeOf(runVectorPrewarm(f.engine))).toBe('vector_prewarm_unsupported_engine');
+ expect(f.statements).toEqual([]);
+ });
+});
+
+describe('serve.vector_prewarm config merge', () => {
+ test('off unless the snapshot says so', () => {
+ expect(mergeServeVectorPrewarm({ engine: 'postgres' }, null).serve_vector_prewarm).toBeUndefined();
+ expect(mergeServeVectorPrewarm({ engine: 'postgres' }, {}).serve_vector_prewarm).toBeUndefined();
+ expect(mergeServeVectorPrewarm({ engine: 'postgres' }, { 'serve.vector_prewarm': ' true ' }).serve_vector_prewarm).toBe(true);
+ expect(mergeServeVectorPrewarm({ engine: 'postgres' }, { 'serve.vector_prewarm': 'off' }).serve_vector_prewarm).toBe(false);
+ });
+});
+
+describe('gbrain embeddings prewarm (CLI)', () => {
+ async function cli(args: string[]): Promise<{ code: number; stdout: string }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-prewarm-cli-'));
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, 'brain.pglite') }));
+ const p = Bun.spawn(['bun', '--no-env-file', 'src/cli.ts', 'embeddings', ...args], { cwd: process.cwd(), env: { ...process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' }, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, code] = await Promise.all([new Response(p.stdout).text(), p.exited]);
+ return { code, stdout };
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }
+
+ test('a PGLite brain is refused with the unsupported-engine code', async () => {
+ const r = await cli(['prewarm', '--json']);
+ expect(r.code).not.toBe(0);
+ expect(JSON.parse(r.stdout).code).toBe('vector_prewarm_unsupported_engine');
+ }, 60_000);
+
+ test('an unknown option is refused', async () => {
+ const r = await cli(['prewarm', '--bogus', '--json']);
+ expect(r.code).not.toBe(0);
+ expect(JSON.parse(r.stdout).code).toBe('unknown_flag');
+ }, 60_000);
+});