Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): exact-title page ranks first in the title arm; remote title arm is index-backed (#5889)

garrytan744374a6b9fa
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index bb2b4e2c9c..3de41bd5b8 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -24,6 +24,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/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/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index 4b98440c01..b0106bbad4 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -106,6 +106,11 @@ command runs, or Postgres will reject the trigger recreation with
- Keep `GBRAIN_FTS_LANGUAGE` set consistently in every environment that
writes to the brain (CLI shells, MCP server, cron jobs) — a writer without
the env var tokenizes new rows in `english` until the next reindex.
+- Remote title matching (MCP and other safe-chunks callers) reads the title
+ lexemes stored in `pages.search_vector`, so it follows the language those
+ vectors were built with. After a language change, run
+ `gbrain reindex-search-vector` so remote title search tokenizes like the
+ query.
- **Interrupted reindex:** the trigger flip commits before the backfill, so a
`reindex-search-vector` run killed mid-way (crash, full disk, SIGKILL)
leaves new writes in the new language and un-backfilled rows in the old one
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 5caae7164e..c5acc7bef8 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -414,6 +414,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// (src/core/search/cjk-keyword-sql.ts). The cross-engine parity is pinned — any change here must re-run the pin. (Matches
// src/core/engine-sql/** too; selector unions the entries.)
"src/core/engine-sql/cjk-search.ts": ["test/e2e/engine-parity-cjk.test.ts"],
+ // #5889 / title FTS: the title arm (engine-sql/titles.ts + its statement in
+ // search/title-statement.ts) — dual-backend ranking + remote plan proof.
+ "src/core/engine-sql/titles.ts": ["test/e2e/title-arm-postgres.test.ts"],
+ "src/core/search/title-statement.ts": ["test/e2e/title-arm-postgres.test.ts"],
// D7 parity batch: the code-edge read paths (getCallersOf / getCalleesOf /
// getEdgesByChunk) live in engine-sql/code-edges.ts (PGLite's getEdgesByChunk
// stays in its engine module dir); both key the cross-engine read-parity
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsv
index 0383baf289..f5bc04ce81 100644
--- a/scripts/engine-sql-baseline.tsv
+++ b/scripts/engine-sql-baseline.tsv
@@ -20,6 +20,7 @@ migrated sources
migrated tags
migrated takes
migrated timeline
+migrated titles
method src/core/pglite-engine.ts PGLiteEngine._connectInternal
method src/core/pglite-engine.ts PGLiteEngine.deleteEvalCandidatesBefore
method src/core/pglite-engine.ts PGLiteEngine.discoverOntologyDimensions
@@ -44,7 +45,6 @@ method src/core/pglite-engine.ts PGLiteEngine.putDreamVerdict
method src/core/pglite-engine.ts PGLiteEngine.putRawData
method src/core/pglite-engine.ts PGLiteEngine.searchKeyword
method src/core/pglite-engine.ts PGLiteEngine.searchKeywordChunks
-method src/core/pglite-engine.ts PGLiteEngine.searchTitles
method src/core/pglite-engine.ts PGLiteEngine.setConfig
method src/core/pglite-engine.ts PGLiteEngine.sweepDreamVerdicts
method src/core/pglite-engine.ts PGLiteEngine.unsetConfig
@@ -78,7 +78,6 @@ method src/core/postgres-engine.ts PostgresEngine.putRawData
method src/core/postgres-engine.ts PostgresEngine.resolveFactsEmbeddingCast
method src/core/postgres-engine.ts PostgresEngine.searchKeyword
method src/core/postgres-engine.ts PostgresEngine.searchKeywordChunks
-method src/core/postgres-engine.ts PostgresEngine.searchTitles
method src/core/postgres-engine.ts PostgresEngine.setConfig
method src/core/postgres-engine.ts PostgresEngine.sweepDreamVerdicts
method src/core/postgres-engine.ts PostgresEngine.unsetConfig
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 7a8df14bb3..b751e915cc 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,8 +20,8 @@ src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2230 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)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
src/core/operations.ts 331 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
-src/core/pglite-engine.ts 3225 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); 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)
-src/core/postgres-engine.ts 3252 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)
+src/core/pglite-engine.ts 3117 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); 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)
+src/core/postgres-engine.ts 3119 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); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133)
src/core/search/hybrid.ts 1584 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
src/core/types.ts 2105 ratchet +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
src/core/minions/queue.ts 2522 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
diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.ts
new file mode 100644
index 0000000000..123d6efe88
--- /dev/null
+++ b/src/core/engine-sql/titles.ts
@@ -0,0 +1,92 @@
+/**
+ * Page-grain title arm (`BrainEngine.searchTitles`, fix/title-retrieval-arm
+ * D1): one implementation for both engines. The statement builds in
+ * `src/core/search/title-statement.ts` (shared with the plan-proof E2E, the
+ * cjk-search / vector-statement pattern); this module runs it through the
+ * engine's scoped read, with the engine's session settings and the OR
+ * fallback.
+ *
+ * Ranks pages whose title matches the websearch query with the same
+ * page-grain filters the keyword arm applies (type/types/excludeSlugs/date/
+ * source scoping, hard-excludes, visibility), joined to one representative
+ * chunk per output page, with the same AND→OR recall fallback as
+ * searchKeyword. Ordinary long titles are preserved; oversized pasted context
+ * is bounded before websearch FTS.
+ *
+ * Exact-title key (#5889): every title holding a query term once ties on
+ * `ts_rank_cd`, and ties broke by page id, so an identity page titled exactly
+ * like the query fell out of the arm's top rows once ~50 other titles
+ * contained the word; the exact-lookup tier only sees those rows. Both
+ * orderings (the inner `top_pages` LIMIT and the outer projection) now sort
+ * `lower(btrim(title, <space, quotes, NBSP>)) = normalizeAlias(query)` first.
+ * The normalized query is its own bind parameter, so the OR fallback never
+ * rebinds it. The SQL key is a cheap approximation (no internal whitespace
+ * collapse: a regexp measured +37 ms); the tier's JS `normalizeAlias` recheck
+ * stays authoritative, so a mismatch can only miss, never promote.
+ *
+ * Remote predicate (title FTS; diagnosis credited to PR #5853 by morven-ai):
+ * safe-chunks callers must match the title alone, which used to mean a
+ * per-row `to_tsvector(title)` that no index serves (a scan of every page in
+ * scope). `pages.search_vector` carries the title, and only the title, at
+ * weight A (schema trigger, `reindex-search-vector`, page-state projection),
+ * so the remote arm matches `search_vector @@ q_a`, where `q_a` is the
+ * websearch query with every lexeme labeled `:A`. That is served by
+ * `idx_pages_search`, and negated or phrase terms are evaluated on title
+ * lexemes only, so timeline text can never change which titles a remote
+ * caller sees. Ranking uses the weight-A slice (`ts_filter(..., '{a}')`).
+ * Remote matching follows the language `search_vector` was built with;
+ * `gbrain reindex-search-vector` rebuilds it after an FTS language change.
+ * A page with a NULL `search_vector` is absent from the remote arm (the
+ * BEFORE INSERT/UPDATE trigger keeps it non-NULL). The local arm keeps
+ * ranking the whole `search_vector` (title weight A dominates).
+ */
+import type { SearchOpts, SearchResult } from '../types.ts';
+import { searchLimitCap } from '../search/eval-pool-depth.ts';
+import { boundWebsearchQuery, buildOrFallbackWebsearchQuery } from '../search/sql-ranking.ts';
+import { buildSearchTitlesStatement, type SearchTitlesDialect } from '../search/title-statement.ts';
+import { rowToSearchResult } from '../utils.ts';
+import type { ScopedReadRunner } from './cjk-search.ts';
+
+export type { SearchTitlesDialect } from '../search/title-statement.ts';
+
+export async function searchTitles(
+ scoped: ScopedReadRunner,
+ query: string,
+ opts: SearchOpts | undefined,
+ dialect: SearchTitlesDialect,
+): Promise<SearchResult[]> {
+ // language/symbolKind are chunk-grain code filters with no page-grain
+ // meaning; a code-scoped query gets no title candidates rather than rows
+ // that silently violate the caller's filter.
+ if (opts?.language || opts?.symbolKind) return [];
+ if (opts?.limit && opts.limit > searchLimitCap()) {
+ console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);
+ }
+ const statement = buildSearchTitlesStatement(query, opts, dialect);
+ const run = (queryText: string, relaxed: boolean) =>
+ scoped(async (exec) => {
+ if (dialect.statementTimeout) {
+ await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [dialect.statementTimeout]);
+ }
+ const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;
+ const previous = preferIndex
+ ? (await exec.query<{ enable_seqscan: string }>(`SHOW enable_seqscan`)).rows[0].enable_seqscan
+ : '';
+ if (preferIndex) await exec.query(`SELECT set_config('enable_seqscan', 'off', true)`);
+ const params = [...statement.params];
+ params[0] = queryText;
+ const { rows } = await exec.unsafe(statement.sql, params);
+ if (preferIndex) await exec.query(`SELECT set_config('enable_seqscan', $1, true)`, [previous]);
+ return rows;
+ });
+
+ const strictQuery = statement.params[0] as string;
+ const rows = await run(strictQuery, false);
+ if (rows.length > 0) return rows.map(rowToSearchResult);
+ const orQuery = buildOrFallbackWebsearchQuery(strictQuery);
+ if (!orQuery) return [];
+ // 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's fusion can
+ // demote them (SearchResult.keyword_relaxed).
+ const relaxedRows = await run(boundWebsearchQuery(orQuery), true);
+ return relaxedRows.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index bc8deb9061..c33f2eacc8 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -147,6 +147,7 @@ import * as filesImpl from './engine-sql/files.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.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 { applyForwardReferenceBootstrap, pgliteBootstrapTarget } from './engine-sql/bootstrap.ts';
/**
@@ -1458,123 +1459,14 @@ export class PGLiteEngine implements BrainEngine {
}
/**
- * fix/title-retrieval-arm (D1): page-grain title candidate arm. See the
- * BrainEngine interface doc for the full contract. Queries
- * pages.search_vector (title weight 'A' dominates ts_rank_cd by
- * construction) with the same page-grain filters the keyword arm applies
- * (type/types/excludeSlugs/date/source scoping, hard-excludes,
- * visibility), joined to one representative chunk per page. Applies the
- * same AND→OR recall fallback as searchKeyword. Ordinary long titles are
- * preserved; oversized pasted context is bounded before websearch FTS.
- *
- * CJK queries fall through to websearch FTS here (a single-token CJK
+ * fix/title-retrieval-arm (D1): page-grain title candidate arm. SQL lives
+ * once in engine-sql/titles.ts (exact-title key #5889, index-backed remote
+ * predicate). CJK queries fall through to websearch FTS (a single-token CJK
* query CAN exact-match a single-token CJK title); the richer CJK ILIKE
* fallback stays keyword-arm-only.
*/
async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {
- // language/symbolKind are chunk-grain code filters with no page-grain
- // meaning; a code-scoped query gets no title candidates rather than
- // rows that silently violate the caller's filter.
- if (opts?.language || opts?.symbolKind) return [];
- const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
- const offset = opts?.offset || 0;
- const detailLow = opts?.detail === 'low';
-
- if (opts?.limit && opts.limit > searchLimitCap()) {
- console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);
- }
-
- const boostMap = opts?.source_boosts ?? resolveBoostMap();
- const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
- const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
- const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's', opts);
- // FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
- // — safe to interpolate into raw SQL.
- const ftsLang = getFtsLanguage();
- const titleVector = requiresSafeChunks(opts) ? `to_tsvector('${ftsLang}', COALESCE(p.title, ''))` : 'p.search_vector';
-
- const params: unknown[] = [boundWebsearchQuery(query), limit, offset];
- let extraFilter = '';
- if (opts?.type) {
- params.push(opts.type);
- extraFilter += ` AND p.type = $${params.length}`;
- }
- if (opts?.types && opts.types.length > 0) {
- params.push(opts.types);
- extraFilter += ` AND p.type = ANY($${params.length}::text[])`;
- }
- if (opts?.exclude_slugs?.length) {
- params.push(opts.exclude_slugs);
- extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;
- }
- if (opts?.afterDate) {
- params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
- }
- if (opts?.beforeDate) {
- params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
- }
- if (opts?.sourceIds && opts.sourceIds.length > 0) {
- params.push(opts.sourceIds);
- extraFilter += ` AND p.source_id = ANY($${params.length}::text[])`;
- } else if (opts?.sourceId) {
- params.push(opts.sourceId);
- extraFilter += ` AND p.source_id = $${params.length}`;
- }
-
- // Page grain: one row per page, so no best_per_page pool. top_pages ranks
- // and limits first; the representative-chunk LATERAL (compiled_truth
- // first, then lowest chunk_index) and the stale probe then run per OUTPUT
- // row, not per matched page. Neither affects order, so rows are unchanged.
- // COALESCEs keep chunkless pages retrievable (chunk_id 0, empty text).
- // Accepted limitations (Reviewer F5/F6): the synthetic chunkless row
- // dedups on empty chunk_text (fusion's compiledTruthBoost skips it since
- // #3695); detail='low' filters only the representative.
- const titlesSql =
- `WITH top_pages AS (
- SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id,
- p.effective_date, p.effective_date_source, p.updated_at,
- ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score
- FROM pages p JOIN sources s ON s.id = p.source_id
- WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)
- ${extraFilter} ${hardExcludeClause} ${visibilityClause}
- ORDER BY score DESC, p.id ASC
- LIMIT $2 OFFSET $3
- )
- SELECT tp.slug, tp.page_id, tp.title, tp.type, tp.source_id,
- tp.effective_date, tp.effective_date_source,
- COALESCE(rep.id, 0) as chunk_id,
- COALESCE(rep.chunk_index, 0) as chunk_index,
- COALESCE(rep.chunk_text, '') as chunk_text,
- COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source, tp.score,
- CASE WHEN tp.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te
- WHERE te.page_id = tp.page_id) THEN true ELSE false END AS stale
- FROM top_pages tp
- LEFT JOIN LATERAL (
- SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_source
- FROM content_chunks cc
- WHERE cc.page_id = tp.page_id AND cc.modality = 'text'
- ${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}
- ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
- LIMIT 1
- ) rep ON true
- ORDER BY tp.score DESC, tp.page_id ASC`;
-
- let { rows } = await this.db.query(titlesSql, params);
- if (rows.length === 0) {
- const orQuery = buildOrFallbackWebsearchQuery(params[0] as string);
- if (orQuery) {
- const fallbackParams = [...params];
- fallbackParams[0] = boundWebsearchQuery(orQuery);
- ({ rows } = await this.db.query(titlesSql, fallbackParams));
- // 2026-09 (#3617 follow-up): same relaxed-row tagging as the keyword
- // arm — see SearchResult.keyword_relaxed.
- return (rows as Record<string, unknown>[]).map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));
- }
- }
- return (rows as Record<string, unknown>[]).map(rowToSearchResult);
+ 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.ts
index db444ac93a..dd5e5d1980 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -128,6 +128,7 @@ import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './sea
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 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';
@@ -1089,152 +1090,18 @@ export class PostgresEngine implements BrainEngine {
}
/**
- * fix/title-retrieval-arm (D1): page-grain title candidate arm. See the
- * BrainEngine interface doc for the full contract. Queries
- * pages.search_vector (title weight 'A' dominates ts_rank_cd by
- * construction) with the same page-grain filters the keyword arm applies
- * (type/types/excludeSlugs/date/source scoping, hard-excludes,
- * visibility), joined to one representative chunk per page. Applies the
- * same AND→OR recall fallback as searchKeyword. Ordinary long titles are
- * preserved; oversized pasted context is bounded before websearch FTS.
+ * fix/title-retrieval-arm (D1): page-grain title candidate arm. SQL lives
+ * once in engine-sql/titles.ts (exact-title key #5889, index-backed remote
+ * predicate). Each attempt (strict, then OR fallback) runs in its own
+ * scoped read transaction with an 8s statement timeout.
*/
async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {
- // language/symbolKind are chunk-grain code filters with no page-grain
- // meaning; a code-scoped query gets no title candidates rather than
- // rows that silently violate the caller's filter.
- if (opts?.language || opts?.symbolKind) return [];
- const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
- const offset = opts?.offset || 0;
- const detailLow = opts?.detail === 'low';
-
- if (opts?.limit && opts.limit > searchLimitCap()) {
- console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);
- }
-
- const boostMap = opts?.source_boosts ?? resolveBoostMap();
- const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
- const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
- const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's', opts);
- // FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
- // — safe to interpolate into raw SQL.
- const ftsLang = getFtsLanguage();
- const titleVector = requiresSafeChunks(opts) ? `to_tsvector('${ftsLang}', COALESCE(p.title, ''))` : 'p.search_vector';
-
- const params: unknown[] = [boundWebsearchQuery(query)];
- let typeClause = '';
- if (opts?.type) {
- params.push(opts.type);
- typeClause = `AND p.type = $${params.length}`;
- }
- let typesClause = '';
- if (opts?.types && opts.types.length > 0) {
- params.push(opts.types);
- typesClause = `AND p.type = ANY($${params.length}::text[])`;
- }
- let excludeSlugsClause = '';
- if (opts?.exclude_slugs?.length) {
- params.push(opts.exclude_slugs);
- excludeSlugsClause = `AND p.slug != ALL($${params.length}::text[])`;
- }
- // Date filters read COALESCE(effective_date, …) — upstream unified the
- // Postgres keyword arm onto the PGLite effective-date-first convention
- // (v0.29.1 parity); the title arm matches it for filter parity.
- let afterDateClause = '';
- if (opts?.afterDate) {
- params.push(opts.afterDate);
- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
- }
- let beforeDateClause = '';
- if (opts?.beforeDate) {
- params.push(opts.beforeDate);
- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
- }
- let sourceClause = '';
- if (opts?.sourceIds && opts.sourceIds.length > 0) {
- params.push(opts.sourceIds);
- sourceClause = `AND p.source_id = ANY($${params.length}::text[])`;
- } else if (opts?.sourceId) {
- params.push(opts.sourceId);
- sourceClause = `AND p.source_id = $${params.length}`;
- }
- params.push(limit);
- const limitParam = `$${params.length}`;
- params.push(offset);
- const offsetParam = `$${params.length}`;
-
- // Page grain: one row per page, so no best_per_page pool. top_pages ranks
- // and limits first; the representative-chunk LATERAL (compiled_truth
- // first, then lowest chunk_index) then runs per OUTPUT row, not per
- // matched page. It never affects order, so rows are unchanged.
- // COALESCEs keep chunkless pages retrievable (chunk_id 0, empty text).
- // Accepted limitations (Reviewer F5/F6): the synthetic chunkless row
- // dedups on empty chunk_text (fusion's compiledTruthBoost skips it since
- // #3695); detail='low' filters only the representative.
- const rawQuery = `
- WITH top_pages AS (
- SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id,
- p.effective_date, p.effective_date_source,
- ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score
- FROM pages p
- JOIN sources s ON s.id = p.source_id
- WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)
- ${typeClause} ${typesClause} ${excludeSlugsClause}
- ${afterDateClause} ${beforeDateClause} ${sourceClause}
- ${hardExcludeClause}
- ${visibilityClause}
- ORDER BY score DESC, p.id ASC
- LIMIT ${limitParam}
- OFFSET ${offsetParam}
- )
- SELECT tp.slug, tp.page_id, tp.title, tp.type, tp.source_id,
- tp.effective_date, tp.effective_date_source,
- COALESCE(rep.id, 0) as chunk_id,
- COALESCE(rep.chunk_index, 0) as chunk_index,
- COALESCE(rep.chunk_text, '') as chunk_text,
- COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,
- tp.score,
- false AS stale
- FROM top_pages tp
- LEFT JOIN LATERAL (
- SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_source
- FROM content_chunks cc
- WHERE cc.page_id = tp.page_id
- AND cc.modality = 'text'
- ${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}
- ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
- LIMIT 1
- ) rep ON true
- ORDER BY tp.score DESC, tp.page_id ASC
- `;
-
- // Same RLS scope-binding wrapper as searchKeyword (alwaysTransaction:
- // the SET LOCAL statement_timeout needs a transaction regardless of the
- // GBRAIN_RLS_SCOPE_BINDING flag). The OR retry re-executes through the
- // same scoped wrapper.
- const runTitles = (queryText: string, relaxed = false) =>
- this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
- await tx`SET LOCAL statement_timeout = '8s'`;
- const preferIndex = relaxed && !requiresSafeChunks(opts);
- const previous = preferIndex ? await tx`SHOW enable_seqscan` : [];
- if (preferIndex) await tx`SET LOCAL enable_seqscan = off`;
- const boundParams = [...params];
- boundParams[0] = queryText;
- const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
- if (preferIndex) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;
- return rows;
- }, { alwaysTransaction: true });
- let rows = await runTitles(params[0] as string);
- if (rows.length === 0) {
- const orQuery = buildOrFallbackWebsearchQuery(params[0] as string);
- if (orQuery) {
- rows = await runTitles(boundWebsearchQuery(orQuery), true);
- // 2026-09 (#3617 follow-up): same relaxed-row tagging as the keyword
- // arm — see SearchResult.keyword_relaxed.
- return rows.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));
- }
- }
- return rows.map(rowToSearchResult);
+ return titlesImpl.searchTitles(
+ (read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true }),
+ query,
+ opts,
+ { statementTimeout: '8s', relaxedPrefersIndex: true, staleProbe: false },
+ );
}
/**
diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.ts
new file mode 100644
index 0000000000..9ba99852fa
--- /dev/null
+++ b/src/core/search/title-statement.ts
@@ -0,0 +1,144 @@
+/**
+ * The title-arm statement (`BrainEngine.searchTitles`), built once for both
+ * engines and the plan-proof E2E (test/e2e/title-arm-postgres.test.ts) so the
+ * SQL they run or EXPLAIN can never drift. Execution, the per-engine session
+ * settings and the OR fallback live in engine-sql/titles.ts; see its module
+ * doc for the exact-title key (#5889) and the weight-A remote predicate.
+ */
+import type { SearchOpts } from '../types.ts';
+import { clampSearchLimit } from '../engine.ts';
+import { searchLimitCap } from './eval-pool-depth.ts';
+import { getFtsLanguage } from '../fts-language.ts';
+import { requiresSafeChunks } from './safe-chunks.ts';
+import { normalizeAlias } from './alias-normalize.ts';
+import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';
+import {
+ boundWebsearchQuery,
+ buildHardExcludeClause,
+ buildSourceFactorCase,
+ buildVisibilityClause,
+} from './sql-ranking.ts';
+
+/** Engine behavior the title arm keeps from each engine's original method. */
+export interface SearchTitlesDialect {
+ /** Per-attempt `statement_timeout` (Postgres: '8s'); unset means none. */
+ statementTimeout?: string;
+ /** Run the relaxed (OR) local re-run with `enable_seqscan` off (Postgres). */
+ relaxedPrefersIndex: boolean;
+ /** Project `stale` from timeline_entries (PGLite); otherwise `false`. */
+ staleProbe: boolean;
+}
+
+export interface SearchTitlesStatement {
+ sql: string;
+ /** `$1` is the websearch text (rebound by the OR fallback); `$2` the exact-title key. */
+ params: unknown[];
+ safeChunks: boolean;
+}
+
+/**
+ * Label every lexeme of a tsquery's text form with weight A
+ * (`'acm' & !'secret'` → `'acm':A & !'secret':A`; prefix `'acm':*` →
+ * `'acm':*A`). Lexemes are single-quoted with `''` escapes in that form.
+ */
+const WEIGHT_A_QUERY = (ftsLang: string): string =>
+ `regexp_replace(websearch_to_tsquery('${ftsLang}', $1)::text, '(''(?:[^'']|'''')*'')(?::(\\*))?', '\\1:\\2A', 'g')::tsquery`;
+
+export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undefined, dialect: SearchTitlesDialect): SearchTitlesStatement {
+ const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
+ const offset = opts?.offset || 0;
+ const detailLow = opts?.detail === 'low';
+ const safeChunks = requiresSafeChunks(opts);
+
+ const boostMap = opts?.source_boosts ?? resolveBoostMap();
+ const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
+ const hardExcludeClause = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));
+ const visibilityClause = buildVisibilityClause('p', 's', opts);
+ // FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
+ // — safe to interpolate into raw SQL.
+ const ftsLang = getFtsLanguage();
+ const tsq = `websearch_to_tsquery('${ftsLang}', $1)`;
+ const matchSql = safeChunks ? `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}` : `p.search_vector @@ ${tsq}`;
+ const rankSql = safeChunks ? `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})` : `ts_rank_cd(p.search_vector, ${tsq})`;
+
+ const params: unknown[] = [boundWebsearchQuery(query), normalizeAlias(query), limit, offset];
+ let filters = '';
+ if (opts?.type) {
+ params.push(opts.type);
+ filters += ` AND p.type = $${params.length}`;
+ }
+ if (opts?.types && opts.types.length > 0) {
+ params.push(opts.types);
+ filters += ` AND p.type = ANY($${params.length}::text[])`;
+ }
+ if (opts?.exclude_slugs?.length) {
+ params.push(opts.exclude_slugs);
+ filters += ` AND p.slug != ALL($${params.length}::text[])`;
+ }
+ // Date filters read COALESCE(effective_date, …), the keyword arm's
+ // effective-date-first convention.
+ if (opts?.afterDate) {
+ params.push(opts.afterDate);
+ filters += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
+ }
+ if (opts?.beforeDate) {
+ params.push(opts.beforeDate);
+ filters += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
+ }
+ if (opts?.sourceIds && opts.sourceIds.length > 0) {
+ params.push(opts.sourceIds);
+ filters += ` AND p.source_id = ANY($${params.length}::text[])`;
+ } else if (opts?.sourceId) {
+ params.push(opts.sourceId);
+ filters += ` AND p.source_id = $${params.length}`;
+ }
+
+ // Page grain: one row per page, so no best_per_page pool. top_pages ranks
+ // and limits first; the representative-chunk LATERAL (compiled_truth first,
+ // then lowest chunk_index) and the stale probe run per OUTPUT row. Neither
+ // affects order. COALESCEs keep chunkless pages retrievable (chunk_id 0,
+ // empty text). Accepted limitations (Reviewer F5/F6): the synthetic
+ // chunkless row dedups on empty chunk_text (fusion's compiledTruthBoost
+ // skips it since #3695); detail='low' filters only the representative.
+ const staleSql = dialect.staleProbe
+ ? `CASE WHEN tp.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te
+ WHERE te.page_id = tp.page_id) THEN true ELSE false END`
+ : 'false';
+ const sql = `
+ WITH top_pages AS (
+ SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id,
+ p.effective_date, p.effective_date_source, p.updated_at,
+ (lower(btrim(p.title, ' "''' || chr(160))) = $2) AS exact_title,
+ ${rankSql} * ${sourceFactorCase} AS score
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${matchSql}
+ ${filters}
+ ${hardExcludeClause}
+ ${visibilityClause}
+ ORDER BY exact_title DESC, score DESC, p.id ASC
+ LIMIT $3 OFFSET $4
+ )
+ SELECT tp.slug, tp.page_id, tp.title, tp.type, tp.source_id,
+ tp.effective_date, tp.effective_date_source,
+ COALESCE(rep.id, 0) AS chunk_id,
+ COALESCE(rep.chunk_index, 0) AS chunk_index,
+ COALESCE(rep.chunk_text, '') AS chunk_text,
+ COALESCE(rep.chunk_source, 'compiled_truth') AS chunk_source,
+ tp.score,
+ ${staleSql} AS stale
+ FROM top_pages tp
+ LEFT JOIN LATERAL (
+ SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_source
+ FROM content_chunks cc
+ WHERE cc.page_id = tp.page_id
+ AND cc.modality = 'text'
+ ${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}
+ ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
+ LIMIT 1
+ ) rep ON true
+ ORDER BY tp.exact_title DESC, tp.score DESC, tp.page_id ASC
+ `;
+ return { sql, params, safeChunks };
+}
+
diff --git a/test/e2e/title-arm-postgres.test.ts b/test/e2e/title-arm-postgres.test.ts
new file mode 100644
index 0000000000..cc306d3e40
--- /dev/null
+++ b/test/e2e/title-arm-postgres.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Title arm on PostgreSQL: the dual-backend cases in
+ * test/search/title-arm-exact.test.ts, plus a plan proof for the remote
+ * (safe-chunks) predicate. The plan proof EXPLAINs the statement the engine
+ * runs (search/title-statement.ts buildSearchTitlesStatement, the one builder
+ * both engines call) and requires `idx_pages_search` with no per-row
+ * `to_tsvector(title)` filter (the pre-fix remote arm scanned every page in
+ * scope). `enable_seqscan = off` inside the transaction keeps the plan
+ * choice deterministic on a small fixture.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { buildSearchTitlesStatement } from '../../src/core/search/title-statement.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { registerPostgresTests, requirePostgresTestDatabase } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../search/title-arm-exact.test.ts'));
+
+const POSTGRES_DIALECT = { statementTimeout: '8s', relaxedPrefersIndex: true, staleProbe: false };
+const REMOTE = { requireSafeChunks: true, excludePrivate: true, sourceId: 'default', limit: 50 };
+
+describe('remote title arm plan (postgres)', () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedPersistencePostgres(requirePostgresTestDatabase()));
+ for (let i = 1; i <= 40; i++) {
+ const slug = `notes/page-${i}`;
+ const body = `Body ${i}.`;
+ await engine.putPage(slug, { type: 'note', title: i % 10 === 0 ? `Acme review ${i}` : `Globex weekly sync ${i}`, compiled_truth: body });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }]);
+ }
+ await engine.executeRaw('ANALYZE pages');
+ }, 120_000);
+
+ afterAll(async () => { await close?.(); });
+
+ async function plan(query: string): Promise<string> {
+ const statement = buildSearchTitlesStatement(query, REMOTE, POSTGRES_DIALECT);
+ return engine.transaction(async (tx) => {
+ await tx.executeRaw(`SET LOCAL enable_seqscan = off`);
+ const rows = await tx.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${statement.sql}`, statement.params);
+ return rows.map((r) => r['QUERY PLAN']).join('\n');
+ });
+ }
+
+ for (const query of ['acme', 'acme -secret', '"weekly sync"', 'globex or acme']) {
+ test(`\`${query}\` uses idx_pages_search with no per-row to_tsvector(title)`, async () => {
+ const text = await plan(query);
+ expect(text).toContain('idx_pages_search');
+ expect(text).not.toMatch(/to_tsvector\([^)]*title/);
+ });
+ }
+
+ test('the engine runs the same statement the plan proof explains', async () => {
+ const statement = buildSearchTitlesStatement('acme', REMOTE, POSTGRES_DIALECT);
+ const direct = await engine.executeRaw<{ slug: string }>(statement.sql, statement.params);
+ const viaEngine = await engine.searchTitles('acme', REMOTE);
+ expect(viaEngine.map((r) => r.slug)).toEqual(direct.map((r) => r.slug));
+ expect(viaEngine.length).toBe(4);
+ });
+});
diff --git a/test/search/title-arm-exact.test.ts b/test/search/title-arm-exact.test.ts
new file mode 100644
index 0000000000..91da13e8f7
--- /dev/null
+++ b/test/search/title-arm-exact.test.ts
@@ -0,0 +1,196 @@
+/**
+ * #5889 + remote title FTS: the page-grain title arm (engine-sql/titles.ts)
+ * on PGLite here and on PostgreSQL through test/e2e/title-arm-postgres.test.ts.
+ *
+ * #5889: every title holding the query term once ties on ts_rank_cd, ties
+ * broke by page id, and the exact-lookup tier only sees the arm's top rows,
+ * so an identity page titled exactly "Acme" (created last) was buried under
+ * 60+ "Acme weekly sync N" pages for local and remote callers.
+ *
+ * Remote predicate: safe-chunks callers match weight-A (title) lexemes of
+ * pages.search_vector. Parity cases compare against the previous title-only
+ * predicate (`to_tsvector(lang, title) @@ websearch_to_tsquery(lang, q)`),
+ * so timeline text can never change which titles a remote caller sees.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { hybridSearch, hybridSearchCached } from '../../src/core/search/hybrid.ts';
+import { configureGateway } from '../../src/core/ai/gateway.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const DIM = 1536;
+const LOCAL: SearchOpts = {};
+const REMOTE: SearchOpts = { requireSafeChunks: true, excludePrivate: true };
+const SYNC_PAGES = 64;
+
+for (const kind of testBackends()) {
+ describe(`title arm (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ // Empty env: no embedding, so hybridSearch takes the keyword + title path.
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIM, env: {} });
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await close?.();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIM, env: { ...process.env } });
+ });
+
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ });
+
+ async function page(slug: string, title: string, body: string, timeline = '') {
+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body, timeline });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }]);
+ }
+
+ async function seedSyncPages(prefix: string) {
+ for (let i = 1; i <= SYNC_PAGES; i++) {
+ await page(`${prefix}/acme-sync-${i}`, `Acme weekly sync ${i}`, `Acme sync ${i} notes: the Acme team reviewed the Acme roadmap.`);
+ }
+ }
+
+ describe('#5889 exact-title page ranks first', () => {
+ for (const prefix of ['notes', 'meetings']) {
+ test(`${prefix}/ variant, local and remote callers`, async () => {
+ await seedSyncPages(prefix);
+ await page('projects/acme', 'Acme', 'Our flagship client project.');
+ for (const [label, opts] of [['local', LOCAL], ['remote', REMOTE]] as const) {
+ const titles = await engine.searchTitles('Acme', { ...opts, limit: 50 });
+ expect({ label, slug: titles[0]?.slug }).toEqual({ label, slug: 'projects/acme' });
+ const results = await hybridSearch(engine, 'Acme', { ...opts, limit: 20, expansion: false });
+ expect({ label, slug: results[0]?.slug, exact: results[0]?.exact_lookup }).toEqual({ label, slug: 'projects/acme', exact: 'title' });
+ }
+ }, 120_000);
+ }
+
+ test('production cached path (search cache on) ranks it first too', async () => {
+ await seedSyncPages('notes');
+ await page('projects/acme', 'Acme', 'Our flagship client project.');
+ for (const opts of [LOCAL, REMOTE]) {
+ const results = await hybridSearchCached(engine, 'Acme', { ...opts, limit: 20, expansion: false, useCache: true });
+ expect(results[0]?.slug).toBe('projects/acme');
+ expect(results[0]?.exact_lookup).toBe('title');
+ }
+ }, 120_000);
+
+ for (const [label, title] of [['quoted YAML title', '"Acme"'], ['trailing NBSP', 'Acme\u00a0']] as const) {
+ test(`${label} ranks first with exact_lookup: title`, async () => {
+ await seedSyncPages('notes');
+ await page('projects/acme', title, 'Our flagship client project.');
+ for (const opts of [LOCAL, REMOTE]) {
+ const results = await hybridSearch(engine, 'Acme', { ...opts, limit: 20, expansion: false });
+ expect(results[0]?.slug).toBe('projects/acme');
+ expect(results[0]?.exact_lookup).toBe('title');
+ }
+ }, 120_000);
+ }
+
+ test('negative control: "Acme Corp" gets no exact_lookup', async () => {
+ await seedSyncPages('notes');
+ await page('companies/acme-corp', 'Acme Corp', 'A supplier.');
+ for (const opts of [LOCAL, REMOTE]) {
+ const results = await hybridSearch(engine, 'Acme', { ...opts, limit: 20, expansion: false });
+ expect(results.some((r) => r.exact_lookup !== undefined)).toBe(false);
+ }
+ }, 120_000);
+
+ test('the OR fallback re-runs the same statement and tags relaxed rows', async () => {
+ await seedSyncPages('notes');
+ await page('projects/acme-zebra', 'Acme Zebra', 'Unrelated body.');
+ // Strict AND matches nothing, so the arm re-runs as OR; no title equals the query.
+ const rows = await engine.searchTitles('Acme Zebra Quokka', { limit: 50 });
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.every((r) => r.keyword_relaxed === true)).toBe(true);
+ }, 120_000);
+ });
+
+ describe('remote predicate matches the title alone', () => {
+ async function legacyRemoteSlugs(query: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE to_tsvector('english', COALESCE(title, '')) @@ websearch_to_tsquery('english', $1) ORDER BY slug`,
+ [query],
+ );
+ return rows.map((r) => r.slug);
+ }
+ async function remoteSlugs(query: string): Promise<string[]> {
+ return (await engine.searchTitles(query, { ...REMOTE, limit: 100 })).map((r) => r.slug).sort();
+ }
+
+ beforeEach(async () => {
+ await page('notes/acme-plan', 'Acme launch plan', 'Body without title words.', '- 2026-01-01: secret kickoff with the zebra team');
+ await page('notes/acme-secret', 'Acme secret roadmap', 'Body.');
+ await page('notes/globex-sync', 'Globex weekly sync', 'Body.', '- 2026-01-02: Acme mentioned in passing');
+ await page('notes/launch-acme', 'Launch the Acme product', 'Body.');
+ await page('notes/zebra', 'Zebra crossing', 'Body.');
+ });
+
+ const queries = [
+ ['negation where only a timeline mentions the term', 'acme -secret'],
+ ['phrase', '"acme launch"'],
+ ['phrase across title words only', '"launch plan"'],
+ ['OR', 'globex or zebra'],
+ ['timeline-only term', 'kickoff'],
+ ['purely negative', '-acme'],
+ ['prefix-style token', 'acme*'],
+ ['negated phrase', 'acme -"secret roadmap"'],
+ ] as const;
+ for (const [label, query] of queries) {
+ test(`${label}: \`${query}\` matches the legacy title-only predicate`, async () => {
+ expect(await remoteSlugs(query)).toEqual(await legacyRemoteSlugs(query));
+ });
+ }
+
+ test('negation pins the expected titles', async () => {
+ expect(await remoteSlugs('acme -secret')).toEqual(['notes/acme-plan', 'notes/launch-acme']);
+ expect(await remoteSlugs('kickoff')).toEqual([]);
+ });
+
+ test('order follows the title rank, like the legacy predicate', async () => {
+ const rows = await engine.searchTitles('acme', { ...REMOTE, limit: 100 });
+ const legacy = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE to_tsvector('english', title) @@ websearch_to_tsquery('english', 'acme')
+ ORDER BY ts_rank_cd(to_tsvector('english', title), websearch_to_tsquery('english', 'acme')) DESC, id`,
+ );
+ expect(rows.map((r) => r.slug)).toEqual(legacy.map((r) => r.slug));
+ });
+
+ test('a page with a NULL search_vector is absent from the remote arm (accepted)', async () => {
+ await engine.executeRaw(`UPDATE pages SET search_vector = NULL WHERE slug = 'notes/zebra'`);
+ expect(await legacyRemoteSlugs('zebra')).toEqual(['notes/zebra']);
+ expect(await remoteSlugs('zebra')).toEqual([]);
+ });
+
+ test('weight A of pages.search_vector is the title alone', async () => {
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, summary, detail)
+ SELECT id, '2026-01-03', 'Quokka summit', 'quokka detail' FROM pages WHERE slug = 'notes/acme-plan'`,
+ );
+ await engine.executeRaw(`UPDATE pages SET timeline = timeline || ' more quokka text' WHERE slug = 'notes/acme-plan'`);
+ const [row] = await engine.executeRaw<{ a: string; title: string; c: string }>(
+ `SELECT strip(ts_filter(search_vector, '{a}'))::text AS a,
+ strip(to_tsvector('english', title))::text AS title,
+ strip(ts_filter(search_vector, '{c}'))::text AS c
+ FROM pages WHERE slug = 'notes/acme-plan'`,
+ );
+ expect(row.a).toBe(row.title);
+ expect(row.c).toContain('quokka');
+ });
+ });
+ });
+}