Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): resolve slug handles in keyword search, quoted or bare (GBRA-108)

garrytan030e715184b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f176f13e06..a7e5634ffe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision
## [0.60.440.0] - 2026-10-24
-**A question that names a page by an identifier ("What did the latest weekly digest (#412) say?") now returns the page holding `#412`, even when the question's other words keep it from matching every word and near-identical template pages tie with it on meaning. The coverage notice also stops blaming indexing for unrelated image pages.**
+**A question that names a page by an identifier ("What did the latest weekly digest (#412) say?") now returns the page holding `#412`, even when the question's other words keep it from matching every word and near-identical template pages tie with it on meaning. A handle such as `dan-example` now finds the page it names (`people/dan-example`) in keyword search, quoted or not. The coverage notice also stops blaming indexing for unrelated image pages.**
### Identifiers in questions
@@ -24,6 +24,16 @@ identifiers and attribution are available in the pre-removal Git revision
An identifier is a `#` number, a run of 6 or more digits, a code such as INV-2026-00417, an email, a URL or a phone number, asked together with other words. Queries without one, a quoted phrase or a `-` negation run exactly as before, and the any-word rows that don't hold an identifier are still dropped while semantic search is healthy.
+### Handles in keyword search
+
+| Situation | Before | Now |
+|---|---|---|
+| `gbrain search '"dan-example" OR "erin-example"' --match keyword`, where the person pages hold the handles only in their slugs | the pages that mention the handles came back, never the pages they name: a hyphenated handle only matches text holding the literal handle | the pages whose slug ends in each handle (`people/dan-example`, `people/erin-example`) are listed and counted first |
+| The same query with `--types '["person"]'` | no results | the two person pages |
+| The same query in hybrid search | quoted terms skip the any-word retry, so the title arm found nothing either | the named pages lead the keyword arm, as rows that count like strict keyword rows |
+
+A handle is a hyphenated token with a letter in it, bare or quoted on its own (`acme-example-2` counts, `2026-10-24` does not), and resolves only to a page whose slug ends in exactly that handle. A negated handle (`-dan-example`) or one inside a longer quoted phrase is not resolved. The named pages pass the same filters as any keyword match: `--types`, the caller's sources, and for remote callers no private or quarantined page.
+
### Coverage notice
| Situation | Before | Now |
@@ -37,6 +47,7 @@ An identifier is a `#` number, a run of 6 or more digits, a code such as INV-202
### What to watch for after you upgrade
- A search naming an identifier costs one more keyword statement, served by the full-text index. Other searches run the same statements as before, except that an any-word retry of 5 to 12 words now also runs the bounded rare-word read and, when a rare word is found, one more retry statement (both already ran for retries of up to 4 words). The rare-word read skips stopwords, and on Postgres it skips words the column statistics already estimate as common, so its cost follows the question's rare words, not its length.
+- A query with a hyphenated token costs one more index lookup on page slugs: one more statement in hybrid search, and one more arm of the same statement with `--match keyword`. `keyword_total` and the `--match keyword` count include the named pages.
- Pages that hold the identifier but not the other words can now rank above pages that match the question's meaning better. The page holding every word still comes first among keyword rows.
- `_meta.retrieval.coverage.could_affect` can carry `pending_images`, and `could_affect.pending_projection` can drop for queries whose digits or short words used to match unrelated slugs.
- Nothing is rewritten on upgrade, no setting changed, and there is no schema migration.
diff --git a/docs/architecture/key-files/core-search-cjk.md b/docs/architecture/key-files/core-search-cjk.md
index 73d19e6d3b..65796b1580 100644
--- a/docs/architecture/key-files/core-search-cjk.md
+++ b/docs/architecture/key-files/core-search-cjk.md
@@ -1,4 +1,4 @@
-# Key files: Core Search (keyword arm: CJK fallback, OR retry, identifier probe)
+# Key files: Core Search (keyword arm: CJK fallback, OR retry, identifier probe, slug handles)
[Subsystem index](../KEY_FILES.md) · [Core Search (2/2)](core-search-2.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
@@ -6,3 +6,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`, and `onStatementBudget`, which reports each Postgres statement's timeout and the arm ... (line truncated to 2000 chars)
- `src/core/search/keyword-or-rarity.ts` — rare words first in both engines' keyword OR retry. For at most `RARITY_MAX_KEYWORD_TERMS` (12) words (the title arm keeps `RARITY_MAX_TERMS` = 4: it runs one statement per word), `rareTermPagesSql` reads the pages of each word's first `RARE_TERM_CHUNK_CAP` + 1 visible chunks (brain-wide, weights only; stopwords and, on Postgres, words `commonOrTokens` in keyword-or-narrow.ts estimates past the cap are skipped); a fitting word weighs 1 / pages. `rankOrFallbackByRarity` re-runs the retry with the rarest words' OR and sorts by summed weight.
- `src/core/search/keyword-identifier-probe.ts` — #7491: `keywordArmRows` builds both engines' `searchKeyword` rows from the strict rows. With `orFallback`, offset 0 and no quote or negation, a query naming an identifier (`identifierTokens`: a hash number `#412`, or a token `identifier-query.ts` recognizes: a 6+ digit run, hex id, code, email, URL or phone) and other words runs the arm's own statement once more with the AND of the identifier tokens as the match query and the any-word query as the rank query: same scope, visibility, chunk predicate, filters and candidate cap as strict. Its rows are untagged (they vote like strict rows): after the strict rows when strict matched, ahead of the relaxed rows (`keyword_relaxed`) when it did not; one row per page, cut to the limit. A failed probe adds nothing. `holdsIdentifiers` lets the title arm's OR retry (`engine-sql/titles.ts`) lead with, untagged, the titles holding every identifier. Pinned by `test/search/identifier-probe.serial.test.ts` (+ Postgres E2E) and `test/search/keyword-identifier-probe.test.ts`.
+- `src/core/search/keyword-handles.ts` — GBRA-108: `slugHandles` finds the query's slug handles (a hyphenated slug-leaf token with a letter, bare or quoted on its own, at most `MAX_SLUG_HANDLES` = 16; negated tokens and tokens inside a longer quoted phrase are not handles). They resolve by exact slug basename (`handleMatchSql`, served by `idx_pages_slug_basename` like `whois`) as an arm of the keyword statement (`search/keyword-statement.ts`) under its filters, scope and visibility, so `--types`, granted sources, private pages and quarantine apply. `match: "keyword"` lists and counts the named pages first; in `searchKeyword` (orFallback, offset 0) `keywordArmRows` puts them ahead of every other row, untagged. A query without a handle builds the statements it built before. Pinned by `test/search/slug-handles.serial.test.ts` (+ Postgres E2E) and `test/search/keyword-handles.test.ts`.
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 33332eeb88..f60550a848 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -28,7 +28,7 @@ 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 match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
+- `src/core/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). A query with slug handles (`search/keyword-handles.ts`) adds a second arm under the same filters, the chunks of the pages whose slug basename equals a handle (`idx_pages_slug_basename`), scored 1 + rank so they lead; the count is a `UNION` of both arms and `buildKeywordHandlePagesStatement` reads the handle arm alone for `searchKeyword`. The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.
- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm. #7471: a 2-4 word name query ORs in its given-name variants (`titleNameVariants`: "Matt Example" also matches the title "Matthew Example"), each its own bound websearch query; the OR fallback of a query of at most `RARITY_MAX_TERMS` words runs once per word in one scoped read and `rankByRarity` puts titles holding the rarest word first (ts_rank_cd knows no term rarity, so a surname's one title used to tie thousands of first-name titles and lose on page id). #7491: OR-retry titles holding every identifier the query names (`holdsIdentifiers`, search/keyword-identifier-probe.ts) lead untagged; the rest stay `keyword_relaxed`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c0e59a35ac..a3c373a42a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1222,6 +1222,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.427.0', id: 'whois_exact_identity', text: 'New read operation `whois` (CLI `gbrain whois <email or name>`, MCP tool `whois`): an exact identity lookup for agents triaging email or calendar. It returns the entity pages whose frontmatter `email`/`emails`, title or declared alias equals the query, ignoring case, accents and surrounding quotes, labels each match `email`, `title` or `alias`, sets `ambiguous` when more than one page matches, and returns an empty list, never a search fallback, when none does. Remote callers see only their granted sources and no private or quarantined page. Nothing existing changes.' },
// GBRA-156 (#7491, #7492). `since` is stamped at the merge slot.
{ since: '0.60.440.0', id: 'keyword_identifier_probe', text: 'A search or query naming an identifier (`#412`, a 6+ digit run, a code like INV-2026-00417, an email or a URL) together with other words now runs one more keyword statement: the arm\'s own statement, with the same scope, visibility and filters, matching every identifier the query names. Those rows vote like strict keyword rows, so the page holding the identifier is no longer dropped when filler words ("What did the latest weekly digest (#412) say?") keep it from matching every word, and a title holding every identifier leads the title arm\'s any-word retry. The keyword arm\'s any-word retry ranks rare words first for questions of up to 12 words (it was 4). Queries without an identifier keep their keyword rows. `_meta.retrieval.coverage` counts a pending page only when a query word is a whole token of its title or slug (`412` no longer matches `t004120`), counts pending image pages only when an image arm ran, and adds `could_affect.pending_images`; the `projection_pending` notice says text pages are being indexed and that image pages wait for `gbrain projections drain` or a paid re-import, with doctor\'s `text_projection_readiness` as the fix.' },
+ { since: '0.60.440.0', id: 'keyword_slug_handles', text: 'Keyword search resolves slug handles: a hyphenated token with a letter in it (`dan-example`), bare or quoted on its own, now also matches the pages whose slug ends in exactly that handle (`people/dan-example`), under the same scope, filters and visibility as any keyword match. Those pages lead `match: "keyword"` results and its count, and lead the hybrid keyword arm as rows that vote like strict rows, so `"dan-example" OR "erin-example"` with `--types \'["person"]\'` returns the two person pages instead of nothing. Queries without such a token run as before.' },
];
/** 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.ts
index b819d76a43..49c734849e 100644
--- a/src/core/engine-sql/keyword-pages.ts
+++ b/src/core/engine-sql/keyword-pages.ts
@@ -10,7 +10,7 @@
*/
import type { SearchOpts, SearchResult } from '../types.ts';
import { rowToSearchResult } from '../utils.ts';
-import { buildKeywordCountStatement, buildKeywordPagesStatement, type KeywordPageWindow } from '../search/keyword-statement.ts';
+import { buildKeywordCountStatement, buildKeywordHandlePagesStatement, 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. */
@@ -32,7 +32,17 @@ export async function countKeywordPages(
export async function searchKeywordPages(
scoped: ScopedReadRunner, query: string, opts: SearchOpts | undefined, page: KeywordPageWindow, dialect: KeywordPagesDialect,
): Promise<SearchResult[]> {
- const statement = buildKeywordPagesStatement(query, opts, page);
+ return readPages(scoped, buildKeywordPagesStatement(query, opts, page), dialect);
+}
+
+/** GBRA-108: the pages the query's slug handles name (search/keyword-handles.ts), best chunk each; the keyword arm's rows for them. */
+export async function searchHandlePages(
+ scoped: ScopedReadRunner, query: string, handles: readonly string[], opts: SearchOpts | undefined, limit: number, dialect: KeywordPagesDialect,
+): Promise<SearchResult[]> {
+ return readPages(scoped, buildKeywordHandlePagesStatement(query, handles, opts, limit), dialect);
+}
+
+async function readPages(scoped: ScopedReadRunner, statement: { sql: string; params: unknown[] } | null, dialect: KeywordPagesDialect): Promise<SearchResult[]> {
if (!statement) return [];
const rows = await scoped(async exec => (await exec.unsafe(statement.sql, statement.params)).rows,
dialect.statementTimeout ? { statement_timeout: dialect.statementTimeout } : undefined);
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 7bca67c480..c8b4c45735 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1527,6 +1527,7 @@ export class PGLiteEngine implements BrainEngine {
// relaxed-row tag (#3617 follow-up) live in search/keyword-identifier-probe.ts.
const run = async (matchQuery: string, rankQuery: string) => (await this.db.query(keywordSql, params.map((v, i) => i === 0 ? matchQuery : i === rankIdx && !opts?.rankQuery ? rankQuery : v))).rows as Record<string, unknown>[];
return keywordArmRows({ query, strict: strict as Record<string, unknown>[], orFallback: opts?.orFallback, limit, offset, toResult: rowToSearchResult, runProbe: run,
+ runHandles: handles => keywordPagesImpl.searchHandlePages(async (read) => read(scopedRead(this.engineSql)), query, handles, opts, limit, {}),
runRelaxed: async orQuery => rankOrFallbackByRarity({ query, rows: await run(orQuery, orQuery), limit, offset, runRare: q => run(q, orQuery),
readTermPages: async terms => (await this.db.query(rareTermPagesSql(ftsLang), [terms, RARE_TERM_CHUNK_CAP])).rows as RareTermPages[] }) }).finally(settle);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 7520a8d871..1a1e8b49b0 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1200,6 +1200,7 @@ export class PostgresEngine implements BrainEngine {
// search/keyword-identifier-probe.ts.
return keywordArmRows<Record<string, unknown>>({ query, strict, orFallback: opts?.orFallback, limit, offset, toResult: rowToSearchResult,
runProbe: (match, rank) => runKeyword(match, true, rank),
+ runHandles: handles => keywordPagesImpl.searchHandlePages((read, settings) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true, settings }), query, handles, opts, limit, { statementTimeout }),
runRelaxed: async (orQuery) => {
const shares = await readOrTokenShares((sql, p) => this.executeRaw(sql, p), query, ftsLang);
const narrowed = narrowedOrFallbackText(shares), common = commonOrTokens(shares, RARE_TERM_CHUNK_CAP);
diff --git a/src/core/search/keyword-handles.ts b/src/core/search/keyword-handles.ts
new file mode 100644
index 0000000000..d5b20c1248
--- /dev/null
+++ b/src/core/search/keyword-handles.ts
@@ -0,0 +1,45 @@
+/**
+ * GBRA-108: slug handles in keyword search. A person page slugged
+ * `people/dan-example` and titled "Dan Example" holds its handle only in the
+ * slug, and `websearch_to_tsquery` turns `dan-example` (quoted or bare) into
+ * a phrase that needs the compound lexeme `dan-exampl`, which only text
+ * holding the literal hyphenated handle has. So `"dan-example" OR
+ * "erin-example"` matched the pages that mention the handles and never the
+ * pages they name, and with `--types '["person"]'` it matched nothing.
+ *
+ * A handle is a hyphenated slug-leaf token with a letter in it (`dan-example`,
+ * `acme-example-2`), bare or quoted on its own; each quoted handle of an OR is
+ * resolved on its own, and a negated one (`-dan-example`) or one inside a
+ * longer quoted phrase is not resolved. Resolution is an exact match of the
+ * slug's basename (the part after the last `/`, the whole slug for a root
+ * page), served by idx_pages_slug_basename like `whois`. The match is a second
+ * arm of the keyword statement (search/keyword-statement.ts) under the same
+ * filters, scope and visibility, so `--types`, remote scope, private pages and
+ * quarantine apply as for any text match. Queries without a handle build
+ * exactly the statements they built before.
+ */
+
+const HANDLE_RE = /^[a-z0-9]+(?:-[a-z0-9]+)+$/;
+const EDGE_PUNCTUATION = /^[(\[{<'\u2018\u201c]+|[)\]}>'\u2019\u201d.,;:!?]+$/gu;
+
+/** At most this many handles per query (a pasted list of slugs stays one bounded index probe). */
+export const MAX_SLUG_HANDLES = 16;
+
+/** The query's slug handles, lowercased, or null when it has none. */
+export function slugHandles(query: string): string[] | null {
+ const handles = new Set<string>();
+ for (const m of query.normalize('NFKC').matchAll(/"([^"]*)"|(\S+)/g)) {
+ const bare = m[2];
+ if (bare?.startsWith('-')) continue;
+ const token = (bare === undefined ? m[1]!.trim() : bare.replace(EDGE_PUNCTUATION, '')).toLowerCase();
+ if (token.length > 128 || !HANDLE_RE.test(token) || !/[a-z]/.test(token)) continue;
+ handles.add(token);
+ if (handles.size === MAX_SLUG_HANDLES) break;
+ }
+ return handles.size ? [...handles] : null;
+}
+
+/** The pages whose slug basename is one of the handles in `param` (a text[] bind). */
+export function handleMatchSql(pageAlias: string, param: string): string {
+ return `regexp_replace(${pageAlias}.slug, '^.*/', '') = ANY(${param}::text[])`;
+}
diff --git a/src/core/search/keyword-identifier-probe.ts b/src/core/search/keyword-identifier-probe.ts
index f08072c66e..2d8c0c722b 100644
--- a/src/core/search/keyword-identifier-probe.ts
+++ b/src/core/search/keyword-identifier-probe.ts
@@ -27,6 +27,7 @@
import type { SearchResult } from '../types.ts';
import { parseIdentifier } from './identifier-query.ts';
import { buildOrFallbackWebsearchQuery, orFallbackTokens } from './sql-ranking.ts';
+import { slugHandles } from './keyword-handles.ts';
const HASH_NUMBER_RE = /^#(\d+)$/;
@@ -84,11 +85,15 @@ export async function keywordArmRows<R>(a: {
toResult: (row: R) => SearchResult;
runProbe: (matchQuery: string, rankQuery: string) => Promise<R[]>;
runRelaxed: (orQuery: string) => Promise<R[]>;
+ /** GBRA-108: the pages the query's slug handles name (search/keyword-handles.ts); they lead the rows, untagged. */
+ runHandles?: (handles: string[]) => Promise<SearchResult[]>;
}): Promise<SearchResult[]> {
+ const handles = a.orFallback && a.offset === 0 && a.runHandles ? slugHandles(a.query) : null;
+ const named = handles ? await a.runHandles!(handles).catch(() => [] as SearchResult[]) : [];
const orQuery = a.orFallback ? buildOrFallbackWebsearchQuery(a.query) : null;
const probeQuery = orQuery && a.offset === 0 ? identifierProbeQuery(a.query) : null;
const probe = probeQuery ? (await a.runProbe(probeQuery, orQuery!).catch(() => [] as R[])).map(a.toResult) : [];
- if (a.strict.length > 0 || !orQuery) return appendPages(a.strict.map(a.toResult), probe, a.limit);
+ if (a.strict.length > 0 || !orQuery) return appendPages(named, appendPages(a.strict.map(a.toResult), probe, a.limit), a.limit);
const relaxed = (await a.runRelaxed(orQuery)).map(r => ({ ...a.toResult(r), keyword_relaxed: true as const }));
- return appendPages(probe, relaxed, a.limit);
+ return appendPages(named, appendPages(probe, relaxed, a.limit), a.limit);
}
diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.ts
index 1ddf693666..4c463bc43d 100644
--- a/src/core/search/keyword-statement.ts
+++ b/src/core/search/keyword-statement.ts
@@ -25,6 +25,7 @@ import { getFtsLanguage } from '../fts-language.ts';
import { frontmatterWhereSql } from './frontmatter-where.ts';
import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';
import { buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';
+import { handleMatchSql, slugHandles } from './keyword-handles.ts';
/** Counts stop here; a capped count is reported as "10000+". */
export const KEYWORD_COUNT_CAP = 10_000;
@@ -34,13 +35,17 @@ export interface KeywordPageAfter { score: number; page_id: number }
export interface KeywordPageWindow { limit: number; offset?: number; after?: KeywordPageAfter }
-/** `params[0..whereParamCount)` are the ones `where` reads; the rank params follow, read only by `score`. */
-interface KeywordMatch { where: string; score: string; params: unknown[]; whereParamCount: number }
+/**
+ * `params[0..whereParamCount)` are the ones `where` and `handleWhere` read; the rank params follow, read only by
+ * the scores. `handleWhere` (GBRA-108): the chunks of pages a slug handle in the query names (search/keyword-handles.ts),
+ * under the same filters and visibility; its pages score 1 + their best chunk's rank, ahead of every text match.
+ */
+interface KeywordMatch { where: string; score: string; handleWhere?: string; handleScore?: string; params: unknown[]; whereParamCount: number }
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 {
+export function buildKeywordMatch(query: string, opts: SearchOpts | undefined, handles: readonly string[] | null = slugHandles(query), handlesOnly = false): KeywordMatch | null {
const params: unknown[] = [];
let predicate: string;
let rank: () => string;
@@ -63,6 +68,19 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):
predicate = `cc.search_vector @@ ${tsq}`;
rank = () => `ts_rank(cc.search_vector, ${tsq})`;
}
+ const where = handlesOnly ? '' : predicate + keywordFilters(opts, params);
+ let handleWhere: string | undefined;
+ if (handles?.length && !hasCJK(query)) handleWhere = `${handleMatchSql('p', `$${params.push(handles)}`)}${keywordFilters(opts, params)}`;
+ const whereParamCount = params.length;
+ const factor = buildSourceFactorCase('p.slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail);
+ return {
+ where, score: `((${rank()}) * ${factor})::float8`, params, whereParamCount,
+ ...(handleWhere ? { handleWhere, handleScore: `((1 + ${rank()}) * ${factor})::float8` } : {}),
+ };
+}
+
+/** The page filters, hard excludes and visibility every keyword match applies after its predicate. */
+function keywordFilters(opts: SearchOpts | undefined, params: unknown[]): string {
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'`;
@@ -78,10 +96,7 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):
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);
- const where = `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' })} AND cc.modality = 'text'`;
- const whereParamCount = params.length;
- return { where, score: `((${rank()}) * ${factor})::float8`, params, whereParamCount };
+ return `${filters} ${hardExclude} ${buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' })} AND cc.modality = 'text'`;
}
/** Distinct matching pages, capped at KEYWORD_COUNT_CAP + 1. */
@@ -89,15 +104,31 @@ export function buildKeywordCountStatement(query: string, opts: SearchOpts | und
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`,
+ sql: `SELECT count(*)::int AS n FROM (SELECT DISTINCT cc.page_id FROM ${FROM} WHERE ${m.where}${m.handleWhere ? ` UNION SELECT cc.page_id FROM ${FROM} WHERE ${m.handleWhere}` : ''} LIMIT ${KEYWORD_COUNT_CAP + 1}) matched`,
params: m.params.slice(0, m.whereParamCount),
};
}
/** 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);
+ return pagesStatement(buildKeywordMatch(query, opts), page, false);
+}
+
+/**
+ * GBRA-108: only the pages the query's slug handles name (best chunk each, the keyword arm's rows for them), or null
+ * when it names none. One statement served by idx_pages_slug_basename; the same filters and visibility as the match.
+ */
+export function buildKeywordHandlePagesStatement(query: string, handles: readonly string[], opts: SearchOpts | undefined, limit: number): { sql: string; params: unknown[] } | null {
+ const m = buildKeywordMatch(query, opts, handles, true);
+ return m?.handleWhere ? pagesStatement(m, { limit }, true) : null;
+}
+
+function pagesStatement(m: KeywordMatch | null, page: KeywordPageWindow, handlesOnly: boolean): { sql: string; params: unknown[] } | null {
if (!m) return null;
+ const arms = [
+ ...(handlesOnly ? [] : [`SELECT cc.page_id, cc.id AS chunk_id, ${m.score} AS score FROM ${FROM} WHERE ${m.where}`]),
+ ...(m.handleWhere ? [`SELECT cc.page_id, cc.id AS chunk_id, ${m.handleScore} AS score FROM ${FROM} WHERE ${m.handleWhere}`] : []),
+ ];
const params = [...m.params];
let after = '';
if (page.after) {
@@ -109,7 +140,7 @@ export function buildKeywordPagesStatement(query: string, opts: SearchOpts | und
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}
+ ${arms.join('\n UNION ALL\n ')}
), best AS (
SELECT DISTINCT ON (page_id) page_id, chunk_id, score FROM matched ORDER BY page_id, score DESC, chunk_id ASC
)
@@ -117,7 +148,7 @@ export function buildKeywordPagesStatement(query: string, opts: SearchOpts | und
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
+ FROM best b JOIN pages p ON p.id = b.page_id JOIN content_chunks cc ON cc.id = b.chunk_id -- chunk-visibility-ok: best holds only chunks the matched arms passed through keywordFilters (buildVisibilityClause with the chunk alias)
${after}
ORDER BY b.score DESC, b.page_id ASC
LIMIT $${params.length - 1} OFFSET $${params.length}`,
diff --git a/test/e2e/slug-handles-postgres.test.ts b/test/e2e/slug-handles-postgres.test.ts
new file mode 100644
index 0000000000..68b059bf9f
--- /dev/null
+++ b/test/e2e/slug-handles-postgres.test.ts
@@ -0,0 +1,4 @@
+/** Slug handles in keyword search (GBRA-108) on PostgreSQL: the dual-backend cases in test/search/slug-handles.serial.test.ts. */
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../search/slug-handles.serial.test.ts'));
diff --git a/test/search/keyword-handles.test.ts b/test/search/keyword-handles.test.ts
new file mode 100644
index 0000000000..4af92a1c37
--- /dev/null
+++ b/test/search/keyword-handles.test.ts
@@ -0,0 +1,70 @@
+/** GBRA-108: which query tokens are slug handles (search/keyword-handles.ts) and where their rows go in the keyword arm. */
+import { describe, expect, test } from 'bun:test';
+import { MAX_SLUG_HANDLES, slugHandles } from '../../src/core/search/keyword-handles.ts';
+import { keywordArmRows } from '../../src/core/search/keyword-identifier-probe.ts';
+import { buildKeywordCountStatement, buildKeywordPagesStatement } from '../../src/core/search/keyword-statement.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+
+describe('slugHandles', () => {
+ test('quoted handles of an OR are each resolved, bare ones too, lowercased', () => {
+ expect(slugHandles('"dan-example" OR "erin-example"')).toEqual(['dan-example', 'erin-example']);
+ expect(slugHandles('what did Dan-Example say about acme-example-2?')).toEqual(['dan-example', 'acme-example-2']);
+ });
+
+ test('no hyphenated token, a token without a letter, a negation or a longer quoted phrase resolves nothing', () => {
+ expect(slugHandles('Dan Example procurement')).toBeNull();
+ expect(slugHandles('meeting on 2026-10-24')).toBeNull();
+ expect(slugHandles('northwind -dan-example')).toBeNull();
+ expect(slugHandles('northwind -"dan-example"')).toBeNull();
+ expect(slugHandles('"met dan-example yesterday"')).toBeNull();
+ expect(slugHandles('people/dan-example')).toBeNull();
+ });
+
+ test('at most MAX_SLUG_HANDLES handles', () => {
+ const q = Array.from({ length: 40 }, (_, i) => 'p-' + i + 'x').join(' ');
+ expect(slugHandles(q)).toHaveLength(MAX_SLUG_HANDLES);
+ });
+});
+
+describe('the keyword statement', () => {
+ test('a query without a handle builds the statement it built before (no handle arm)', () => {
+ for (const st of [buildKeywordCountStatement('northwind procurement', undefined), buildKeywordPagesStatement('northwind procurement', undefined, { limit: 10 })]) {
+ expect(st!.sql).not.toContain("regexp_replace(p.slug, '^.*/', '')");
+ expect(st!.sql).not.toContain('UNION');
+ }
+ });
+
+ test('a handle adds the basename arm under the same filters', () => {
+ const st = buildKeywordPagesStatement('"dan-example"', { types: ['person'] }, { limit: 10 })!;
+ expect(st.sql).toContain('UNION ALL');
+ expect(st.sql.match(/p\.type = ANY/g)).toHaveLength(2);
+ });
+});
+
+describe('keywordArmRows with handles', () => {
+ const row = (page_id: number) => ({ page_id, slug: 'p' + page_id }) as unknown as SearchResult;
+ const run = (query: string, o: { strict?: number[]; offset?: number; orFallback?: boolean; handles?: () => Promise<SearchResult[]> } = {}) => {
+ const calls: string[] = [];
+ return keywordArmRows<SearchResult>({
+ query, strict: (o.strict ?? []).map(row), orFallback: o.orFallback ?? true, limit: 5, offset: o.offset ?? 0, toResult: r => r,
+ runProbe: () => Promise.resolve([]),
+ runRelaxed: () => Promise.resolve([row(7)]),
+ runHandles: h => { calls.push(h.join(',')); return o.handles ? o.handles() : Promise.resolve([row(3)]); },
+ }).then(rows => ({ calls, rows: rows.map(r => [r.page_id, r.keyword_relaxed === true]) }));
+ };
+
+ test('named pages lead untagged, ahead of the strict rows, one row per page', async () => {
+ expect(await run('"dan-example" OR "erin-example"', { strict: [1, 3] })).toEqual({ calls: ['dan-example,erin-example'], rows: [[3, false], [1, false]] });
+ });
+
+ test('ahead of the relaxed rows when strict is empty', async () => {
+ expect((await run('dan-example procurement')).rows).toEqual([[3, false], [7, true]]);
+ });
+
+ test('no handle, a paged read or a precision caller resolves nothing; a failed read adds nothing', async () => {
+ expect((await run('northwind procurement', { strict: [1] })).calls).toEqual([]);
+ expect((await run('dan-example', { strict: [1], offset: 5 })).calls).toEqual([]);
+ expect((await run('dan-example', { strict: [1], orFallback: false })).calls).toEqual([]);
+ expect((await run('dan-example', { strict: [1], handles: () => Promise.reject(new Error('boom')) })).rows).toEqual([[1, false]]);
+ });
+});
diff --git a/test/search/slug-handles.serial.test.ts b/test/search/slug-handles.serial.test.ts
new file mode 100644
index 0000000000..094cf68259
--- /dev/null
+++ b/test/search/slug-handles.serial.test.ts
@@ -0,0 +1,144 @@
+/**
+ * GBRA-108: a slug handle (`dan-example`) names the page `people/dan-example`
+ * even when no indexed text holds it: the page is titled "Dan Example" and
+ * `websearch_to_tsquery` turns a hyphenated handle into a phrase only the
+ * literal handle matches. Keyword search resolves each handle by exact slug
+ * basename (search/keyword-handles.ts) under the keyword statement's scope,
+ * filters and visibility, in `match: "keyword"` and in the hybrid keyword
+ * arm, and the resolved pages vote like strict rows.
+ *
+ * PGLite here, PostgreSQL through test/e2e/slug-handles-postgres.test.ts.
+ * Serial: it stubs the process-wide embedding transport.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { hybridSearch } from '../../src/core/search/hybrid.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { callSearch } from '../helpers/keyword-paging-fixture.ts';
+
+const DIMS = 1536;
+const MODEL = 'openai:text-embedding-3-large';
+const QUERY_VEC = Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0));
+const vec = (spread: number) => '[' + Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : j === 1000 ? spread : 0)).join(',') + ']';
+const CLOSE = vec(0.05);
+const FAR = vec(0.6);
+
+const Q = '"dan-example" OR "erin-example"';
+const PEOPLE = ['people/dan-example', 'people/erin-example'];
+const LEAKS = ['people/gina-example', 'people/hank-example', 'people/ivy-example'];
+const LEAK_Q = '"dan-example" OR "gina-example" OR "hank-example" OR "ivy-example"';
+
+let prevHome: string | undefined;
+let home: string;
+
+beforeAll(() => {
+ prevHome = process.env.GBRAIN_HOME;
+ home = mkdtempSync(join(tmpdir(), 'gbrain-slug-handles-'));
+ process.env.GBRAIN_HOME = home;
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => QUERY_VEC) }) as any);
+});
+
+afterAll(() => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = prevHome;
+ rmSync(home, { recursive: true, force: true });
+});
+
+for (const kind of testBackends()) {
+ describe('slug handles in keyword search (' + kind + ')', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ async function page(slug: string, type: string, title: string, body: string, embedding: string, extra: { sourceId?: string; frontmatter?: Record<string, unknown> } = {}) {
+ const sourceId = extra.sourceId ?? 'default';
+ await engine.putPage(slug, { type, title, compiled_truth: body, frontmatter: extra.frontmatter ?? {} } as never, { sourceId } as never);
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }], { sourceId });
+ await engine.executeRaw(
+ 'UPDATE content_chunks SET embedding = $1::vector, model = $4, embedded_text_hash = md5(chunk_text) WHERE page_id = (SELECT id FROM pages WHERE slug = $2 AND source_id = $3)',
+ [embedding, slug, sourceId, MODEL],
+ );
+ }
+
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES ('other','other','{}') ON CONFLICT DO NOTHING");
+ await page('people/dan-example', 'person', 'Dan Example', 'VP of Procurement at northwind-example. Reports to the COO.', FAR);
+ await page('people/erin-example', 'person', 'Erin Example', 'Product Manager, Mobile at lumen-example.', FAR);
+ await page('companies/northwind-example', 'company', 'Northwind Example', 'Procurement led by dan-example. Renewal due in Q3.', CLOSE);
+ await page('meetings/2026-10-06-mobile-planning', 'meeting', 'Mobile planning', 'Attendees: erin-example, frank-example. Mobile planning for the launch.', CLOSE);
+ for (let i = 0; i < 20; i++) await page('notes/planning-' + i, 'note', 'Planning note ' + i, 'Weekly planning note ' + i + ' for the launch.', CLOSE);
+ await page('people/gina-example', 'person', 'Gina Example', 'Private notes on a candidate.', FAR, { frontmatter: { visibility: 'private' } });
+ await page('people/hank-example', 'person', 'Hank Example', 'A contact filed in another source.', FAR, { sourceId: 'other' });
+ await page('people/ivy-example', 'person', 'Ivy Example', 'An unverified stub.', FAR, { frontmatter: { quarantine: 'unverified' } });
+ }, 300_000);
+
+ afterAll(async () => {
+ await close?.();
+ });
+
+ const slugs = (rows: Array<{ slug?: unknown }>) => rows.map((r) => String(r.slug));
+
+ test('match: "keyword" lists the pages the quoted handles name first, and counts them', async () => {
+ const { rows, retrieval } = await callSearch(engine, { query: Q, match: 'keyword' }, false);
+ expect(slugs(rows).slice(0, 2).sort()).toEqual(PEOPLE);
+ expect(slugs(rows)).toContain('companies/northwind-example');
+ expect(retrieval.total).toBe(rows.length);
+ });
+
+ test('match: "keyword" with types person returns the named people', async () => {
+ const { rows, retrieval } = await callSearch(engine, { query: Q, match: 'keyword', types: ['person'] }, false);
+ expect(slugs(rows).sort()).toEqual(PEOPLE);
+ expect(retrieval.total).toBe(2);
+ });
+
+ test('the hybrid keyword arm leads with the named pages as rows that vote like strict rows', async () => {
+ const rows = await engine.searchKeyword(Q, { limit: 20, orFallback: true });
+ expect(slugs(rows).slice(0, 2).sort()).toEqual(PEOPLE);
+ expect(rows.slice(0, 2).every((r) => r.keyword_relaxed === undefined)).toBe(true);
+ const results = await hybridSearch(engine, Q, { limit: 10, expansion: false });
+ expect(slugs(results).slice(0, 2).sort()).toEqual(PEOPLE);
+ const people = await hybridSearch(engine, Q, { limit: 10, expansion: false, types: ['person'] });
+ expect(slugs(people).slice(0, 2).sort()).toEqual(PEOPLE);
+ });
+
+ test('a bare handle in keyword mode returns the page it names', async () => {
+ const { rows } = await callSearch(engine, { query: 'dan-example', match: 'keyword', types: ['person'] }, false);
+ expect(slugs(rows)).toEqual(['people/dan-example']);
+ });
+
+ test('precision callers (no orFallback) keep the strict-AND contract', async () => {
+ expect(slugs(await engine.searchKeyword(Q, { limit: 20 }))).not.toContain('people/dan-example');
+ });
+
+ test('a local unscoped read resolves the private and other-source handles (the fixture can leak)', async () => {
+ const rows = await engine.searchKeywordPages(LEAK_Q, {}, { limit: 20 });
+ expect(slugs(rows)).toEqual(expect.arrayContaining(['people/dan-example', 'people/gina-example', 'people/hank-example']));
+ expect(slugs(rows)).not.toContain('people/ivy-example');
+ });
+
+ test('a remote caller resolves no handle naming an ungranted source, a private page or a quarantined page', async () => {
+ for (const params of [{ query: LEAK_Q, match: 'keyword' }, { query: LEAK_Q, match: 'keyword', types: ['person'] }, { query: LEAK_Q }]) {
+ const { rows } = await callSearch(engine, params, true);
+ expect(slugs(rows)).toContain('people/dan-example');
+ for (const leaked of LEAKS) expect(slugs(rows)).not.toContain(leaked);
+ }
+ });
+ });
+}
diff --git a/test/sql-bind-placeholders.test.ts b/test/sql-bind-placeholders.test.ts
index eec1469c5a..7a8b817baa 100644
--- a/test/sql-bind-placeholders.test.ts
+++ b/test/sql-bind-placeholders.test.ts
@@ -9,7 +9,7 @@
import { describe, expect, test } from 'bun:test';
import type { SearchOpts } from '../src/core/types.ts';
import { fileClaimCandidatesQuery } from '../src/core/persistence/file-claims.ts';
-import { buildKeywordCountStatement, buildKeywordPagesStatement } from '../src/core/search/keyword-statement.ts';
+import { buildKeywordCountStatement, buildKeywordHandlePagesStatement, buildKeywordPagesStatement } from '../src/core/search/keyword-statement.ts';
function referenced(sql: string): number[] {
return [...new Set([...sql.matchAll(/\$(\d+)(?!\d)/g)].map(m => Number(m[1])))].sort((a, b) => a - b);
@@ -38,7 +38,7 @@ describe('keyword statements', () => {
afterDate: '2026-01-01', beforeDate: '2026-12-31', sourceIds: ['default', 'other'],
}],
];
- for (const query of ['quasar budget', '혈당', '혈당 관리']) {
+ for (const query of ['quasar budget', '혈당', '혈당 관리', '"dan-example" OR quasar']) {
for (const [label, opts] of filterSets) {
test(`count: ${JSON.stringify(query)} with ${label}`, () => {
expectEveryBindReferenced(buildKeywordCountStatement(query, opts));
@@ -49,4 +49,9 @@ describe('keyword statements', () => {
});
}
}
+ for (const [label, opts] of filterSets) {
+ test(`slug handles only (GBRA-108) with ${label}`, () => {
+ expectEveryBindReferenced(buildKeywordHandlePagesStatement('"dan-example" OR quasar', ['dan-example'], opts, 20));
+ });
+ }
});