Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): capped operator knob for the Postgres keyword statement timeout and a keyword_plan doctor canary (Refs #6495, wave 16)
garrytan0690569da03a
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex afe6cf4f41..9d327e619d 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -29,7 +29,7 @@ link it here rather than raising the cap.| [Agent operator contract](key-files/agent-contract.md) | `agent-output.ts`, error registry + docs, notice ledger, `isCallable`, `--json` guard, contract scanner || [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` || [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` and `src/commands/doctor/` |-| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `doctor/checks/routing-federation.ts`, `git-convergence.ts`, `dream-retriage.ts` to `embed.ts` |+| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `doctor/checks/routing-federation.ts`, `git-convergence.ts`, `keyword-plan.ts`, `dream-retriage.ts` to `embed.ts` || [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/extract-timeline-db.ts` || [Commands (3/6, continued)](key-files/commands-3-continued.md) | `src/commands/features.ts` through `src/commands/frontmatter-install-hook.ts` || [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `src/commands/pglite-repair.ts` |diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex e29e7b4d41..3c11d5f95f 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -38,6 +38,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.+- `src/commands/config/keyword-timeout-value.ts` — `config set` value check for `search.keyword_statement_timeout_ms` (#6495): a value outside 1000..60000 or not an integer is refused (`invalid_params`, exit 2, a `config get` verify, nothing written) because the Postgres engine reads a stored value outside the range as the default; called from `setConfigWithDecideHooks` for every `search.*` key. Pinned by `test/keyword-statement-timeout-knob-6495.test.ts`.- `src/commands/config/facts-values.ts` — `config set` value checks for `facts.*` keys, called from `setConfigWithDecideHooks` before the write: `facts.page_write_notability_filter` (#6231) must be a `NOTABILITY_FILTERS` value (`invalid_params` with a `config get` verify, nothing written), and `facts.drain_*` keeps `drain-config.ts`'s validation. Pinned by `test/config-set.test.ts`.- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (the user's approval for `--install`: `installConsent` asks through `requireConsent`, effects `credentials` + `persistent_install`, via the `isTTY`/`promptYesNo` seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex b9cedb4193..65b8fd73cc 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -20,4 +20,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.+- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 45964b940b..5c1d668f29 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -40,7 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` file-plane value at connect, else the DB plane's row, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.- `src/core/snapshot-schema-inputs.ts` — the inputs of the PGLite snapshot schema hash (`computeSnapshotSchemaHash` in `pglite-engine.ts` hashes each file's raw bytes). Computed, not hand-kept: the static import closure (`import`, `export ... from`; type-only imports skipped) of `SNAPSHOT_SCHEMA_ROOTS` (`pglite-schema.ts`, `schema-migrations/registry.generated.ts`, `migrate.ts`, `engine-sql/bootstrap.ts`) plus `SNAPSHOT_SCHEMA_LEAVES`; every literal dynamic `import()` inside the closure must be classified as a leaf or in `SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED`. Pure (the caller supplies file access). `test/snapshot-inputs-closure.test.ts` names any missing file and checks every `pglite-snapshot-*` CI cache key covers the same inputs.@@ -53,4 +53,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, slug, source_id, timeline, knowledge_revision` plus whether a `fact_withdrawals`/`fact_purges` row covers the page or its whole source), takes the seal's effective timeline (the raw column, or for a withdrawn/purged page `readPageSnapshot`'s overlaid timeline, so a database withdrawal never returns to the vector), sanitizes it with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). Each statement scans at most `BACKFILL_RANGE` (50 000) ids past the cursor and rebuilds at most `BACKFILL_BATCH_SIZE` (5000) of them, never one transaction; the cursor advances to the range end even when nothing matched (so a filtered run on a brain with no CJK text never scans the whole table in one statement), and the run stops at the max(id) the first batch read; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`, `test/search-vector-backfill-withdrawal.test.ts`, `test/search-vector-backfill-range.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort discards the transaction's connection through the begin handle's `discard()`, so the server rolls the transaction back and the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause`; an already-aborted signal rejects before BEGIN); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort discards the transaction's connection through the begin handle's `discard()`, so the server rolls the transaction back and the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause`; an already-aborted signal rejects before BEGIN); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex 9e29cc4f55..d6c44b658f 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -150,6 +150,18 @@ Seven of the knobs deserve a sentence:one capped retry (see [multi-language FTS](multi-language-fts.md)). A cutarm reports `keyword_candidates_incomplete`; another value is refusedwith exit 2.+- **`keyword_statement_timeout_ms`** (Postgres only; config key+ `search.keyword_statement_timeout_ms`, integer milliseconds, default 8000,+ range 1000 to 60000; for example+ `gbrain config set search.keyword_statement_timeout_ms 20000`) is the+ transaction-local `statement_timeout` around every keyword, keyword-count,+ keyword-page, title and CJK search statement. It is an operator knob, read+ once per connection (restart `gbrain serve` or the workers after setting+ it) and never taken from a request; another value is refused with exit 2.+ A keyword statement the bound cancels fails open to the vector arm+ (`keyword_arm_failed`); doctor's `keyword_plan` check warns when the+ brain's commonest term is near the bound (see+ [troubleshooting](troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain)).- **`hnsw_iterative_scan`** (Postgres with pgvector 0.8+; config key`search.hnsw_iterative_scan`, string, default `relaxed_order`, one of`relaxed_order | strict_order | off`; env `GBRAIN_HNSW_ITERATIVE_SCAN`diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex dd79691b5a..af557e8ed3 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -53,6 +53,7 @@| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` || [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` || [Search answers look keyword-only on a large Postgres brain](#hybrid-search-returns-only-keyword-hits) | read doctor's `vector_plan`; run the index command it prints | brain host | none | `gbrain doctor --only vector_plan --json` |+| [Broad keyword queries take about 8 s and come back vector-only (`keyword_arm_failed`) on a large Postgres brain](#keyword-search-times-out-on-a-large-postgres-brain) | read doctor's `keyword_plan`; narrow with `--source-id`, or raise `search.keyword_statement_timeout_ms` on the brain host and restart the serving process | brain host | none | `gbrain doctor --only keyword_plan --json` || A second `gbrain serve` cannot open the brain | the readiness `harness_wiring` fix: every session shares one `gbrain serve --http` | user | `persistent_install`, `credentials` | `gbrain doctor --only harness_wiring --json` || `harness_wiring` reports `http_serve_unreachable` or `http_serve_unhealthy` for an HTTP registration | nothing automatic: doctor probed the registered `/health` without credentials and the endpoint did not answer as a healthy gbrain server; check the URL in the harness config and the server it points at (a hosted brain is its operator's). A `wired_running` verdict with `mcp_access: unverified` proves a listener only: confirm tools in a new session | user | none | `gbrain doctor --only harness_wiring --json` || A tool the fix names is missing after a serve recovered | restart the gbrain MCP server in the harness, or start a new session ([why](../protocol/AGENT_OPERATOR_v1.md#tool-catalog-changes-toolslist_changed)) | user | none | list the tools again |@@ -369,6 +370,56 @@ report the regression:The guard is temporary. The release that retires it prints a one-time noticewhen the inert setting is still present.+## Keyword search times out on a large Postgres brain++**Symptom.** On a large Postgres brain (hundreds of thousands of pages), a+broad `gbrain search` or `gbrain query` with common words takes about 8+seconds and comes back with only vector hits; search metadata carries+`keyword_arm_failed`, and the server log says `canceling statement due to+statement timeout` (SQLSTATE 57014). The strict keyword statement ranks every+matching chunk before its `LIMIT`, so its cost grows with how common the terms+are, and the commonest terms cannot finish inside the keyword statement bound.+An arm that timed out is not evidence of absence: the pages exist, the arm+could not rank them in time.++**Say to your agent:** *"Check whether keyword search is hitting its time+limit"* — the agent runs `gbrain doctor` and reads the `keyword_plan` check.++`gbrain doctor` reports `keyword_plan` (Postgres only):++- `ok`: the brain's commonest keyword term (from the planner's statistics for+ `content_chunks.search_vector`) is counted inside half of the bound; the+ message shows the plan the planner chose for it.+- skipped: PGLite (no statement timeout), fewer than 10,000 chunks, or no+ planner statistics yet (run `ANALYZE content_chunks` on the brain host, or+ let the next sync refresh them).+- warn, `canary_timed_out` or `canary_slow`: the commonest term's bounded count+ did not finish in 2 s, or took more than half of the bound. Broad queries on+ this brain will hit the bound. One canary term is not workload coverage, and+ a timed-out count is never "no matches".++**The bound is an operator knob.** `search.keyword_statement_timeout_ms`+(integer milliseconds, default 8000, range 1000 to 60000) is the+transaction-local `statement_timeout` the Postgres engine sets around every+keyword, keyword-count, keyword-page, title and CJK search statement. A remote+caller cannot change it, and `gbrain config set` refuses a value outside the+range (exit 2, nothing written). It is read once per connection, so:++1. Set it on the brain host: `gbrain config set search.keyword_statement_timeout_ms 20000`+ (or `search.keyword_statement_timeout_ms` under `search` in the config file,+ which wins over the database value).+2. Restart the process that runs searches (`gbrain serve`, autopilot, job+ workers); the next CLI command picks it up by itself.+3. Confirm with `gbrain doctor --only keyword_plan --json`: `details.timeout_ms`+ shows the value in effect.++A longer bound buys time, not a cheaper statement: a query whose terms match+most of the corpus still reads and ranks every match, so prefer narrowing with+`--source-id` (MCP `source_id`) or `match: "keyword"` paging, and follow+[#6495](https://github.com/garrytan/gbrain/issues/6495) for the bounded+candidate set that will answer broad terms from a capped set instead of+failing open.+## Global maintenance timeouts**Doctor warns `global_maintenance_timeouts`, or late maintenance phasesdiff --git a/llms-full.txt b/llms-full.txtindex 4ae3aad621..7eaf5e766c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9954,6 +9954,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` || [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` || [Search answers look keyword-only on a large Postgres brain](#hybrid-search-returns-only-keyword-hits) | read doctor's `vector_plan`; run the index command it prints | brain host | none | `gbrain doctor --only vector_plan --json` |+| [Broad keyword queries take about 8 s and come back vector-only (`keyword_arm_failed`) on a large Postgres brain](#keyword-search-times-out-on-a-large-postgres-brain) | read doctor's `keyword_plan`; narrow with `--source-id`, or raise `search.keyword_statement_timeout_ms` on the brain host and restart the serving process | brain host | none | `gbrain doctor --only keyword_plan --json` || A second `gbrain serve` cannot open the brain | the readiness `harness_wiring` fix: every session shares one `gbrain serve --http` | user | `persistent_install`, `credentials` | `gbrain doctor --only harness_wiring --json` || `harness_wiring` reports `http_serve_unreachable` or `http_serve_unhealthy` for an HTTP registration | nothing automatic: doctor probed the registered `/health` without credentials and the endpoint did not answer as a healthy gbrain server; check the URL in the harness config and the server it points at (a hosted brain is its operator's). A `wired_running` verdict with `mcp_access: unverified` proves a listener only: confirm tools in a new session | user | none | `gbrain doctor --only harness_wiring --json` || A tool the fix names is missing after a serve recovered | restart the gbrain MCP server in the harness, or start a new session ([why](../protocol/AGENT_OPERATOR_v1.md#tool-catalog-changes-toolslist_changed)) | user | none | list the tools again |@@ -10270,6 +10271,56 @@ report the regression:The guard is temporary. The release that retires it prints a one-time noticewhen the inert setting is still present.+## Keyword search times out on a large Postgres brain++**Symptom.** On a large Postgres brain (hundreds of thousands of pages), a+broad `gbrain search` or `gbrain query` with common words takes about 8+seconds and comes back with only vector hits; search metadata carries+`keyword_arm_failed`, and the server log says `canceling statement due to+statement timeout` (SQLSTATE 57014). The strict keyword statement ranks every+matching chunk before its `LIMIT`, so its cost grows with how common the terms+are, and the commonest terms cannot finish inside the keyword statement bound.+An arm that timed out is not evidence of absence: the pages exist, the arm+could not rank them in time.++**Say to your agent:** *"Check whether keyword search is hitting its time+limit"* — the agent runs `gbrain doctor` and reads the `keyword_plan` check.++`gbrain doctor` reports `keyword_plan` (Postgres only):++- `ok`: the brain's commonest keyword term (from the planner's statistics for+ `content_chunks.search_vector`) is counted inside half of the bound; the+ message shows the plan the planner chose for it.+- skipped: PGLite (no statement timeout), fewer than 10,000 chunks, or no+ planner statistics yet (run `ANALYZE content_chunks` on the brain host, or+ let the next sync refresh them).+- warn, `canary_timed_out` or `canary_slow`: the commonest term's bounded count+ did not finish in 2 s, or took more than half of the bound. Broad queries on+ this brain will hit the bound. One canary term is not workload coverage, and+ a timed-out count is never "no matches".++**The bound is an operator knob.** `search.keyword_statement_timeout_ms`+(integer milliseconds, default 8000, range 1000 to 60000) is the+transaction-local `statement_timeout` the Postgres engine sets around every+keyword, keyword-count, keyword-page, title and CJK search statement. A remote+caller cannot change it, and `gbrain config set` refuses a value outside the+range (exit 2, nothing written). It is read once per connection, so:++1. Set it on the brain host: `gbrain config set search.keyword_statement_timeout_ms 20000`+ (or `search.keyword_statement_timeout_ms` under `search` in the config file,+ which wins over the database value).+2. Restart the process that runs searches (`gbrain serve`, autopilot, job+ workers); the next CLI command picks it up by itself.+3. Confirm with `gbrain doctor --only keyword_plan --json`: `details.timeout_ms`+ shows the value in effect.++A longer bound buys time, not a cheaper statement: a query whose terms match+most of the corpus still reads and ranks every match, so prefer narrowing with+`--source-id` (MCP `source_id`) or `match: "keyword"` paging, and follow+[#6495](https://github.com/garrytan/gbrain/issues/6495) for the bounded+candidate set that will answer broad terms from a capped set instead of+failing open.+## Global maintenance timeouts**Doctor warns `global_maintenance_timeouts`, or late maintenance phasesdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 2e6873a30a..cde3171b7a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,9 +21,9 @@ src/core/import-file.ts 2027 ratchet +2: pre-publication withdrawal validation;src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3026 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts)-src/core/postgres-engine.ts 3030 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts)+src/core/postgres-engine.ts 3042 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts)src/core/search/hybrid.ts 1632 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)-src/core/types.ts 2292 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts)+src/core/types.ts 2294 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/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 refreshsrc/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 1955 ratchet +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)+src/core/config.ts 1961 ratchet +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)src/core/bootstrap/harness.ts 2610 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)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 optionsrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)@@ -44,4 +44,4 @@ src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subsetsrc/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)-src/commands/config.ts 1507 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook+src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)diff --git a/src/commands/config.ts b/src/commands/config.tsindex a13db21e91..2bb281ac88 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -397,6 +397,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:if (err) { console.error(`[config] ${err}`); process.exit(1); }}if (key.startsWith('loops.')) (await import('./config/loops-values.ts')).refuseInvalidLoopsConfigValue(key, value);+ if (key.startsWith('search.')) (await import('./config/keyword-timeout-value.ts')).refuseInvalidKeywordTimeoutValue(key, value);if (key === 'persistence.max_claim_ms') {const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');const err = validateMaxClaimConfigValue(key, value);diff --git a/src/commands/config/keyword-timeout-value.ts b/src/commands/config/keyword-timeout-value.tsnew file mode 100644index 0000000000..ca97c1fccd--- /dev/null+++ b/src/commands/config/keyword-timeout-value.ts@@ -0,0 +1,22 @@+/**+ * `config set` value check for `search.keyword_statement_timeout_ms` (#6495):+ * nothing is written when the value is outside the range the Postgres engine+ * would accept, because a stored value outside it reads as the default.+ */+import { exitCliError, usageError } from '../../cli/cli-error.ts';+import {+ KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS,+ KEYWORD_STATEMENT_TIMEOUT_KEY,+ KEYWORD_STATEMENT_TIMEOUT_MAX_MS,+ keywordStatementTimeoutValueProblem,+} from '../../core/postgres-engine/keyword-statement-timeout.ts';++export function refuseInvalidKeywordTimeoutValue(key: string, value: string): void {+ if (key !== KEYWORD_STATEMENT_TIMEOUT_KEY) return;+ const problem = keywordStatementTimeoutValueProblem(value);+ if (!problem) return;+ exitCliError(usageError(problem, `Re-run with an integer number of milliseconds, e.g. gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} ${KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS} (the cap is ${KEYWORD_STATEMENT_TIMEOUT_MAX_MS}).`, {+ why: 'The Postgres engine reads the keyword statement timeout once per connection and treats a value outside 1000..60000 as the default, so writing it would change nothing.',+ fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false },+ }), 'config');+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 41503d7dfc..3cb102df2c 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -318,6 +318,7 @@ export const timelineHistoryEntry: DoctorEntry = {'writer_version','self_capture','vector_plan',+ 'keyword_plan','stale_embedding_effects','google_file_modes','extractor_facts_expired',diff --git a/src/commands/doctor/checks/keyword-plan.ts b/src/commands/doctor/checks/keyword-plan.tsnew file mode 100644index 0000000000..78d5d05d8e--- /dev/null+++ b/src/commands/doctor/checks/keyword-plan.ts@@ -0,0 +1,137 @@+/**+ * keyword_plan (#6495): a read-only canary for the Postgres keyword arm's+ * statement bound. The strict keyword statement ranks every matching chunk+ * before its LIMIT, so its cost grows with how common the query's terms are;+ * on a large brain the commonest terms cannot finish inside+ * `search.keyword_statement_timeout_ms` and the arm fails open to the vector+ * arm (`keyword_arm_failed`). This check takes the commonest lexeme the+ * planner knows for `content_chunks.search_vector` (`pg_stats`), EXPLAINs+ * (no ANALYZE) the strict page-count statement for it and times the engine's+ * own bounded count (`countKeywordPages`, 2 s), then warns when that count+ * times out or already spends more than half the configured bound.+ *+ * It names the knob and its range, says that one canary term is not workload+ * coverage, and never reports a timed-out count as "no matches". Skipped on+ * PGLite (no statement timeout), below 10,000 chunks (`pg_class.reltuples`)+ * and when the planner has no statistics for the column.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { loadConfig, loadConfigWithEngine } from '../../../core/config.ts';+import {+ KEYWORD_STATEMENT_TIMEOUT_KEY,+ KEYWORD_STATEMENT_TIMEOUT_MAX_MS,+ KEYWORD_STATEMENT_TIMEOUT_MIN_MS,+ resolveKeywordStatementTimeoutMs,+} from '../../../core/postgres-engine/keyword-statement-timeout.ts';+import { isStatementTimeoutError } from '../../../core/retry-matcher.ts';+import { buildKeywordCountStatement } from '../../../core/search/keyword-statement.ts';++const name = 'keyword_plan';+const DOCS = 'docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain';+export const KEYWORD_PLAN_MIN_CHUNKS = 10_000;+export const KEYWORD_PLAN_CANARY_TIMEOUT_MS = 2_000;++export type KeywordPlanCount = { outcome: 'counted'; pages: number; ms: number } | { outcome: 'timed_out'; ms: number };++/** The database reads behind the check; tests inject a fake to drive each outcome. */+export interface KeywordPlanProbe {+ /** Planner row estimate for content_chunks (-1 when never analyzed). */+ chunkEstimate(): Promise<number>;+ /** The commonest lexeme in content_chunks.search_vector and its estimated share of chunks, or null without statistics. */+ canary(): Promise<{ term: string; share: number } | null>;+ /** Scan nodes over content_chunks in the plan of the strict page-count statement for the term. */+ explain(term: string): Promise<string[]>;+ /** The engine's bounded strict page count for the term, timed. */+ count(term: string, timeoutMs: number): Promise<KeywordPlanCount>;+}++interface PlanNode { 'Node Type'?: string; 'Index Name'?: string; 'Relation Name'?: string; Plans?: PlanNode[]; Plan?: PlanNode }++function chunkScans(node: PlanNode | undefined, out: string[] = []): string[] {+ if (!node) return out;+ if (node['Relation Name'] === 'content_chunks') out.push(node['Index Name'] ? `${node['Node Type']} using ${node['Index Name']}` : String(node['Node Type']));+ for (const child of node.Plans ?? []) chunkScans(child, out);+ return out;+}++export function engineKeywordPlanProbe(engine: BrainEngine): KeywordPlanProbe {+ return {+ async chunkEstimate() {+ const [row] = await engine.executeRaw<{ reltuples: number }>(`SELECT reltuples::float8 AS reltuples FROM pg_class WHERE oid = to_regclass('content_chunks')`);+ return Number(row?.reltuples ?? -1);+ },+ async canary() {+ const [row] = await engine.executeRaw<{ term: string | null; share: number | null }>(+ `SELECT e.term, f.share+ FROM pg_stats s,+ LATERAL unnest(s.most_common_elems::text::text[]) WITH ORDINALITY AS e(term, i),+ LATERAL unnest(s.most_common_elem_freqs) WITH ORDINALITY AS f(share, j)+ WHERE s.schemaname = 'public' AND s.tablename = 'content_chunks' AND s.attname = 'search_vector' AND e.i = f.j+ ORDER BY f.share DESC+ LIMIT 1`);+ return row?.term ? { term: row.term, share: Number(row.share ?? 0) } : null;+ },+ async explain(term) {+ const statement = buildKeywordCountStatement(term, undefined);+ if (!statement) return [];+ const rows = await engine.executeRaw<Record<string, unknown>>(`EXPLAIN (FORMAT JSON) ${statement.sql}`, statement.params);+ const plan = rows[0] ? (Object.values(rows[0])[0] as PlanNode[] | string) : undefined;+ const parsed = typeof plan === 'string' ? (JSON.parse(plan) as PlanNode[]) : plan;+ return chunkScans(parsed?.[0]?.Plan);+ },+ async count(term, timeoutMs) {+ const started = performance.now();+ try {+ const pages = await engine.countKeywordPages(term, { timeoutMs });+ return { outcome: 'counted', pages, ms: Math.round(performance.now() - started) };+ } catch (error) {+ if (isStatementTimeoutError(error)) return { outcome: 'timed_out', ms: Math.round(performance.now() - started) };+ throw error;+ }+ },+ };+}++export async function keywordPlanCheck(engine: BrainEngine, probe: KeywordPlanProbe = engineKeywordPlanProbe(engine)): Promise<Check> {+ if (engine.kind !== 'postgres') {+ return { name, status: 'ok', message: 'Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.',+ details: { outcome: 'skipped', reason: 'pglite' } };+ }+ try {+ const cfg = await loadConfigWithEngine(engine).catch(() => loadConfig());+ const timeoutMs = resolveKeywordStatementTimeoutMs(cfg?.search?.keyword_statement_timeout_ms, undefined);+ const knob = `${KEYWORD_STATEMENT_TIMEOUT_KEY} = ${timeoutMs} ms (range ${KEYWORD_STATEMENT_TIMEOUT_MIN_MS}-${KEYWORD_STATEMENT_TIMEOUT_MAX_MS})`;+ const base = { timeout_ms: timeoutMs, canary_timeout_ms: KEYWORD_PLAN_CANARY_TIMEOUT_MS, docs: DOCS };+ const chunks = await probe.chunkEstimate();+ if (chunks < KEYWORD_PLAN_MIN_CHUNKS) {+ return { name, status: 'ok', message: `Skipped: fewer than ${KEYWORD_PLAN_MIN_CHUNKS} chunks by the planner's estimate; the keyword statements finish well inside ${knob}.`,+ details: { ...base, outcome: 'skipped', reason: 'small_brain' } };+ }+ const canary = await probe.canary();+ if (!canary) {+ return { name, status: 'ok', message: `Skipped: the planner has no statistics for content_chunks.search_vector yet (run ANALYZE content_chunks on the brain host, or let the next sync refresh them); the keyword bound is ${knob}.`,+ details: { ...base, outcome: 'skipped', reason: 'no_statistics' } };+ }+ const percent = `${(canary.share * 100).toFixed(1)}%`;+ const scans = await probe.explain(canary.term);+ const count = await probe.count(canary.term, Math.min(KEYWORD_PLAN_CANARY_TIMEOUT_MS, timeoutMs));+ const details = { ...base, chunks_estimate: chunks, canary_term: canary.term, canary_share: canary.share, plan_scans: scans, count };+ const coverage = `One canary term is not workload coverage: other common terms, source scopes and OR fallbacks are not measured here. See ${DOCS}.`;+ if (count.outcome === 'timed_out') {+ return { name, status: 'warn', details: { ...details, outcome: 'canary_timed_out' },+ message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) did not finish a strict page count within ${count.ms} ms, so broad keyword queries on this brain are likely to hit ${knob} and fail open to the vector arm (keyword_arm_failed). `+ + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart gbrain serve or the workers) buys time, not a cheaper statement: ranking cost grows with the number of matching chunks (#6495); narrow queries with --source-id / source_id. Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ }+ if (count.ms > timeoutMs / 2) {+ return { name, status: 'warn', details: { ...details, outcome: 'canary_slow' },+ message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) took ${count.ms} ms for a strict page count, more than half of ${knob}; a slightly broader query or a busier host will hit the bound and fail open to the vector arm (keyword_arm_failed). `+ + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart gbrain serve or the workers) buys time, not a cheaper statement (#6495); narrow queries with --source-id / source_id. Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ }+ return { name, status: 'ok', details: { ...details, outcome: 'ok' },+ message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) counted ${count.pages} page(s) in ${count.ms} ms, inside half of ${knob}. Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ } catch (error) {+ return { name, status: 'warn', message: `Keyword plan could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown', docs: DOCS } };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 3adeefa6c2..6cb156a3c7 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -235,6 +235,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'Upgrade gbrain on the brain host and rerun `gbrain doctor`; check the HNSW index state doctor reports; remove `search.vector_legacy_guard` / GBRAIN_VECTOR_LEGACY_GUARD unless it rolled back a regression, then restart the owning service (docs/guides/troubleshooting.md#hybrid-search-returns-only-keyword-hits).',run: async engine => (await import('./checks/vector-plan.ts')).vectorPlanCheck(engine),},+ {+ id: 'keyword_plan', resolution: 'operator', registration: 'wave',+ count: d => (d.outcome === 'canary_timed_out' || d.outcome === 'canary_slow' ? 1 : 0),+ impact: 'The commonest keyword term on this brain cannot be counted inside the keyword statement bound, so broad keyword queries time out and hybrid search answers from the vector arm alone',+ instruction: 'Read the canary doctor reports (one term is not workload coverage); raise `search.keyword_statement_timeout_ms` on the brain host only to buy time (1000-60000 ms, then restart gbrain serve or the workers), narrow broad queries with --source-id, and follow #6495 for the bounded candidate set (docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain).',+ run: async engine => (await import('./checks/keyword-plan.ts')).keywordPlanCheck(engine),+ },{id: 'stale_embedding_effects', resolution: 'repair', registration: 'wave',count: d => Number(d.stale_effects ?? 0),diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 215c8b656f..fcd4d47551 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -473,6 +473,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },+ // wave 16 (GBRA-79) G5.1 #6495. `since` is provisional at the current VERSION; the integrator moves it to the merge-slot stamp.+ { since: '0.60.183.0', text: 'On Postgres, the keyword, keyword-count, keyword-page, title and CJK search statements run under one operator bound, `search.keyword_statement_timeout_ms` (default 8000, range 1000-60000; `gbrain config set`, then restart `gbrain serve` or the workers), instead of a fixed 8 s; a value outside the range is refused and never set from a request. `gbrain doctor` gains `keyword_plan`, a read-only canary that warns when the brain\'s commonest keyword term cannot be counted inside the bound (one term is not workload coverage, and a timed-out count is never "no matches"). A longer bound buys time, not a cheaper statement (#6495 stays open).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex 32ff08c483..763e242d66 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -265,6 +265,8 @@ export interface GBrainConfig {hnsw_iterative_scan?: string;/** #5989 CJK keyword arm deadline in ms (search/cjk-keyword-deadline.ts); file > DB. */cjk_keyword_deadline_ms?: number;+ /** #6495 Postgres keyword/title statement_timeout in ms (postgres-engine/keyword-statement-timeout.ts); file > DB, resolved per connection. */+ keyword_statement_timeout_ms?: number;};/**@@ -839,6 +841,8 @@ async function mergeSearchScanKnobs(if (mergedSearch.hnsw_iterative_scan === undefined && dbHnswIterativeScan !== undefined) mergedSearch.hnsw_iterative_scan = dbHnswIterativeScan;const dbCjkDeadline = Number(await dbStr('search.cjk_keyword_deadline_ms'));if (mergedSearch.cjk_keyword_deadline_ms === undefined && Number.isFinite(dbCjkDeadline) && dbCjkDeadline > 0) mergedSearch.cjk_keyword_deadline_ms = dbCjkDeadline;+ const dbKeywordTimeout = Number(await dbStr('search.keyword_statement_timeout_ms'));+ if (mergedSearch.keyword_statement_timeout_ms === undefined && Number.isFinite(dbKeywordTimeout) && dbKeywordTimeout > 0) mergedSearch.keyword_statement_timeout_ms = dbKeywordTimeout;}/*** v0.27.1 — async config loader that overlays DB-plane config on top of the@@ -1375,6 +1379,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.vector_legacy_guard','search.hnsw_iterative_scan','search.cjk_keyword_deadline_ms',+ 'search.keyword_statement_timeout_ms','search.adaptive_return','search.adaptive_return_entity_max','search.adaptive_return_other_max',@@ -1893,6 +1898,7 @@ export function toEngineConfig(config: GBrainConfig): EngineConfig {engine: config.engine,database_url: config.database_url,database_path: config.database_path,+ keyword_statement_timeout_ms: config.search?.keyword_statement_timeout_ms,};}diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex b142b3cd1d..a2b5713163 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -81,9 +81,6 @@ export interface ConnectionManagerOpts {/** Default direct-pool size (P1 raised from 2 to 3). Override via env. */export const DEFAULT_DIRECT_POOL_SIZE = 3;-/** Search statement timeout (F5 consolidation) — was 8s scattered. */-export const SEARCH_STMT_TIMEOUT_MS = 8000;-/** DDL pool default statement_timeout (Fix 1). */const DDL_STMT_TIMEOUT_MS = 30 * 60 * 1000; // 30mindiff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex f5d52b5594..b29f0efd09 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -271,6 +271,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['host_identity_mismatch','stale_embedding_effects','vector_plan',+ 'keyword_plan','writer_version','pgbouncer_prepare','pglite_data_dir',diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex bf5fa0e042..557e9b4802 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -120,6 +120,7 @@ import { PageMissingError } from './engine-errors.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';import { withSearchJitOff } from './postgres-engine/search-settings.ts';+import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';import * as factsImpl from './engine-sql/facts.ts';import * as takesImpl from './engine-sql/takes.ts';@@ -187,6 +188,7 @@ export function getPostgresSchema(export class PostgresEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;+ private keywordStatementTimeout?: Promise<string>;private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL), ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;@@ -372,6 +374,7 @@ export class PostgresEngine implements BrainEngine {// Lifecycleasync connect(config: EngineConfig & { poolSize?: number; parentConnectionManager?: ConnectionManager }): Promise<void> {this.vectorIterativeScan = undefined;+ this.keywordStatementTimeout = undefined;this._savedConfig = config;const url = config.database_url;if (config.poolSize) {@@ -451,6 +454,7 @@ export class PostgresEngine implements BrainEngine {async disconnect(): Promise<void> {this.vectorIterativeScan = undefined;+ this.keywordStatementTimeout = undefined;if (this._disconnectPromise) return this._disconnectPromise;const work = this.disconnectInternal();this._disconnectPromise = work;@@ -1127,9 +1131,10 @@ export class PostgresEngine implements BrainEngine {// the GUC can never leak onto a pooled connection). Flag off → the// wrap is identical to master's; flag on → set_config('app.scopes')// shares the same transaction as the timeout.+ const statementTimeout = await this.keywordStatementTimeoutSetting();const runKeyword = (queryText: string, relaxed = false) =>this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {- await tx`SET LOCAL statement_timeout = '8s'`;+ await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;const previous = relaxed ? await tx`SHOW enable_seqscan` : [];if (relaxed) await tx`SET LOCAL enable_seqscan = off`;const boundParams = [...params];@@ -1165,14 +1170,14 @@ export class PostgresEngine implements BrainEngine {* fix/title-retrieval-arm (D1): page-grain title candidate arm. SQL lives* once in engine-sql/titles.ts (exact-title key #5889, index-backed remote* predicate). Each attempt (strict, then OR fallback) runs in its own- * scoped read transaction with an 8s statement timeout.+ * scoped read transaction under the keyword statement timeout (#6495 knob).*//** Cat 40 Hard F2 strict keyword count and keyword-mode pages; SQL in engine-sql/keyword-pages.ts. */async countKeywordPages(query: string, opts?: SearchOpts & { timeoutMs?: number }): Promise<number> {- return keywordPagesImpl.countKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, { statementTimeout: '8s', timeoutMs: opts?.timeoutMs });+ return keywordPagesImpl.countKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, { statementTimeout: await this.keywordStatementTimeoutSetting(), timeoutMs: opts?.timeoutMs });}async searchKeywordPages(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): Promise<SearchResult[]> {- return keywordPagesImpl.searchKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, page, { statementTimeout: '8s' });+ return keywordPagesImpl.searchKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, page, { statementTimeout: await this.keywordStatementTimeoutSetting() });}async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {@@ -1180,7 +1185,7 @@ export class PostgresEngine implements BrainEngine {(read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }),query,opts,- { statementTimeout: '8s', relaxedPrefersIndex: true, staleProbe: false },+ { statementTimeout: await this.keywordStatementTimeoutSetting(), relaxedPrefersIndex: true, staleProbe: false },);}@@ -1323,8 +1328,9 @@ export class PostgresEngine implements BrainEngine {// RLS scope binding + search-only timeout. alwaysTransaction: master// already wrapped this in sql.begin() for the SET LOCAL; flag off is// identical to that wrap, flag on adds set_config in the same tx.+ const statementTimeout = await this.keywordStatementTimeoutSetting();const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {- await tx`SET LOCAL statement_timeout = '8s'`;+ await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);}, { alwaysTransaction: true, jitOff: true });return rows.map(rowToSearchResult);@@ -1333,14 +1339,15 @@ export class PostgresEngine implements BrainEngine {/*** #3986: CJK keyword fallback (parity port of PGLite's v0.32.7 branch).* SQL builds in the shared cjk-keyword-sql.ts; execution goes through the- * same scoped read transaction (RLS scope binding + 8s statement timeout)- * as the FTS keyword paths. See src/core/engine-sql/cjk-search.ts.+ * same scoped read transaction (RLS scope binding + the keyword statement+ * timeout) as the FTS keyword paths. See src/core/engine-sql/cjk-search.ts.*/private async _searchKeywordCJK(query: string, ctx: CjkKeywordCtx): Promise<SearchResult[]> {+ const statementTimeout = await this.keywordStatementTimeoutSetting();return searchKeywordCJKImpl(async (read) =>await this.withScopedReadTransaction(ctx.opts?.sourceIds, ctx.opts?.sourceId, async (tx) => {- await tx`SET LOCAL statement_timeout = '8s'`;+ await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;return await read(scopedRead(postgresExecutor(tx, {runUnsafe: (conn, sql, params, opts) => this.runUnsafe(conn, sql, params, opts),gauge: this.checkoutGauge,@@ -1401,6 +1408,11 @@ export class PostgresEngine implements BrainEngine {return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;}+ /** #6495: the keyword/title statement bound, resolved once per connection (postgres-engine/keyword-statement-timeout.ts); never a request parameter. */+ private keywordStatementTimeoutSetting(): Promise<string> {+ return this.keywordStatementTimeout ??= loadKeywordStatementTimeout(this, this._savedConfig?.keyword_statement_timeout_ms);+ }+private async vectorIterativeScanSupported(): Promise<boolean> {this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));diff --git a/src/core/postgres-engine/keyword-statement-timeout.ts b/src/core/postgres-engine/keyword-statement-timeout.tsnew file mode 100644index 0000000000..d66a162655--- /dev/null+++ b/src/core/postgres-engine/keyword-statement-timeout.ts@@ -0,0 +1,59 @@+/**+ * `search.keyword_statement_timeout_ms` (#6495): the per-statement bound the+ * Postgres engine sets (`statement_timeout`, transaction-local) around every+ * keyword, keyword-page, keyword-count, title and CJK search statement.+ * Integer milliseconds, default 8000, range 1000..60000; `config set` refuses+ * other values and a stored value outside the range reads as the default.+ *+ * The bound is an operator mitigation, never a request parameter: a remote+ * caller cannot widen it, and the cap keeps a broad keyword query from+ * holding a backend for minutes. It is resolved once per engine connection+ * (the file plane at connect, then the DB plane on the first keyword+ * statement), so `gbrain config set` takes effect on the next connection:+ * the next CLI command, or a restart of `gbrain serve` / the workers. It+ * mitigates #6495 (a brain whose commonest terms cannot be ranked within the+ * bound) by letting the operator trade latency for coverage; ranking cost+ * stays proportional to the matching corpus, so a longer bound buys time,+ * not a faster statement. `countKeywordPages` keeps its own narrower+ * `timeoutMs` when a caller passes one.+ *+ * Postgres only: PGLite runs these statements with no statement timeout.+ */+export const KEYWORD_STATEMENT_TIMEOUT_KEY = 'search.keyword_statement_timeout_ms';+export const KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS = 8000;+export const KEYWORD_STATEMENT_TIMEOUT_MIN_MS = 1000;+export const KEYWORD_STATEMENT_TIMEOUT_MAX_MS = 60_000;++/** The configured milliseconds when `raw` is an integer in range, else undefined. */+export function keywordStatementTimeoutMs(raw: unknown): number | undefined {+ if (raw === undefined || raw === null || raw === '') return undefined;+ const n = typeof raw === 'string' ? Number(raw.trim()) : Number(raw);+ return Number.isInteger(n) && n >= KEYWORD_STATEMENT_TIMEOUT_MIN_MS && n <= KEYWORD_STATEMENT_TIMEOUT_MAX_MS ? n : undefined;+}++/** File plane, then DB plane, then the default. */+export function resolveKeywordStatementTimeoutMs(fileValue: unknown, dbValue: unknown): number {+ return keywordStatementTimeoutMs(fileValue) ?? keywordStatementTimeoutMs(dbValue) ?? KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS;+}++/** `config set` refusal text, or null when the value is valid. */+export function keywordStatementTimeoutValueProblem(value: string): string | null {+ return keywordStatementTimeoutMs(value) !== undefined+ ? null+ : `${KEYWORD_STATEMENT_TIMEOUT_KEY} must be an integer number of milliseconds from ${KEYWORD_STATEMENT_TIMEOUT_MIN_MS} to ${KEYWORD_STATEMENT_TIMEOUT_MAX_MS} (got '${value}'). Nothing was written.`;+}++/**+ * The `statement_timeout` setting value (`<ms>ms`) for one engine connection:+ * the file plane's value when set, else the DB plane's. A config table that+ * cannot be read yet (a fresh brain before its schema) yields the default.+ */+export async function loadKeywordStatementTimeout(+ reader: { getConfig(key: string): Promise<string | null | undefined> },+ fileValue: unknown,+): Promise<string> {+ const fileMs = keywordStatementTimeoutMs(fileValue);+ if (fileMs !== undefined) return `${fileMs}ms`;+ const dbValue = await reader.getConfig(KEYWORD_STATEMENT_TIMEOUT_KEY).catch(() => undefined);+ return `${resolveKeywordStatementTimeoutMs(undefined, dbValue)}ms`;+}diff --git a/src/core/types.ts b/src/core/types.tsindex 7f53bf068d..069a34fc0d 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2276,6 +2276,8 @@ export interface EngineConfig {database_url?: string;database_path?: string;engine?: 'postgres' | 'pglite';+ /** #6495 file-plane `search.keyword_statement_timeout_ms`, read by the Postgres engine at connect (postgres-engine/keyword-statement-timeout.ts). */+ keyword_statement_timeout_ms?: number;}// Errorsdiff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex e8a4aa69bd..a1cecbe0b4 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -35,6 +35,7 @@ const DIRECTLY_READ_SINGLETONS = ['search.vector_legacy_guard', // search/vector-legacy-guard.ts via loadConfigWithEngine'search.hnsw_iterative_scan', // search/hnsw-iterative-scan.ts via loadConfigWithEngine'search.cjk_keyword_deadline_ms', // search/cjk-keyword-deadline.ts via loadConfigWithEngine+ 'search.keyword_statement_timeout_ms', // postgres-engine/keyword-statement-timeout.ts (engine.getConfig once per connection) + loadConfigWithEngine'search.crag_escalation', // ops/search.ts'search.alias_fanout_max', // search/alias-fanout.ts'search.demote_generated', // search/provenance-demotion.tsdiff --git a/test/doctor-keyword-plan-6495.test.ts b/test/doctor-keyword-plan-6495.test.tsnew file mode 100644index 0000000000..391c619383--- /dev/null+++ b/test/doctor-keyword-plan-6495.test.ts@@ -0,0 +1,193 @@+/**+ * #6495: doctor `keyword_plan`, the read-only canary for the Postgres keyword+ * arm's statement bound (`search.keyword_statement_timeout_ms`).+ *+ * Contract protected: the check is registered as an operator-resolution wave+ * check; on a fake probe it warns when the commonest term's bounded count+ * times out or spends more than half the bound, names the knob and its+ * range, says one canary is not workload coverage, and never reports a+ * timed-out count as "no matches"; it skips PGLite, small brains and a brain+ * without planner statistics; and on a real Postgres brain the probe reads+ * the commonest lexeme from pg_stats, EXPLAINs the strict count statement and+ * times the engine's own bounded count. Existing doctor coverage has no+ * keyword-arm check.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import type { BrainEngine } from '../src/core/engine.ts';+import { OPS_CHECK_NAMES } from '../src/core/doctor-categories.ts';+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';+import {+ engineKeywordPlanProbe,+ keywordPlanCheck,+ KEYWORD_PLAN_CANARY_TIMEOUT_MS,+ KEYWORD_PLAN_MIN_CHUNKS,+ type KeywordPlanCount,+ type KeywordPlanProbe,+} from '../src/commands/doctor/checks/keyword-plan.ts';+import { KEYWORD_STATEMENT_TIMEOUT_KEY } from '../src/core/postgres-engine/keyword-statement-timeout.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const postgresEngine = { kind: 'postgres' } as unknown as BrainEngine;++function fakeProbe(count: KeywordPlanCount, opts: { chunks?: number; canary?: { term: string; share: number } | null; scans?: string[] } = {}): KeywordPlanProbe & { counted: Array<[string, number]> } {+ const counted: Array<[string, number]> = [];+ return {+ counted,+ chunkEstimate: async () => opts.chunks ?? 500_000,+ canary: async () => (opts.canary === undefined ? { term: 'contract', share: 0.82 } : opts.canary),+ explain: async () => opts.scans ?? ['Seq Scan'],+ count: async (term, timeoutMs) => { counted.push([term, timeoutMs]); return count; },+ };+}++describe('keyword_plan is a registered operator wave check', () => {+ test('WAVE_CHECKS and the doctor categories carry keyword_plan', () => {+ const spec = WAVE_CHECKS.find(s => s.id === 'keyword_plan');+ expect(spec?.resolution).toBe('operator');+ expect(spec?.registration).toBe('wave');+ expect(spec?.instruction).toContain(KEYWORD_STATEMENT_TIMEOUT_KEY);+ expect(spec?.count({ outcome: 'canary_timed_out' })).toBe(1);+ expect(spec?.count({ outcome: 'canary_slow' })).toBe(1);+ expect(spec?.count({ outcome: 'ok' })).toBe(0);+ expect(OPS_CHECK_NAMES.has('keyword_plan')).toBe(true);+ });+});++describe('keyword_plan on a fake probe', () => {+ /** Every outcome names the knob with its range, says the canary is not coverage, and never calls a timed-out count "no matches". */+ const required = (message: string) => {+ expect(message).toContain(`${KEYWORD_STATEMENT_TIMEOUT_KEY} = 8000 ms (range 1000-60000)`);+ expect(message).toContain('One canary term is not workload coverage');+ expect(message.replace('A timed-out count is never "no matches".', '')).not.toMatch(/no matches/i);+ };++ test('a timed-out canary count warns, names the knob and never reads as no matches', async () => {+ const probe = fakeProbe({ outcome: 'timed_out', ms: 2003 });+ const check = await keywordPlanCheck(postgresEngine, probe);+ expect(check.status).toBe('warn');+ expect(check.details?.outcome).toBe('canary_timed_out');+ expect(check.message).toContain('"contract" (about 82.0% of chunks) did not finish a strict page count within 2003 ms');+ expect(check.message).toContain('A timed-out count is never "no matches"');+ expect(check.message).toContain('fail open to the vector arm (keyword_arm_failed)');+ expect(check.message).toContain('buys time, not a cheaper statement');+ expect(check.message).toContain('Plan: Seq Scan');+ required(check.message);+ expect(probe.counted).toEqual([['contract', KEYWORD_PLAN_CANARY_TIMEOUT_MS]]);+ });++ test('a count above half the bound warns as slow', async () => {+ const check = await keywordPlanCheck(postgresEngine, fakeProbe({ outcome: 'counted', pages: 10_001, ms: 4500 }));+ expect(check.status).toBe('warn');+ expect(check.details?.outcome).toBe('canary_slow');+ expect(check.message).toContain('took 4500 ms for a strict page count, more than half of');+ expect(check.message).toContain('A timed-out count is never "no matches"');+ required(check.message);+ });++ test('a fast count is ok and still says the canary is not coverage', async () => {+ const check = await keywordPlanCheck(postgresEngine, fakeProbe({ outcome: 'counted', pages: 1200, ms: 310 }, { scans: ['Bitmap Heap Scan', 'Bitmap Index Scan using idx_chunks_search_vector'] }));+ expect(check.status).toBe('ok');+ expect(check.details?.outcome).toBe('ok');+ expect(check.message).toContain('counted 1200 page(s) in 310 ms');+ expect(check.message).toContain('Plan: Bitmap Heap Scan, Bitmap Index Scan using idx_chunks_search_vector');+ required(check.message);+ });++ test('small brains and missing statistics are skipped with the reason, and nothing is counted', async () => {+ const small = fakeProbe({ outcome: 'timed_out', ms: 2000 }, { chunks: KEYWORD_PLAN_MIN_CHUNKS - 1 });+ const skippedSmall = await keywordPlanCheck(postgresEngine, small);+ expect(skippedSmall.status).toBe('ok');+ expect(skippedSmall.details).toMatchObject({ outcome: 'skipped', reason: 'small_brain' });+ expect(small.counted).toEqual([]);+ const noStats = fakeProbe({ outcome: 'timed_out', ms: 2000 }, { canary: null });+ const skippedStats = await keywordPlanCheck(postgresEngine, noStats);+ expect(skippedStats.status).toBe('ok');+ expect(skippedStats.details).toMatchObject({ outcome: 'skipped', reason: 'no_statistics' });+ expect(skippedStats.message).toContain('ANALYZE content_chunks');+ expect(noStats.counted).toEqual([]);+ });++ test('a probe failure reports unknown health, not ok', async () => {+ const probe = fakeProbe({ outcome: 'counted', pages: 1, ms: 1 });+ probe.canary = async () => { throw new Error('permission denied for table pg_stats'); };+ const check = await keywordPlanCheck(postgresEngine, probe);+ expect(check.status).toBe('warn');+ expect(check.details?.health).toBe('unknown');+ expect(check.message).toContain('permission denied for table pg_stats');+ });++ test('PGLite is skipped before any probe read', async () => {+ const probe = fakeProbe({ outcome: 'timed_out', ms: 2000 });+ const check = await keywordPlanCheck({ kind: 'pglite' } as unknown as BrainEngine, probe);+ expect(check).toMatchObject({ name: 'keyword_plan', status: 'ok', details: { outcome: 'skipped', reason: 'pglite' } });+ expect(probe.counted).toEqual([]);+ });+});++if (testBackends().includes('postgres')) {+ describe('keyword_plan on Postgres', () => {+ let engine: BrainEngine;+ let databaseUrl: string;+ let close: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, databaseUrl, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ for (let i = 1; i <= 12; i++) {+ const slug = `notes/page-${i}`;+ const body = i <= 10 ? `renewal contract clause ${i}` : `ledgerbook entry ${i}`;+ await engine.putPage(slug, { type: 'note', title: `Page ${i}`, compiled_truth: body });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }]);+ }+ await engine.executeRaw('ANALYZE content_chunks');+ }, 120_000);+ afterAll(async () => { await close?.(); });++ test('the real probe reads the commonest lexeme, its plan and the engine\'s bounded count', async () => {+ const probe = engineKeywordPlanProbe(engine);+ expect(await probe.chunkEstimate()).toBeGreaterThanOrEqual(12);+ const canary = await probe.canary();+ expect(canary).not.toBeNull();+ expect(['contract', 'claus', 'renew']).toContain(canary!.term);+ expect(canary!.share).toBeGreaterThan(0.5);+ const scans = await probe.explain(canary!.term);+ expect(scans.length).toBeGreaterThan(0);+ const count = await probe.count(canary!.term, KEYWORD_PLAN_CANARY_TIMEOUT_MS);+ expect(count).toMatchObject({ outcome: 'counted', pages: 10 });+ });++ test('the check itself skips a small brain and names the skip', async () => {+ const check = await keywordPlanCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ outcome: 'skipped', reason: 'small_brain' });+ expect(check.message).toContain(`${KEYWORD_STATEMENT_TIMEOUT_KEY} = 8000 ms`);+ });++ test('a count the bound cancels on a real engine is classified timed_out, never a page count of zero', async () => {+ const locker = postgres(databaseUrl, { max: 1, prepare: false });+ let release!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ let locked!: () => void;+ const lockedUp = new Promise<void>(resolve => { locked = resolve; });+ const held = locker.begin(async tx => {+ await tx.unsafe('LOCK TABLE content_chunks IN ACCESS EXCLUSIVE MODE');+ locked();+ await released;+ }).catch(() => {});+ await lockedUp;+ try {+ const timed = await engineKeywordPlanProbe(engine).count('contract', 1000);+ expect(timed.outcome).toBe('timed_out');+ expect(timed.ms).toBeGreaterThanOrEqual(900);+ expect(timed.ms).toBeLessThan(4000);+ } finally {+ release();+ await held;+ await locker.end({ timeout: 5 });+ }+ expect(await engineKeywordPlanProbe(engine).count('contract', 1000)).toMatchObject({ outcome: 'counted', pages: 10 });+ }, 30_000);+ });+}diff --git a/test/e2e/title-arm-postgres.test.ts b/test/e2e/title-arm-postgres.test.tsindex cc306d3e40..9b34fd4a70 100644--- a/test/e2e/title-arm-postgres.test.ts+++ b/test/e2e/title-arm-postgres.test.ts@@ -13,11 +13,12 @@ import type { PostgresEngine } from '../../src/core/postgres-engine.ts';import { buildSearchTitlesStatement } from '../../src/core/search/title-statement.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS } from '../../src/core/postgres-engine/keyword-statement-timeout.ts';import { registerPostgresTests, requirePostgresTestDatabase } from '../helpers/test-backends.ts';await registerPostgresTests(() => import('../search/title-arm-exact.test.ts'));-const POSTGRES_DIALECT = { statementTimeout: '8s', relaxedPrefersIndex: true, staleProbe: false };+const POSTGRES_DIALECT = { statementTimeout: `${KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS}ms`, relaxedPrefersIndex: true, staleProbe: false };const REMOTE = { requireSafeChunks: true, excludePrivate: true, sourceId: 'default', limit: 50 };describe('remote title arm plan (postgres)', () => {diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 76bc6e9c5a..f29fab40ae 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -100,6 +100,7 @@" [OK] writer_version: Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer."," [OK] self_capture: No session corpus is configured; nothing to classify."," [OK] vector_plan: Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",+ " [OK] keyword_plan: Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains."," [OK] stale_embedding_effects: No committed write has a stale queued or failed embedding effect."," [OK] google_file_modes: No group- or world-readable gbrain files under Google source directories outside ~/.gbrain."," [OK] extractor_facts_expired: No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex f87f23f40d..e92eb565db 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1041,6 +1041,16 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "outcome": "skipped",+ "reason": "pglite"+ },+ "message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 984b9d0131..d68d2cf11f 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1151,6 +1151,16 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "outcome": "skipped",+ "reason": "pglite"+ },+ "message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {@@ -4230,6 +4240,16 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "outcome": "skipped",+ "reason": "pglite"+ },+ "message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 956f43374d..284736efc8 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1144,6 +1144,19 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "canary_timeout_ms": "<volatile>",+ "docs": "docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain",+ "outcome": "skipped",+ "reason": "small_brain",+ "timeout_ms": "<volatile>"+ },+ "message": "Skipped: fewer than 10000 chunks by the planner's estimate; the keyword statements finish well inside search.keyword_statement_timeout_ms = 8000 ms (range 1000-60000).",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {@@ -4212,6 +4225,19 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "canary_timeout_ms": "<volatile>",+ "docs": "docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain",+ "outcome": "skipped",+ "reason": "small_brain",+ "timeout_ms": "<volatile>"+ },+ "message": "Skipped: fewer than 10000 chunks by the planner's estimate; the keyword statements finish well inside search.keyword_statement_timeout_ms = 8000 ms (range 1000-60000).",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex e5514a7b78..470dd4305f 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -981,6 +981,16 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "outcome": "skipped",+ "reason": "pglite"+ },+ "message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 436d9a5e97..74d487fa73 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1000,6 +1000,16 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "outcome": "skipped",+ "reason": "pglite"+ },+ "message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex efdc376260..b64b6387b7 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -993,6 +993,19 @@"name": "vector_plan","status": "ok"},+ {+ "category": "ops",+ "details": {+ "canary_timeout_ms": "<volatile>",+ "docs": "docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain",+ "outcome": "skipped",+ "reason": "small_brain",+ "timeout_ms": "<volatile>"+ },+ "message": "Skipped: fewer than 10000 chunks by the planner's estimate; the keyword statements finish well inside search.keyword_statement_timeout_ms = 8000 ms (range 1000-60000).",+ "name": "keyword_plan",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 227972f87c..26159dcf0f 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -441,6 +441,10 @@"category": "ops","name": "vector_plan"},+ {+ "category": "ops",+ "name": "keyword_plan"+ },{"category": "ops","name": "stale_embedding_effects"diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.jsonindex c8b08eb94c..80ef4cd79a 100644--- a/test/fixtures/goldens/doctor/registry-report-remote.json+++ b/test/fixtures/goldens/doctor/registry-report-remote.json@@ -253,6 +253,10 @@"category": "ops","name": "vector_plan"},+ {+ "category": "ops",+ "name": "keyword_plan"+ },{"category": "ops","name": "stale_embedding_effects"diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex b8570463af..b174fe3151 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -292,6 +292,7 @@"invalidateContentDriftEmbeddings","invalidateStaleSignatureEmbeddings","jitOffRead",+ "keywordStatementTimeoutSetting","listActiveTakesForPages","listAllPageRefs","listAllSources",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 61543b7033..7344a425d2 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -568,7 +568,8 @@"members": ["database_path?: string | undefined","database_url?: string | undefined",- "engine?: \"postgres\" | \"pglite\" | undefined"+ "engine?: \"postgres\" | \"pglite\" | undefined",+ "keyword_statement_timeout_ms?: number | undefined"],"name": "EngineConfig"},@@ -1165,6 +1166,8 @@"private engineSqlOn","private getBulkRetryOpts","private jitOffRead",+ "private keywordStatementTimeout",+ "private keywordStatementTimeoutSetting","private onPoisoned","private poisonedDiscards","private poolHealth",@@ -2716,7 +2719,7 @@"retrieval_reflex_volunteer?: boolean | undefined","retrieval_reflex_window_turns?: number | undefined","schema_pack?: string | undefined",- "search?: { adaptive_return?: boolean; adaptive_return_entity_max?: number; adaptive_return_other_max?: number; adaptive_return_min_keep?: number; vector_legacy_guard?: boolean; hnsw_iterative_scan?: string; cjk_keyword_deadline_ms?: number; } | undefined",+ "search?: { adaptive_return?: boolean; adaptive_return_entity_max?: number; adaptive_return_other_max?: number; adaptive_return_min_keep?: number; vector_legacy_guard?: boolean; hnsw_iterative_scan?: string; cjk_keyword_deadline_ms?: number; keyword_statement_timeout_ms?: number; } | undefined","search_embedding_column?: string | undefined","self_upgrade?: { mode?: \"auto\" | \"notify\" | \"off\"; 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","storage?: unknown",@@ -8312,7 +8315,8 @@"members": ["database_path?: string | undefined","database_url?: string | undefined",- "engine?: \"postgres\" | \"pglite\" | undefined"+ "engine?: \"postgres\" | \"pglite\" | undefined",+ "keyword_statement_timeout_ms?: number | undefined"],"name": "EngineConfig"},diff --git a/test/keyword-statement-timeout-knob-6495.test.ts b/test/keyword-statement-timeout-knob-6495.test.tsnew file mode 100644index 0000000000..421ccbc5f6--- /dev/null+++ b/test/keyword-statement-timeout-knob-6495.test.ts@@ -0,0 +1,321 @@+/**+ * #6495: the Postgres engine's keyword, keyword-count, keyword-page, title,+ * chunk-keyword and CJK search statements all run under one transaction-local+ * `statement_timeout`, and that bound comes from the operator knob+ * `search.keyword_statement_timeout_ms` (default 8000 ms, range 1000..60000,+ * file plane over DB plane, resolved once per connection, never from the+ * request) instead of six `'8s'` literals.+ *+ * Contract protected: a value the operator set is the value every one of the+ * six sites binds; a stored value outside the range reads as the default;+ * `countKeywordPages` keeps a narrower caller `timeoutMs`; PGLite sets no+ * statement timeout at all. Regression that fails it: a site that keeps a+ * literal, reads the request, or ignores the range. Existing coverage runs+ * these statements but never looks at the timeout they set.+ *+ * Unit arm: the real engine methods over a recording transaction handle (no+ * database). Postgres arm (DATABASE_URL): a session holding an ACCESS+ * EXCLUSIVE lock on the searched tables makes each statement wait, and the+ * knob, not the old 8 s, decides when Postgres cancels it (SQLSTATE 57014).+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import postgres from '#postgres';+import { runConfig } from '../src/commands/config.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import {+ KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS,+ KEYWORD_STATEMENT_TIMEOUT_KEY,+ KEYWORD_STATEMENT_TIMEOUT_MAX_MS,+ KEYWORD_STATEMENT_TIMEOUT_MIN_MS,+ keywordStatementTimeoutValueProblem,+ resolveKeywordStatementTimeoutMs,+} from '../src/core/postgres-engine/keyword-statement-timeout.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++interface Recorded { sql: string; params: unknown[] }++/** The six engine entry points that bind the keyword statement timeout. */+const SITES: Record<string, (engine: PostgresEngine, countTimeoutMs?: number) => Promise<unknown>> = {+ searchKeyword: engine => engine.searchKeyword('alpha beta'),+ countKeywordPages: (engine, timeoutMs) => engine.countKeywordPages('alpha', timeoutMs === undefined ? undefined : { timeoutMs }),+ searchKeywordPages: engine => engine.searchKeywordPages('alpha', undefined, { limit: 10, offset: 0 }),+ searchTitles: engine => engine.searchTitles('alpha'),+ searchKeywordChunks: engine => engine.searchKeywordChunks('alpha'),+ searchKeywordCJK: engine => engine.searchKeyword('日本語'),+};++/** A PostgresEngine whose scoped read transactions run over a recording handle; config comes from the stubs. */+function recordingEngine(opts: { dbValue?: string | null; fileValue?: unknown }): { engine: PostgresEngine; recorded: Recorded[] } {+ const engine = new PostgresEngine();+ const recorded: Recorded[] = [];+ const rows = (sql: string): unknown[] => (/SHOW enable_seqscan/i.test(sql) ? [{ enable_seqscan: 'on' }] : Object.assign([], { count: 0 }));+ const tx = Object.assign(+ async (strings: TemplateStringsArray, ...values: unknown[]) => {+ const sql = strings.join('$');+ recorded.push({ sql, params: values });+ return rows(sql);+ },+ { unsafe: async (sql: string, params?: unknown[]) => { recorded.push({ sql, params: params ?? [] }); return rows(sql); } },+ );+ const priv = engine as unknown as {+ withScopedReadTransaction: (ids: unknown, id: unknown, cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;+ getConfig: (key: string) => Promise<string | null>;+ _savedConfig: unknown;+ _pageTransaction: boolean;+ };+ priv.withScopedReadTransaction = (_ids, _id, cb) => cb(tx);+ priv.getConfig = async key => (key === KEYWORD_STATEMENT_TIMEOUT_KEY ? opts.dbValue ?? null : null);+ priv._savedConfig = { keyword_statement_timeout_ms: opts.fileValue };+ priv._pageTransaction = true;+ return { engine, recorded };+}++/** Every statement timeout a recording set: the `set_config('statement_timeout', $1, true)` argument or a `SET LOCAL` literal. */+function timeoutsSet(recorded: Recorded[]): string[] {+ const out: string[] = [];+ for (const { sql, params } of recorded) {+ if (/set_config\('statement_timeout'/.test(sql)) out.push(String(params[0]));+ const literal = /SET LOCAL statement_timeout\s*=\s*'([^']+)'/.exec(sql);+ if (literal) out.push(literal[1]);+ }+ return out;+}++async function timeoutFor(site: string, opts: { dbValue?: string | null; fileValue?: unknown }, countTimeoutMs?: number): Promise<string[]> {+ const { engine, recorded } = recordingEngine(opts);+ await SITES[site](engine, countTimeoutMs);+ return timeoutsSet(recorded);+}++describe('search.keyword_statement_timeout_ms: the resolver', () => {+ test('default, range and precedence', () => {+ expect(resolveKeywordStatementTimeoutMs(undefined, undefined)).toBe(KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS);+ expect(KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS).toBe(8000);+ expect([KEYWORD_STATEMENT_TIMEOUT_MIN_MS, KEYWORD_STATEMENT_TIMEOUT_MAX_MS]).toEqual([1000, 60_000]);+ expect(resolveKeywordStatementTimeoutMs(undefined, '2500')).toBe(2500);+ expect(resolveKeywordStatementTimeoutMs(3000, '2500')).toBe(3000);+ for (const outside of ['999', '60001', '0', '-5', '2500.5', 'abc', '']) {+ expect(resolveKeywordStatementTimeoutMs(undefined, outside), outside).toBe(KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS);+ expect(resolveKeywordStatementTimeoutMs(outside, '2500'), `file ${outside}`).toBe(2500);+ }+ expect(resolveKeywordStatementTimeoutMs(undefined, '1000')).toBe(1000);+ expect(resolveKeywordStatementTimeoutMs(undefined, '60000')).toBe(60_000);+ });++ test('config set refuses a value outside the range and accepts the bounds', () => {+ expect(keywordStatementTimeoutValueProblem('8000')).toBeNull();+ expect(keywordStatementTimeoutValueProblem('1000')).toBeNull();+ expect(keywordStatementTimeoutValueProblem('60000')).toBeNull();+ for (const bad of ['999', '60001', '8s', '2500.5', '']) {+ expect(keywordStatementTimeoutValueProblem(bad)).toBe(+ `${KEYWORD_STATEMENT_TIMEOUT_KEY} must be an integer number of milliseconds from 1000 to 60000 (got '${bad}'). Nothing was written.`);+ }+ });+});++describe('gbrain config set search.keyword_statement_timeout_ms', () => {+ async function configSet(value: string): Promise<{ errs: string; exit: number | null; written: Array<[string, string]> }> {+ const written: Array<[string, string]> = [];+ const engine = {+ getConfig: async () => null,+ setConfig: async (key: string, v: string) => { written.push([key, v]); },+ unsetConfig: async () => 1,+ } as unknown as BrainEngine;+ const errs: string[] = [];+ let exit: number | null = null;+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { errs.push(String(chunk)); return true; }) as never);+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try {+ await runConfig(engine, ['set', KEYWORD_STATEMENT_TIMEOUT_KEY, value]);+ } catch (e) {+ if (!(e as Error).message.startsWith('EXIT:')) throw e;+ } finally {+ logSpy.mockRestore(); errSpy.mockRestore(); writeSpy.mockRestore(); exitSpy.mockRestore();+ }+ return { errs: errs.join('\n'), exit, written };+ }++ test('a value outside 1000..60000 is refused with exit 2 and nothing is written', async () => {+ for (const bad of ['500', '60001', '8s']) {+ const { errs, exit, written } = await configSet(bad);+ expect(exit, bad).toBe(2);+ expect(written, bad).toEqual([]);+ expect(errs).toContain(`Error [invalid_params]: ${KEYWORD_STATEMENT_TIMEOUT_KEY} must be an integer number of milliseconds from 1000 to 60000 (got '${bad}'). Nothing was written.`);+ expect(errs).toContain(`Fix: gbrain config get ${KEYWORD_STATEMENT_TIMEOUT_KEY}`);+ expect(errs).toContain('Why: The Postgres engine reads the keyword statement timeout once per connection');+ }+ });++ test('a value in range is written', async () => {+ const { exit, written } = await configSet('15000');+ expect(exit).toBeNull();+ expect(written).toEqual([[KEYWORD_STATEMENT_TIMEOUT_KEY, '15000']]);+ });+});++describe('search.keyword_statement_timeout_ms governs all six Postgres keyword sites (recording handle)', () => {+ for (const site of Object.keys(SITES)) {+ test(`${site}: default 8000ms, the DB plane's value, the file plane over the DB plane, out-of-range reads as the default`, async () => {+ expect(await timeoutFor(site, { dbValue: '2500' })).toEqual(['2500ms']);+ expect(await timeoutFor(site, {})).toEqual(['8000ms']);+ expect(await timeoutFor(site, { dbValue: '2500', fileValue: 3000 })).toEqual(['3000ms']);+ expect(await timeoutFor(site, { dbValue: '500' })).toEqual(['8000ms']);+ expect(await timeoutFor(site, { dbValue: '70000' })).toEqual(['8000ms']);+ expect(await timeoutFor(site, { dbValue: '60000', fileValue: 999 })).toEqual(['60000ms']);+ });+ }++ test('countKeywordPages keeps a narrower caller timeoutMs under the knob', async () => {+ expect(await timeoutFor('countKeywordPages', { dbValue: '5000' }, 1500)).toEqual(['1500ms']);+ expect(await timeoutFor('countKeywordPages', {}, 2000)).toEqual(['2000ms']);+ });++ test('the knob is resolved once per engine, not per request', async () => {+ const { engine, recorded } = recordingEngine({ dbValue: '2500' });+ let reads = 0;+ const priv = engine as unknown as { getConfig: (key: string) => Promise<string | null> };+ const inner = priv.getConfig;+ priv.getConfig = async key => { reads++; return inner(key); };+ await SITES.searchKeyword(engine);+ await SITES.searchTitles(engine);+ await SITES.searchKeywordChunks(engine);+ expect(timeoutsSet(recorded)).toEqual(['2500ms', '2500ms', '2500ms']);+ expect(reads).toBe(1);+ });+});++describe('PGLite sets no statement timeout (unchanged)', () => {+ let engine: PGLiteEngine;+ const seen: string[] = [];+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig(KEYWORD_STATEMENT_TIMEOUT_KEY, '2500');+ await engine.putPage('notes/alpha', { type: 'note', title: 'Alpha beta', compiled_truth: 'alpha beta gamma' });+ const db = (engine as unknown as { _db: { query: (...a: unknown[]) => Promise<unknown>; transaction: (fn: (tx: { query: (...a: unknown[]) => Promise<unknown> }) => Promise<unknown>) => Promise<unknown> } })._db;+ const query = db.query.bind(db);+ db.query = (...args: unknown[]) => { seen.push(String(args[0])); return query(...args); };+ const transaction = db.transaction.bind(db);+ db.transaction = fn => transaction(tx => {+ const txQuery = tx.query.bind(tx);+ tx.query = (...args: unknown[]) => { seen.push(String(args[0])); return txQuery(...args); };+ return fn(tx);+ });+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); });++ test('the keyword, count, page, title, chunk and CJK statements run with no statement_timeout', async () => {+ await engine.searchKeyword('alpha beta');+ await engine.countKeywordPages('alpha');+ await engine.searchKeywordPages('alpha', undefined, { limit: 10, offset: 0 });+ await engine.searchTitles('alpha');+ await engine.searchKeywordChunks('alpha');+ await engine.searchKeyword('日本語');+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.filter(sql => /statement_timeout/i.test(sql))).toEqual([]);+ });+});++if (testBackends().includes('postgres')) {+ describe('postgres: the configured bound is the one Postgres enforces', () => {+ let engine: PostgresEngine;+ let databaseUrl: string;+ let close: () => Promise<void>;+ let locker: ReturnType<typeof postgres>;+ let releaseLock: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, databaseUrl, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ await engine.putPage('notes/alpha', { type: 'note', title: 'Alpha beta', compiled_truth: 'alpha beta gamma' });+ await installFixtureChunks(engine, 'notes/alpha', [{ chunk_index: 0, chunk_text: 'alpha beta gamma', chunk_source: 'compiled_truth' }]);+ locker = postgres(databaseUrl, { max: 1, prepare: false });+ }, 120_000);+ afterAll(async () => {+ await releaseLock?.().catch(() => {});+ await locker?.end({ timeout: 5 }).catch(() => {});+ await close?.();+ });++ /** Holds ACCESS EXCLUSIVE on the searched tables until released, so every keyword statement waits on the lock. */+ async function holdLock(): Promise<void> {+ let release!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ let locked!: () => void;+ const lockedUp = new Promise<void>(resolve => { locked = resolve; });+ const held = locker.begin(async tx => {+ await tx.unsafe('LOCK TABLE content_chunks, pages IN ACCESS EXCLUSIVE MODE');+ locked();+ await released;+ }).catch(() => {});+ releaseLock = async () => { release(); await held; };+ await lockedUp;+ }++ async function cancelledAfter(run: () => Promise<unknown>): Promise<{ ms: number; code: string }> {+ const started = performance.now();+ try {+ await run();+ } catch (error) {+ return { ms: performance.now() - started, code: String((error as { code?: string }).code ?? (error as Error).message) };+ }+ throw new Error('the statement completed although the searched tables were locked');+ }++ async function connectWith(config: { keyword_statement_timeout_ms?: number }): Promise<PostgresEngine> {+ const fresh = new PostgresEngine();+ await fresh.connect({ database_url: databaseUrl, poolSize: 2, ...config });+ return fresh;+ }++ test('a 1000 ms knob cancels each of the six statements after about a second, not eight', async () => {+ await engine.setConfig(KEYWORD_STATEMENT_TIMEOUT_KEY, '1000');+ const bounded = await connectWith({});+ try {+ await holdLock();+ for (const [site, run] of Object.entries(SITES)) {+ const { ms, code } = await cancelledAfter(() => run(bounded));+ expect(code, site).toBe('57014');+ expect(ms, `${site} took ${ms.toFixed(0)} ms`).toBeGreaterThanOrEqual(900);+ expect(ms, `${site} took ${ms.toFixed(0)} ms`).toBeLessThan(4000);+ }+ } finally {+ await releaseLock();+ await bounded.disconnect();+ }+ }, 120_000);++ test('the file plane wins over the DB plane and countKeywordPages keeps a narrower caller bound', async () => {+ await engine.setConfig(KEYWORD_STATEMENT_TIMEOUT_KEY, '30000');+ const bounded = await connectWith({ keyword_statement_timeout_ms: 1000 });+ try {+ await holdLock();+ const title = await cancelledAfter(() => bounded.searchTitles('alpha'));+ expect(title.code).toBe('57014');+ expect(title.ms).toBeLessThan(4000);+ const count = await cancelledAfter(() => bounded.countKeywordPages('alpha', { timeoutMs: 1200 }));+ expect(count.code).toBe('57014');+ expect(count.ms).toBeGreaterThanOrEqual(1000);+ expect(count.ms).toBeLessThan(4000);+ } finally {+ await releaseLock();+ await bounded.disconnect();+ }+ }, 120_000);++ test('the stored page is intact and every site answers once the lock is gone', async () => {+ await engine.unsetConfig(KEYWORD_STATEMENT_TIMEOUT_KEY);+ expect((await engine.searchKeyword('alpha beta')).map(h => h.slug)).toEqual(['notes/alpha']);+ expect(await engine.countKeywordPages('alpha')).toBe(1);+ expect((await engine.searchKeywordPages('alpha', undefined, { limit: 10, offset: 0 })).map(h => h.slug)).toEqual(['notes/alpha']);+ expect((await engine.searchTitles('alpha')).map(h => h.slug)).toEqual(['notes/alpha']);+ expect((await engine.searchKeywordChunks('alpha')).map(h => h.slug)).toEqual(['notes/alpha']);+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 62207336c5..5836f7049e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -27,6 +27,7 @@ test/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.tstest/doctor-frontmatter-holds.test.tstest/doctor-image-embedding-coverage.test.ts+test/doctor-keyword-plan-6495.test.tstest/doctor-routing-skill-pack-source.test.tstest/embed-stale-images-managed-6529.test.tstest/embedding-completion-atomic.serial.test.ts@@ -52,6 +53,7 @@ test/held-read-signals.test.tstest/import-frontmatter-key-order-5158.test.tstest/import-inline-chunk-keep.test.tstest/import-revision-concurrency.test.ts+test/keyword-statement-timeout-knob-6495.test.tstest/lane-apply-pipelining.test.tstest/link-cross-source.test.tstest/link-preparation-shared-index.test.ts