Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(wave): rare-word read honours chunk visibility; CHANGELOG and behavior row for the keyword tie

garrytandaf790d93a84
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d35532d45..492b9c886f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,13 +12,13 @@ identifiers and attribution are available in the pre-removal Git revision
## [0.60.434.0] - 2026-10-24
-**Agents triaging email or calendar can now ask whether a sender or attendee is a known contact and get an exact answer: `gbrain whois <email or name>` (MCP tool `whois`) returns only pages whose email, title or declared alias equals the query, and an empty list when none does.**
+**Keyword search now finds the page holding a rare query word when no page holds every word, and agents triaging email or calendar can ask whether a sender or attendee is a known contact and get an exact answer: `gbrain whois <email or name>` (MCP tool `whois`) returns only pages whose email, title or declared alias equals the query, and an empty list when none does.**
Semantic search can rank the wrong person first for a name or address, and `gbrain entity` resolves fuzzy name variants on purpose. `whois` never does either.
**Say to your agent:** *"Is [email protected] a known contact in my brain?"*
-### What changed
+### Exact identity lookup
| Situation | Before | Now |
|---|---|---|
@@ -27,6 +27,12 @@ Semantic search can rank the wrong person first for a name or address, and `gbra
| Two pages carry the same name or address | the agent saw whichever ranked first | every match is returned, labeled `email`, `title` or `alias` (in that order), with `ambiguous: true` |
| No page matches | an unrelated nearest result | `matches: []`, not an error and never a search fallback |
+### Keyword search with a rare word
+
+| Situation | Before | Now |
+|---|---|---|
+| A keyword search of up to four words where no page holds every word, on a brain where one word is common ("Acme Quokka" over many Acme notes) | the any-word retry ranked pages that repeat the common word first, so the one page holding the rare word could fall past the result limit | pages holding the rarest query words come first, then the rest in their usual order; the strict all-words search, and queries of five or more words, are unchanged |
+
### What to watch for after you upgrade
- By default `whois` reads the schema pack's entity types (people, companies, accounts); pass `types` to widen or narrow it, and `source_id` for one source.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 3a3c645f4a..4e74cd4de0 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (`cc` source, full-text match, text modality). For excludePrivate callers it plans the match alone in an `OFFSET 0` subquery; joined, the visibility subplans' cost let a seq scan detoasting every `search_vector` win (1.1 → 0.2 s, common term, 250k chunks). Local callers keep the unfenced, parallel-capable join. `KEYWORD_RANKED_ROWS_CTE`: ranking carries only ids, score and bounded_rows; display columns come from one `LIMIT 1` key probe per ranked chunk. Output equals the wide statement's; under the 50k bound (sample in plan order), its unspilled output. Not on PGLite. Pinned by `test/search/keyword-arm-ranking.test.ts`, `test/e2e/keyword-arm-ranking-postgres.test.ts`.
-- `src/core/search/keyword-or-rarity.ts` — rare words in the keyword arm's OR retry (GBRA-156, after #7471). For a retry of at most `RARITY_MAX_TERMS` words (also the title arm's `rankByRarity` bound), `rareTermPagesSql` reads per word the pages of its first `RARE_TERM_CHUNK_CAP` + 1 matching text chunks (index served, global, used only to weigh rows the retry already authorized); a word whose chunks all fit weighs 1 / its page count. `rankOrFallbackByRarity` re-runs the retry statement once with the OR of the rarest words whose pages fit the limit (ranked with the full OR query, so scores stay comparable), then sorts rows by summed rare-word weight, then retry order. No rare word, a paged retry (offset) or a failed read leaves the retry's rows unchanged. Called from both engines' `searchKeyword`; PGLite binds the rank query as its own parameter when it may relax, like Postgres.
+- `src/core/search/keyword-or-rarity.ts` — rare words first in both engines' keyword OR retry. For at most `RARITY_MAX_TERMS` words, `rareTermPagesSql` reads the pages of each word's first `RARE_TERM_CHUNK_CAP` + 1 visible chunks (brain-wide, weights only); a fitting word weighs 1 / pages. `rankOrFallbackByRarity` re-runs the retry with the rarest words' OR and sorts by summed weight.
- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost uses: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. `titleNameVariants(query)` (#7471) is the query with its given name swapped for each other form in its nickname group (`givenNameVariants` in `entities/name-variants.ts`), none for websearch-operator queries; the title arm ORs them into its query and the T2 boost accepts a variant title-phrase match. Exports `tokenizeTitle` + `__test__` internals.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index e7e9c62aa9..292a46c1fe 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1217,6 +1217,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.424.0', text: 'doctor `parked_effects` and `gbrain sources writer status` now report `stalled_catchups`: per source, effects that have waited on a busy canonical worktree for over 10 minutes, with when the wait began and the read-only writer status command that shows who holds the worktree. doctor warns "Catch-up not progressing" for them even when nothing is parked.' },
{ since: '0.60.426.0', text: 'With `--job-isolation process`, `--max-rss` now caps each job child too: the worker measures the child\'s process tree (RssAnon + RssShmem) every 5 seconds, and a child past the cap gets SIGTERM, then SIGKILL after the 25-second grace. Its attempt fails with `ChildRssLimitError`, so a job that grows the same way on every retry ends at its `max_attempts`. Before, the cap read only the worker\'s own memory, and a runaway child grew until the host or container limit restarted every process.' },
{ since: '0.60.427.0', text: 'A search for a full name with a short first name ("Matt Example") now finds the page titled "Matthew Example", and back (Bob and Robert, Liz and Elizabeth and the other common given-name groups): the title arm also matches the other forms of the given name, and the title boost counts them as a title match. When no title holds every word of a query of up to four words, the title arm\'s any-word retry now puts titles holding the rarest word first instead of tying them with titles that hold only a common word (#7471).' },
+ { since: '0.60.434.0', id: 'keyword_or_rarity', text: 'When no page holds every word of a keyword search of up to four words, the any-word retry of the keyword arm now ranks pages holding the rarest query words first, instead of ranking pages that repeat a common word above the few that hold a rare one. The strict all-words search and longer queries are unchanged.' },
// GBRA-156 (exact identity lookup). `since` is stamped at the merge slot.
{ since: '0.60.434.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.' },
];
diff --git a/src/core/search/keyword-or-rarity.ts b/src/core/search/keyword-or-rarity.ts
index cf0173e01d..1ff5dcebf5 100644
--- a/src/core/search/keyword-or-rarity.ts
+++ b/src/core/search/keyword-or-rarity.ts
@@ -16,6 +16,7 @@
* rare words their page holds, then in retry order. With no rare word, or
* when the read fails, the retry's rows are returned unchanged.
*/
+import { chunkVisibleFilter } from './safe-chunks.ts';
import { orFallbackTokens } from './sql-ranking.ts';
/** OR retries of at most this many words rank rare words first (this module and the title arm's rankByRarity). */
@@ -27,8 +28,8 @@ export const RARE_TERM_CHUNK_CAP = 400;
/** Per word (`$1` text[]), the distinct pages of its first `$2` + 1 matching text chunks and that chunk count. */
export function rareTermPagesSql(ftsLang: string): string {
return `SELECT u.term,
- (SELECT count(*) FROM (SELECT 1 FROM content_chunks cc WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' LIMIT $2::int + 1) m)::int AS chunks,
- ARRAY(SELECT DISTINCT m.page_id FROM (SELECT cc.page_id FROM content_chunks cc WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' LIMIT $2::int + 1) m) AS page_ids
+ (SELECT count(*) FROM (SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' AND ${chunkVisibleFilter('p', 'cc')} LIMIT $2::int + 1) m)::int AS chunks,
+ ARRAY(SELECT DISTINCT m.page_id FROM (SELECT cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', u.term) AND cc.modality = 'text' AND ${chunkVisibleFilter('p', 'cc')} LIMIT $2::int + 1) m) AS page_ids
FROM unnest($1::text[]) WITH ORDINALITY AS u(term, ord)
ORDER BY u.ord`;
}