Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): honest keyword counts and match: "keyword" paging for remote callers
garrytan93d2959a61b6
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 35ca5a1566..a975bb659a 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -201,7 +201,7 @@ Every non-localOnly operation on the MCP surface: 140 tools across 23 areas. **S| `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | || `query` | Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). | read | yes | || `rate_answer` | Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). | write | | |-| `search` | Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. | read | yes | |+| `search` | Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. | read | yes | || `search_by_image` | Image-as-query retrieval. | read | | || `search_modes` | Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with attribution (mode default vs config override), the three frozen bundles, and a reranker_readiness verdict (whether the resolved reranker will actually run; remote callers get the verdict without the host key inventory). | read | | || `search_stats` | Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. | admin | | |diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 30db5e715a..b76494ff63 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -46,6 +46,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; shared guarded transport pins validated DNS answers and streams decoded bodies with a 2 MiB remote cap (10 MiB local cap). `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).+- `src/core/search/keyword-paging.ts` — honest keyword counts and keyword-mode paging for the `search` op. `parseSearchPaging` validates `match` (`hybrid` default, `keyword`), `cursor`, the 10,000 offset cap (`search_offset_over_cap`; hybrid `offset` keeps its ranked-list meaning) and refuses an agent-facing `mode` (`search_mode_local_only`) and a cursor outside keyword mode (`search_cursor_requires_keyword`), each with a fix naming `match: "keyword"`. `startKeywordCount` / `countKeywordMatches` run `engine.countKeywordPages` beside the search under a 2-second deadline; the result is `keyword_total` / `keyword_truncated` (`keyword_total_capped` past 10,000) or the `keyword_count_unavailable` degraded stage, never a guessed number. `readKeywordPage` reads `limit + 1` rows from `engine.searchKeywordPages` (so `truncated` and `next` never depend on the count) and builds `next`, a ready-to-send argument object whose `cursor` is a base64url keyset `(score, page_id, rows shown)` bound to the query, `types` and `source_id`. `keepEnumeratedRows` keeps every enumerated page after evidence delivery (`evidence_omitted: true`, empty text, when its text did not fit). `searchCountLine` renders the one model-visible line `src/mcp/dispatch.ts` appends after the rows on every search call. Tests: `test/search-keyword-paging.test.ts`, `test/search-keyword-cap.slow.test.ts`, `test/e2e/search-keyword-paging-parity.test.ts`.+- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.- `src/core/search/metadata-boost-gate.ts` — the ONE parse + decision contract for `search.metadata_boost_gate` (`always` | `lexical`; every bundle is `lexical`, `DEFAULT_METADATA_BOOST_GATE` stays `always` so a knobs literal without the field keeps its pre-wave hash identity). `lexicalArmsVoted` answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); `decideMetadataBoosts({gate, lexicalVoted})` returns `{gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}`. Image-modality queries are exempt from the gate: `hybridSearch` never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and `lexical` would silently disable the boosts for the whole modality — the caller passes `modality` (from `effectiveModality`) and an image decision applies the boosts as before (reason `image_modality`). Under `lexical`, `hybridSearch` passes `skipMetadataBoosts` into `runPostFusionStages` so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to `lexical` in all three bundles. The decision is surfaced as `HybridSearchMeta.metadata_boost_gate` (`--explain`); knobs-hash part `mbg=`; override chain per-call `metadataBoostGate` → config → bundle (`normalizeMetadataBoostGate` is the shared parser, garbage falls through). Pinned by `test/search/metadata-boost-gate.test.ts` (pure contract, hash participation, resolution chain) and `test/search/metadata-boost-gate-hybrid.test.ts` (hermetic PGLite hub-vs-gold corpus: `always` reproduces the hub-first regression, the default yields gold-first, config and per-call planes, unparseable falls through).diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex d351b643b2..fd8940f479 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -25,6 +25,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL`fragment.ts` numbers placeholders at render time, so text is byte-identical to the tagged templates it replaced (`test/fixtures/goldens/sql-text/`). Capabilities (`maxBindParamsPerStatement`, `transactionAdvisoryLocks`, `probesEmbeddingCast`) carry the real engine differences; `docs/designs/refactor-wave-1/w1-inventory.md` classifies every method. Page-state orchestration stays in the engines: `putPage`'s transaction, page-key lock and revision check, and the `updateSlug` / `setPageAliases` transactions, call `pages.ts` on the transaction clone's executor; `getPage` / `readPageSnapshot` keep their SQL in `page-state/snapshot.ts`. Reads with an early return that must not open a scoped transaction (`listPrefixSampledPages`, `listCorpusSample`) take a `ScopedReadRunner`. Nothing here imports an engine façade (`check:layering`); SQL may splice only constant text (`check:engine-sql-dynamic`); brands are unforgeable (`check:engine-sql-brands`); engine SQL only shrinks (`check:engine-sql-ratchet`). Tests: docs/TESTING.md "Engine-sql".- `src/core/engine-sql/facts.ts` `listFactsKeyset` + `src/core/engine-sql/pages.ts` keyset predicates — delta's two keyset reads. Both bind the cursor timestamp as `${value}::text::timestamptz`: a bare `::timestamptz` param is typed by the postgres.js driver, which serializes a string through a JS Date and truncates it to milliseconds (on Postgres that re-selected the whole last millisecond every wake and never drained a >limit cluster inside one millisecond). `listFactsKeyset` reads ascending `(created_at, id)` strictly after the keyset (`id: null` = strictly after the timestamp) and projects `created_at_iso` at column precision; recall's newest-first `listFactsSince` is unchanged. `test/engine-sql-facts-keyset.test.ts`, `test/delta-cursor-integrity.test.ts` (both engines).+- `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 count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; 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/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). Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.- `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 in-scope link endpoints grouped per entity page (ties break by slug in code-point order). 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. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are three functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ea43fd22b9..88c30f04bc 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2178,6 +2178,30 @@ Reasons: `rename_source_changed`.More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### search_cursor_requires_keyword++<a id="search_cursor_requires_keyword"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A search cursor was sent without match: "keyword"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page). | The request itself was wrong or no longer matches the brain; nothing was changed. | Send the next object from the previous search response unchanged; it carries match: "keyword". | agent | `repeat the read that failed` | 1 | no |++### search_mode_local_only++<a id="search_mode_local_only"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An agent-facing caller set search's mode, which only the brain's operator chooses. | The request itself was wrong or no longer matches the brain; nothing was changed. | Omit mode; for keyword-only matching with a total and paging, pass match: "keyword". | agent | `repeat the read that failed` | 1 | no |++### search_offset_over_cap++<a id="search_offset_over_cap"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A search offset was over the 10,000 limit. | The request itself was wrong or no longer matches the brain; nothing was changed. | Page with match: "keyword" and the next object each response returns; a cursor has no depth limit. | agent | `repeat the read that failed` | 1 | no |+### serve_port_in_use<a id="serve_port_in_use"></a>diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex bd65778bda..8bd2db6da5 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -376,12 +376,16 @@ Fuzzy-resolve a partial slug to matching page slugsCheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.+Every call also reports how many pages match the query's keywords (`keyword_total`, `keyword_truncated`; "10000+" past 10,000) in one line after the rows. That count covers keyword (full-text) matches only, not the ranked rows. To list every one of those pages, pass `match: "keyword"`: rows come one per page in keyword-score order with `total`, `truncated` and `next`, a ready-to-send argument object; keep calling with `next` until it is absent. A page whose text did not fit `token_budget` still gets a row, with `evidence_omitted: true`. If the count times out, the line says it is unavailable (degraded stage `keyword_count_unavailable`), never zero.+| Parameter | Type | Guidance || --- | --- | --- || `query` (required) | string | Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param. || `limit` | number | Max results (default 20) |-| `offset` | number | Skip first N results (for pagination) |-| `mode` | string | Search mode (conservative\|balanced\|tokenmax). Local callers only. |+| `offset` | number | Skip the first N rows of the ranked list (at most 10,000). Hybrid rows are a ranked top-K, so offset paging can miss pages; use `match: "keyword"` and `next` to list every keyword match. |+| `match` | string (`hybrid`, `keyword`) | `hybrid` (default): ranked top-K rows plus the keyword count line. `keyword`: every page matching the query's keywords (strict full-text match, the same set `keyword_total` counts), paged with `next`. Remote-safe; keyword matching costs less than hybrid. |+| `cursor` | string | The keyset cursor inside a `match: "keyword"` response's `next`. Send `next` unchanged; a cursor without `match: "keyword"` is refused (`search_cursor_requires_keyword`). |+| `mode` | string | Search mode (conservative\|balanced\|tokenmax). Local callers only: an agent-facing caller that sets it is refused (`search_mode_local_only`) with a fix naming `match: "keyword"`. || `source_id` | string | Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile); when unset, an unqualified read spans every federated source. Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources. || `types` | array | Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters. || `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ebd1b1b524..10495da62d 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -16,14 +16,14 @@ src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceilingsrc/core/cycle.ts 3264 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts)src/core/cycle/synthesize.ts 3208 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt-src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract+src/core/engine.ts 2726 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +5 Cat 40 Hard F2: countKeywordPages + searchKeywordPages declarations and KeywordPageWindow type importsrc/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row-src/core/pglite-engine.ts 2997 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); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out)-src/core/postgres-engine.ts 2942 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); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out)+src/core/pglite-engine.ts 3007 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); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out); +10 Cat 40 Hard F2: countKeywordPages + searchKeywordPages delegates (SQL in engine-sql/keyword-pages.ts) and their imports+src/core/postgres-engine.ts 2952 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); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out); +10 Cat 40 Hard F2: countKeywordPages + searchKeywordPages delegates (SQL in engine-sql/keyword-pages.ts) and their importssrc/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts-src/core/types.ts 2243 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +4 cat40 hard wave F1.6: SearchOpts.rankQuery and SearchResult.matched_alias+src/core/types.ts 2246 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +4 cat40 hard wave F1.6: SearchOpts.rankQuery and SearchResult.matched_alias; +3 Cat 40 Hard F2: keyword_count_unavailable degraded stage, SearchResult.evidence_omittedsrc/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c82e95f962..4d68fdc178 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -294,6 +294,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.105.0', text: 'gbrain learns more of the names an entity goes by: declared aliases now cover common prose cues ("also known as", "goes by", "formerly", "doing business as"), alias label lines and table rows ("Internal nickname: Copper Fox"), and multi-word names. Every brain re-derives aliases and rescans mentions once on its next `gbrain extract --stale` (autopilot runs it); `gbrain config set mentions.multiword_aliases false` keeps one-word aliases only and `mentions.alias_deny` drops a name.' },{ since: '0.60.105.0', text: 'Pages that name the same subject under different title prefixes ("Account sheet: X" and "CRM record: X") are shown as identity siblings on the entity card, never merged; a name both claim now links mentions to each of them instead of to neither. Frontmatter `identity: separate` or `gbrain config set mentions.sibling_merge false` keeps pages apart.' },{ since: '0.60.105.0', text: 'The entity card gains `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines that may name the entity otherwise) and `alias_guidance`; `aka` is unchanged. search and query also search every other name of the entity a query names (up to 4, keyword-only, rows marked `matched_alias`); `gbrain config set search.alias_fanout_max 0` turns that off.' },+ { since: '0.60.105.0', text: 'search now says how many pages match the query\'s keywords (`keyword_total`, up to 10000+) and adds one line after the rows saying they are a ranked top-K. `match: "keyword"` lists every keyword match with `total`, `truncated` and a ready-to-send `next`. An agent-facing `mode` is now refused (it was ignored) with a fix naming `match: "keyword"`, and an offset over 10,000 is refused.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/keyword-pages.ts b/src/core/engine-sql/keyword-pages.tsnew file mode 100644index 0000000000..5cee7a838a--- /dev/null+++ b/src/core/engine-sql/keyword-pages.ts@@ -0,0 +1,44 @@+/**+ * Page-grain keyword reads for `search` (Cat 40 Hard F2): the strict match+ * count and the keyword-mode page query, one implementation for both+ * engines. The statements build in `src/core/search/keyword-statement.ts`+ * from one WHERE builder; this module runs them through the engine's scoped+ * read (Postgres: `withScopedReadTransaction`, so RLS scope binding and+ * `SET LOCAL` settings stay transaction-scoped; PGLite brands its own+ * executor). Neither read retries with OR-of-terms: they report the strict+ * match set only.+ */+import type { SearchOpts, SearchResult } from '../types.ts';+import { rowToSearchResult } from '../utils.ts';+import { buildKeywordCountStatement, buildKeywordPagesStatement, type KeywordPageWindow } from '../search/keyword-statement.ts';+import type { ScopedReadRunner } from './cjk-search.ts';++/** Engine session settings: Postgres bounds each read with a statement timeout; PGLite has none. */+export interface KeywordPagesDialect { statementTimeout?: string }++/** Distinct pages matching the strict keyword query, at most KEYWORD_COUNT_CAP + 1. */+export async function countKeywordPages(+ scoped: ScopedReadRunner, query: string, opts: SearchOpts | undefined, dialect: KeywordPagesDialect & { timeoutMs?: number },+): Promise<number> {+ const statement = buildKeywordCountStatement(query, opts);+ if (!statement) return 0;+ const timeout = dialect.statementTimeout && dialect.timeoutMs ? `${Math.max(1, Math.floor(dialect.timeoutMs))}ms` : dialect.statementTimeout;+ const rows = await scoped(async (exec) => {+ if (timeout) await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [timeout]);+ return (await exec.unsafe<{ n: number }>(statement.sql, statement.params)).rows;+ });+ return Number(rows[0]?.n ?? 0);+}++/** One window of matching pages (best chunk each) in (score DESC, page_id ASC) order. */+export async function searchKeywordPages(+ scoped: ScopedReadRunner, query: string, opts: SearchOpts | undefined, page: KeywordPageWindow, dialect: KeywordPagesDialect,+): Promise<SearchResult[]> {+ const statement = buildKeywordPagesStatement(query, opts, page);+ if (!statement) return [];+ const rows = await scoped(async (exec) => {+ if (dialect.statementTimeout) await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [dialect.statementTimeout]);+ return (await exec.unsafe(statement.sql, statement.params)).rows;+ });+ return rows.map(rowToSearchResult);+}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 38d2c763f0..99bdb7c410 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -2,6 +2,7 @@ import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } froimport type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';import type { LinkReadScope } from './link-validity.ts';import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';+import type { KeywordPageWindow } from './search/keyword-statement.ts';import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';import type {@@ -1106,6 +1107,10 @@ export interface BrainEngine {// SearchsearchKeyword(query: string, opts?: SearchOpts): Promise<SearchResult[]>;+ /** Cat 40 Hard F2: pages matching searchKeyword's strict query (never the OR retry), capped at KEYWORD_COUNT_CAP + 1; `timeoutMs` bounds the Postgres statement. */+ countKeywordPages(query: string, opts?: SearchOpts & { timeoutMs?: number }): Promise<number>;+ /** Cat 40 Hard F2: `match: "keyword"` pages, best chunk each, ordered (score DESC, page_id ASC) with no global chunk cap. */+ searchKeywordPages(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): Promise<SearchResult[]>;/*** fix/title-retrieval-arm (D1): page-grain title candidate arm.*diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 91dfac266d..c1728ba101 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -299,6 +299,9 @@ export const CODES = {revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ search_cursor_requires_keyword: { class: 'caller', summary: "A search cursor was sent without match: \"keyword\"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page).", suggestion: 'Send the next object from the previous search response unchanged; it carries match: "keyword".' },+ search_mode_local_only: { class: 'caller', summary: "An agent-facing caller set search's mode, which only the brain's operator chooses.", suggestion: 'Omit mode; for keyword-only matching with a total and paging, pass match: "keyword".' },+ search_offset_over_cap: { class: 'caller', summary: "A search offset was over the 10,000 limit.", suggestion: 'Page with match: "keyword" and the next object each response returns; a cursor has no depth limit.' },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex a3fe6ebc76..5c166b4d7c 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -54,6 +54,7 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidancekeyword_candidates_incomplete: { why: 'CJK keyword matching hit its deadline or its candidate cap on a large corpus, so some keyword matches can be missing; narrow the search with source_id (the CLI source-id flag), or 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_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 },deadline: { why: 'the pack hit its time limit and is partial', fix: null },server_budget: { why: 'the server ran out of time budget for this pack', fix: null },};diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex e5d0c5fba0..d421c7107f 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -52,7 +52,10 @@ export const QUERY_DESCRIPTION ="Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.";export const SEARCH_DESCRIPTION =- "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.";+ "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match. Concepts or landscape: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.";++/** `search`'s `match` param (Cat 40 Hard F2). */+export const SEARCH_MATCH_DESCRIPTION = 'keyword: every keyword match, paged.';// ──────────────────────────────────────────────────────────────────────────────// v0.32.6 — contradiction probe MCP surface (M3)diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 6685b80b4e..6e011d896e 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -39,10 +39,12 @@ import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';import { probeProjectionReadiness } from '../search/projection-readiness.ts';import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';import { pageReadFilter } from '../search/read-policy-sql.ts';-import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';+import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';import { declaredNames, titleName } from '../mentions/aliases.ts';import { withAliasFanOut, type FanoutMeta } from '../search/alias-fanout.ts';import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';+import { keepEnumeratedRows, keywordCountMeta, parseSearchPaging, readKeywordPage, startKeywordCount, withCountMeta } from '../search/keyword-paging.ts';+import { searchLimitCap } from '../search/eval-pool-depth.ts';import { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';import { opError } from './contract.ts';import type { Operation, OperationContext } from './contract.ts';@@ -116,11 +118,11 @@ const FIELDS_PARAM = {const RETURN_UNIT_PARAM = {type: 'string' as const,enum: ['chunk', 'window', 'section', 'page', 'auto'],- description: 'auto (default) returns whole conversations.',+ description: 'Default auto: whole conversations.',};const RETURN_WINDOW_PARAM = {type: 'number' as const,- description: 'Neighbor chunks each side for window (1-3).',+ description: 'Window radius 1-3.',};/**@@ -157,9 +159,23 @@ async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, r/** withEvidence + the response meta for the rows actually returned + searchOutput. */async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null, scope: DeliveryScope,- meta: HybridSearchMeta | null, snippetCap: number, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>): Promise<SearchResult[]> {+ meta: HybridSearchMeta | null, snippetCap: number, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>, keepEnumerated = false): Promise<SearchResult[]> {const ev = await withEvidence(ctx, p, results, plan, scope, meta);- return searchOutput(ctx, p, ev.rows, await buildMeta(ev.rows), snippetCap, ev.evidence);+ const rows = keepEnumerated ? keepEnumeratedRows(results, ev.rows) : ev.rows;+ return searchOutput(ctx, p, rows, await buildMeta(rows), snippetCap, ev.evidence);+}++/** Keyword rows (every one a direct FTS hit): the markers hybridSearch would stamp, then bookkeeping. */+async function stampKeywordRows(ctx: OperationContext, results: SearchResult[], scope: SourceScope & { excludePrivate: boolean }, queryText: string, startedAt: number): Promise<void> {+ // #3783: mark before stamping so evidence still reads keyword_exact.+ markKeywordHits(results);+ stampDeepResearchIds(results);+ stampEvidenceSafe(results);+ // #1699 / #160: the content_flag channel and the unverified-stub marker still surface off the hybrid path.+ await stampContentFlags(ctx.engine, results, scope);+ await stampUnverifiedExtractions(ctx.engine, results, scope);+ bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));+ maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);}/**@@ -499,7 +515,7 @@ function normalizeTypesParam(ctx: OperationContext, tool: 'search' | 'query', raconst TYPES_PARAM_DESCRIPTION = "Page types, e.g. ['person'].";const SOURCE_ID_PARAM_DESCRIPTION = "One source, or '__all__'.";-const SALIENCE_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: 'Boost emotional pages (default: auto).' };+const SALIENCE_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: 'Boost emotional pages.' };/*** Ranking explanation params, declared on `query` only and advertised on the@@ -575,9 +591,9 @@ function finishExplainTarget(const { fix: _fix, ...wire } = diag;return wire as ExplainTargetDiagnosis;}-const RECENCY_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: "Boost recent pages (default: auto)." };+const RECENCY_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: "Boost recent pages." };-const SNIPPET_CHARS_PARAM_DESCRIPTION = 'Max chars per chunk_text (0 = full).';+const SNIPPET_CHARS_PARAM_DESCRIPTION = 'Chars per row (0 = full).';/** The query op's image branch embed; a brain that opted out of embedding refuses before the image reaches a provider. */async function embedSearchImage(ctx: OperationContext, data: string, mime: string): Promise<Float32Array> {@@ -617,8 +633,10 @@ const search: Operation = {description: SEARCH_DESCRIPTION,params: {query: { type: 'string', required: true, description: "Exact tokens or names, e.g. 'acme-example series A'." },- limit: { type: 'number', description: 'Max results (default 20).' },+ limit: { type: 'number', description: 'Default 20.' },offset: { type: 'number', description: 'Rows to skip.' },+ match: { type: 'string', enum: ['hybrid', 'keyword'], description: SEARCH_MATCH_DESCRIPTION },+ cursor: { type: 'string', description: 'From next.' },mode: { type: 'string', description: 'Local callers only.' },// #4398: per-call source scope, mirroring `query` — MCP clients passed it// here, got 'unknown parameter ignored', and read UNSCOPED results.@@ -629,7 +647,7 @@ const search: Operation = {snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },return_unit: RETURN_UNIT_PARAM,return_window: RETURN_WINDOW_PARAM,- token_budget: { type: 'number', description: 'Evidence token cap (default 6000).' },+ token_budget: { type: 'number', description: 'Default 6000.' },// #4415: explicit ranking-axis overrides (the same knobs `query` has had// since v0.29.1). The auto-detect banks are English regex, so on a// non-English brain the recency/salience stages never fire — these flags@@ -643,7 +661,9 @@ const search: Operation = {const startedAt = Date.now();const queryText = p.query as string;const limit = (p.limit as number) || 20;- const offset = (p.offset as number) || 0;+ // F2: match / cursor / offset cap / remote mode, refused before any search runs.+ const paging = parseSearchPaging(ctx, p);+ const offset = paging.offset;// #3985: validated multi-type filter, threaded into both branches below.let types = normalizeTypesParam(ctx, 'search', p.types);// #3800: snippet cap (param > subagent config default > full text).@@ -673,38 +693,30 @@ const search: Operation = {// hybrid `search` contract (privacy/cost: no query text to an embedding// provider). Defaults to cheap-hybrid (D4/D15).const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';+ const readOpts = { excludePrivate, requireSafeChunks: ctx.remote !== false, ...scope };- if (keywordOnly) {+ if (keywordOnly || paging.match === 'keyword') {if (types) {types = (await expandEngineTypeFilters(ctx.engine, { types, ...scope })).types;if (types?.length === 0) return [];}const sourceBoosts = resolveBoostMap(undefined, await ctx.engine.getConfig(SOURCE_BOOSTS_KEY));- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, source_boosts: sourceBoosts, ...(types ? { types } : {}), ...scope });- const results = dedupResults(raw).map(r => ({ ...r }));- // #3783 — every row here IS a keyword hit (direct FTS path); mark- // before stamping so evidence still reads keyword_exact.- markKeywordHits(results);- stampDeepResearchIds(results);- stampEvidenceSafe(results);- // #1699: the keyword-only opt-out must STILL surface the content_flag- // agent-warning channel (hybridSearch stamps it; this branch bypasses- // hybridSearch, so stamp explicitly). Fail-open inside the helper.- await stampContentFlags(ctx.engine, results, { ...scope, excludePrivate });- // #160: same for the unverified auto-extracted stub marker (no boost- // to cancel on this path — keyword-only never applies the compiled-- // truth boost — but the provenance marker must still surface).- await stampUnverifiedExtractions(ctx.engine, results, { ...scope, excludePrivate });- bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));- maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);+ const keywordOpts = { ...readOpts, source_boosts: sourceBoosts, ...(types ? { types } : {}) };+ // F2 `match: "keyword"`: page-grain enumeration, no diversity pruning, every page keeps a row.+ const page = paging.match === 'keyword' ? await readKeywordPage(ctx.engine, p, keywordOpts, paging, Math.min(limit, searchLimitCap())) : null;+ const keywordCount = page ? null : startKeywordCount(ctx.engine, queryText, undefined, keywordOpts);+ const results = (page ? page.rows : dedupResults(await ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts }))).map(r => ({ ...r }));+ await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt);// #3800: cap AFTER capture/meta so eval + cache see the real payload.return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap,- rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice }));+ async rows => withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice }),+ page ?? keywordCountMeta(await keywordCount!, offset + limit)), page !== null);}// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but// expansion OFF (no per-call LLM cost). `query` op is the full-control variant.let capturedMeta: HybridSearchMeta | null = null;+ const keywordCount = startKeywordCount(ctx.engine, queryText, types, readOpts);const explainPrep = await prepareExplainTarget(ctx, p, scope, excludePrivate, 'search');const searchOpts = {limit,@@ -737,7 +749,8 @@ const search: Operation = {maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);// #3800: cap AFTER capture/meta so eval + cache see the real payload.return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')));+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),+ keywordCountMeta(await keywordCount, offset + limit)));},scope: 'read', mutating: false,cliHints: { name: 'search', positional: ['query'] },diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 5346dbcd6d..b802112a51 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -146,9 +146,11 @@ import * as timelineImpl from './engine-sql/timeline.ts';import * as sourcesImpl from './engine-sql/sources.ts';import * as filesImpl from './engine-sql/files.ts';import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';+import type { KeywordPageWindow } from './search/keyword-statement.ts';import * as chunksImpl from './engine-sql/chunks.ts';import { searchKeywordCJK } from './engine-sql/cjk-search.ts';import * as titlesImpl from './engine-sql/titles.ts';+import * as keywordPagesImpl from './engine-sql/keyword-pages.ts';import { applyForwardReferenceBootstrap, pgliteBootstrapTarget } from './engine-sql/bootstrap.ts';/**@@ -1526,6 +1528,14 @@ export class PGLiteEngine implements BrainEngine {* query CAN exact-match a single-token CJK title); the richer CJK ILIKE* fallback stays keyword-arm-only.*/+ /** Cat 40 Hard F2 strict keyword count and keyword-mode pages; SQL in engine-sql/keyword-pages.ts. */+ async countKeywordPages(query: string, opts?: SearchOpts & { timeoutMs?: number }): Promise<number> {+ return keywordPagesImpl.countKeywordPages(async (read) => read(scopedRead(this.engineSql)), query, opts, {});+ }+ async searchKeywordPages(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): Promise<SearchResult[]> {+ return keywordPagesImpl.searchKeywordPages(async (read) => read(scopedRead(this.engineSql)), query, opts, page, {});+ }+async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {return titlesImpl.searchTitles(async (read) => read(scopedRead(this.engineSql)), query, opts, { relaxedPrefersIndex: false, staleProbe: true });}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 19f4dc5972..eb6c82751e 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -126,10 +126,12 @@ import * as timelineImpl from './engine-sql/timeline.ts';import * as sourcesImpl from './engine-sql/sources.ts';import * as filesImpl from './engine-sql/files.ts';import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';+import type { KeywordPageWindow } from './search/keyword-statement.ts';import * as chunksImpl from './engine-sql/chunks.ts';import { hasCJK } from './cjk.ts';import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';import * as titlesImpl from './engine-sql/titles.ts';+import * as keywordPagesImpl from './engine-sql/keyword-pages.ts';import type { CjkKeywordCtx } from './search/cjk-keyword-sql.ts';import { postgresExecutor, type RunUnsafeOpts } from './engine-sql/dialect-postgres.ts';import type { SqlExecutor } from './engine-sql/executor.ts';@@ -1119,6 +1121,14 @@ export class PostgresEngine implements BrainEngine {* predicate). Each attempt (strict, then OR fallback) runs in its own* scoped read transaction with an 8s statement timeout.*/+ /** Cat 40 Hard F2 strict keyword count and keyword-mode pages; SQL in engine-sql/keyword-pages.ts. */+ async countKeywordPages(query: string, opts?: SearchOpts & { timeoutMs?: number }): Promise<number> {+ return keywordPagesImpl.countKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, { statementTimeout: '8s', timeoutMs: opts?.timeoutMs });+ }+ async searchKeywordPages(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): Promise<SearchResult[]> {+ return keywordPagesImpl.searchKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, page, { statementTimeout: '8s' });+ }+async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {return titlesImpl.searchTitles((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }),diff --git a/src/core/search/keyword-paging.ts b/src/core/search/keyword-paging.tsnew file mode 100644index 0000000000..a1b79e7a8c--- /dev/null+++ b/src/core/search/keyword-paging.ts@@ -0,0 +1,225 @@+/**+ * Honest counts and exhaustive paging for `search` (Cat 40 Hard F2).+ *+ * Hybrid rows are a ranked top-K; agents read a full page of them as "this is+ * everything" and re-search instead of paging. So:+ * - every `search` reports `keyword_total` / `keyword_truncated`: distinct+ * pages matching the strict keyword query under the call's filters and+ * visibility (engine.countKeywordPages, never the OR-of-terms retry or a+ * capped pool), counted in parallel with the search under a deadline and+ * capped at 10,000 ("10000+"); a count that misses its deadline is the+ * `keyword_count_unavailable` degraded stage, never a number;+ * - `match: "keyword"` enumerates exactly that set at page grain in+ * (score DESC, page_id ASC) order with `total`, `truncated` and `next`+ * (a ready-to-send argument object holding a keyset cursor), the words+ * get_backlinks uses. Every enumerated page keeps a row, so `next` never+ * skips a page the caller did not receive;+ * - one model-visible line after the rows says which set the count covers+ * (dispatch renders `searchCountLine` from `_meta.retrieval`).+ *+ * Hybrid `offset` keeps its meaning (rows to skip in the ranked list). Any+ * offset is capped at 10,000; a `cursor` outside keyword mode and a remote+ * `mode` are refused with a fix that names `match: "keyword"`.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { DegradedStageEntry, SearchOpts, SearchResult } from '../types.ts';+import { opError, type OperationContext } from '../ops/contract.ts';+import { invalidParam } from '../ops/op-fix.ts';+import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';+import { KEYWORD_COUNT_CAP, type KeywordPageAfter } from './keyword-statement.ts';++export type SearchMatch = 'hybrid' | 'keyword';++export const SEARCH_OFFSET_CAP = 10_000;+/** The count's deadline: it runs beside the search and never holds the response longer. */+export const KEYWORD_COUNT_TIMEOUT_MS = 2_000;++/** Params a keyword `next` carries over unchanged. */+const CARRIED_PARAMS = ['limit', 'types', 'source_id', 'snippet_chars', 'return_unit', 'return_window', 'token_budget', 'fields'] as const;++interface KeywordCursor extends KeywordPageAfter { shown: number }++export interface SearchPaging { match: SearchMatch; offset: number; cursor: KeywordCursor | null }++/** Binds a cursor to the query and filters it was issued for. */+function fingerprint(p: Record<string, unknown>): string {+ return createHash('sha256').update(JSON.stringify([p.query, p.types ?? null, p.source_id ?? null])).digest('base64url').slice(0, 12);+}++function encodeCursor(after: KeywordPageAfter, shown: number, p: Record<string, unknown>): string {+ return Buffer.from(JSON.stringify({ v: 1, s: after.score, p: after.page_id, n: shown, f: fingerprint(p) })).toString('base64url');+}++function decodeCursor(raw: string, p: Record<string, unknown>): KeywordCursor | 'mismatch' | null {+ try {+ const c = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8')) as { v?: unknown; s?: unknown; p?: unknown; n?: unknown; f?: unknown };+ if (c.v !== 1 || typeof c.s !== 'number' || !Number.isFinite(c.s) || !Number.isInteger(c.p) || !Number.isInteger(c.n) || (c.n as number) < 0) return null;+ if (c.f !== fingerprint(p)) return 'mismatch';+ return { score: c.s, page_id: c.p as number, shown: c.n as number };+ } catch {+ return null;+ }+}++/** Validates `match`, `cursor`, `offset` and a remote `mode` before any search runs. */+export function parseSearchPaging(ctx: OperationContext, p: Record<string, unknown>): SearchPaging {+ if (p.match !== undefined && p.match !== 'hybrid' && p.match !== 'keyword') {+ throw invalidParam(ctx, 'search', 'match', `\`match\` must be "hybrid" or "keyword" (got ${JSON.stringify(p.match)}).`, { choices: ['hybrid', 'keyword'], example: 'keyword' });+ }+ const match: SearchMatch = p.match === 'keyword' ? 'keyword' : 'hybrid';+ if (ctx.remote !== false && typeof p.mode === 'string' && p.mode !== '') {+ const { mode: _mode, ...rest } = p;+ throw opError('search_mode_local_only', 'search: mode is set by the brain\'s operator and cannot be chosen per call.',+ 'Omit mode. For keyword-only matching with a total and a next page, pass match: "keyword".',+ { fix: { mcp: { tool: 'search', arguments: { ...rest, ...(/keyword|lexical|exact|fts|text/i.test(p.mode) ? { match: 'keyword' } : {}) } },+ consent: [], actor: 'agent', requires_exclusive: false, why: 'The same search without mode.' } });+ }+ const offset = typeof p.offset === 'number' && Number.isFinite(p.offset) ? Math.max(0, Math.floor(p.offset)) : 0;+ if (offset > SEARCH_OFFSET_CAP) {+ throw opError('search_offset_over_cap', `search: offset ${offset} is over the ${SEARCH_OFFSET_CAP.toLocaleString('en-US')} limit.`,+ 'Page with match: "keyword" and send the next object each response returns; a cursor has no depth limit.');+ }+ if (p.cursor === undefined) return { match, offset, cursor: null };+ if (match !== 'keyword') {+ throw opError('search_cursor_requires_keyword', 'search: cursor continues a match: "keyword" listing; this call is hybrid.',+ 'Send the next object from the previous response unchanged (it carries match: "keyword"). Hybrid rows are a ranked top-K with no next page.',+ { fix: { mcp: { tool: 'search', arguments: { ...p, match: 'keyword' } }, consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Continues the keyword listing from the cursor.' } });+ }+ if (offset > 0) throw invalidParam(ctx, 'search', 'offset', 'search: pass cursor or offset, not both.', { example: 0 });+ const cursor = typeof p.cursor === 'string' ? decodeCursor(p.cursor, p) : null;+ if (cursor === null) throw invalidParam(ctx, 'search', 'cursor', 'search: cursor is not one this tool returned.', { example: 'the next object from the previous response' });+ if (cursor === 'mismatch') {+ throw invalidParam(ctx, 'search', 'cursor', 'search: this cursor belongs to a different query, types or source_id.', { example: 'the next object from the previous response' });+ }+ return { match, offset, cursor };+}++export type KeywordCount = { total: number; capped: boolean } | { unavailable: 'timeout' | 'error' };++const isTimeout = (e: unknown) => /statement timeout|canceling statement/i.test(e instanceof Error ? e.message : String(e))+ || (e as { code?: unknown } | null)?.code === '57014';++/** The strict keyword count under a deadline; a late or failed count is unavailable, never a number. */+export async function countKeywordMatches(engine: BrainEngine, query: string, opts: SearchOpts, timeoutMs = KEYWORD_COUNT_TIMEOUT_MS): Promise<KeywordCount> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<KeywordCount>(resolve => { timer = setTimeout(() => resolve({ unavailable: 'timeout' }), timeoutMs); });+ const count = engine.countKeywordPages(query, { ...opts, timeoutMs })+ .then((n): KeywordCount => ({ total: Math.min(n, KEYWORD_COUNT_CAP), capped: n > KEYWORD_COUNT_CAP }))+ .catch((e): KeywordCount => ({ unavailable: isTimeout(e) ? 'timeout' : 'error' }));+ try {+ return await Promise.race([count, deadline]);+ } finally {+ clearTimeout(timer);+ }+}++/**+ * The hybrid path's count, started before the search so both run at once.+ * Types expand the way hybridSearch expands them; a filter that expands to+ * nothing matches nothing.+ */+export function startKeywordCount(engine: BrainEngine, query: string, types: string[] | undefined, opts: SearchOpts): Promise<KeywordCount> {+ return (async (): Promise<KeywordCount> => {+ const expanded = types ? (await expandEngineTypeFilters(engine, { types, ...opts })).types : undefined;+ if (expanded?.length === 0) return { total: 0, capped: false };+ return countKeywordMatches(engine, query, { ...opts, ...(expanded ? { types: expanded } : {}) });+ })().catch((): KeywordCount => ({ unavailable: 'error' }));+}++/** Adds count fields (and the unavailable stage) to a built retrieval meta. */+export function withCountMeta(meta: Record<string, unknown>, extra: { meta: Record<string, unknown>; degraded?: DegradedStageEntry }): Record<string, unknown> {+ if (!extra.degraded) return { ...meta, ...extra.meta };+ return { ...meta, ...extra.meta, degraded: [...((meta.degraded as unknown[] | undefined) ?? []), extra.degraded] };+}++/** Response meta for the hybrid path: `keyword_total` / `keyword_truncated`, or the unavailable stage. */+export function keywordCountMeta(count: KeywordCount, shownThrough: number): { meta: Record<string, unknown>; degraded?: DegradedStageEntry } {+ if ('unavailable' in count) {+ return { meta: { keyword_total: null }, degraded: { stage: 'keyword_count_unavailable', ...(count.unavailable === 'timeout' ? { reason: 'timeout' as const } : {}) } };+ }+ return { meta: { keyword_total: count.total, keyword_truncated: count.capped || count.total > shownThrough, ...(count.capped ? { keyword_total_capped: true } : {}) } };+}++export interface KeywordPage {+ rows: SearchResult[];+ meta: Record<string, unknown>;+ degraded?: DegradedStageEntry;+}++/**+ * One `match: "keyword"` page: limit + 1 rows probe `truncated` (so `next`+ * never depends on the count), the count runs beside them.+ */+export async function readKeywordPage(engine: BrainEngine, p: Record<string, unknown>, opts: SearchOpts, paging: SearchPaging, limit: number): Promise<KeywordPage> {+ const queryText = String(p.query);+ const [probe, count] = await Promise.all([+ engine.searchKeywordPages(queryText, opts, { limit: limit + 1, ...(paging.cursor ? { after: paging.cursor } : { offset: paging.offset }) }),+ countKeywordMatches(engine, queryText, opts),+ ]);+ const rows = probe.slice(0, limit);+ const start = paging.cursor ? paging.cursor.shown : paging.offset;+ const truncated = probe.length > limit;+ const last = rows[rows.length - 1];+ let next: Record<string, unknown> | undefined;+ if (truncated && last) {+ next = { query: queryText, match: 'keyword' };+ for (const key of CARRIED_PARAMS) if (p[key] !== undefined) next[key] = p[key];+ next.cursor = encodeCursor({ score: last.score, page_id: last.page_id }, start + rows.length, p);+ }+ const counted = 'unavailable' in count ? null : count;+ const degraded = counted ? undefined : keywordCountMeta(count, 0).degraded;+ return {+ rows,+ meta: {+ match: 'keyword',+ total: counted ? counted.total : null,+ ...(counted?.capped ? { total_capped: true } : {}),+ truncated,+ shown_from: start + 1,+ shown_to: start + rows.length,+ ...(next ? { next } : {}),+ },+ ...(degraded ? { degraded } : {}),+ };+}++/**+ * Enumeration is separate from evidence: every enumerated page keeps its row+ * in order. A page whose text did not fit the evidence budget (or could not+ * be read for it) comes back without text and with `evidence_omitted: true`.+ */+export function keepEnumeratedRows<T extends SearchResult>(enumerated: SearchResult[], delivered: T[]): Array<T | SearchResult> {+ const byPage = new Map(delivered.map(r => [r.page_id, r]));+ return enumerated.map(r => byPage.get(r.page_id) ?? { ...r, chunk_text: '', evidence_omitted: true });+}++const countWords = (n: number, capped: boolean | undefined) => `${capped ? `${n}+` : n} page${n === 1 && !capped ? '' : 's'}`;++/**+ * The model-visible line after the rows (null when the call carries no+ * count): which set the rows are, which set the count covers, and the next+ * call. Reads only `_meta.retrieval` keys this module writes.+ */+export function searchCountLine(rows: unknown, retrieval: unknown): string | null {+ if (retrieval === null || typeof retrieval !== 'object') return null;+ const r = retrieval as Record<string, unknown>;+ const stage = Array.isArray(r.degraded) ? r.degraded.find(d => (d as { stage?: unknown })?.stage === 'keyword_count_unavailable') : undefined;+ const reason = (stage as { reason?: unknown } | undefined)?.reason === 'timeout' ? 'timed out' : 'failed';+ if (r.match === 'keyword') {+ const total = typeof r.total === 'number'+ ? `Keyword matches: ${countWords(r.total, r.total_capped === true)}`+ : `Keyword match count unavailable (${reason}; not a count of zero)`;+ const omitted = Array.isArray(rows) ? rows.filter(x => (x as { evidence_omitted?: unknown })?.evidence_omitted === true).length : 0;+ const shown = Number(r.shown_to) < Number(r.shown_from) ? 'none on this page' : `showing ${r.shown_from}-${r.shown_to}, keyword-score order`;+ return `[gbrain search] ${total}; ${shown}.`+ + (omitted ? ` ${omitted} row(s) have evidence_omitted: true (text did not fit token_budget; read with get_page).` : '')+ + (r.next ? ` More: call search with next = ${JSON.stringify(r.next)}` : ' No more keyword matches.');+ }+ if (!('keyword_total' in r)) return null;+ const count = typeof r.keyword_total === 'number'+ ? `Keyword matches: ${countWords(r.keyword_total, r.keyword_total_capped === true)} (pages matching the query's keywords, not a count of these rows)`+ : `Keyword match count unavailable (${reason}; not a count of zero)`;+ return `[gbrain search] Rows are a ranked top-K, not proof of coverage. ${count}. List every keyword match with match: "keyword".`;+}diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.tsnew file mode 100644index 0000000000..8d690900a5--- /dev/null+++ b/src/core/search/keyword-statement.ts@@ -0,0 +1,126 @@+/**+ * Page-grain keyword statements for `search` (Cat 40 Hard F2): the strict+ * keyword match count (`keyword_total` on hybrid calls, `total` with+ * `match: "keyword"`) and the keyword-mode page query. Both read ONE WHERE+ * builder, so a count can never include a page the rows could not return.+ *+ * The match is `engine.searchKeyword`'s strict match, never its OR-of-terms+ * retry: `websearch_to_tsquery` over `content_chunks.search_vector` (the CJK+ * branch: every term as a LIKE/ILIKE substring), text chunks only, with the+ * same page filters (type/types, exclude_slugs, language/symbol kind, dates,+ * source scope, hard-excluded prefixes) and the same visibility predicate+ * (soft delete, archived source, quarantine, current projection, private+ * pages, safe chunks). Safe-chunk pages hold no private takes/facts fence+ * text, so an untrusted caller's count never counts fence text.+ *+ * The page query takes the best chunk of every matching page BEFORE paging+ * (no global chunk cap: one page with hundreds of matching chunks cannot+ * crowd the others out) and orders pages by (score DESC, page_id ASC), the+ * keyset the cursor resumes from. Scores are float8 so a cursor's score+ * round-trips through JSON exactly.+ */+import type { SearchOpts } from '../types.ts';+import { escapeLikePattern, hasCJK, splitCJKQueryTerms } from '../cjk.ts';+import { getFtsLanguage } from '../fts-language.ts';+import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';+import { buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';++/** Counts stop here; a capped count is reported as "10000+". */+export const KEYWORD_COUNT_CAP = 10_000;++/** Where the keyword-mode page query resumes: after this (score, page_id). */+export interface KeywordPageAfter { score: number; page_id: number }++export interface KeywordPageWindow { limit: number; offset?: number; after?: KeywordPageAfter }++interface KeywordMatch { where: string; score: string; params: unknown[] }++const FROM = `content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id`;++/** The shared match: WHERE text (with leading predicate) and the chunk score, or null when nothing can match. */+export function buildKeywordMatch(query: string, opts: SearchOpts | undefined): KeywordMatch | null {+ const params: unknown[] = [];+ let predicate: string;+ let rank: string;+ if (hasCJK(query)) {+ const terms = splitCJKQueryTerms(query);+ if (terms.length === 0) return null;+ const likes = terms.map(term => {+ params.push(`%${escapeLikePattern(term)}%`);+ return `cc.chunk_text ${term.toLowerCase() === term.toUpperCase() ? 'LIKE' : 'ILIKE'} $${params.length} ESCAPE '\\'`;+ });+ const freq = terms.map(term => {+ params.push(term);+ return `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${params.length}, ''))) / NULLIF(LENGTH($${params.length}), 0)::real)`;+ });+ predicate = likes.join(' AND ');+ rank = freq.join(' + ');+ } else {+ if (query.trim() === '') return null;+ params.push(query);+ const tsq = `websearch_to_tsquery('${getFtsLanguage()}', $${params.length})`;+ predicate = `cc.search_vector @@ ${tsq}`;+ rank = `ts_rank(cc.search_vector, ${tsq})`;+ }+ const add = (value: unknown, clause: (n: string) => string): string => { params.push(value); return ` AND ${clause(`$${params.length}`)}`; };+ let filters = '';+ if (opts?.detail === 'low') filters += ` AND cc.chunk_source = 'compiled_truth'`;+ if (opts?.language) filters += add(opts.language, n => `cc.language = ${n}`);+ if (opts?.symbolKind) filters += add(opts.symbolKind, n => `cc.symbol_type = ${n}`);+ if (opts?.type) filters += add(opts.type, n => `p.type = ${n}`);+ if (opts?.types?.length) filters += add(opts.types, n => `p.type = ANY(${n}::text[])`);+ if (opts?.exclude_slugs?.length) filters += add(opts.exclude_slugs, n => `p.slug != ALL(${n}::text[])`);+ const dated = `COALESCE(p.effective_date, p.updated_at, p.created_at)`;+ if (opts?.afterDate) filters += add(opts.afterDate, n => `${dated} ${opts.afterDateInclusive ? '>=' : '>'} ${n}::text::timestamptz`);+ if (opts?.beforeDate) filters += add(opts.beforeDate, n => `${dated} ${opts.beforeDateInclusive ? '<=' : '<'} ${n}::text::timestamptz`);+ if (opts?.sourceIds?.length) filters += add(opts.sourceIds, n => `p.source_id = ANY(${n}::text[])`);+ else if (opts?.sourceId) filters += add(opts.sourceId, n => `p.source_id = ${n}`);+ const hardExclude = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));+ const factor = buildSourceFactorCase('p.slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail);+ return {+ where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts)} AND cc.modality = 'text'`,+ score: `((${rank}) * ${factor})::float8`,+ params,+ };+}++/** Distinct matching pages, capped at KEYWORD_COUNT_CAP + 1. */+export function buildKeywordCountStatement(query: string, opts: SearchOpts | undefined): { sql: string; params: unknown[] } | null {+ const m = buildKeywordMatch(query, opts);+ if (!m) return null;+ return {+ sql: `SELECT count(*)::int AS n FROM (SELECT DISTINCT cc.page_id FROM ${FROM} WHERE ${m.where} LIMIT ${KEYWORD_COUNT_CAP + 1}) matched`,+ params: m.params,+ };+}++/** One page of matching pages, best chunk each, in keyset order. */+export function buildKeywordPagesStatement(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): { sql: string; params: unknown[] } | null {+ const m = buildKeywordMatch(query, opts);+ if (!m) return null;+ const params = [...m.params];+ let after = '';+ if (page.after) {+ params.push(page.after.score, page.after.page_id);+ const s = `$${params.length - 1}::float8`;+ after = `WHERE b.score < ${s} OR (b.score = ${s} AND b.page_id > $${params.length}::bigint)`;+ }+ params.push(page.limit, page.offset ?? 0);+ const messageId = `NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL`;+ return {+ sql: `WITH matched AS (+ SELECT cc.page_id, cc.id AS chunk_id, ${m.score} AS score FROM ${FROM} WHERE ${m.where}+ ), best AS (+ SELECT DISTINCT ON (page_id) page_id, chunk_id, score FROM matched ORDER BY page_id, score DESC, chunk_id ASC+ )+ SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source,+ CASE WHEN ${messageId} THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,+ CASE WHEN ${messageId} THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,+ cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, b.score, false AS stale+ FROM best b JOIN pages p ON p.id = b.page_id JOIN content_chunks cc ON cc.id = b.chunk_id+ ${after}+ ORDER BY b.score DESC, b.page_id ASC+ LIMIT $${params.length - 1} OFFSET $${params.length}`,+ params,+ };+}diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.tsindex 33e7cd51c4..4e55d9e2e1 100644--- a/src/core/search/lean-rows.ts+++ b/src/core/search/lean-rows.ts@@ -15,7 +15,8 @@* message_id, thread_id, source_subject, matched_alias (the other name the* alias fan-out searched); modality when not text; stale* only when set (true, or the held-file object from #5988);- * - `delivered: { truncated: true }` whenever evidence delivery truncated.+ * - `delivered: { truncated: true }` whenever evidence delivery truncated;+ * - `evidence_omitted` on a keyword-mode row whose text did not fit.* `fields: "full"`, the `mcp.result_rows: full` host config and gbrain's own* thin client get every field; trusted local callers always do.*/@@ -29,6 +30,8 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set(['evidence', 'create_safety','injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by','message_id', 'thread_id', 'source_subject', 'relational', 'matched_alias',+ // `match: "keyword"`: an enumerated page whose text did not fit the evidence budget.+ 'evidence_omitted',// Present only when the caller asked for `explain: true`.'score_details',]);diff --git a/src/core/types.ts b/src/core/types.tsindex fbf1492c38..c139be3f28 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -846,6 +846,8 @@ export interface SearchResult {keyword_relaxed?: boolean;/** Set on rows search's alias fan-out spliced in: the entity's other name that found this page (search/alias-fanout.ts). */matched_alias?: string;+ /** `search` `match: "keyword"`: an enumerated page whose text did not fit the evidence budget keeps its row, without text. */+ evidence_omitted?: boolean;/*** Extraction quarantine lane (issue #160): true when the result's page is* an unverified auto-extracted entity stub (frontmatter@@ -2006,6 +2008,7 @@ export const DEGRADED_STAGES = ['keyword_candidates_incomplete','projection_pending','projection_status_unknown',+ 'keyword_count_unavailable',] as const;export type DegradedStage = (typeof DEGRADED_STAGES)[number];diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex f5feb66dc0..8aba94132f 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -19,6 +19,7 @@ import { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger, type NoticeAudience } from '../core/notice-ledger.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';+import { searchCountLine } from '../core/search/keyword-paging.ts';import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';import { hiddenToolHint } from './hidden-tool-hint.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';@@ -370,7 +371,7 @@ export function summarizeMcpParams(opName: string, params: unknown): ParamSummar/*** Model-visible notices the search/query ops attach to `_meta.retrieval`: the* D8 empty-retrieval diagnosis, a reconciled type filter, other names declared in the evidence, and saved- * facts that match the query. Each rides as its own text block after the+ * facts that match the query, and search's keyword count line. Each rides as its own text block after the* results (content[0] stays the bare result array for thin clients).*/export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): string[] {@@ -396,6 +397,9 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri'\n', SAVED_FACTS_NOTICE_MAX_CHARS);blocks.push(more ? `${text}\n(+${more} more; recall returns them)` : text);}+ // F2: which set the rows are and which set the keyword count covers, on every search call.+ const countLine = searchCountLine(result, retrieval);+ if (countLine) blocks.push(countLine);if (typeof r.answer_id === 'string' && r.feedback?.rateable === true) blocks.push(rateLine(r.answer_id, typeof r.feedback.how_to_rate === 'string'));return blocks;}diff --git a/test/dispatch-response-meta.serial.test.ts b/test/dispatch-response-meta.serial.test.tsindex ece36a7a10..d67e5943e3 100644--- a/test/dispatch-response-meta.serial.test.ts+++ b/test/dispatch-response-meta.serial.test.ts@@ -37,6 +37,8 @@ const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');const engineStub = {getConfig: async () => null,+ // Cat 40 Hard F2: the strict keyword count every search reports (no matches here).+ countKeywordPages: async () => 0,executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],} as unknown as BrainEngine;@@ -67,11 +69,13 @@ describe('dispatch response meta (WP2/D3/D8)', () => {expect(JSON.parse(out.content[0].text)).toEqual([]);// D8: the model-visible diagnosis block, then F3's degraded_recall notice// (agent contract v1: a recall-affecting stage always rides a notice).- expect(out.content.length).toBe(3);- expect(out.content[2].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');- expect(out.content[1].text).toContain('0 results');- expect(out.content[1].text).toContain('retrieved 3');- expect(out.content[1].text).toContain('degraded: embed_unavailable');+ // F2: the keyword count line rides right after the rows, before the notices.+ expect(out.content.length).toBe(4);+ expect(out.content[1].text).toStartWith('[gbrain search] Rows are a ranked top-K');+ expect(out.content[3].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');+ expect(out.content[2].text).toContain('0 results');+ expect(out.content[2].text).toContain('retrieved 3');+ expect(out.content[2].text).toContain('degraded: embed_unavailable');const retrieval = (out._meta as Record<string, any>).retrieval;expect(retrieval.returned_count).toBe(0);expect(retrieval.retrieved_count).toBe(3);@@ -82,8 +86,9 @@ describe('dispatch response meta (WP2/D3/D8)', () => {nextResults = [];nextMeta = { vector_enabled: true, expansion_applied: false, detail_resolved: null };const out = await callSearch();- expect(out.content.length).toBe(2);- expect(out.content[1].text).toContain('clean miss');+ expect(out.content.length).toBe(3);+ expect(out.content[1].text).toContain('Keyword matches: 0 pages');+ expect(out.content[2].text).toContain('clean miss');const retrieval = (out._meta as Record<string, any>).retrieval;expect(retrieval.degraded).toBeUndefined();expect(retrieval.vector_enabled).toBe(true);@@ -94,8 +99,9 @@ describe('dispatch response meta (WP2/D3/D8)', () => {nextMeta = DEGRADED_META;const out = await callSearch();// No empty-retrieval block; F3's degraded notice rides every affected HTTP call.- expect(out.content.length).toBe(2);- expect(out.content[1].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');+ expect(out.content.length).toBe(3);+ expect(out.content[1].text).toStartWith('[gbrain search] Rows are a ranked top-K');+ expect(out.content[2].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');const retrieval = (out._meta as Record<string, any>).retrieval;expect(retrieval.returned_count).toBe(1);});diff --git a/test/dispatch-vector-incomplete.serial.test.ts b/test/dispatch-vector-incomplete.serial.test.tsindex 0dba0fb456..c5ce1b940c 100644--- a/test/dispatch-vector-incomplete.serial.test.ts+++ b/test/dispatch-vector-incomplete.serial.test.ts@@ -19,6 +19,7 @@ mock.module('../src/core/search/hybrid.ts', () => ({const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');const engine = {getConfig: async () => null,+ countKeywordPages: async () => 0,executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],} as unknown as BrainEngine;@@ -33,8 +34,9 @@ describe('HTTP MCP dispatch preserves bounded-vector incompleteness', () => {expect(retrieval.degraded).toContainEqual({ stage: 'vector_candidates_incomplete', reason: 'candidate_budget' });expect(retrieval.vector_pool_underfilled).toEqual({ escalations: 3, innerLimit: 1600, candidatePool: 0, incomplete: true });if (!nonempty) {- expect(response.content[1].text).toContain('vector_candidates_incomplete');- expect(response.content[1].text).not.toContain('clean miss');+ // content[1] is F2's keyword count line; the empty-retrieval diagnosis follows it.+ expect(response.content[2].text).toContain('vector_candidates_incomplete');+ expect(response.content[2].text).not.toContain('clean miss');}});});diff --git a/test/e2e/search-keyword-paging-parity.test.ts b/test/e2e/search-keyword-paging-parity.test.tsnew file mode 100644index 0000000000..efa778c3e0--- /dev/null+++ b/test/e2e/search-keyword-paging-parity.test.ts@@ -0,0 +1,118 @@+/**+ * Cat 40 Hard F2 engine parity: the strict keyword count and the keyword-mode+ * walk behave the same on PGLite and Postgres (Postgres arm runs when+ * DATABASE_URL is set; the PGLite arm always runs).+ *+ * Both engines delegate to src/core/engine-sql/keyword-pages.ts, but Postgres+ * runs it inside withScopedReadTransaction with a statement timeout and+ * returns float8 scores through postgres.js; a keyset cursor that does not+ * round-trip there would repeat or skip pages only on Postgres.+ *+ * Authoring gate: (1) every page `total` reports is reachable on both engines,+ * with a dominant page, mixed types, a mid-walk write and private fence text;+ * (2) fails if either engine's scores lose precision through the cursor, if+ * the count drifts from the rows, or if the OR retry leaks into the count;+ * (3) the unit suite runs PGLite only; (4) no seam.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { DOMINANT_SLUG, MIXED_TYPES, TERM, callSearch, seedKeywordCorpus, seedPage, walkKeyword } from '../helpers/keyword-paging-fixture.ts';++const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;+const arms: Partial<Record<(typeof backends)[number], { engine: BrainEngine; matching: string[] }>> = {};+const closers: Array<() => Promise<void>> = [];++beforeAll(async () => {+ for (const backend of backends) {+ let engine: BrainEngine;+ if (backend === 'postgres') {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = isolated.engine;+ closers.push(isolated.close);+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ closers.push(() => engine.disconnect());+ }+ arms[backend] = { engine, matching: await seedKeywordCorpus(engine) };+ }+}, 300_000);++afterAll(async () => { for (const close of closers) await close(); });++for (const backend of backends) {+ describe(`keyword paging on ${backend}`, () => {+ const arm = () => arms[backend]!;++ test('walk past 3 x limit recovers every page total reports, the dominant page once', async () => {+ const { pages, slugs } = await walkKeyword(arm().engine, { query: TERM, limit: 4 });+ expect(pages.length).toBeGreaterThan(3);+ expect(pages[0].retrieval.total).toBe(arm().matching.length);+ expect(new Set(slugs).size).toBe(slugs.length);+ expect([...slugs].sort()).toEqual([...arm().matching].sort());+ expect(slugs.filter(s => s === DOMINANT_SLUG).length).toBe(1);+ });++ test('a query only the OR retry matches: total 0', async () => {+ expect((await arm().engine.searchKeyword('zephyrine obsidianite', { orFallback: true })).length).toBe(2);+ const page = await callSearch(arm().engine, { query: 'zephyrine obsidianite', match: 'keyword' });+ expect(page.retrieval).toMatchObject({ total: 0, truncated: false });+ expect(page.rows).toEqual([]);+ expect((await callSearch(arm().engine, { query: 'zephyrine obsidianite' })).retrieval.keyword_total).toBe(0);+ });++ test('page boundaries and mixed types', async () => {+ const n = arm().matching.length;+ const exact = await walkKeyword(arm().engine, { query: TERM, limit: n / 4 });+ expect(exact.pages.map(p => p.retrieval.truncated)).toEqual([true, true, true, false]);+ expect(exact.pages[3].retrieval.next).toBeUndefined();+ const typed = await walkKeyword(arm().engine, { query: TERM, limit: 3, types: ['meeting'] });+ expect(typed.pages[0].retrieval.total).toBe(MIXED_TYPES);+ expect(typed.slugs.length).toBe(MIXED_TYPES);+ });++ test('a write mid-walk repeats nothing and loses no unchanged page', async () => {+ const { slugs } = await walkKeyword(arm().engine, { query: TERM, limit: 5 }, true, 50, async page => {+ if (page === 1) await seedPage(arm().engine, 'notes/zz-mid-walk', `A ${TERM} note written mid-walk.`);+ });+ expect(new Set(slugs).size).toBe(slugs.length);+ for (const slug of arm().matching) expect(slugs).toContain(slug);+ await arm().engine.executeRaw(`DELETE FROM pages WHERE slug = 'notes/zz-mid-walk'`);+ });++ test('short, oversized, short under a small evidence budget keeps every row in order', async () => {+ const e = arm().engine;+ await seedPage(e, 'meetings/sos-1', `${TERM} ${TERM} ${TERM} sos short one.`, { type: 'meeting' });+ await seedPage(e, 'meetings/sos-2', `${TERM} sos oversized middle. ${'Filler sentence about logistics planning. '.repeat(400)}`, { type: 'meeting' });+ await seedPage(e, 'meetings/sos-3', `${TERM} sos short three.`, { type: 'meeting' });+ try {+ const page = await callSearch(e, { query: `${TERM} sos`, match: 'keyword', types: ['meeting'], return_unit: 'page', token_budget: 60 });+ expect(page.rows.map(r => r.slug)).toEqual(['meetings/sos-1', 'meetings/sos-2', 'meetings/sos-3']);+ expect(page.rows.filter(r => r.evidence_omitted).map(r => r.slug)).toEqual(['meetings/sos-2']);+ } finally {+ await e.executeRaw(`DELETE FROM pages WHERE slug LIKE 'meetings/sos-%'`);+ }+ });++ test('private fence text is not counted for remote callers', async () => {+ const e = arm().engine;+ await seedPage(e, 'notes/fenced', 'Public body.\n<!--- gbrain:takes:begin -->\nThe marmoset deal is risky.\n<!--- gbrain:takes:end -->');+ try {+ expect((await callSearch(e, { query: 'marmoset' }, true)).retrieval.keyword_total).toBe(0);+ expect((await callSearch(e, { query: 'marmoset', match: 'keyword' }, true)).retrieval.total).toBe(0);+ } finally {+ await e.executeRaw(`DELETE FROM pages WHERE slug = 'notes/fenced'`);+ }+ });+ });+}++if (backends.length === 2) {+ test('both engines enumerate the same pages in the same order', async () => {+ const [a, b] = await Promise.all(backends.map(k => walkKeyword(arms[k]!.engine, { query: TERM, limit: 6 })));+ expect(b.slugs).toEqual(a.slugs);+ });+}diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.tsindex 112aacbf0f..40cc2d6bd4 100644--- a/test/engine-surface-coverage.test.ts+++ b/test/engine-surface-coverage.test.ts@@ -54,7 +54,7 @@ const INTERFACE_METHODS: readonly string[] = ['softDeletePage', 'softDeletePages', 'restorePage', 'purgeDeletedPages', 'listPages', 'resolveSlugs', 'getAllSlugs','listAllPageRefs', 'listAllSources', 'updateSourceConfig', 'listPrefixSampledPages', 'listCorpusSample',// Search- 'searchKeyword', 'searchTitles', 'searchVector', 'getEmbeddingsByChunkIds',+ 'searchKeyword', 'countKeywordPages', 'searchKeywordPages', 'searchTitles', 'searchVector', 'getEmbeddingsByChunkIds',// Chunks'upsertChunks', 'getChunks', 'getChunkWindows', 'countStaleChunks', 'sumStaleChunkChars', 'setPageEmbeddingSignature','invalidateStaleSignatureEmbeddings', 'invalidateContentDriftEmbeddings', 'listStaleChunks',diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 2db565e1ea..7fb4031952 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -688,9 +688,9 @@" --limit Default 10/25/50 by search mode."," --offset Rows to skip."," --types Page types, e.g. ['person'].",- " --snippet-chars Max chars per chunk_text (0 = full).",- " --return-unit auto (default) returns whole conversations.",- " --return-window Neighbor chunks each side for window (1-3).",+ " --snippet-chars Chars per row (0 = full).",+ " --return-unit Default auto: whole conversations.",+ " --return-window Window radius 1-3."," --token-budget Evidence token cap."," --expand Default true; false skips the LLM expansion."," --detail low (compiled truth), medium (default) or high (all chunks).",@@ -700,8 +700,8 @@" --symbol-kind Code symbol type."," --near-symbol Anchor code symbol."," --walk-depth Code walk depth 1-2.",- " --salience Boost emotional pages (default: auto).",- " --recency Boost recent pages (default: auto).",+ " --salience Boost emotional pages.",+ " --recency Boost recent pages."," --since On/after: YYYY-MM-DD or 7d/2w/1y."," --until On/before."," --source-id One source, or '__all__'.",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 2bfd3bf9a3..1fd814aa2b 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 208662,- "stdoutSha256": "fae8f0c4da15f44cc70930976ee107142ab781deada2794a89c6f5947ab95082",+ "stdoutBytes": 208759,+ "stdoutSha256": "5de3a39404e4ab9c60d0a87de666fadafb6e96795bc53031c1507238e64787ad","toolNames": ["remember","entity",@@ -1005,14 +1005,16 @@"scope": "write"},{- "description": "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.",+ "description": "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match. Concepts or landscape: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.","idempotent": true,"local_only": false,"mutating": false,"name": "search","parameters": {+ "cursor": "string?","fields": "string?","limit": "number?",+ "match": "string?","mode": "string?","offset": "number?","query": "string",@@ -1028,6 +1030,10 @@"required_scopes": [],"schema": {"properties": {+ "cursor": {+ "description": "From next.",+ "type": "string"+ },"fields": {"description": "lean (remote default) or full.","enum": [@@ -1037,9 +1043,17 @@"type": "string"},"limit": {- "description": "Max results (default 20).",+ "description": "Default 20.","type": "number"},+ "match": {+ "description": "keyword: every keyword match, paged.",+ "enum": [+ "hybrid",+ "keyword"+ ],+ "type": "string"+ },"mode": {"description": "Local callers only.","type": "string"@@ -1053,7 +1067,7 @@"type": "string"},"recency": {- "description": "Boost recent pages (default: auto).",+ "description": "Boost recent pages.","enum": ["off","on",@@ -1062,7 +1076,7 @@"type": "string"},"return_unit": {- "description": "auto (default) returns whole conversations.",+ "description": "Default auto: whole conversations.","enum": ["chunk","window",@@ -1073,11 +1087,11 @@"type": "string"},"return_window": {- "description": "Neighbor chunks each side for window (1-3).",+ "description": "Window radius 1-3.","type": "number"},"salience": {- "description": "Boost emotional pages (default: auto).",+ "description": "Boost emotional pages.","enum": ["off","on",@@ -1086,7 +1100,7 @@"type": "string"},"snippet_chars": {- "description": "Max chars per chunk_text (0 = full).",+ "description": "Chars per row (0 = full).","type": "number"},"source_id": {@@ -1094,7 +1108,7 @@"type": "string"},"token_budget": {- "description": "Evidence token cap (default 6000).",+ "description": "Default 6000.","type": "number"},"types": {@@ -1232,7 +1246,7 @@"type": "string"},"recency": {- "description": "Boost recent pages (default: auto).",+ "description": "Boost recent pages.","enum": ["off","on",@@ -1245,7 +1259,7 @@"type": "boolean"},"return_unit": {- "description": "auto (default) returns whole conversations.",+ "description": "Default auto: whole conversations.","enum": ["chunk","window",@@ -1256,11 +1270,11 @@"type": "string"},"return_window": {- "description": "Neighbor chunks each side for window (1-3).",+ "description": "Window radius 1-3.","type": "number"},"salience": {- "description": "Boost emotional pages (default: auto).",+ "description": "Boost emotional pages.","enum": ["off","on",@@ -1273,7 +1287,7 @@"type": "string"},"snippet_chars": {- "description": "Max chars per chunk_text (0 = full).",+ "description": "Chars per row (0 = full).","type": "number"},"source_id": {@@ -1353,7 +1367,7 @@"type": "string"},"return_window": {- "description": "Neighbor chunks each side for window (1-3).",+ "description": "Window radius 1-3.","type": "number"},"token_budget": {diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 138dcd4d68..415399c0a0 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -27,6 +27,7 @@"connectWithHeldLock","consolidateFact","countChunklessPagesWithContent",+ "countKeywordPages","countStaleChunks","countStalePagesForExtraction","countStaleTakes",@@ -156,6 +157,7 @@"runMigration","searchKeyword","searchKeywordChunks",+ "searchKeywordPages","searchTakes","searchTakesVector","searchTitles",@@ -206,6 +208,7 @@"connect","consolidateFact","countChunklessPagesWithContent",+ "countKeywordPages","countStaleChunks","countStalePagesForExtraction","countStaleTakes",@@ -343,6 +346,7 @@"runVectorAttempt","searchKeyword","searchKeywordChunks",+ "searchKeywordPages","searchTakes","searchTakesVector","searchTitles",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex cd82f574f2..d0e2cc9926 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -64,6 +64,7 @@"connect: (config: EngineConfig) => Promise<void>","consolidateFact: (id: number, takeId: number) => Promise<void>","countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",+ "countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>","countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>","countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; }) => Promise<number>","countStaleTakes: (opts?: StaleTakeOpts) => Promise<number>",@@ -191,6 +192,7 @@"runMigration: (version: number, sql: string) => Promise<void>","searchKeyword: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>","searchKeywordChunks: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",+ "searchKeywordPages: (query: string, opts: SearchOpts | undefined, page: KeywordPageWindow) => Promise<SearchResult[]>","searchTakes: (query: string, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTakesVector: (embedding: Float32Array, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTitles: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",@@ -454,7 +456,7 @@"kind": "variable","name": "DEGRADED_STAGES","signature": [- "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_status_unknown\"]"+ "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_status_unknown\", \"keyword_count_unavailable\"]"]},{@@ -468,14 +470,14 @@"kind": "type","name": "DegradedStage","signature": [- "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""+ "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\""]},{"kind": "interface","members": ["reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | undefined",- "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""+ "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\""],"name": "DegradedStageEntry"},@@ -1011,6 +1013,7 @@"connectionManager: ConnectionManager | null","consolidateFact: (id: number, takeId: number) => Promise<void>","countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",+ "countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>","countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>","countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; }) => Promise<number>","countStaleTakes: (opts?: StaleTakeOpts) => Promise<number>",@@ -1174,6 +1177,7 @@"runMigration: (_version: number, sqlStr: string) => Promise<void>","searchKeyword: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>","searchKeywordChunks: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",+ "searchKeywordPages: (query: string, opts: SearchOpts | undefined, page: KeywordPageWindow) => Promise<SearchResult[]>","searchTakes: (query: string, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTakesVector: (embedding: Float32Array, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTitles: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",@@ -1216,7 +1220,7 @@"kind": "variable","name": "RANKING_ONLY_DEGRADED_STAGES","signature": [- "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\">"+ "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\">"]},{@@ -1399,6 +1403,7 @@"effective_date?: string | null | undefined","effective_date_source?: string | null | undefined","evidence?: Evidence | undefined",+ "evidence_omitted?: boolean | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined","feedback_boost?: number | undefined",@@ -3207,6 +3212,7 @@"connect: (config: EngineConfig) => Promise<void>","consolidateFact: (id: number, takeId: number) => Promise<void>","countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",+ "countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>","countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>","countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; }) => Promise<number>","countStaleTakes: (opts?: StaleTakeOpts) => Promise<number>",@@ -3334,6 +3340,7 @@"runMigration: (version: number, sql: string) => Promise<void>","searchKeyword: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>","searchKeywordChunks: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",+ "searchKeywordPages: (query: string, opts: SearchOpts | undefined, page: KeywordPageWindow) => Promise<SearchResult[]>","searchTakes: (query: string, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTakesVector: (embedding: Float32Array, opts?: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[]; }) => Promise<TakeHit[]>","searchTitles: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",@@ -5861,7 +5868,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",@@ -6077,6 +6084,7 @@"connectWithHeldLock: (config: EngineConfig, lock: LockHandle) => Promise<void>","consolidateFact: (id: number, takeId: number) => Promise<void>","countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",+ "countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>","countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>","countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; }) => Promise<number>","countStaleTakes: (opts?: StaleTakeOpts) => Promise<number>",@@ -6236,6 +6244,7 @@"runMigration: (_version: number, sql: string) => Promise<void>","searchKeyword: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>","searchKeywordChunks: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",+ "searchKeywordPages: (query: string, opts: SearchOpts | undefined, page: KeywordPageWindow) => Promise<SearchResult[]>","searchTakes: (query: string, opts?: SearchOpts & { takesHoldersAllowList?: string[]; }) => Promise<TakeHit[]>","searchTakesVector: (embedding: Float32Array, opts?: SearchOpts & { takesHoldersAllowList?: string[]; }) => Promise<TakeHit[]>","searchTitles: (query: string, opts?: SearchOpts) => Promise<SearchResult[]>",@@ -7825,7 +7834,7 @@"kind": "variable","name": "DEGRADED_STAGES","signature": [- "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_status_unknown\"]"+ "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_status_unknown\", \"keyword_count_unavailable\"]"]},{@@ -7839,14 +7848,14 @@"kind": "type","name": "DegradedStage","signature": [- "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""+ "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\""]},{"kind": "interface","members": ["reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | undefined",- "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""+ "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\""],"name": "DegradedStageEntry"},@@ -8370,7 +8379,7 @@"kind": "variable","name": "RANKING_ONLY_DEGRADED_STAGES","signature": [- "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\">"+ "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\" | \"keyword_count_unavailable\">"]},{@@ -8553,6 +8562,7 @@"effective_date?: string | null | undefined","effective_date_source?: string | null | undefined","evidence?: Evidence | undefined",+ "evidence_omitted?: boolean | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined","feedback_boost?: number | undefined",diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 6b40c98d03..21473e3cdf 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -3327,10 +3327,11 @@}},"static": {- "callSites": 23,+ "callSites": 25,"directMethods": {"_searchKeywordCJK": 1,"countChunklessPagesWithContent": 1,+ "countKeywordPages": 1,"countStaleChunks": 1,"countStalePagesForExtraction": 1,"findDuplicatePage": 1,@@ -3350,6 +3351,7 @@"runVectorAttempt": 1,"searchKeyword": 1,"searchKeywordChunks": 1,+ "searchKeywordPages": 1,"searchTitles": 1,"searchVector": 1},@@ -3373,6 +3375,7 @@"connect": "none","consolidateFact": "none","countChunklessPagesWithContent": "direct",+ "countKeywordPages": "direct","countStaleChunks": "direct","countStalePagesForExtraction": "direct","countStaleTakes": "none",@@ -3510,6 +3513,7 @@"runVectorAttempt": "direct","searchKeyword": "direct","searchKeywordChunks": "direct",+ "searchKeywordPages": "direct","searchTakes": "none","searchTakesVector": "none","searchTitles": "direct",diff --git a/test/fixtures/goldens/search-c5/notices.json b/test/fixtures/goldens/search-c5/notices.jsonindex fac4c93a18..589f79b014 100644--- a/test/fixtures/goldens/search-c5/notices.json+++ b/test/fixtures/goldens/search-c5/notices.json@@ -5,6 +5,7 @@"[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"matched_alias\":\"Numbat Labs\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"}]","Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in contracts/numbat-labs-msa).","Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -59,6 +60,8 @@"aliases_skipped": [],"truncated": false},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},@@ -66,6 +69,7 @@"content": ["[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"matched_alias\":\"NULA\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]","Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs).",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -110,6 +114,8 @@"aliases_skipped": [],"truncated": false},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},@@ -118,6 +124,7 @@"[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]","Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight).","Saved facts (remember) matching this query, newest first; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -172,12 +179,15 @@"aliases_skipped": [],"truncated": false},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},"search renewal quote": {"content": ["[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -202,6 +212,8 @@"status": "ready","ready": true},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},@@ -322,6 +334,7 @@"search NULA billing contact": {"content": ["[{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5081967213114754,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4998656275194841,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 0 pages (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -346,12 +359,15 @@"status": "ready","ready": true},+ "keyword_total": 0,+ "keyword_truncated": false,"rows": "lean"}},"search Numbat Labs payment terms": {"content": ["[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -376,12 +392,15 @@"status": "ready","ready": true},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},"search OCFR renewal": {"content": ["[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 0 pages (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -406,12 +425,15 @@"status": "ready","ready": true},+ "keyword_total": 0,+ "keyword_truncated": false,"rows": "lean"}},"search renewal quote": {"content": ["[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",+ "[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".","[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."],"retrieval": {@@ -436,6 +458,8 @@"status": "ready","ready": true},+ "keyword_total": 1,+ "keyword_truncated": false,"rows": "lean"}},diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.jsonindex 817dcfa7ae..e478310683 100644--- a/test/fixtures/goldens/sql-text/_classification.json+++ b/test/fixtures/goldens/sql-text/_classification.json@@ -15,7 +15,7 @@"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 15,"out-of-scope:no-sql-stub": 1,"out-of-scope:raw-data": 2,- "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 3,+ "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 5,"out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 9,"out-of-scope:stats-health (brain-wide aggregates)": 2,"pages": 33,@@ -45,6 +45,7 @@"consolidateFact": "facts","constructor": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","countChunklessPagesWithContent": "chunks",+ "countKeywordPages": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)","countStaleChunks": "chunks","countStalePagesForExtraction": "pages","countStaleTakes": "takes",@@ -182,6 +183,7 @@"runVectorAttempt": "out-of-scope:internal-helper (private; exercised through public callers)","searchKeyword": "cjk-search","searchKeywordChunks": "cjk-search",+ "searchKeywordPages": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)","searchTakes": "takes","searchTakesVector": "takes","searchTitles": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)",diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.tsindex a50a6754cf..19e33fa024 100644--- a/test/helpers/evidence-delivery-fixture.ts+++ b/test/helpers/evidence-delivery-fixture.ts@@ -42,7 +42,7 @@ export async function captureOffPath(engine: BrainEngine): Promise<Record<stringconst run = async (label: string, name: string, params: Record<string, unknown>, overrides: Partial<OperationContext> = {}) => {const meta: Record<string, unknown>[] = [];const result = await op(name).handler(ctxOf(engine, meta, overrides), params);- out[label] = JSON.stringify({ result, meta });+ out[label] = JSON.stringify({ result, meta: meta.map(m => m.key === 'retrieval' ? { ...m, value: withoutCounts(m.value as Record<string, unknown>) } : m) });};for (const variant of [{}, { return_unit: 'chunk' }]) {const tag = Object.keys(variant).length ? ':chunk' : '';@@ -64,8 +64,10 @@ export async function captureOffPath(engine: BrainEngine): Promise<Record<string{ remote: true, transport: 'stdio', sourceId: 'default' });// Agent contract v1 notices (extra prefixed blocks + _meta.gbrain_notices, e.g. degraded_recall on this// keyless corpus) are additive and pinned in test/mcp-notice-channels.test.ts; the off path compares the rest.- const content = res.content.filter(c => !c.text.startsWith('[gbrain notice '));+ // Cat 40 Hard F2's keyword count line and fields are additive too (pinned in test/search-keyword-paging.test.ts).+ const content = res.content.filter(c => !c.text.startsWith('[gbrain notice ') && !c.text.startsWith('[gbrain search] '));const { gbrain_notices: _notices, ...meta } = res._meta ?? {};+ if (meta.retrieval) meta.retrieval = withoutCounts(meta.retrieval as Record<string, unknown>);out[`mcp-${name}`] = JSON.stringify({ ...res, content, ...(res._meta ? { _meta: meta } : {}) });}});@@ -83,6 +85,12 @@ export async function captureOffPath(engine: BrainEngine): Promise<Record<stringconst leanRetrieval = (meta: Record<string, unknown>) => ({ ...meta, rows: 'lean' });+/** Cat 40 Hard F2's additive keyword count fields, compared in test/search-keyword-paging.test.ts instead. */+function withoutCounts(meta: Record<string, unknown>): Record<string, unknown> {+ const { keyword_total: _t, keyword_truncated: _r, keyword_total_capped: _c, ...rest } = meta;+ return rest;+}+/*** The cost wave changes remote output on purpose: C1 projects remote* search/query rows to lean rows (and reports `rows: "lean"` in the retrievaldiff --git a/test/helpers/keyword-paging-fixture.ts b/test/helpers/keyword-paging-fixture.tsnew file mode 100644index 0000000000..35684f2313--- /dev/null+++ b/test/helpers/keyword-paging-fixture.ts@@ -0,0 +1,88 @@+/**+ * Cat 40 Hard F2 fixture: a keyword corpus both engines can seed, plus a+ * keyword-mode walk through the real `search` op (cursor encoding included).+ * Shared by test/search-keyword-paging.test.ts (PGLite) and+ * test/e2e/search-keyword-paging-parity.test.ts (PGLite + Postgres).+ *+ * Corpus (term "quasar"): one dominant page whose body repeats the term in+ * DOMINANT_CHUNKS chunks, MANY_PAGES short notes, MIXED_TYPES pages of type+ * `meeting`, plus an OR-only pair (each page holds one of two words, never+ * both). All names are placeholders.+ */+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { operations } from '../../src/core/operations.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';++export const TERM = 'quasar';+export const DOMINANT_SLUG = 'ledgers/widget-co-ledger';+export const DOMINANT_CHUNKS = 300;+export const MANY_PAGES = 23;+export const MIXED_TYPES = 4;++export async function seedPage(engine: BrainEngine, slug: string, body: string, opts: { type?: string; title?: string; frontmatter?: Record<string, unknown> } = {}): Promise<void> {+ await importFromContent(engine, slug, serializeMarkdown(opts.frontmatter ?? {}, body, '', { type: opts.type ?? 'note', title: opts.title ?? slug, tags: [] }),+ { noEmbed: true, forceRechunk: true });+}++/** Seeds the corpus; returns every slug that matches TERM. */+export async function seedKeywordCorpus(engine: BrainEngine): Promise<string[]> {+ const slugs: string[] = [];+ await seedPage(engine, DOMINANT_SLUG, `The ${TERM} ledger for widget-co. Every entry below cites the ${TERM} invoice.`);+ // Hundreds of matching chunks on one page: copies of its first chunk (the chunk trigger indexes each row).+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality)+ SELECT cc.page_id, cc.chunk_index + g, cc.chunk_text || ' entry ' || g, cc.chunk_source, cc.modality+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id, generate_series(1, ${DOMINANT_CHUNKS - 1}) g+ WHERE p.slug = $1 AND cc.chunk_index = 0`, [DOMINANT_SLUG]);+ slugs.push(DOMINANT_SLUG);+ for (let i = 0; i < MANY_PAGES; i++) {+ const slug = `notes/acme-example-${String(i).padStart(2, '0')}`;+ await seedPage(engine, slug, `Note ${i} for acme-example mentions the ${TERM} rollout once.`);+ slugs.push(slug);+ }+ for (let i = 0; i < MIXED_TYPES; i++) {+ const slug = `meetings/alice-example-${i}`;+ await seedPage(engine, slug, `Meeting ${i} with alice-example about the ${TERM} budget.`, { type: 'meeting' });+ slugs.push(slug);+ }+ await seedPage(engine, 'notes/or-only-a', 'The zephyrine report is filed.');+ await seedPage(engine, 'notes/or-only-b', 'The obsidianite report is filed.');+ return slugs;+}++export interface Captured { rows: Array<Record<string, unknown>>; retrieval: Record<string, unknown> }++export function searchCtx(engine: BrainEngine, remote: boolean): OperationContext & { captured: Record<string, unknown> } {+ const captured: Record<string, unknown> = {};+ return {+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote, sourceId: 'default',+ ...(remote ? { transport: 'http' } : {}),+ emitResponseMeta: (key: string, value: unknown) => { captured[key] = value; },+ emitNotice: () => {},+ captured,+ } as unknown as OperationContext & { captured: Record<string, unknown> };+}++const searchOp = operations.find(o => o.name === 'search')!;++export async function callSearch(engine: BrainEngine, params: Record<string, unknown>, remote = true): Promise<Captured> {+ const ctx = searchCtx(engine, remote);+ const rows = await searchOp.handler(ctx, params) as Array<Record<string, unknown>>;+ return { rows, retrieval: (ctx.captured.retrieval ?? {}) as Record<string, unknown> };+}++/** Follows `next` until it is absent (or `maxPages`); returns every page and its slugs in order. */+export async function walkKeyword(engine: BrainEngine, first: Record<string, unknown>, remote = true, maxPages = 50,+ between?: (page: number) => Promise<void>): Promise<{ pages: Captured[]; slugs: string[] }> {+ const pages: Captured[] = [];+ let args: Record<string, unknown> | undefined = { ...first, match: 'keyword' };+ while (args && pages.length < maxPages) {+ const page = await callSearch(engine, args, remote);+ pages.push(page);+ if (between) await between(pages.length);+ args = page.retrieval.next as Record<string, unknown> | undefined;+ }+ return { pages, slugs: pages.flatMap(p => p.rows.map(r => String(r.slug))) };+}diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.tsindex c26ae02cce..ac850751c7 100644--- a/test/helpers/postgres-engine-sql-cases.ts+++ b/test/helpers/postgres-engine-sql-cases.ts@@ -133,7 +133,7 @@ export const DOMAIN_OF: Record<string, string> = {'searchKeyword': 'cjk-search', 'searchKeywordChunks': 'cjk-search',// out of scope- 'searchTitles': OOS.search, 'searchVector': OOS.search, 'explainVectorSearch': OOS.search,+ 'searchTitles': OOS.search, 'countKeywordPages': OOS.search, 'searchKeywordPages': OOS.search, 'searchVector': OOS.search, 'explainVectorSearch': OOS.search,'relationalFanout': OOS.enrichment, 'relationalChainHop': OOS.enrichment, 'getBacklinkCounts': OOS.enrichment, 'getAdjacencyBoosts': OOS.enrichment,'getContentFlagsByPageIds': OOS.enrichment, 'getUnverifiedExtractionPageIds': OOS.enrichment,'getEffectiveDates': OOS.enrichment, 'getSalienceScores': OOS.enrichment, 'resolveAliases': OOS.enrichment,diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.tsindex 7bbbbc6a97..250691b9a6 100644--- a/test/mcp-backup-nag.serial.test.ts+++ b/test/mcp-backup-nag.serial.test.ts@@ -125,8 +125,8 @@ async function callSearch(opts: CallOpts = {}) {});// F3's degraded_recall notice (this keyless stub searches keyword-only) is// orthogonal to the backup block under test; it is pinned in- // test/mcp-notice-channels.test.ts.- return { ...out, content: out.content.filter(c => !c.text.startsWith('[gbrain notice degraded_recall ')) };+ // test/mcp-notice-channels.test.ts. So is F2's keyword count line (test/search-keyword-paging.test.ts).+ return { ...out, content: out.content.filter(c => !c.text.startsWith('[gbrain notice degraded_recall ') && !c.text.startsWith('[gbrain search] ')) };}async function waitFor(pred: () => boolean, ms = 2000): Promise<boolean> {diff --git a/test/mcp-result-size-ceiling.test.ts b/test/mcp-result-size-ceiling.test.tsindex 2e3b7fb683..046640b58f 100644--- a/test/mcp-result-size-ceiling.test.ts+++ b/test/mcp-result-size-ceiling.test.ts@@ -24,8 +24,12 @@ import { serializeMarkdown } from '../src/core/markdown.ts';import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';import { withEnv } from './helpers/with-env.ts';-/** ceil(measured x 1.05) on the fixture below. */-const CEILINGS = { search: 2540, query: 2540 };+/**+ * ceil(measured x 1.05) on the fixture below. search 2540 -> 2754 (2622+ * measured): Cat 40 Hard F2's keyword count line rides on every search call+ * (the rows are top-K; the line says how many pages match the keywords).+ */+const CEILINGS = { search: 2754, query: 2540 };/*** The keyless fixture also gets the operator contract's degraded_recall* notice (F3) on every HTTP call. It is bounded on its own so the ceilingsdiff --git a/test/postgres-rls-scope-inventory.test.ts b/test/postgres-rls-scope-inventory.test.tsindex 3d99dce7c8..b6a44e1784 100644--- a/test/postgres-rls-scope-inventory.test.ts+++ b/test/postgres-rls-scope-inventory.test.ts@@ -21,8 +21,10 @@* naming `withScopedReadTransaction` = 1 definition + 22 call sites, in 21* methods (searchVector had 2); evidence delivery's getChunkWindows adds one,* and #5824 moves searchVector's ANN-attempt call into runVectorAttempt- * (shared with explainVectorSearch): 23 call sites, 23 methods. The golden- * pins the exact numbers.+ * (shared with explainVectorSearch): 23 call sites, 23 methods. Cat 40 Hard+ * F2 adds the scoped keyword count and keyword-mode page reads+ * (countKeywordPages, searchKeywordPages): 25 and 25. The golden pins the+ * exact numbers.*/import { describe, expect, test } from 'bun:test';@@ -150,8 +152,8 @@ describe('EO4 RLS scope inventory (master)', () => {const scoping = astScoping(capture.ast);const callSites = Object.values(capture.ast).reduce((a, m) => a + m.directCallSites, 0);- expect(callSites).toBe(23);- expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(23);+ expect(callSites).toBe(25);+ expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(25);const byMethod = new Map<string, RuntimeObservation[]>();for (const [key, obs] of Object.entries(capture.runtime)) {diff --git a/test/search-keyword-cap.slow.test.ts b/test/search-keyword-cap.slow.test.tsnew file mode 100644index 0000000000..68bcfbd4bf--- /dev/null+++ b/test/search-keyword-cap.slow.test.ts@@ -0,0 +1,54 @@+/**+ * Cat 40 Hard F2: a remote caller paging to the cap. Keyword counts stop at+ * 10,000 (shown as "10000+"), offset 10,000 is the deepest offset any search+ * accepts, and a keyword-mode cursor continues past it. Slow lane: it seeds+ * 10,005 matching pages.+ *+ * Authoring gate: (1) the cap and its model-visible "10000+"; (2) fails if the+ * count loses its LIMIT, reports a wrong number at the cap, or the offset cap+ * moves; (3) the fast suite cannot afford 10,000 pages; (4) no seam.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { KEYWORD_COUNT_CAP } from '../src/core/search/keyword-statement.ts';+import { withEnv } from './helpers/with-env.ts';+import { callSearch, seedPage } from './helpers/keyword-paging-fixture.ts';++const REMOTE = { remote: true, transport: 'http' as const, sourceId: 'default' };+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => { await engine?.disconnect(); });++const countLine = (res: ToolResult) => res.content.map(c => c.text).find(t => t.startsWith('[gbrain search] ')) ?? '';+const mcp = (args: Record<string, unknown>) => withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', args, REMOTE));++describe('a remote caller paging to the cap', () => {+ test('counts stop at 10,000 ("10000+"), offset 10,000 is the deepest offset, a cursor goes further', async () => {+ const extra = KEYWORD_COUNT_CAP + 5;+ await seedPage(engine, 'bulk/template', 'The nebulite archive entry.');+ const cols = (await engine.executeRaw<{ column_name: string }>(+ `SELECT column_name FROM information_schema.columns WHERE table_name = 'pages' AND column_name NOT IN ('id', 'slug', 'search_vector') AND is_generated = 'NEVER'`))+ .map(r => r.column_name);+ await engine.executeRaw(`INSERT INTO pages (slug, ${cols.join(', ')}) SELECT 'bulk/p' || g, ${cols.map(c => `t.${c}`).join(', ')}+ FROM pages t, generate_series(1, ${extra - 1}) g WHERE t.slug = 'bulk/template'`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality)+ SELECT p.id, 0, 'The nebulite archive entry ' || p.slug, 'compiled_truth', 'text' FROM pages p WHERE p.slug LIKE 'bulk/p%'`);+ const hybrid = await mcp({ query: 'nebulite' });+ expect(countLine(hybrid)).toContain('Keyword matches: 10000+ pages');+ const top = await callSearch(engine, { query: 'nebulite', match: 'keyword', limit: 100 });+ expect(top.retrieval).toMatchObject({ total: KEYWORD_COUNT_CAP, total_capped: true, truncated: true });+ const deepest = await callSearch(engine, { query: 'nebulite', match: 'keyword', offset: 10_000, limit: 3 });+ expect(deepest.rows.length).toBe(3);+ expect(JSON.parse((await mcp({ query: 'nebulite', match: 'keyword', offset: 10_001 })).content[0].text).code).toBe('search_offset_over_cap');+ const cursorPage = await callSearch(engine, { ...(deepest.retrieval.next as Record<string, unknown>) });+ expect(cursorPage.rows.length).toBe(2);+ expect(cursorPage.retrieval).toMatchObject({ truncated: false, shown_from: 10_004 });+ }, 120_000);+});diff --git a/test/search-keyword-paging.test.ts b/test/search-keyword-paging.test.tsnew file mode 100644index 0000000000..f4efc84439--- /dev/null+++ b/test/search-keyword-paging.test.ts@@ -0,0 +1,328 @@+/**+ * Cat 40 Hard F2: honest keyword counts and exhaustive keyword paging on+ * `search` (PGLite; the engine-level walks run on Postgres too in+ * test/e2e/search-keyword-paging-parity.test.ts).+ *+ * Pins: `keyword_total` on the default hybrid path counts the strict keyword+ * match set (never the OR retry); `match: "keyword"` walks every page that+ * `total` reports, past 3 x limit, with a dominant page of hundreds of+ * matching chunks, mixed types and a write mid-walk; `total` / `truncated` /+ * `next` at page boundaries; every enumerated page keeps a row under a small+ * evidence budget; the refusals (remote `mode`, cursor outside keyword mode,+ * offset over 10,000) and the unavailable count; the model-visible line read+ * from MCP content blocks only (never `_meta`); private fence text and+ * private pages are not counted for remote callers. The 10,000 cap is in+ * test/search-keyword-cap.slow.test.ts.+ *+ * Authoring gate: (1) protects the count and paging contract agents read in+ * MCP text; (2) fails if the count reads the OR retry or a capped pool, if a+ * page with many chunks crowds others out, if evidence delivery drops an+ * enumerated page, or if a refusal loses its fix; (3) no existing test covers+ * keyword counts or keyword-mode paging (new surface); (4) no new seam: the+ * unavailable-count tests wrap the real engine.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { errorCodeRow } from '../src/core/error-docs.ts';+import { countKeywordMatches, searchCountLine } from '../src/core/search/keyword-paging.ts';+import { withEnv } from './helpers/with-env.ts';+import {+ DOMINANT_CHUNKS, DOMINANT_SLUG, MANY_PAGES, MIXED_TYPES, TERM, callSearch, seedKeywordCorpus, seedPage, walkKeyword,+} from './helpers/keyword-paging-fixture.ts';++const REMOTE = { remote: true, transport: 'http' as const, sourceId: 'default' };++let engine: PGLiteEngine;+let matching: string[];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ matching = await seedKeywordCorpus(engine);+}, 180_000);++afterAll(async () => { await engine?.disconnect(); });++/** Every text block an agent sees, never `_meta`. */+const visible = (res: ToolResult) => res.content.map(c => c.text);+const countLine = (res: ToolResult) => visible(res).find(t => t.startsWith('[gbrain search] ')) ?? '';+const mcp = (args: Record<string, unknown>) => withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', args, REMOTE));+/** The `next` object exactly as the model reads it from the count line. */+const nextFromLine = (line: string) => {+ const at = line.indexOf('next = ');+ return at < 0 ? undefined : JSON.parse(line.slice(at + 'next = '.length)) as Record<string, unknown>;+};++describe('engine: strict keyword pages', () => {+ test('the dominant page has hundreds of matching chunks', async () => {+ const [{ n }] = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1`, [DOMINANT_SLUG]);+ expect(Number(n)).toBeGreaterThanOrEqual(DOMINANT_CHUNKS);+ });++ test('count is distinct pages, equal to what searchKeyword finds with room to spare', async () => {+ const total = await engine.countKeywordPages(TERM, { requireSafeChunks: true });+ expect(total).toBe(matching.length);+ expect(total).toBe(1 + MANY_PAGES + MIXED_TYPES);+ });++ test('a query only the OR retry matches counts 0 and pages nothing', async () => {+ const relaxed = await engine.searchKeyword('zephyrine obsidianite', { orFallback: true });+ expect(relaxed.length).toBe(2);+ expect(await engine.countKeywordPages('zephyrine obsidianite')).toBe(0);+ expect(await engine.searchKeywordPages('zephyrine obsidianite', undefined, { limit: 10 })).toEqual([]);+ });+});++describe('match: "keyword" walk', () => {+ test('pages past 3 x limit and recovers every page total reports, the dominant page once', async () => {+ const limit = 5;+ const { pages, slugs } = await walkKeyword(engine, { query: TERM, limit });+ expect(pages.length).toBeGreaterThan(3);+ expect(pages[0].retrieval.total).toBe(matching.length);+ expect(new Set(slugs).size).toBe(slugs.length);+ expect([...slugs].sort()).toEqual([...matching].sort());+ expect(slugs.filter(s => s === DOMINANT_SLUG).length).toBe(1);+ for (const [i, page] of pages.entries()) {+ expect(page.retrieval.truncated).toBe(i < pages.length - 1);+ expect('next' in page.retrieval).toBe(i < pages.length - 1);+ expect(page.retrieval.shown_from).toBe(i * limit + 1);+ }+ });++ test('order is keyword score, then page id', async () => {+ const { pages } = await walkKeyword(engine, { query: TERM, limit: 7 }, false);+ const rows = pages.flatMap(p => p.rows) as Array<{ score: number; page_id: number }>;+ for (let i = 1; i < rows.length; i++) {+ const [a, b] = [rows[i - 1], rows[i]];+ expect(a.score > b.score || (a.score === b.score && a.page_id < b.page_id)).toBe(true);+ }+ });++ test('page boundaries: total a multiple of limit ends with truncated false and no next', async () => {+ const limit = matching.length / 4;+ expect(Number.isInteger(limit)).toBe(true);+ const { pages } = await walkKeyword(engine, { query: TERM, limit });+ expect(pages.length).toBe(4);+ expect(pages[3].rows.length).toBe(limit);+ expect(pages[3].retrieval.truncated).toBe(false);+ expect(pages[3].retrieval.next).toBeUndefined();+ const one = await walkKeyword(engine, { query: TERM, limit: matching.length - 1 });+ expect(one.pages.map(p => p.rows.length)).toEqual([matching.length - 1, 1]);+ const all = await callSearch(engine, { query: TERM, match: 'keyword', limit: matching.length });+ expect(all.retrieval).toMatchObject({ total: matching.length, truncated: false });+ expect(all.retrieval.next).toBeUndefined();+ });++ test('offset paging matches cursor paging and an offset past the end is an empty page', async () => {+ const byCursor = (await walkKeyword(engine, { query: TERM, limit: 6 })).slugs;+ const byOffset: string[] = [];+ for (let offset = 0; offset < matching.length; offset += 6) {+ byOffset.push(...(await callSearch(engine, { query: TERM, match: 'keyword', limit: 6, offset })).rows.map(r => String(r.slug)));+ }+ expect(byOffset).toEqual(byCursor);+ const past = await callSearch(engine, { query: TERM, match: 'keyword', offset: 500 });+ expect(past.rows).toEqual([]);+ expect(past.retrieval).toMatchObject({ total: matching.length, truncated: false });+ });++ test('mixed types: a type filter counts and walks only that type', async () => {+ const { pages, slugs } = await walkKeyword(engine, { query: TERM, limit: 3, types: ['meeting'] });+ expect(pages[0].retrieval.total).toBe(MIXED_TYPES);+ expect(slugs.every(s => s.startsWith('meetings/'))).toBe(true);+ expect(slugs.length).toBe(MIXED_TYPES);+ const unfiltered = await walkKeyword(engine, { query: TERM, limit: 50 });+ expect(new Set(unfiltered.pages.flatMap(p => p.rows.map(r => r.type)))).toEqual(new Set(['note', 'meeting']));+ });++ test('a write landing mid-walk never repeats a page or loses an unchanged one', async () => {+ const before = new Set(matching);+ const { slugs } = await walkKeyword(engine, { query: TERM, limit: 4 }, true, 50, async page => {+ if (page === 2) await seedPage(engine, 'notes/zz-late-arrival', `A late ${TERM} note.`);+ });+ expect(new Set(slugs).size).toBe(slugs.length);+ for (const slug of before) expect(slugs).toContain(slug);+ await engine.executeRaw(`DELETE FROM pages WHERE slug = 'notes/zz-late-arrival'`);+ });++ test('a cursor is bound to its query', async () => {+ const first = await callSearch(engine, { query: TERM, match: 'keyword', limit: 3 });+ const next = first.retrieval.next as Record<string, unknown>;+ await expect(callSearch(engine, { ...next, query: 'rollout' })).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(callSearch(engine, { ...next, cursor: 'not-a-cursor' })).rejects.toMatchObject({ code: 'invalid_params' });+ });+});++describe('MCP: model-visible counts and paging (content blocks only, no _meta)', () => {+ test('hybrid search carries one count line after the rows', async () => {+ const res = await mcp({ query: TERM, limit: 3 });+ expect(JSON.parse(res.content[0].text).length).toBeGreaterThan(0);+ const line = countLine(res);+ expect(line).toBe(`[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: ${matching.length} pages (pages matching the query's keywords, not a count of these rows). List every keyword match with match: "keyword".`);+ expect(visible(res).filter(t => t.startsWith('[gbrain search] ')).length).toBe(1);+ expect(visible(res).indexOf(line)).toBe(1);+ });++ test('empty results: hybrid and keyword mode still say what was counted', async () => {+ const hybrid = await mcp({ query: 'nonexistentterm' });+ expect(JSON.parse(hybrid.content[0].text)).toEqual([]);+ expect(countLine(hybrid)).toContain('Keyword matches: 0 pages');+ const keyword = await mcp({ query: 'nonexistentterm', match: 'keyword' });+ expect(JSON.parse(keyword.content[0].text)).toEqual([]);+ expect(countLine(keyword)).toBe('[gbrain search] Keyword matches: 0 pages; none on this page. No more keyword matches.');+ });++ test('a keyword walk driven only by the visible next recovers every page', async () => {+ const seen: string[] = [];+ let args: Record<string, unknown> | undefined = { query: TERM, match: 'keyword', limit: 4 };+ let first = '';+ while (args) {+ const res = await mcp(args);+ expect(res.isError).toBeUndefined();+ seen.push(...(JSON.parse(res.content[0].text) as Array<{ slug: string }>).map(r => r.slug));+ first ||= countLine(res);+ args = nextFromLine(countLine(res));+ }+ expect(first).toStartWith(`[gbrain search] Keyword matches: ${matching.length} pages; showing 1-4, keyword-score order. More: call search with next = {`);+ expect([...seen].sort()).toEqual([...matching].sort());+ });++ test('small token budgets and oversized pages: every enumerated page keeps a row, next continues after it', async () => {+ await seedPage(engine, 'meetings/zz-oversized', `${`The ${TERM} review ran long. `.repeat(400)}`, { type: 'meeting' });+ try {+ const args = { query: TERM, match: 'keyword', types: ['meeting'], return_unit: 'page', token_budget: 40, limit: 3 };+ const seen: Array<{ slug: string; evidence_omitted?: boolean; chunk_text: string }> = [];+ let next: Record<string, unknown> | undefined = args;+ let omittedLine = '';+ while (next) {+ const res = await mcp(next);+ const rows = JSON.parse(res.content[0].text) as typeof seen;+ expect(rows.length).toBeGreaterThan(0);+ seen.push(...rows);+ if (rows.some(r => r.evidence_omitted)) omittedLine = countLine(res);+ next = nextFromLine(countLine(res));+ }+ expect(seen.map(r => r.slug).sort()).toEqual([...matching.filter(s => s.startsWith('meetings/')), 'meetings/zz-oversized'].sort());+ expect(seen.some(r => r.evidence_omitted === true && r.chunk_text === '')).toBe(true);+ expect(omittedLine).toContain('evidence_omitted: true');+ } finally {+ await engine.executeRaw(`DELETE FROM pages WHERE slug = 'meetings/zz-oversized'`);+ }+ });++ test('short, oversized, short: the oversized middle page keeps its row in order', async () => {+ await seedPage(engine, 'meetings/sos-1', `${TERM} ${TERM} ${TERM} sos short one.`, { type: 'meeting' });+ await seedPage(engine, 'meetings/sos-2', `${TERM} sos oversized middle. ${'Filler sentence about logistics planning. '.repeat(400)}`, { type: 'meeting' });+ await seedPage(engine, 'meetings/sos-3', `${TERM} sos short three.`, { type: 'meeting' });+ try {+ const keyword = await callSearch(engine, { query: `${TERM} sos`, match: 'keyword', types: ['meeting'] });+ const order = keyword.rows.map(r => String(r.slug));+ const res = await mcp({ query: `${TERM} sos`, match: 'keyword', types: ['meeting'], return_unit: 'page', token_budget: 60 });+ const rows = JSON.parse(res.content[0].text) as Array<{ slug: string; evidence_omitted?: boolean }>;+ expect(rows.map(r => r.slug)).toEqual(order);+ expect(rows.length).toBe(3);+ expect(order).toEqual(['meetings/sos-1', 'meetings/sos-2', 'meetings/sos-3']);+ expect(rows.filter(r => r.evidence_omitted).map(r => r.slug)).toEqual(['meetings/sos-2']);+ } finally {+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'meetings/sos-%'`);+ }+ });++ test('repeated chunks: one row per page', async () => {+ const res = await mcp({ query: TERM, match: 'keyword', limit: 50 });+ const slugs = (JSON.parse(res.content[0].text) as Array<{ slug: string }>).map(r => r.slug);+ expect(slugs.filter(s => s === DOMINANT_SLUG).length).toBe(1);+ expect(new Set(slugs).size).toBe(slugs.length);+ });++ test('remote callers may pass match; mode stays local-only and its refusal points to match: "keyword"', async () => {+ const ok = await mcp({ query: TERM, match: 'keyword', limit: 2 });+ expect(ok.isError).toBeUndefined();+ expect(visible(ok).some(t => t.includes('unknown_param'))).toBe(false);+ const refused = await mcp({ query: TERM, mode: 'keyword' });+ expect(refused.isError).toBe(true);+ const body = JSON.parse(refused.content[0].text);+ expect(body.code).toBe('search_mode_local_only');+ expect(body.message).toBe("search: mode is set by the brain's operator and cannot be chosen per call.");+ expect(body.suggestion).toBe('Omit mode. For keyword-only matching with a total and a next page, pass match: "keyword".');+ const local = await callSearch(engine, { query: TERM, mode: 'balanced', limit: 2 }, false);+ expect(local.rows.length).toBeGreaterThan(0);+ });++ test('a cursor outside keyword mode and an offset over 10,000 are refused with the fix named', async () => {+ const first = await callSearch(engine, { query: TERM, match: 'keyword', limit: 2 });+ const { match: _m, ...hybrid } = first.retrieval.next as Record<string, unknown>;+ const res = await mcp(hybrid);+ const body = JSON.parse(res.content[0].text);+ expect(body.code).toBe('search_cursor_requires_keyword');+ expect(body.message).toBe('search: cursor continues a match: "keyword" listing; this call is hybrid.');+ expect(body.suggestion).toBe('Send the next object from the previous response unchanged (it carries match: "keyword"). Hybrid rows are a ranked top-K with no next page.');+ const deep = JSON.parse((await mcp({ query: TERM, offset: 10_001 })).content[0].text);+ expect(deep.code).toBe('search_offset_over_cap');+ expect(deep.message).toBe('search: offset 10001 is over the 10,000 limit.');+ expect(deep.suggestion).toBe('Page with match: "keyword" and send the next object each response returns; a cursor has no depth limit.');+ const hybridOffset = await mcp({ query: TERM, offset: 2, limit: 2 });+ expect(hybridOffset.isError).toBeUndefined();+ });++ test('every new code is in the gbrain errors catalogue', () => {+ for (const code of ['search_cursor_requires_keyword', 'search_mode_local_only', 'search_offset_over_cap']) {+ expect(errorCodeRow(code)?.class).toBe('caller');+ }+ });+});++describe('count unavailable: a degraded stage, never a number', () => {+ const stalled = (base: BrainEngine, how: 'hang' | 'timeout'): BrainEngine => new Proxy(base, {+ get(target, prop, receiver) {+ if (prop === 'countKeywordPages') {+ return how === 'hang' ? () => new Promise(() => {}) : async () => { throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }); };+ }+ const v = Reflect.get(target, prop, receiver);+ return typeof v === 'function' ? v.bind(target) : v;+ },+ });++ test('a count past its deadline is unavailable', async () => {+ expect(await countKeywordMatches(stalled(engine, 'hang'), TERM, {}, 50)).toEqual({ unavailable: 'timeout' });+ expect(await countKeywordMatches(stalled(engine, 'timeout'), TERM, {}, 1000)).toEqual({ unavailable: 'timeout' });+ });++ test('over MCP: the line says unavailable, the stage is recorded, keyword paging still works', async () => {+ const e = stalled(engine, 'timeout');+ const hybrid = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(e, 'search', { query: TERM }, REMOTE));+ expect(countLine(hybrid)).toContain('Keyword match count unavailable (timed out; not a count of zero)');+ expect((hybrid._meta as { retrieval: { degraded: unknown[] } }).retrieval.degraded).toContainEqual({ stage: 'keyword_count_unavailable', reason: 'timeout' });+ const keyword = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(e, 'search', { query: TERM, match: 'keyword', limit: 3 }, REMOTE));+ expect(countLine(keyword)).toStartWith('[gbrain search] Keyword match count unavailable (timed out; not a count of zero); showing 1-3');+ expect(nextFromLine(countLine(keyword))).toBeDefined();+ });++ test('the line renderer never invents a number', () => {+ expect(searchCountLine([], { keyword_total: null, degraded: [{ stage: 'keyword_count_unavailable' }] }))+ .toContain('Keyword match count unavailable (failed; not a count of zero)');+ expect(searchCountLine([], { returned_count: 0 })).toBeNull();+ });+});++describe('visibility: untrusted callers never count private text', () => {+ test('private takes/facts fence text and private pages are not counted', async () => {+ const fenced = 'Public body.\n<!--- gbrain:takes:begin -->\nThe marmoset deal is risky.\n<!--- gbrain:takes:end -->';+ await seedPage(engine, 'notes/fenced', fenced);+ await seedPage(engine, 'notes/private-marmoset', 'The marmoset memo.', { frontmatter: { visibility: 'private' } });+ try {+ const remote = await callSearch(engine, { query: 'marmoset' }, true);+ expect(remote.retrieval.keyword_total).toBe(0);+ const remoteKeyword = await callSearch(engine, { query: 'marmoset', match: 'keyword' }, true);+ expect(remoteKeyword.retrieval.total).toBe(0);+ expect(remoteKeyword.rows).toEqual([]);+ const local = await callSearch(engine, { query: 'marmoset' }, false);+ expect(local.retrieval.keyword_total).toBe(1);+ } finally {+ await engine.executeRaw(`DELETE FROM pages WHERE slug IN ('notes/fenced', 'notes/private-marmoset')`);+ }+ });+});diff --git a/test/search-readiness-http.test.ts b/test/search-readiness-http.test.tsindex aa5add4b4b..fb8cb91b52 100644--- a/test/search-readiness-http.test.ts+++ b/test/search-readiness-http.test.ts@@ -182,10 +182,11 @@ describe('search projection readiness over legacy bearer HTTP MCP', () => {test('empty search keeps its bare-array body and exposes visible pending projection work only through retrieval metadata', async () => {const response = await search('http-readiness-no-match');- // Body + empty-retrieval block + F3's degraded_recall notice (agent contract v1).- expect(response.content).toHaveLength(3);- expect(response.content[2]!.text).toStartWith('[gbrain notice degraded_recall kind=degraded]');- expect(response.content[2]!.text).toContain('projection_pending');+ // Body + F2's keyword count line + empty-retrieval block + F3's degraded_recall notice (agent contract v1).+ expect(response.content).toHaveLength(4);+ expect(response.content[1]!.text).toStartWith('[gbrain search] Rows are a ranked top-K');+ expect(response.content[3]!.text).toStartWith('[gbrain notice degraded_recall kind=degraded]');+ expect(response.content[3]!.text).toContain('projection_pending');expect(response.body).toEqual([]);expectPendingMetadata(response.retrieval);expect(JSON.stringify(response.result)).not.toContain(PRIVATE_PENDING);@@ -194,9 +195,10 @@ describe('search projection readiness over legacy bearer HTTP MCP', () => {test('partial nonempty search exposes the same readiness metadata without changing the public result body', async () => {const response = await search(MATCH);- // Body + F3's degraded_recall notice (recall-affecting stage present).- expect(response.content).toHaveLength(2);- expect(response.content[1]!.text).toStartWith('[gbrain notice degraded_recall kind=degraded]');+ // Body + F2's keyword count line + F3's degraded_recall notice (recall-affecting stage present).+ expect(response.content).toHaveLength(3);+ expect(response.content[1]!.text).toStartWith('[gbrain search] Rows are a ranked top-K');+ expect(response.content[2]!.text).toStartWith('[gbrain notice degraded_recall kind=degraded]');expect(response.body).toHaveLength(1);expect(JSON.stringify(response.body)).toContain(MATCH);expectPendingMetadata(response.retrieval);