Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): identifier probe in the keyword arm, rare words for long OR retries, coverage notice by token and class (#7491, #7492)
garrytanf4e8a8afd3e9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac718e6717..f176f13e06 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,37 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.440.0] - 2026-10-24++**A question that names a page by an identifier ("What did the latest weekly digest (#412) say?") now returns the page holding `#412`, even when the question's other words keep it from matching every word and near-identical template pages tie with it on meaning. The coverage notice also stops blaming indexing for unrelated image pages.**++### Identifiers in questions++| Situation | Before | Now |+|---|---|---|+| No chunk holds every word of the question, and the any-word retry ranks the page holding `#412` first | the retry's rows are dropped before fusion whenever semantic search returns anything, so on a brain of near-identical template pages an older copy won | the keyword arm runs one more statement matching every identifier the question names, with the same scope, visibility and filters as the strict search; its rows vote like strict rows, and a title holding the identifier leads the title arm |+| Long pages repeat the question's common words ("say", "report") | they outranked the short chunk holding the identifier once, so the page fell out of the keyword arm | the identifier match comes first, and the any-word retry ranks rare words first for questions of up to 12 words (it was 4) |+| One unrelated chunk happens to hold every word, the number included | that chunk was the only keyword row; the page holding the identifier never entered the arm | the identifier rows follow the strict rows, so the page is a keyword candidate again |++An identifier is a `#` number, a run of 6 or more digits, a code such as INV-2026-00417, an email, a URL or a phone number, asked together with other words. Queries without one, a quoted phrase or a `-` negation run exactly as before, and the any-word rows that don't hold an identifier are still dropped while semantic search is healthy.++### Coverage notice++| Situation | Before | Now |+|---|---|---|+| A pending image page's slug contains the query's digits (`412` in `frames/t004120`) | counted as able to match the query | a query word counts only as a whole word of the title or slug |+| Pending image pages and a text-only search | counted, although text search never returns image pages | counted only when an image search arm ran |+| The `projection_pending` part of `degraded_recall` | "recently written pages are not in the search index yet" for every page | text pages "are being indexed"; image pages "will not be indexed on their own" and wait for `gbrain projections drain` or a paid re-import, with doctor's `text_projection_readiness` check as the fix |++**Say to your agent:** *"What did the latest weekly digest (#412) say?"*++### What to watch for after you upgrade++- A search naming an identifier costs one more keyword statement, served by the full-text index. Other searches run the same statements as before, except that an any-word retry of 5 to 12 words now also runs the bounded rare-word read and, when a rare word is found, one more retry statement (both already ran for retries of up to 4 words). The rare-word read skips stopwords, and on Postgres it skips words the column statistics already estimate as common, so its cost follows the question's rare words, not its length.+- Pages that hold the identifier but not the other words can now rank above pages that match the question's meaning better. The page holding every word still comes first among keyword rows.+- `_meta.retrieval.coverage.could_affect` can carry `pending_images`, and `could_affect.pending_projection` can drop for queries whose digits or short words used to match unrelated slugs.+- Nothing is rewritten on upgrade, no setting changed, and there is no schema migration.+## [0.60.427.0] - 2026-10-24**A search for a full name that uses a short first name ("Matt Example") now finds the page titled "Matthew Example", keyword search finds the page holding a rare query word when no page holds every word, and agents triaging email or calendar can ask whether a sender is a known contact and get an exact answer with `gbrain whois <email or name>` (MCP tool `whois`).**diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 69a1ff129d..15a0ccb4d6 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -54,7 +54,7 @@ link it here rather than raising the cap.| [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `diagnostics.ts`, `worktree-manifest.ts` || [Managed sync bookkeeping](key-files/managed-sync-bookkeeping.md) | `sync-failures.ts`, `managed-sync-orphans.ts`, `sync-checkpoint-replaced.ts` || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `search/read-policy-sql.ts` |-| [Core Search (2/2)](key-files/core-search-2.md) | `search/rerank.ts` through `search/vector-pool.ts`, relational, multi-hop, `hub-dampening.ts`, `crag.ts`; [CJK](key-files/core-search-cjk.md), [evidence](key-files/core-search-evidence.md) |+| [Core Search (2/2)](key-files/core-search-2.md) | `search/rerank.ts` through `search/vector-pool.ts`, relational, multi-hop, `hub-dampening.ts`, `crag.ts`; [keyword](key-files/core-search-cjk.md), [evidence](key-files/core-search-evidence.md) || [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/*.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/ops/sources.ts`, except `src/core/persistence/` |diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 349654c111..1656b6bfc3 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -22,7 +22,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook (document mode, exit 0; the event records `command`, `version`, `guard: 'document'` and `exit_code: 0`, never argv values; `outcome` keeps its value, #6629/D26). The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local `remember --visibility private` save is recall-only and never pushed into a session; names the world re-save and the private copy to forget), `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`. D2: `hiddenTakesNotice(hidden, route, fix)` → `hidden_tool_content` (info, per-call): a get_page/search/query result left out takes (counts and the result's own slugs, never take text); the fix is the hidden-tool route's next step.+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. That why is worded by class (#7492): text pages are being indexed; could-affect images (`could_affect.pending_images`, the `sealable`/`reimport` classes) never index on their own, so the why names `gbrain projections drain`, the paid re-import and doctor's `text_projection_readiness`, and when projection_pending is the only doctor stage the fix is that read-only check (`gbrain doctor --only text_projection_readiness --json`). `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local `remember --visibility private` save is recall-only and never pushed into a session; names the world re-save and the private copy to forget), `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`. D2: `hiddenTakesNotice(hidden, route, fix)` → `hidden_tool_content` (info, per-call): a get_page/search/query result left out takes (counts and the result's own slugs, never take text); the fix is the hidden-tool route's next step.- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 4e74cd4de0..09397f97b5 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | rate_limited | unreachable | auth | provider_error` (gateway `rate_limit` → `rate_limited`, a transport failure with no HTTP response → `unreachable`, 401/403 → `auth`, 5xx and everything else → `provider_error`; Cat 40 R0, pinned on the real wire by `test/rerank-failure-reason.serial.test.ts`), which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.-- `src/core/search/retrieval-coverage.ts` — query-scoped `_meta.retrieval.coverage`: relevant pending and held counts, capped, null on failure.+- `src/core/search/retrieval-coverage.ts` — query-scoped `_meta.retrieval.coverage`: relevant pending and held counts, capped, null on failure. A query word counts only as a whole token of a title, slug or path (`~` regex bounded by non-alphanumerics, so `412` never matches `t004120`); an image page counts only when an image arm ran (`HybridSearchMeta.image_arm`) or it was returned; `could_affect.pending_images` counts the could-affect `sealable`/`reimport` images, which the notice words as waiting for an operator.- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget (`snippet_chars` does not turn it off; `capDeliveredSnippets` skips `reason: long_page` rows and cuts every other row); `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`. Large pages: a `page` (or auto→page) unit over 256 KB is delivered as a window with `fallback_reason: page_over_inline_bytes`; above 1 MiB, hits are located only by stored spans (`locateChunksByStoredSpans`) and the anchor fallback never whitespace-folds the whole text. A segmented page (Wave B PR 2) is planned by `planSegmentedBlock` from the windows `segmented-evidence.ts` reads around its hits, one run per window (emission marks the gap between runs, a section never crosses one); no page text, whole-page projection or `locateChunks` runs for it, and a failed segment read falls back to the hit chunk (`segment_read_failed`, live hits only).@@ -41,7 +41,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (`cc` source, full-text match, text modality). For excludePrivate callers it plans the match alone in an `OFFSET 0` subquery; joined, the visibility subplans' cost let a seq scan detoasting every `search_vector` win (1.1 → 0.2 s, common term, 250k chunks). Local callers keep the unfenced, parallel-capable join. `KEYWORD_RANKED_ROWS_CTE`: ranking carries only ids, score and bounded_rows; display columns come from one `LIMIT 1` key probe per ranked chunk. Output equals the wide statement's; under the 50k bound (sample in plan order), its unspilled output. Not on PGLite. Pinned by `test/search/keyword-arm-ranking.test.ts`, `test/e2e/keyword-arm-ranking-postgres.test.ts`.-- `src/core/search/keyword-or-rarity.ts` — rare words first in both engines' keyword OR retry. For at most `RARITY_MAX_TERMS` words, `rareTermPagesSql` reads the pages of each word's first `RARE_TERM_CHUNK_CAP` + 1 visible chunks (brain-wide, weights only); a fitting word weighs 1 / pages. `rankOrFallbackByRarity` re-runs the retry with the rarest words' OR and sorts by summed weight.- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost uses: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. `titleNameVariants(query)` (#7471) is the query with its given name swapped for each other form in its nickname group (`givenNameVariants` in `entities/name-variants.ts`), none for websearch-operator queries; the title arm ORs them into its query and the T2 boost accepts a variant title-phrase match. Exports `tokenizeTitle` + `__test__` internals.diff --git a/docs/architecture/key-files/core-search-cjk.md b/docs/architecture/key-files/core-search-cjk.mdindex c35da7c3cb..73d19e6d3b 100644--- a/docs/architecture/key-files/core-search-cjk.md+++ b/docs/architecture/key-files/core-search-cjk.md@@ -1,6 +1,8 @@-# Key files: Core Search (CJK keyword fallback)+# Key files: Core Search (keyword arm: CJK fallback, OR retry, identifier probe)[Subsystem index](../KEY_FILES.md) · [Core Search (2/2)](core-search-2.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`, and `onStatementBudget`, which reports each Postgres statement's timeout and the arm time it was computed at so the E2E asserts budgets instead of wall time); hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.+- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`, and `onStatementBudget`, which reports each Postgres statement's timeout and the arm ... (line truncated to 2000 chars)+- `src/core/search/keyword-or-rarity.ts` — rare words first in both engines' keyword OR retry. For at most `RARITY_MAX_KEYWORD_TERMS` (12) words (the title arm keeps `RARITY_MAX_TERMS` = 4: it runs one statement per word), `rareTermPagesSql` reads the pages of each word's first `RARE_TERM_CHUNK_CAP` + 1 visible chunks (brain-wide, weights only; stopwords and, on Postgres, words `commonOrTokens` in keyword-or-narrow.ts estimates past the cap are skipped); a fitting word weighs 1 / pages. `rankOrFallbackByRarity` re-runs the retry with the rarest words' OR and sorts by summed weight.+- `src/core/search/keyword-identifier-probe.ts` — #7491: `keywordArmRows` builds both engines' `searchKeyword` rows from the strict rows. With `orFallback`, offset 0 and no quote or negation, a query naming an identifier (`identifierTokens`: a hash number `#412`, or a token `identifier-query.ts` recognizes: a 6+ digit run, hex id, code, email, URL or phone) and other words runs the arm's own statement once more with the AND of the identifier tokens as the match query and the any-word query as the rank query: same scope, visibility, chunk predicate, filters and candidate cap as strict. Its rows are untagged (they vote like strict rows): after the strict rows when strict matched, ahead of the relaxed rows (`keyword_relaxed`) when it did not; one row per page, cut to the limit. A failed probe adds nothing. `holdsIdentifiers` lets the title arm's OR retry (`engine-sql/titles.ts`) lead with, untagged, the titles holding every identifier. Pinned by `test/search/identifier-probe.serial.test.ts` (+ Postgres E2E) and `test/search/keyword-identifier-probe.test.ts`.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 6d5095a8e7..33332eeb88 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/engine-sql/keyword-pages.ts` + `src/core/search/keyword-statement.ts` — the strict keyword count (`BrainEngine.countKeywordPages`) and the keyword-mode page query (`BrainEngine.searchKeywordPages`) for both engines. `buildKeywordMatch` is the ONE WHERE builder both statements read: `searchKeyword`'s strict match (websearch FTS on `content_chunks.search_vector`, or the CJK LIKE/ILIKE terms), never its OR retry, with the same page filters, hard excludes and `buildVisibilityClause` (private pages, safe chunks, so no private fence text). The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.-- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm. #7471: a 2-4 word name query ORs in its given-name variants (`titleNameVariants`: "Matt Example" also matches the title "Matthew Example"), each its own bound websearch query; the OR fallback of a query of at most `RARITY_MAX_TERMS` words runs once per word in one scoped read and `rankByRarity` puts titles holding the rarest word first (ts_rank_cd knows no term rarity, so a surname's one title used to tie thousands of first-name titles and lose on page id).+- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm. #7471: a 2-4 word name query ORs in its given-name variants (`titleNameVariants`: "Matt Example" also matches the title "Matthew Example"), each its own bound websearch query; the OR fallback of a query of at most `RARITY_MAX_TERMS` words runs once per word in one scoped read and `rankByRarity` puts titles holding the rarest word first (ts_rank_cd knows no term rarity, so a surname's one title used to tie thousands of first-name titles and lose on page id). #7491: OR-retry titles holding every identifier the query names (`holdsIdentifiers`, search/keyword-identifier-probe.ts) lead untagged; the rest stay `keyword_relaxed`.- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).- `src/core/engine-sql/graph-rank.ts` — #7168: `rankEntitiesStatement(opts)`, the one `rank_entities` aggregate for both engines (a statement builder: the op runs it through `executeRaw` with its statement deadline, like `extractionLagStatement`). Edges are distinct `(from, to, link_type)` triples between live, in-scope endpoints (both endpoints scoped by `sourceIds`), self-links, non-ranking types (`rankingLinkSql`) and, unless `includeMentions`, mention rows excluded. Retired pages (`retiredPageSql`) fold into their `superseded_by`/`merged_into` target in the same source through a recursive chain over retired pages only, capped at `MAX_RETIREMENT_HOPS`; edges dedupe after folding and folded self-links drop. With `remote` every endpoint, chain hop, fold target and non-null link origin must be in scope, live, unquarantined, in an unarchived source and (with `excludePrivate`) not private, so a hidden target never folds. Ordered by the direction's count, then slug and source id (`COLLATE "C"`), LIMIT after folding. Tests: `test/rank-entities.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 1e265ed905..cd2dabddf2 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 245 ratchet +1 #7168: graphRankOperations import (ops/grasrc/core/pglite-engine.ts 3089 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); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move)src/core/postgres-engine.ts 3147 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); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move)src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts-src/core/types.ts 2347 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +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); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured)+src/core/types.ts 2348 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +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); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +1 GBRA-156 #7492: HybridSearchMeta.image_arm (coverage counts pending image pages only when an image arm ran; interface fields cannot move, logic in search/retrieval-coverage.ts)src/core/minions/queue.ts 2544 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); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured)src/commands/init.ts 1884 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); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.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)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e4db1c0402..c0e59a35ac 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1220,6 +1220,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.427.0', id: 'keyword_or_rarity', text: 'When no page holds every word of a keyword search of up to four words, the any-word retry of the keyword arm now ranks pages holding the rarest query words first, instead of ranking pages that repeat a common word above the few that hold a rare one. The strict all-words search and longer queries are unchanged.' },// GBRA-156 (exact identity lookup, same release as the #7471 row). `since` is stamped at the merge slot.{ since: '0.60.427.0', id: 'whois_exact_identity', text: 'New read operation `whois` (CLI `gbrain whois <email or name>`, MCP tool `whois`): an exact identity lookup for agents triaging email or calendar. It returns the entity pages whose frontmatter `email`/`emails`, title or declared alias equals the query, ignoring case, accents and surrounding quotes, labels each match `email`, `title` or `alias`, sets `ambiguous` when more than one page matches, and returns an empty list, never a search fallback, when none does. Remote callers see only their granted sources and no private or quarantined page. Nothing existing changes.' },+ // GBRA-156 (#7491, #7492). `since` is stamped at the merge slot.+ { since: '0.60.440.0', id: 'keyword_identifier_probe', text: 'A search or query naming an identifier (`#412`, a 6+ digit run, a code like INV-2026-00417, an email or a URL) together with other words now runs one more keyword statement: the arm\'s own statement, with the same scope, visibility and filters, matching every identifier the query names. Those rows vote like strict keyword rows, so the page holding the identifier is no longer dropped when filler words ("What did the latest weekly digest (#412) say?") keep it from matching every word, and a title holding every identifier leads the title arm\'s any-word retry. The keyword arm\'s any-word retry ranks rare words first for questions of up to 12 words (it was 4). Queries without an identifier keep their keyword rows. `_meta.retrieval.coverage` counts a pending page only when a query word is a whole token of its title or slug (`412` no longer matches `t004120`), counts pending image pages only when an image arm ran, and adds `could_affect.pending_images`; the `projection_pending` notice says text pages are being indexed and that image pages wait for `gbrain projections drain` or a paid re-import, with doctor\'s `text_projection_readiness` as the fix.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.tsindex 8c6fd44932..d2ae32b188 100644--- a/src/core/engine-sql/titles.ts+++ b/src/core/engine-sql/titles.ts@@ -48,6 +48,7 @@ import { searchLimitCap } from '../search/eval-pool-depth.ts';import { boundWebsearchQuery, buildOrFallbackWebsearchQuery, orFallbackTokens } from '../search/sql-ranking.ts';import { buildSearchTitlesStatement, type SearchTitlesDialect } from '../search/title-statement.ts';import { RARITY_MAX_TERMS } from '../search/keyword-or-rarity.ts';+import { holdsIdentifiers, identifierTokens } from '../search/keyword-identifier-probe.ts';import { rowToSearchResult } from '../utils.ts';import type { ScopedRead } from './brands.ts';import type { ScopedReadRunner } from './cjk-search.ts';@@ -102,10 +103,14 @@ export async function searchTitles(const terms = orFallbackTokens(strictQuery);const rarity = terms.length <= RARITY_MAX_TERMS && !opts?.offset;const [orRows, ...wordLists] = await run([boundWebsearchQuery(orQuery), ...(rarity ? terms : [])], true);- const relaxedRows = rarity ? rankByRarity(orRows, wordLists, statement.params[2] as number) : orRows;+ const relaxedRows = (rarity ? rankByRarity(orRows, wordLists, statement.params[2] as number) : orRows).map(rowToSearchResult);// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's fusion can- // demote them (SearchResult.keyword_relaxed).- return relaxedRows.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));+ // demote them (SearchResult.keyword_relaxed). #7491: a title holding every+ // identifier the query names (search/keyword-identifier-probe.ts) is the+ // identifier probe's match on the title, so it leads untagged.+ const idents = identifierTokens(query);+ const named = idents ? relaxedRows.filter(r => holdsIdentifiers(r.title, idents)) : [];+ return [...named, ...relaxedRows.filter(r => !named.includes(r)).map(r => ({ ...r, keyword_relaxed: true as const }))];}diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex d2c97610b2..53a3546422 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -54,7 +54,7 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidancesafe_index_pending: { why: 'some pages in scope are still being safety-indexed for agent readers and are withheld until that finishes', fix: 'doctor' },vector_candidates_incomplete: { why: 'vector search hit its candidate limit or deadline, so some semantic matches can be missing', fix: null },keyword_candidates_incomplete: { why: 'keyword matching returned a bounded result on a large corpus (the CJK deadline or candidate cap, or common words ranked from a sample), so some keyword matches can be missing; add a rarer word or an exact phrase, narrow with source_id (the CLI source-id flag) or types, or for CJK text ask the user to raise search.cjk_keyword_deadline_ms (milliseconds, default 3000)', fix: null },- projection_pending: { why: 'recently written pages are not in the search index yet', fix: 'doctor' },+ projection_pending: { why: 'some pages in scope are not in the search index yet: recently written pages are being indexed, and image pages wait for an operator (doctor\'s text_projection_readiness check names which)', fix: 'doctor' },projection_by_design: { why: 'some image pages in scope hold protected OCR content and stay out of the search index by design; nothing is pending', fix: null },projection_status_unknown: { why: 'whether recent writes are in the search index could not be checked', fix: 'doctor' },keyword_count_unavailable: { why: 'the keyword match count did not finish, so how many pages match the query is unknown', fix: null },@@ -132,6 +132,27 @@ function keywordPlanFix(): Action {};}+const PROJECTION_READINESS_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'text_projection_readiness', '--json'] };+/** #7492: pending image pages wait for an operator, not for indexing; doctor's readiness check names the fix per class. */+function projectionReadinessFix(): Action {+ return {+ argv: PROJECTION_READINESS_VERIFY.argv, consent: [], actor: 'agent', requires_exclusive: false, verify: PROJECTION_READINESS_VERIFY,+ why: "Read-only: doctor's text_projection_readiness counts the pending pages by class and names each fix: `gbrain projections drain` (it asks first) seals sealable images, and a paid re-import (`gbrain embed --stale --images`) seals the rest. Running either is the user's call.",+ };+}++/**+ * #7492: the counted `projection_pending` why, worded by class. Text pages are being indexed and need no action;+ * image pages in the `sealable` or `reimport` class never index on their own.+ */+function projectionPendingWhy(coverage: RetrievalCoverage, could: number, total: number): string {+ const counted = `(${could} of ${total}${coverage.capped ? '+' : ''} pending page(s) could match this query)`;+ const images = coverage.could_affect.pending_images ?? 0;+ if (images === 0) return `recently written pages are being indexed and are not in the search index yet ${counted}`;+ const text = could - images;+ return `${images} image page(s) that could match are not in the search index and will not be indexed on their own: sealable images wait for \`gbrain projections drain\` and the rest for a paid re-import (\`gbrain embed --stale --images\`), and doctor's text_projection_readiness check counts them by class${text > 0 ? `; ${text} recently written page(s) are being indexed` : ''} ${counted}`;+}+/** Doctor on the brain host; `run_doctor` where callable (renderAction drops it otherwise). */export function doctorFix(why: string): Action {return { argv: ['gbrain', 'doctor', '--json'], mcp: { tool: 'run_doctor', arguments: {} }, consent: [], actor: 'agent', why, requires_exclusive: false };@@ -179,15 +200,16 @@ export function degradedRecallNotice(const whys = names.map(n => (n === 'rerank_failed'? `reranking failed because ${RERANK_REASON_WHY[rerank!]}, so results keep their fused order (fallback: fused_order${opts.rerankDegradedCalls ? `; reranker-degraded calls this session: ${opts.rerankDegradedCalls}` : ''})`: n === 'keyword_arm_failed' && keywordSkipped ? KEYWORD_SKIPPED_WHY- : n === 'projection_pending' && pendingCounted ? `${DEGRADED_STAGE_GUIDANCE[n].why} (${pendingCould} of ${pendingTotal}${opts.coverage?.capped ? '+' : ''} pending page(s) could match this query)`+ : n === 'projection_pending' && pendingCounted ? projectionPendingWhy(opts.coverage!, pendingCould, pendingTotal): DEGRADED_STAGE_GUIDANCE[n].why));const guidance = names.map(n => DEGRADED_STAGE_GUIDANCE[n]);const fixKind: StageFix = guidance.some(g => g.fix === 'embeddings') ? 'embeddings' : guidance.some(g => g.fix === 'doctor') ? 'doctor' : null;const byChoice = opts.optedOut || entries.some(s => s.reason === 'embedding_disabled');const emb = fixKind === 'embeddings' ? (byChoice ? { byChoice: true } as { fix?: Action; byChoice: boolean } : embeddingsFix(opts.config, opts.transport)) : undefined;const onlyKeywordNeedsDoctor = keywordSkipped && names.every(n => n === 'keyword_arm_failed' || DEGRADED_STAGE_GUIDANCE[n].fix !== 'doctor');+ const onlyImagesNeedDoctor = (opts.coverage?.could_affect?.pending_images ?? 0) > 0 && names.every(n => n === 'projection_pending' || DEGRADED_STAGE_GUIDANCE[n].fix !== 'doctor');const fix = emb ? emb.fix- : fixKind === 'doctor' ? (onlyKeywordNeedsDoctor ? keywordPlanFix() : doctorFix('Doctor names the failing retrieval dependency and its fix.'))+ : fixKind === 'doctor' ? (onlyKeywordNeedsDoctor ? keywordPlanFix() : onlyImagesNeedDoctor ? projectionReadinessFix() : doctorFix('Doctor names the failing retrieval dependency and its fix.')): rerank ? rerankFix(rerank, opts.retry) : undefined;const choice = emb?.byChoice ? ' This brain was set up keyword-only by the user\'s choice; mention it only if the user asks why something was not found. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.' : '';return {diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 6af0998086..94b5655511 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -469,7 +469,7 @@ async function buildRetrievalResponseMeta(const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);const excludeSlugPrefixes = resolveHardExcludes();const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);- const relevance = coverageRelevance(results as SearchResult[], queryText, opts.types, FACT_MATCH_STOPWORDS);+ const relevance = coverageRelevance(results as SearchResult[], queryText, opts.types, FACT_MATCH_STOPWORDS, m?.image_arm === true);const readinessScope = { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes };// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.@@ -503,7 +503,8 @@ async function buildRetrievalResponseMeta(...(pending ? { pending_projection: pending.total } : {}),...(heldTotal ? { held_files: heldTotal } : {}),...(embedding ? { embedding_held: embedding.total } : {}),- could_affect: { ...(pending ? { pending_projection: pending.could_affect } : {}), ...(heldTotal && held.couldAffect !== null ? { held_files: held.couldAffect } : {}),+ could_affect: { ...(pending ? { pending_projection: pending.could_affect } : {}), ...(pending?.could_affect && pending.could_affect_images ? { pending_images: pending.could_affect_images } : {}),+ ...(heldTotal && held.couldAffect !== null ? { held_files: held.couldAffect } : {}),...(embedding ? { embedding_held: embedding.could_affect } : {}) },...(pending?.capped || embedding?.capped ? { capped: true as const } : {}),...(topHitExact ? { top_hit_exact: true as const } : {}),diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex 701c5091a0..b37b590c5a 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -209,7 +209,7 @@ export async function stampHeldHits(engine: Exec, hits: Array<{ page_id?: numberSELECT NULL, NULL, (SELECT count(*)::int FROM (SELECT 1 ${HOLD_PAGE_JOIN}WHERE h.op=$1 AND s.archived IS NOT TRUE AND s.id=ANY($3::text[])AND ((h.completed_keys->0->>'page_id')=ANY($2::text[]) OR p.type=ANY($4::text[])- OR lower(concat_ws(' ', h.completed_keys->0->>'path', h.completed_keys->0->>'slug', p.title)) LIKE ANY($5::text[]))+ OR lower(concat_ws(' ', h.completed_keys->0->>'path', h.completed_keys->0->>'slug', p.title)) ~ ANY($5::text[]))LIMIT ${COVERAGE_COUNT_CAP}) x)`,[GIT_HOLD_OP, ids, coverage.map(source => source.source_id), relevance.types, relevance.patterns]);} catch {diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex df9293f234..7bca67c480 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -124,6 +124,7 @@ import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';import { RARE_TERM_CHUNK_CAP, rankOrFallbackByRarity, rareTermPagesSql, type RareTermPages } from './search/keyword-or-rarity.ts';+import { keywordArmRows } from './search/keyword-identifier-probe.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import {@@ -1518,30 +1519,16 @@ export class PGLiteEngine implements BrainEngine {ORDER BY score DESC, page_id ASC, chunk_id ASCLIMIT $3 OFFSET $4`;- let { rows } = await this.db.query(keywordSql, params);- // D2 fix (fix/title-retrieval-arm): websearch AND semantics at chunk- // grain mean one non-co-occurring token zeroes keyword recall. When the- // strict query returns nothing, retry ONCE with OR-of-terms. Strict-AND- // results always win when non-empty (no change for working queries).- // Opt-in via SearchOpts.orFallback (Reviewer F1): only hybridSearch's- // recall arm relaxes; precision consumers (countMentions,- // link-extraction, eval) keep the strict-AND contract.- if (rows.length === 0 && opts?.orFallback) {- const orQuery = buildOrFallbackWebsearchQuery(query);- if (orQuery) {- const run = async (matchQuery: string) => (await this.db.query(keywordSql, params.map((v, i) => i === 0 ? matchQuery : i === rankIdx && !opts?.rankQuery ? orQuery : v))).rows as Record<string, unknown>[];- rows = await rankOrFallbackByRarity({ query, rows: await run(orQuery), limit, offset, runRare: run,- readTermPages: async terms => (await this.db.query(rareTermPagesSql(ftsLang), [terms, RARE_TERM_CHUNK_CAP])).rows as RareTermPages[] });- settle();- // 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's- // fusion can demote them — an OR-of-common-terms match must not- // outvote a healthy vector arm (SearchResult.keyword_relaxed doc).- return (rows as Record<string, unknown>[]).map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));- }- }-- settle();- return (rows as Record<string, unknown>[]).map(rowToSearchResult);+ const { rows: strict } = await this.db.query(keywordSql, params);+ // D2 fix (fix/title-retrieval-arm): when the strict AND finds nothing,+ // retry ONCE with OR-of-terms. Opt-in via SearchOpts.orFallback (Reviewer+ // F1): only hybridSearch's recall arm relaxes; precision consumers keep+ // the strict-AND contract. #7491: the identifier probe and the+ // relaxed-row tag (#3617 follow-up) live in search/keyword-identifier-probe.ts.+ const run = async (matchQuery: string, rankQuery: string) => (await this.db.query(keywordSql, params.map((v, i) => i === 0 ? matchQuery : i === rankIdx && !opts?.rankQuery ? rankQuery : v))).rows as Record<string, unknown>[];+ return keywordArmRows({ query, strict: strict as Record<string, unknown>[], orFallback: opts?.orFallback, limit, offset, toResult: rowToSearchResult, runProbe: run,+ runRelaxed: async orQuery => rankOrFallbackByRarity({ query, rows: await run(orQuery, orQuery), limit, offset, runRare: q => run(q, orQuery),+ readTermPages: async terms => (await this.db.query(rareTermPagesSql(ftsLang), [terms, RARE_TERM_CHUNK_CAP])).rows as RareTermPages[] }) }).finally(settle);}/**diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d60bb8aa68..7520a8d871 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -118,7 +118,8 @@ import { requestSignal, throwIfRequestAborted } from './request-signal.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';-import { narrowedOrFallbackQuery } from './search/keyword-or-narrow.ts';+import { commonOrTokens, narrowedOrFallbackText, readOrTokenShares } from './search/keyword-or-narrow.ts';+import { keywordArmRows } from './search/keyword-identifier-probe.ts';import { RARE_TERM_CHUNK_CAP, rankOrFallbackByRarity, rareTermPagesSql, type RareTermPages } from './search/keyword-or-rarity.ts';import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES, KEYWORD_RANKED_ROWS_CTE, KEYWORD_STATEMENT_SETTINGS } from './search/keyword-chunk-match.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';@@ -1188,32 +1189,25 @@ export class PostgresEngine implements BrainEngine {const boundParams = params.map((v, i) => i === 0 ? collapseWebsearchDashRuns(queryText) : i === rankIdx && !opts?.rankQuery ? collapseWebsearchDashRuns(rankText) : v);return tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);}, { alwaysTransaction: true, jitOff: true, settings: relaxed ? { statement_timeout: statementTimeout, enable_seqscan: 'off', ...KEYWORD_STATEMENT_SETTINGS } : { statement_timeout: statementTimeout, ...KEYWORD_STATEMENT_SETTINGS } }));- let rows = await runKeyword(query);- // D2 fix (fix/title-retrieval-arm): websearch AND semantics at chunk- // grain mean one non-co-occurring token zeroes keyword recall. When the- // strict query returns nothing, retry ONCE with OR-of-terms — through- // the SAME scoped wrapper (the retry is a fresh scoped transaction, so- // RLS scope binding applies identically). Strict-AND results always win- // when non-empty (no change for working queries).- // Opt-in via SearchOpts.orFallback (Reviewer F1): only hybridSearch's- // recall arm relaxes; precision consumers (countMentions,- // link-extraction, eval) keep the strict-AND contract.- if (rows.length === 0 && opts?.orFallback) {- const orQuery = buildOrFallbackWebsearchQuery(query);- if (orQuery) {- const narrowed = await narrowedOrFallbackQuery((sql, p) => this.executeRaw(sql, p), query, ftsLang);- rows = await runKeyword(narrowed ?? orQuery, true, orQuery);+ const strict = await runKeyword(query);+ if (Number(strict[0]?.bounded_rows) >= KEYWORD_RANK_CANDIDATES) opts?.onKeywordIncomplete?.('candidate_budget');+ // D2 fix (fix/title-retrieval-arm): when the strict AND finds nothing,+ // retry ONCE with OR-of-terms through the SAME scoped wrapper (a fresh+ // scoped transaction, so RLS scope binding applies identically). Opt-in+ // via SearchOpts.orFallback (Reviewer F1): only hybridSearch's recall arm+ // relaxes; precision consumers keep the strict-AND contract. #7491: the+ // identifier probe and the relaxed-row tag (#3617 follow-up) live in+ // search/keyword-identifier-probe.ts.+ return keywordArmRows<Record<string, unknown>>({ query, strict, orFallback: opts?.orFallback, limit, offset, toResult: rowToSearchResult,+ runProbe: (match, rank) => runKeyword(match, true, rank),+ runRelaxed: async (orQuery) => {+ const shares = await readOrTokenShares((sql, p) => this.executeRaw(sql, p), query, ftsLang);+ const narrowed = narrowedOrFallbackText(shares), common = commonOrTokens(shares, RARE_TERM_CHUNK_CAP);+ const rows = await runKeyword(narrowed ?? orQuery, true, orQuery);if (narrowed || Number(rows[0]?.bounded_rows) >= KEYWORD_RANK_CANDIDATES) opts?.onKeywordIncomplete?.('candidate_budget');- const ranked = await rankOrFallbackByRarity<Record<string, unknown>>({ query, rows, limit, offset, runRare: q => runKeyword(q, true, orQuery),- readTermPages: terms => this.executeRaw<RareTermPages>(rareTermPagesSql(ftsLang), [terms, RARE_TERM_CHUNK_CAP]) });- // 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's- // fusion can demote them — an OR-of-common-terms match must not- // outvote a healthy vector arm (SearchResult.keyword_relaxed doc).- return ranked.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));- }- }- if (Number(rows[0]?.bounded_rows) >= KEYWORD_RANK_CANDIDATES) opts?.onKeywordIncomplete?.('candidate_budget');- return rows.map(rowToSearchResult);+ return rankOrFallbackByRarity<Record<string, unknown>>({ query, rows, limit, offset, runRare: q => runKeyword(q, true, orQuery),+ readTermPages: terms => this.executeRaw<RareTermPages>(rareTermPagesSql(ftsLang), [terms.filter(t => !common.has(t)), RARE_TERM_CHUNK_CAP]) });+ } });}/**diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex 9b1e967858..14806449d7 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -367,6 +367,7 @@ export async function runVectorArms(pushVectorList(vectorArms, unifiedList, 'original');queryEmbedding = unifiedEmbedding;unifiedDone = true;+ req.imageArmRan = true;}} catch (err) {const reason = err instanceof Error ? err.message : String(err);@@ -402,6 +403,7 @@ export async function runVectorArms(r.modality = r.modality ?? 'image';}imageVectorList = imageList;+ req.imageArmRan = true;} catch (err) {// Fail-open per behavioral invariant 2.const reason = err instanceof Error ? err.message : String(err);diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex f7981dead9..1ea0de47e0 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -90,6 +90,8 @@ export interface HybridRequest {decide?: DecideSearchContext;/** Set by the rerank stage when the System One reranker answered. */rerankMeta?: { model_resolved: string };+ /** #7492: set when an image-reading vector arm ran; emitted as `image_arm` (coverage counts pending images only then). */+ imageArmRan?: boolean;/** Set by the relational arm when the multi-hop planner ran (meta.relational_plan). */relationalPlan?: import('../relational-recall.ts').RelationalPlanMeta;/** Set by the collapse stage when it folded or read in a row (meta.collapse). */@@ -370,7 +372,9 @@ export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult// never waits.export function emitHybridMeta(req: HybridRequest, armMeta: HybridSearchMeta): void {const { engine, opts } = req;- const rawMeta = req.keywordCandidates ? { ...armMeta, keyword_candidates: req.keywordCandidates } : armMeta;+ const rawMeta = req.keywordCandidates || req.imageArmRan+ ? { ...armMeta, ...(req.keywordCandidates ? { keyword_candidates: req.keywordCandidates } : {}), ...(req.imageArmRan ? { image_arm: true as const } : {}) }+ : armMeta;const decide = decideMetaFor(req.decide);const answerability = req.decide?.answerability;const meta: HybridSearchMeta = decide || req.rerankMeta || answerability || req.relationalPlan || req.collapsediff --git a/src/core/search/keyword-identifier-probe.ts b/src/core/search/keyword-identifier-probe.tsnew file mode 100644index 0000000000..f08072c66e--- /dev/null+++ b/src/core/search/keyword-identifier-probe.ts@@ -0,0 +1,94 @@+/**+ * #7491: the identifier probe of the keyword arm. A question naming a page by+ * an identifier ("What did the latest weekly digest (#412) say?") carries+ * filler words no chunk holds together with the identifier, so the strict+ * AND of every word misses the one page holding it: no chunk holds every+ * word and the any-word retry's rows are relaxed (hybrid drops them while the+ * vector arm is healthy, and near-identical template pages tie on vectors),+ * the retry ranks long chunks repeating common words above the short chunk+ * holding the identifier, or an unrelated chunk holds every word and strict+ * never reaches the target.+ *+ * An identifier-shaped token is evidence in its own right: a hash number+ * (#412) or what search/identifier-query.ts recognizes in one token (a long+ * digit run, a hex id, a code like INV-2026-00417, an email, a URL, a phone+ * number). When the query has one and other words besides it, the keyword arm+ * runs one more statement, the arm's own statement with the AND of the+ * identifier tokens as its match query and the any-word query as its rank+ * query, so the probe has the same scope, visibility, chunk predicate and+ * filters as strict, pages holding more query words rank first among its+ * rows, and Postgres bounds it by the same candidate cap. Its rows hold every+ * identifier the question names, so they vote like strict rows: after the+ * strict rows when strict matched, and ahead of the relaxed rows when it did+ * not. Queries without such a token, a paged read (offset), precision callers+ * (no orFallback) and queries with a quoted phrase or a negation run exactly+ * as before. A failed probe adds nothing.+ */+import type { SearchResult } from '../types.ts';+import { parseIdentifier } from './identifier-query.ts';+import { buildOrFallbackWebsearchQuery, orFallbackTokens } from './sql-ranking.ts';++const HASH_NUMBER_RE = /^#(\d+)$/;++/** The query's identifier tokens (a hash number without its `#`), or null when it names none or nothing else. */+export function identifierTokens(query: string): string[] | null {+ const idents = new Set<string>();+ for (const raw of query.split(/\s+/)) {+ const token = raw.replace(/^[(\[{<'\u2018\u201c]+|[)\]}>'\u2019\u201d.,;:!?]+$/gu, '');+ const hash = HASH_NUMBER_RE.exec(token);+ if (hash) idents.add(hash[1]!);+ else if (parseIdentifier(token)) idents.add(token);+ }+ if (idents.size === 0) return null;+ const identTerms = new Set(orFallbackTokens([...idents].join(' ')).map(t => t.toLowerCase()));+ if (orFallbackTokens(query).every(t => identTerms.has(t.toLowerCase()))) return null;+ return [...idents];+}++/** The websearch AND of the query's identifier tokens, or null (identifierTokens). */+export function identifierProbeQuery(query: string): string | null {+ return identifierTokens(query)?.join(' ') ?? null;+}++/** Whether `text` holds every token, each bounded by characters other than letters and digits. */+export function holdsIdentifiers(text: string | null | undefined, tokens: readonly string[]): boolean {+ const hay = (text ?? '').toLowerCase();+ return tokens.every(token => {+ const needle = token.toLowerCase();+ for (let at = hay.indexOf(needle); at >= 0; at = hay.indexOf(needle, at + 1)) {+ if (!/[\p{L}\p{N}]/u.test(hay[at - 1] ?? '') && !/[\p{L}\p{N}]/u.test(hay[at + needle.length] ?? '')) return true;+ }+ return false;+ });+}++/** `rows`, then the rows of `more` on pages `rows` does not hold, up to `limit`. */+function appendPages(rows: SearchResult[], more: SearchResult[], limit: number): SearchResult[] {+ const pages = new Set(rows.map(r => r.page_id));+ return [...rows, ...more.filter(r => !pages.has(r.page_id))].slice(0, limit);+}++/**+ * The keyword arm's rows from its strict rows: with orFallback, the probe's+ * rows (see the module comment) and, when strict found nothing, the any-word+ * retry's rows tagged `keyword_relaxed` (the #3617 follow-up: hybrid drops+ * them while the vector arm is healthy). `runProbe` runs the arm's statement+ * with a match and a rank query; `runRelaxed` runs the engine's retry.+ */+export async function keywordArmRows<R>(a: {+ query: string;+ strict: R[];+ orFallback?: boolean;+ limit: number;+ offset: number;+ toResult: (row: R) => SearchResult;+ runProbe: (matchQuery: string, rankQuery: string) => Promise<R[]>;+ runRelaxed: (orQuery: string) => Promise<R[]>;+}): Promise<SearchResult[]> {+ const orQuery = a.orFallback ? buildOrFallbackWebsearchQuery(a.query) : null;+ const probeQuery = orQuery && a.offset === 0 ? identifierProbeQuery(a.query) : null;+ const probe = probeQuery ? (await a.runProbe(probeQuery, orQuery!).catch(() => [] as R[])).map(a.toResult) : [];+ if (a.strict.length > 0 || !orQuery) return appendPages(a.strict.map(a.toResult), probe, a.limit);+ const relaxed = (await a.runRelaxed(orQuery)).map(r => ({ ...a.toResult(r), keyword_relaxed: true as const }));+ return appendPages(probe, relaxed, a.limit);+}diff --git a/src/core/search/keyword-or-narrow.ts b/src/core/search/keyword-or-narrow.tsindex 4f087f1ee1..ebb0db1292 100644--- a/src/core/search/keyword-or-narrow.ts+++ b/src/core/search/keyword-or-narrow.ts@@ -70,18 +70,40 @@ export function narrowOrFallbackTokens(tokens: OrTokenShare[], rows: number, capreturn kept;}+export interface OrTokenShareRow { token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }++/** The statistics of an OR retry's tokens (orTokenSharesSql, one statement); [] when the read fails or the column was never analyzed. */+export async function readOrTokenShares(+ read: (sql: string, params: unknown[]) => Promise<OrTokenShareRow[]>,+ query: string,+ ftsLang: string,+): Promise<OrTokenShareRow[]> {+ const shares = await read(orTokenSharesSql(ftsLang), [orFallbackTokens(query)]).catch(() => [] as OrTokenShareRow[]);+ return shares[0]?.analyzed ? shares : [];+}++/** The websearch text an OR retry should match, or null to match the full OR query (no statistics: every term). */+export function narrowedOrFallbackText(shares: OrTokenShareRow[]): string | null {+ if (!shares.length) return null;+ const kept = narrowOrFallbackTokens(shares.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) })), Number(shares[0]!.rows));+ return kept ? kept.join(' OR ') : null;+}+/**- * The websearch text an OR retry of `query` should match, or null to match- * the full OR query. `read` runs one statement; a failed statistics read- * keeps every term.+ * #7491: the tokens the statistics estimate to match more than `cap` chunks. The keyword+ * arm's rare-word read skips them (it would read up to cap + 1 chunks only to find them+ * common), so its cost on a large brain follows the rare words, not the question's length.*/+export function commonOrTokens(shares: OrTokenShareRow[], cap: number): Set<string> {+ const rows = Number(shares[0]?.rows);+ return new Set(shares.filter(s => s.share !== null && Number(s.share) * rows > cap).map(s => s.token));+}++/** The websearch text an OR retry of `query` should match, or null to match the full OR query. */export async function narrowedOrFallbackQuery(- read: (sql: string, params: unknown[]) => Promise<Array<{ token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }>>,+ read: (sql: string, params: unknown[]) => Promise<OrTokenShareRow[]>,query: string,ftsLang: string,): Promise<string | null> {- const shares = await read(orTokenSharesSql(ftsLang), [orFallbackTokens(query)]).catch(() => []);- if (!shares[0]?.analyzed) return null;- const kept = narrowOrFallbackTokens(shares.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) })), Number(shares[0].rows));- return kept ? kept.join(' OR ') : null;+ return narrowedOrFallbackText(await readOrTokenShares(read, query, ftsLang));}diff --git a/src/core/search/keyword-or-rarity.ts b/src/core/search/keyword-or-rarity.tsindex 1ff5dcebf5..07c359e6d4 100644--- a/src/core/search/keyword-or-rarity.ts+++ b/src/core/search/keyword-or-rarity.ts@@ -5,8 +5,8 @@* times outranks the few chunks holding a rare one, so "Acme Quokka" on a* brain of Acme notes returned every Acme note before the one Quokka page.*- * For a retry of at most RARITY_MAX_TERMS words, one statement reads, per- * word, the pages of up to RARE_TERM_CHUNK_CAP chunks that hold it (index+ * For a retry of at most RARITY_MAX_KEYWORD_TERMS words, one statement reads,+ * per word, the pages of up to RARE_TERM_CHUNK_CAP chunks that hold it (index* served, read-only, and only compared against rows the retry already* authorized). A word whose chunks all fit is rare and weighs 1 / its page* count. The engine runs its retry statement once more with the OR of the@@ -15,22 +15,39 @@* scores. Rows sort by the summed weight of the* rare words their page holds, then in retry order. With no rare word, or* when the read fails, the retry's rows are returned unchanged.+ *+ * #7491: the keyword arm first ranked by rarity only for retries of at most+ * RARITY_MAX_TERMS words, so a question ("What did the team say about the+ * quokka?") ranked long chunks repeating its common words above the page+ * holding its rare one. Each word's read is bounded on its own, so the arm+ * now weighs up to RARITY_MAX_KEYWORD_TERMS words; the title arm, which runs+ * one statement per word, keeps RARITY_MAX_TERMS.*/import { chunkVisibleFilter } from './safe-chunks.ts';import { orFallbackTokens } from './sql-ranking.ts';-/** OR retries of at most this many words rank rare words first (this module and the title arm's rankByRarity). */+/** Title-arm OR retries of at most this many words rank rare words first (engine-sql/titles.ts rankByRarity). */export const RARITY_MAX_TERMS = 4;+/** Keyword-arm OR retries of at most this many distinct words rank rare words first; longer ones keep the retry's order. */+export const RARITY_MAX_KEYWORD_TERMS = 12;+/** A word matching at most this many chunks is rare; the read stops one past it. */export const RARE_TERM_CHUNK_CAP = 400;-/** Per word (`$1` text[]), the distinct pages of its first `$2` + 1 matching text chunks and that chunk count. */+/**+ * Per word (`$1` text[]), the distinct pages of its first `$2` + 1 matching text chunks and that chunk count.+ * One bounded read per word, its tsquery built once; a word with no lexemes (a stopword) reads nothing: its+ * empty query matches no row, but the scan visited every chunk (about 55 ms per stopword on a 3,200-chunk PGLite).+ */export function rareTermPagesSql(ftsLang: string): string {- return `SELECT u.term,- (SELECT count(*) FROM (SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' AND ${chunkVisibleFilter('p', 'cc')} LIMIT $2::int + 1) m)::int AS chunks,- ARRAY(SELECT DISTINCT m.page_id FROM (SELECT cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' AND ${chunkVisibleFilter('p', 'cc')} LIMIT $2::int + 1) m) AS page_ids+ return `SELECT u.term, m.chunks, COALESCE(m.page_ids, '{}') AS page_idsFROM unnest($1::text[]) WITH ORDINALITY AS u(term, ord)+ CROSS JOIN LATERAL (SELECT websearch_to_tsquery('${ftsLang}', u.term) AS q) t+ CROSS JOIN LATERAL (SELECT count(*)::int AS chunks, array_agg(DISTINCT x.page_id) AS page_ids FROM (+ SELECT cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE numnode(t.q) > 0 AND cc.search_vector @@ t.q AND cc.modality = 'text' AND ${chunkVisibleFilter('p', 'cc')}+ LIMIT $2::int + 1) x) mORDER BY u.ord`;}@@ -45,7 +62,7 @@ export async function rankOrFallbackByRarity<R>(args: {runRare: (rareOrQuery: string) => Promise<R[]>;}): Promise<R[]> {const terms = orFallbackTokens(args.query);- if (terms.length < 2 || terms.length > RARITY_MAX_TERMS || args.offset > 0) return args.rows;+ if (terms.length < 2 || terms.length > RARITY_MAX_KEYWORD_TERMS || args.offset > 0) return args.rows;const read = await args.readTermPages(terms).catch(() => null);const rare = (read ?? []).filter(t => Number(t.chunks) > 0 && Number(t.chunks) <= RARE_TERM_CHUNK_CAP && t.page_ids.length > 0);if (rare.length === 0) return args.rows;diff --git a/src/core/search/retrieval-coverage.ts b/src/core/search/retrieval-coverage.tsindex d3cb3241df..2e7988a22e 100644--- a/src/core/search/retrieval-coverage.ts+++ b/src/core/search/retrieval-coverage.ts@@ -3,9 +3,19 @@* or a held file is brain state; whether it can change THIS answer depends on* the query. An item could affect a query when it is one of the returned pages,* its page type is one of the result types or the query's types, or its title,- * slug or file path contains a query word. An empty result counts every item:+ * slug or file path holds a query word. An empty result counts every item:* nothing rules it out, and an empty answer must never read as complete.*+ * #7492: a query word counts only as a whole token of the title, slug or path+ * (bounded by characters other than letters and digits), so "412" no longer+ * matches an image frame named `t004120` and short words no longer match+ * inside longer ones. An image page counts only when an image arm ran or the+ * page was returned: text search never reads image chunks, so a pending image+ * cannot change a text-only answer, empty or not. The pending pages that could+ * affect the query are also counted by class (`could_affect.pending_images`:+ * images in the `sealable` or `reimport` class, which wait for an operator,+ * not for indexing), so the notice can say which wait applies.+ ** Counted here: pending text projections (the readiness probe's unsealed pages* that need work) and pages held from embedding (a held or capped* page_embedding_budget row that still applies: no vectors, so the vector arm@@ -23,11 +33,13 @@ export const COVERAGE_COUNT_CAP = 1000;export interface CoverageRelevance {all: boolean;types: string[];- /** Lowercase LIKE patterns, one per query word. */+ /** POSIX regular expressions matching one query word as a whole token, one per word. */patterns: string[];pageIds: number[];/** The top result's page when it is an exact slug, title or alias match for the query, else null. */exactTopPageId: number | null;+ /** Whether an image arm ran: otherwise an image page counts only when it was returned. */+ imageArm: boolean;}/** `_meta.retrieval.coverage`: counts in the read scope and how many of them could affect this query. */@@ -35,13 +47,23 @@ export interface RetrievalCoverage {pending_projection?: number;held_files?: number;embedding_held?: number;- could_affect: { pending_projection?: number; held_files?: number; embedding_held?: number };+ could_affect: {+ pending_projection?: number; held_files?: number; embedding_held?: number;+ /** Of `pending_projection`, image pages in the `sealable` or `reimport` class (absent when none): they wait for an operator. */+ pending_images?: number;+ };capped?: true;/** The top result is the page the query named (exact slug, title or alias) and its projection is current: pending pages are not counted as able to affect this answer. */top_hit_exact?: true;}-export interface ScopedCount { total: number; could_affect: number; capped: boolean; /** With an exact top hit: whether that page is itself counted. */ top_counted?: boolean }+export interface ScopedCount {+ total: number; could_affect: number; capped: boolean;+ /** With an exact top hit: whether that page is itself counted. */+ top_counted?: boolean;+ /** Pending counts: the could-affect images in the `sealable` or `reimport` class. */+ could_affect_images?: number;+}/** What could make a pending or held item relevant to this query (see the module comment). */export function coverageRelevance(@@ -49,15 +71,17 @@ export function coverageRelevance(queryText: string,queryTypes: readonly string[] | undefined,stopwords: ReadonlySet<string>,+ imageArm = false,): CoverageRelevance {const terms = [...new Set(queryText.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}'-]+/gu) ?? [])].filter(t => t.length >= 3 && !stopwords.has(t)).slice(0, 12);return {all: results.length === 0,types: [...new Set([...(queryTypes ?? []), ...results.flatMap(r => (typeof r.type === 'string' ? [r.type] : []))])],- patterns: terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`),+ patterns: terms.map(t => `(^|[^[:alnum:]])${t.replace(/[.*+?^${}()|[\]\\]/g, m => `\\${m}`)}([^[:alnum:]]|$)`),pageIds: [...new Set(results.flatMap(r => (typeof r.page_id === 'number' ? [r.page_id] : [])))],exactTopPageId: results[0] && (results[0].exact_lookup || results[0].alias_hit === true) && typeof results[0].page_id === 'number' ? results[0].page_id : null,+ imageArm,};}@@ -80,21 +104,27 @@ export function coverageScopeFilters(scope: ProjectionReadinessScope, params: unreturn filters;}-/** Pages in scope matching `where` (over `pages p` joined to `sources s` and `join`), up to the cap, and how many could affect the query. Null when the count fails: unknown, never zero. */+/**+ * Pages in scope matching `where` (over `pages p` joined to `sources s` and `join`), up to the cap, and how many could affect the query.+ * `classed` also counts the could-affect images in the `sealable` or `reimport` class. Null when the count fails: unknown, never zero.+ */async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance,- join: string, where: string): Promise<ScopedCount | null> {+ join: string, where: string, classed = false): Promise<ScopedCount | null> {const params: unknown[] = [];const filters = coverageScopeFilters(scope, params);- params.push(relevance.all, relevance.types, relevance.patterns, relevance.pageIds);+ params.push(relevance.imageArm, relevance.all, relevance.types, relevance.patterns, relevance.pageIds);const n = params.length;+ const could = `(($${n - 3}::boolean OR x.type = ANY($${n - 2}::text[]) OR x.haystack ~ ANY($${n - 1}::text[]) OR x.id = ANY($${n}::int[]))+ AND ($${n - 4}::boolean OR x.page_kind IS DISTINCT FROM 'image' OR x.id = ANY($${n}::int[])))`;const top = relevance.exactTopPageId;if (top !== null) params.push(top);try {- const [row] = await engine.executeRaw<{ total: number | string; could_affect: number | string; top_counted?: boolean | null }>(+ const [row] = await engine.executeRaw<{ total: number | string; could_affect: number | string; could_affect_images?: number | string; top_counted?: boolean | null }>(`SELECT count(*)::int AS total,- count(*) FILTER (WHERE $${n - 3}::boolean OR x.type = ANY($${n - 2}::text[]) OR x.haystack LIKE ANY($${n - 1}::text[]) OR x.id = ANY($${n}::int[]))::int AS could_affect${top === null ? '' : `,+ count(*) FILTER (WHERE ${could})::int AS could_affect${classed ? `,+ count(*) FILTER (WHERE ${could} AND x.class IN ('sealable','reimport'))::int AS could_affect_images` : ''}${top === null ? '' : `,EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id ${join} WHERE p.id = $${n + 1}::int AND p.deleted_at IS NULL AND ${where}) AS top_counted`}- FROM (SELECT p.id, p.type, lower(COALESCE(p.title, '') || ' ' || p.slug) AS haystack+ FROM (SELECT p.id, p.type, p.page_kind, lower(COALESCE(p.title, '') || ' ' || p.slug) AS haystack${classed ? `, ${projectionClassSql('p', 's')} AS class` : ''}FROM pages p JOIN sources s ON s.id = p.source_id ${join}WHERE p.deleted_at IS NULL AND ${where} AND ${filters.join(' AND ')}LIMIT ${COVERAGE_COUNT_CAP}) x`,@@ -102,7 +132,8 @@ async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: Proj);const total = Number(row?.total), couldAffect = Number(row?.could_affect);if (!Number.isFinite(total) || !Number.isFinite(couldAffect)) return null;- return { total, could_affect: couldAffect, capped: total >= COVERAGE_COUNT_CAP, ...(top === null ? {} : { top_counted: row?.top_counted === true }) };+ return { total, could_affect: couldAffect, capped: total >= COVERAGE_COUNT_CAP, ...(top === null ? {} : { top_counted: row?.top_counted === true }),+ ...(classed ? { could_affect_images: Number(row?.could_affect_images ?? 0) } : {}) };} catch {return null;}@@ -111,7 +142,7 @@ async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: Proj/** The pending pages the readiness probe found (unsealed, needing work) in the same scope. */export function countPendingProjections(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance): Promise<ScopedCount | null> {return countInScope(engine, scope, relevance, '',- `p.text_projection_revision IS DISTINCT FROM p.knowledge_revision AND ${projectionClassSql('p', 's')} NOT IN ('protected','archived')`);+ `p.text_projection_revision IS DISTINCT FROM p.knowledge_revision AND ${projectionClassSql('p', 's')} NOT IN ('protected','archived')`, true);}/** Pages in scope held from embedding: a held or capped budget row that still applies, on a page no `embed_skip` marker keeps out of embedding for good. */diff --git a/src/core/types.ts b/src/core/types.tsindex ea8d8899f7..87595009b7 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2159,6 +2159,7 @@ export function affectsRecall(d: { stage?: string; reason?: string } | undefinedexport interface HybridSearchMeta {/** True iff vector search actually ran. False when OPENAI_API_KEY missing or embed failed. */vector_enabled: boolean;+ /** #7492: an image-reading vector arm ran (cross-modal image or unified multimodal), so pending image pages could change the answer. */ image_arm?: true;/** System One: slot diagnostics (only when a slot ran visibly) and the reranker model version that answered. */decide?: import('./search/decide-stage.ts').DecideSearchMeta; rerank?: { model_resolved: string };/** System One S4 on the query op (diagnostic only): probability the top-k answer the query, threshold and verdict. */diff --git a/test/e2e/coverage-token-class-7492-postgres.test.ts b/test/e2e/coverage-token-class-7492-postgres.test.tsnew file mode 100644index 0000000000..0662825bbb--- /dev/null+++ b/test/e2e/coverage-token-class-7492-postgres.test.ts@@ -0,0 +1,4 @@+/** #7492 coverage by token and class on PostgreSQL: the dual-backend cases in test/search/coverage-token-class-7492.test.ts. */+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../search/coverage-token-class-7492.test.ts'));diff --git a/test/e2e/identifier-probe-postgres.test.ts b/test/e2e/identifier-probe-postgres.test.tsnew file mode 100644index 0000000000..e4e39b6ea4--- /dev/null+++ b/test/e2e/identifier-probe-postgres.test.ts@@ -0,0 +1,4 @@+/** The identifier probe (#7491) on PostgreSQL: the dual-backend cases in test/search/identifier-probe.serial.test.ts. */+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../search/identifier-probe.serial.test.ts'));diff --git a/test/retrieval-coverage-notices.test.ts b/test/retrieval-coverage-notices.test.tsindex 5373779082..8b6d23c79f 100644--- a/test/retrieval-coverage-notices.test.ts+++ b/test/retrieval-coverage-notices.test.ts@@ -312,7 +312,7 @@ describe('MCP dispatch: one stdio session', () => {const first = await dispatchToolCall(engine, 'search', { query: 'zzqv-absent-term' }, opts) as any;const second = await dispatchToolCall(engine, 'search', { query: 'zzqv-absent-term' }, opts) as any;expect(blocks(first)).toContain('[gbrain notice degraded_recall');- expect(blocks(first)).toContain('recently written pages are not in the search index yet (1 of 1 pending page(s) could match this query)');+ expect(blocks(first)).toContain('recently written pages are being indexed and are not in the search index yet (1 of 1 pending page(s) could match this query)');expect(blocks(second)).not.toContain('[gbrain notice degraded_recall');expect(second._meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });expect(second._meta.retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 1 } });diff --git a/test/search/coverage-token-class-7492.test.ts b/test/search/coverage-token-class-7492.test.tsnew file mode 100644index 0000000000..82a2a1bcef--- /dev/null+++ b/test/search/coverage-token-class-7492.test.ts@@ -0,0 +1,167 @@+/**+ * #7492: the projection_pending coverage count matched query words as+ * substrings (a digit run "412" matched an image frame named t004120), counted+ * image pages that a text-only search can never return, and told agents every+ * pending page was "recently written" and being indexed, although images in the+ * sealable and reimport classes wait for an operator. Coverage now matches+ * whole tokens, counts an image page only when an image arm ran or it was+ * returned, and the notice is worded by class.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { degradedRecallNotice } from '../../src/core/interop-notices.ts';+import { countPendingProjections, coverageRelevance } from '../../src/core/search/retrieval-coverage.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';++const search = operations.find(op => op.name === 'search')!;+const home = mkdtempSync(join(tmpdir(), 'gbrain-coverage-7492-'));+const env = { GBRAIN_HOME: home, GBRAIN_PROJECTION_READINESS_CACHE: '0' };++afterAll(() => rmSync(home, { recursive: true, force: true }));++function call(engine: BrainEngine) {+ const meta: Record<string, any> = {};+ const ctx = {+ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default',+ emitNotice: () => {}, emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },+ } as unknown as OperationContext;+ return { ctx, meta };+}++for (const kind of testBackends()) {+ describe('projection_pending coverage by token and class (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ async function page(slug: string, type: string, title: string, text: string) {+ await engine.putPage(slug, { type, title, compiled_truth: text, frontmatter: {} } as never);+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth' }]);+ }+ /** An unrelated image page left unsealed (the reimport class: no importer chunk). */+ async function pendingImage(slug: string, title: string) {+ await page(slug, 'image', title, title);+ await engine.executeRaw("UPDATE pages SET page_kind = 'image', text_projection_revision = NULL WHERE slug = $1", [slug]);+ }+ const coverageFor = (query: string) => withEnv(env, async () => {+ const c = call(engine);+ const results = await search.handler(c.ctx, { query }) as Array<{ slug: string }>;+ return { results, coverage: c.meta.retrieval.coverage, degraded: c.meta.retrieval.degraded };+ });++ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await page('digests/weekly-digest-412', 'note', 'Weekly digest (#412)', 'Weekly digest #412: channel summary for the week.');+ await pendingImage('media/frames/t004120', 'Frame t004120');+ }, 120_000);++ afterAll(async () => {+ await close?.();+ });++ test('a digit run inside a longer number does not make an image page count', async () => {+ const r = await coverageFor('weekly digest 412');+ expect(r.results.map(x => x.slug)).toContain('digests/weekly-digest-412');+ expect(r.degraded).toContainEqual({ stage: 'projection_pending' });+ expect(r.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 0 } });+ });++ test('an image page whose title holds the query words does not count for a text-only search', async () => {+ await pendingImage('media/frames/weekly-digest-412-cover', 'Weekly digest 412 cover');+ try {+ const r = await coverageFor('weekly digest 412');+ expect(r.coverage).toEqual({ pending_projection: 2, could_affect: { pending_projection: 0 } });+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'media/frames/weekly-digest-412-cover'");+ }+ });++ test('a pending text page holding the query word as a token still counts', async () => {+ await page('notes/digest-412-draft', 'concept', 'Digest 412 draft', 'unrelated body');+ await engine.executeRaw("UPDATE pages SET text_projection_revision = NULL WHERE slug = 'notes/digest-412-draft'");+ try {+ const r = await coverageFor('weekly digest 412');+ expect(r.coverage).toEqual({ pending_projection: 2, could_affect: { pending_projection: 1 } });+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'notes/digest-412-draft'");+ }+ });++ test('a short word does not match inside a longer word', async () => {+ // Another type than the results' (a result type counts every pending page of that type).+ await page('notes/digestion', 'concept', 'Digestion', 'unrelated body');+ await engine.executeRaw("UPDATE pages SET text_projection_revision = NULL WHERE slug = 'notes/digestion'");+ try {+ const r = await coverageFor('weekly digest');+ expect(r.results.length).toBeGreaterThan(0);+ expect(r.coverage.could_affect.pending_projection).toBe(0);+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'notes/digestion'");+ }+ });++ test('when an image arm ran, a matching pending image counts and is classed as waiting for an operator', async () => {+ await pendingImage('media/frames/weekly-digest-412-cover-2', 'Weekly digest 412 cover');+ try {+ const scope = { sourceId: 'default' };+ const textOnly = await countPendingProjections(engine, scope, coverageRelevance([], 'weekly digest 412 cover', undefined, new Set(), false));+ const withImages = await countPendingProjections(engine, scope, coverageRelevance([{ page_id: -1 }], 'weekly digest 412 cover', undefined, new Set(), true));+ expect(textOnly).toMatchObject({ total: 2, could_affect: 0, could_affect_images: 0 });+ expect(withImages).toMatchObject({ total: 2, could_affect: 1, could_affect_images: 1 });+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'media/frames/weekly-digest-412-cover-2'");+ }+ });+ });+}++describe('the projection_pending notice is worded by class', () => {+ const notice = (could: number, images?: number) => degradedRecallNotice([{ stage: 'projection_pending' }], {+ transport: 'stdio', coverage: { pending_projection: 40, could_affect: { pending_projection: could, ...(images ? { pending_images: images } : {}) } },+ })!;++ test('text pages are being indexed', () => {+ const n = notice(2);+ expect(n.code).toBe('degraded_recall');+ expect(n.why).toContain('recently written pages are being indexed');+ expect(n.why).toContain('(2 of 40 pending page(s) could match this query)');+ expect(n.why).not.toContain('projections drain');+ expect(n.fix?.argv).toEqual(['gbrain', 'doctor', '--json']);+ });++ test('image pages wait for a drain or a paid re-import and name the doctor check', () => {+ const n = notice(3, 3);+ expect(n.code).toBe('degraded_recall');+ expect(n.why).not.toContain('being indexed');+ expect(n.why).toContain('will not be indexed on their own');+ expect(n.why).toContain('gbrain projections drain');+ expect(n.why).toContain('paid re-import');+ expect(n.why).toContain('text_projection_readiness');+ expect(n.why).toContain('(3 of 40 pending page(s) could match this query)');+ expect(n.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'text_projection_readiness', '--json']);+ expect(n.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'text_projection_readiness', '--json']);+ expect(n.fix?.consent).toEqual([]);+ });++ test('a mix names both waits', () => {+ const n = notice(5, 2);+ expect(n.why).toContain('2 image page(s)');+ expect(n.why).toContain('3 recently written page(s) are being indexed');+ });+});diff --git a/test/search/identifier-probe.serial.test.ts b/test/search/identifier-probe.serial.test.tsnew file mode 100644index 0000000000..880556de30--- /dev/null+++ b/test/search/identifier-probe.serial.test.ts@@ -0,0 +1,199 @@+/**+ * #7491: a question naming an identifier ("What did the latest weekly digest+ * (#412) say?") must return the one page holding it. Three shapes lost it:+ * (1) no chunk holds every word, the any-word retry ranks the target first,+ * and hybrid drops relaxed rows while the vector arm is healthy; (2) the retry+ * ranks long chunks repeating common words above the short chunk holding the+ * identifier; (3) an unrelated chunk holds every word, so the strict match+ * never reaches the target. The identifier probe+ * (search/keyword-identifier-probe.ts) matches the AND of the query's+ * identifier tokens under the same scope and filters, and its rows vote like+ * strict rows.+ *+ * PGLite here, PostgreSQL through test/e2e/identifier-probe-postgres.test.ts.+ * Serial: it stubs the process-wide embedding transport.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import type { SearchOpts } from '../../src/core/types.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const DIMS = 1536;+const MODEL = 'openai:text-embedding-3-large';+/** The query embeds to e0; template pages sit closer to it than the target. */+const QUERY_VEC = Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0));+const vec = (spread: number) => '[' + Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : j === 1000 ? spread : 0)).join(',') + ']';+const CLOSE = vec(0.05);+const FAR = vec(0.6);++const DIGEST_Q = 'What did the latest weekly digest (#412) say?';+const REPORT_Q = 'What did digest report #412 say?';+const TARGET = 'digests/weekly-digest-412';+const REPORT_TARGET = 'reports/digest-412';+const REMOTE: SearchOpts = { requireSafeChunks: true, excludePrivate: true, sourceId: 'default' };++let prevHome: string | undefined;+let home: string;++beforeAll(() => {+ prevHome = process.env.GBRAIN_HOME;+ home = mkdtempSync(join(tmpdir(), 'gbrain-identifier-probe-'));+ process.env.GBRAIN_HOME = home;+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => QUERY_VEC) }) as any);+});++afterAll(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prevHome;+ rmSync(home, { recursive: true, force: true });+});++for (const kind of testBackends()) {+ describe('identifier probe (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES ('other','other','{}') ON CONFLICT DO NOTHING");+ }, 120_000);++ afterAll(async () => {+ await close?.();+ });++ async function page(slug: string, title: string, body: string, embedding: string, extra: { sourceId?: string; frontmatter?: Record<string, unknown> } = {}) {+ const sourceId = extra.sourceId ?? 'default';+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body, frontmatter: extra.frontmatter ?? {} } as never, { sourceId } as never);+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }], { sourceId });+ await engine.executeRaw(+ 'UPDATE content_chunks SET embedding = $1::vector, model = $4, embedded_text_hash = md5(chunk_text) WHERE page_id = (SELECT id FROM pages WHERE slug = $2 AND source_id = $3)',+ [embedding, slug, sourceId, MODEL],+ );+ }++ const slugs = (rows: Array<{ slug: string }>) => rows.map((r) => r.slug);++ describe('template digests: strict empty, relaxed row demoted (shape 1)', () => {+ beforeAll(async () => {+ await engine.executeRaw('DELETE FROM pages');+ for (let n = 300; n < 420; n++) {+ if (n === 412) continue;+ await page('digests/weekly-digest-' + n, 'Weekly digest (#' + n + ')', 'Weekly digest #' + n + ': channel summary for the week, items reviewed and owners noted.', CLOSE);+ }+ await page(TARGET, 'Weekly digest (#412)', 'Weekly digest #412: channel summary for the week, items reviewed and owners noted.', FAR);+ }, 300_000);++ test('the keyword arm returns the target first, as a row that votes like a strict row', async () => {+ const rows = await engine.searchKeyword(DIGEST_Q, { limit: 20, orFallback: true });+ expect(rows[0]?.slug).toBe(TARGET);+ expect(rows[0]?.keyword_relaxed).toBeUndefined();+ });++ test('hybrid search ranks the target first while the vector arm is healthy', async () => {+ const results = await hybridSearch(engine, DIGEST_Q, { limit: 10, expansion: false });+ expect(results.length).toBeGreaterThan(0);+ expect(results[0]?.slug).toBe(TARGET);+ });++ test('a query of the identifier and template words alone still ranks the target first', async () => {+ const results = await hybridSearch(engine, 'weekly digest #412', { limit: 10, expansion: false });+ expect(results[0]?.slug).toBe(TARGET);+ });++ test('without an identifier the relaxed rows are still dropped from fusion', async () => {+ const q = 'What did the latest weekly digest say?';+ const relaxed = await engine.searchKeyword(q, { limit: 20, orFallback: true });+ expect(relaxed.length).toBeGreaterThan(0);+ expect(relaxed.every((r) => r.keyword_relaxed === true)).toBe(true);+ const results = await hybridSearch(engine, q, { limit: 10, expansion: false });+ expect(results.every((r) => r.keyword_relaxed !== true)).toBe(true);+ });++ test('precision callers (no orFallback) keep the strict-AND contract', async () => {+ expect(await engine.searchKeyword(DIGEST_Q, { limit: 20 })).toHaveLength(0);+ });+ });++ describe('common-word chunks outrank the identifier chunk (shapes 2 and 3)', () => {+ const filler = 'They say the digest report was fine. The digest report says they say the report was fine and the digest was fine.';++ beforeAll(async () => {+ await engine.executeRaw('DELETE FROM pages');+ for (let i = 0; i < 60; i++) await page('reports/filler-' + i, 'Status note ' + i, filler + ' Note ' + i + '.', CLOSE);+ // The vector arm cannot tell these pages apart: every page ties with the target.+ await page(REPORT_TARGET, 'Channel summary', 'Digest 412 channel summary.', CLOSE);+ }, 300_000);++ test('shape 2: strict empty, the any-word retry alone leaves the target out', async () => {+ const rows = await engine.searchKeyword(REPORT_Q, { limit: 20, orFallback: true });+ expect(slugs(rows)).toContain(REPORT_TARGET);+ expect(rows[0]?.slug).toBe(REPORT_TARGET);+ const results = await hybridSearch(engine, REPORT_Q, { limit: 10, expansion: false });+ expect(slugs(results).slice(0, 5)).toContain(REPORT_TARGET);+ });++ test('shape 3: a strict hit on an unrelated chunk does not hide the target', async () => {+ await page('reports/filler-412', 'Status note 412', filler + ' Ticket 412.', CLOSE);+ try {+ const strict = await engine.searchKeyword(REPORT_Q, { limit: 20 });+ expect(slugs(strict)).toEqual(['reports/filler-412']);+ const rows = await engine.searchKeyword(REPORT_Q, { limit: 20, orFallback: true });+ expect(slugs(rows)).toEqual(['reports/filler-412', REPORT_TARGET]);+ expect(rows.every((r) => r.keyword_relaxed !== true)).toBe(true);+ const results = await hybridSearch(engine, REPORT_Q, { limit: 10, expansion: false });+ expect(slugs(results).slice(0, 5)).toContain(REPORT_TARGET);+ } finally {+ await engine.executeRaw("DELETE FROM pages WHERE slug = 'reports/filler-412'");+ }+ });++ });++ describe('scope and visibility (remote caller)', () => {+ beforeAll(async () => {+ await engine.executeRaw('DELETE FROM pages');+ for (let n = 300; n < 330; n++) {+ await page('digests/weekly-digest-' + n, 'Weekly digest (#' + n + ')', 'Weekly digest #' + n + ': channel summary for the week.', CLOSE);+ }+ await page(TARGET, 'Weekly digest (#412)', 'Weekly digest #412: channel summary for the week.', FAR);+ await page('digests/other-source-412', 'Weekly digest (#412) mirror', 'Weekly digest #412: mirrored channel summary for the week.', FAR, { sourceId: 'other' });+ await page('digests/private-412', 'Weekly digest (#412) draft', 'Weekly digest #412: private draft of the channel summary.', FAR, { frontmatter: { visibility: 'private' } });+ await page('digests/unsealed-412', 'Weekly digest (#412) pending', 'Weekly digest #412: pending copy of the channel summary.', FAR);+ await engine.executeRaw("UPDATE pages SET text_projection_revision = NULL WHERE slug = 'digests/unsealed-412'");+ }, 300_000);++ test('a local unscoped read sees the other-source and private copies (the fixture can leak)', async () => {+ const rows = await engine.searchKeyword(DIGEST_Q, { limit: 20, orFallback: true });+ expect(slugs(rows)).toEqual(expect.arrayContaining([TARGET, 'digests/other-source-412', 'digests/private-412']));+ });++ test('a remote read gets the target and no cross-source, private or unsealed row', async () => {+ const rows = await engine.searchKeyword(DIGEST_Q, { ...REMOTE, limit: 20, orFallback: true });+ expect(rows[0]?.slug).toBe(TARGET);+ for (const leaked of ['digests/other-source-412', 'digests/private-412', 'digests/unsealed-412']) expect(slugs(rows)).not.toContain(leaked);+ const results = await hybridSearch(engine, DIGEST_Q, { ...REMOTE, limit: 10, expansion: false });+ expect(results[0]?.slug).toBe(TARGET);+ for (const leaked of ['digests/other-source-412', 'digests/private-412', 'digests/unsealed-412']) expect(slugs(results)).not.toContain(leaked);+ });+ });+ });+}diff --git a/test/search/keyword-identifier-probe.test.ts b/test/search/keyword-identifier-probe.test.tsnew file mode 100644index 0000000000..e302bf3b7b--- /dev/null+++ b/test/search/keyword-identifier-probe.test.ts@@ -0,0 +1,84 @@+/** #7491: which queries run the keyword arm's identifier probe, and what it matches (search/keyword-identifier-probe.ts). */+import { describe, expect, test } from 'bun:test';+import { holdsIdentifiers, identifierProbeQuery, identifierTokens, keywordArmRows } from '../../src/core/search/keyword-identifier-probe.ts';+import type { SearchResult } from '../../src/core/types.ts';++describe('identifierProbeQuery', () => {+ test('a hash number in a question is probed without its #', () => {+ expect(identifierProbeQuery('What did the latest weekly digest (#412) say?')).toBe('412');+ expect(identifierProbeQuery('What did digest report #412 say?')).toBe('412');+ });++ test('codes, long digit runs, emails and URLs are identifiers', () => {+ expect(identifierProbeQuery('status of INV-2026-00417 for acme-example')).toBe('INV-2026-00417');+ expect(identifierProbeQuery('who paid order 88231904 last week')).toBe('88231904');+ expect(identifierProbeQuery('notes from [email protected] about pricing')).toBe('[email protected]');+ });++ test('several identifiers are ANDed', () => {+ expect(identifierProbeQuery('compare #411 and #412 digests')).toBe('411 412');+ });++ test('no identifier, or nothing besides it, runs no probe', () => {+ expect(identifierProbeQuery('What did the latest weekly digest say?')).toBeNull();+ expect(identifierProbeQuery('#412')).toBeNull();+ expect(identifierProbeQuery('INV-2026-00417')).toBeNull();+ expect(identifierProbeQuery('report 412 summary')).toBeNull();+ expect(identifierProbeQuery('meeting on 2026-10-24 with acme-example')).toBeNull();+ });++ test('identifierTokens returns the tokens the title arm checks', () => {+ expect(identifierTokens('What did the latest weekly digest (#412) say?')).toEqual(['412']);+ });+});++describe('holdsIdentifiers', () => {+ test('matches whole tokens only', () => {+ expect(holdsIdentifiers('Weekly digest (#412)', ['412'])).toBe(true);+ expect(holdsIdentifiers('Weekly digest (#4120)', ['412'])).toBe(false);+ expect(holdsIdentifiers('frame t004120', ['412'])).toBe(false);+ expect(holdsIdentifiers('Invoice INV-2026-00417 paid', ['inv-2026-00417'])).toBe(true);+ expect(holdsIdentifiers(null, ['412'])).toBe(false);+ });++ test('every token must be held', () => {+ expect(holdsIdentifiers('Digest #411 and #412', ['411', '412'])).toBe(true);+ expect(holdsIdentifiers('Digest #412', ['411', '412'])).toBe(false);+ });+});++describe('keywordArmRows', () => {+ const row = (page_id: number) => ({ page_id, slug: `p${page_id}` }) as unknown as SearchResult;+ const run = async (query: string, o: { strict?: number[]; offset?: number; orFallback?: boolean; probe?: () => Promise<SearchResult[]> } = {}) => {+ const calls: string[] = [];+ const rows = await keywordArmRows<SearchResult>({+ query, strict: (o.strict ?? []).map(row), orFallback: o.orFallback ?? true, limit: 5, offset: o.offset ?? 0, toResult: r => r,+ runProbe: (m, r) => { calls.push(`probe:${m}|${r}`); return o.probe ? o.probe() : Promise.resolve([row(9)]); },+ runRelaxed: q => { calls.push(`relaxed:${q}`); return Promise.resolve([row(7), row(9)]); },+ });+ return { calls, rows: rows.map(r => [r.page_id, r.keyword_relaxed === true]) };+ };++ test('strict rows lead, probe rows follow untagged, one row per page', async () => {+ expect(await run('weekly digest #412 summary', { strict: [1, 9] })).toEqual({ calls: ['probe:412|weekly OR digest OR 412 OR summary'], rows: [[1, false], [9, false]] });+ });++ test('strict empty: probe rows lead untagged, then the relaxed rows tagged', async () => {+ expect((await run('weekly digest #412 summary')).rows).toEqual([[9, false], [7, true]]);+ });++ test('a quoted phrase, a negation, a paged read or a precision caller runs no probe', async () => {+ for (const q of ['"weekly digest" #412', 'weekly -digest #412']) expect((await run(q, { strict: [1] })).calls).toEqual([]);+ expect((await run('weekly digest #412', { strict: [1], offset: 5 })).calls).toEqual([]);+ expect((await run('weekly digest #412', { orFallback: false })).calls).toEqual([]);+ });++ test('a query without an identifier runs no probe', async () => {+ expect((await run('weekly digest summary', { strict: [1] })).calls).toEqual([]);+ });++ test('a failed probe adds nothing', async () => {+ expect((await run('weekly digest #412', { strict: [1], probe: () => Promise.reject(new Error('boom')) })).rows).toEqual([[1, false]]);+ });+});+diff --git a/test/search/keyword-or-narrow.test.ts b/test/search/keyword-or-narrow.test.tsindex ca731d9ddf..bbe97e8506 100644--- a/test/search/keyword-or-narrow.test.ts+++ b/test/search/keyword-or-narrow.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'bun:test';-import { narrowOrFallbackTokens, OR_FALLBACK_MATCH_CAP, type OrTokenShare } from '../../src/core/search/keyword-or-narrow.ts';+import { commonOrTokens, narrowOrFallbackTokens, OR_FALLBACK_MATCH_CAP, type OrTokenShare } from '../../src/core/search/keyword-or-narrow.ts';const t = (token: string, share: number | null, lexemes = 1): OrTokenShare => ({ token, lexemes, share });@@ -31,3 +31,13 @@ describe('narrowOrFallbackTokens', () => {expect(narrowOrFallbackTokens([t('a1', 0.01), t('b2', 0.01)], OR_FALLBACK_MATCH_CAP * 50)).toBeNull();});});++describe('commonOrTokens (#7491)', () => {+ const row = (token: string, share: number | null) => ({ token, lexemes: 1, share, rows: 2_000_000, analyzed: true });+ test('names the tracked tokens estimated past the cap; untracked tokens are never common', () => {+ expect([...commonOrTokens([row('say', 0.2), row('kalomi', 0.0001), row('412', null)], 400)]).toEqual(['say']);+ });+ test('no statistics, no common tokens', () => {+ expect(commonOrTokens([], 400).size).toBe(0);+ });+});diff --git a/test/search/keyword-or-rarity.test.ts b/test/search/keyword-or-rarity.test.tsindex 533d36f66a..d42d70067d 100644--- a/test/search/keyword-or-rarity.test.ts+++ b/test/search/keyword-or-rarity.test.ts@@ -64,6 +64,16 @@ for (const kind of testBackends()) {}}, 120_000);+ test('a question of more than four words ranks the page holding its rare word first (#7491)', async () => {+ await seed();+ const q = 'What did the Acme team say about the quokka?';+ for (const opts of [{}, REMOTE]) {+ const rows = await engine.searchKeyword(q, { ...opts, limit: 10, orFallback: true });+ expect(rows[0]?.slug).toBe('notes/quokka');+ expect(rows.every((r) => r.keyword_relaxed === true)).toBe(true);+ }+ }, 120_000);+test('a rare page past the retry limit comes back', async () => {await seed();const rows = await engine.searchKeyword('Acme Quokka', { limit: 3, orFallback: true });