Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): match: "keyword" on an entity's name lists records under any of its names
garrytan72b74efefba0
diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 3aecdf03e8..feceb6d192 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -41,7 +41,7 @@ import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts'import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';import { declaredNames, titleName } from '../mentions/aliases.ts';-import { withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';+import { aliasPhrase, wholeQueryEntityNames, withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';import { entitySavedFacts } from '../search/entity-facts.ts';import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';import { keepEnumeratedRows, keywordCountMeta, parseSearchPaging, readKeywordPage, startKeywordCount, withCountMeta } from '../search/keyword-paging.ts';@@ -706,7 +706,18 @@ const search: Operation = {const sourceBoosts = resolveBoostMap(undefined, await ctx.engine.getConfig(SOURCE_BOOSTS_KEY));const keywordOpts = { ...readOpts, source_boosts: sourceBoosts, ...(types ? { types } : {}) };// F2 `match: "keyword"`: page-grain enumeration, no diversity pruning, every page keeps a row.- const page = paging.match === 'keyword' ? await readKeywordPage(ctx.engine, p, keywordOpts, paging, Math.min(limit, searchLimitCap())) : null;+ // A query that is one entity's name lists records filed under any of its names (the agent no longer walks each alias).+ const names = paging.match === 'keyword' && !paging.cursor ? await wholeQueryEntityNames(ctx.engine, queryText, { ...scope, excludePrivate }) : null;+ const pageParams = names ? { ...p, query: names.map(aliasPhrase).join(' OR ') } : p;+ const page = paging.match === 'keyword' ? await readKeywordPage(ctx.engine, pageParams, keywordOpts, paging, Math.min(limit, searchLimitCap())) : null;+ if (page && names) {+ page.meta.match_names = names;+ for (const row of page.rows) {+ const text = (row.chunk_text ?? '').toLowerCase();+ const hit = names.slice(1).find(n => text.includes(n.toLowerCase()));+ if (hit && !text.includes(names[0]!.toLowerCase())) row.matched_alias = hit;+ }+ }const keywordCount = page ? null : startKeywordCount(ctx.engine, queryText, undefined, keywordOpts);const results = (page ? page.rows : dedupResults(await ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts }))).map(r => ({ ...r }));await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt);diff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.tsindex 2f40907e0a..324f770177 100644--- a/src/core/search/alias-fanout.ts+++ b/src/core/search/alias-fanout.ts@@ -164,6 +164,23 @@ async function namesOf(engine: BrainEngine, pages: Array<{ slug: string; source_return [...names.values()].sort((a, b) => a.rank - b.rank || b.alias.length - a.alias.length);}+/**+ * When the whole query is one entity's name or alias, every name it goes by+ * (the query first, then aliases by origin and length, at most `max`);+ * otherwise null. `match: "keyword"` lists the records filed under any of+ * them in one walk, like grepping every name at once.+ */+export async function wholeQueryEntityNames(engine: BrainEngine, query: string, scope: Scope, max = 8): Promise<string[] | null> {+ const tokens = queryTokens(query);+ if (!tokens.length || tokens.length > MAX_NGRAM) return null;+ const entity = await resolveQueryEntity(engine, query, scope);+ if (!entity || entity.tokens[0] !== 0 || entity.tokens[1] !== tokens.length - 1) return null;+ const names = [query.trim(), ...(await namesOf(engine, entity.pages, scope)).map(n => n.alias)];+ const seen = new Set<string>();+ const out = names.filter(n => { const k = normalizeAlias(n); if (!k || seen.has(k)) return false; seen.add(k); return true; }).slice(0, max);+ return out.length > 1 ? out : null;+}+export async function aliasFanoutMax(engine: BrainEngine): Promise<number> {const raw = await engine.getConfig('search.alias_fanout_max').catch(() => null);const n = raw == null || raw === '' ? DEFAULT_ALIAS_FANOUT_MAX : Number(raw);diff --git a/src/core/search/keyword-paging.ts b/src/core/search/keyword-paging.tsindex a1b79e7a8c..23bab7ff86 100644--- a/src/core/search/keyword-paging.ts+++ b/src/core/search/keyword-paging.ts@@ -208,8 +208,10 @@ export function searchCountLine(rows: unknown, retrieval: unknown): string | nulconst stage = Array.isArray(r.degraded) ? r.degraded.find(d => (d as { stage?: unknown })?.stage === 'keyword_count_unavailable') : undefined;const reason = (stage as { reason?: unknown } | undefined)?.reason === 'timeout' ? 'timed out' : 'failed';if (r.match === 'keyword') {+ const names = Array.isArray(r.match_names) && r.match_names.length > 1+ ? ` for any of this entity's names (${(r.match_names as string[]).map(n => `"${n}"`).join(', ')})` : '';const total = typeof r.total === 'number'- ? `Keyword matches: ${countWords(r.total, r.total_capped === true)}`+ ? `Keyword matches${names}: ${countWords(r.total, r.total_capped === true)}`: `Keyword match count unavailable (${reason}; not a count of zero)`;const omitted = Array.isArray(rows) ? rows.filter(x => (x as { evidence_omitted?: unknown })?.evidence_omitted === true).length : 0;const shown = Number(r.shown_to) < Number(r.shown_from) ? 'none on this page' : `showing ${r.shown_from}-${r.shown_to}, keyword-score order`;diff --git a/test/search-alias-fanout.test.ts b/test/search-alias-fanout.test.tsindex ecf59395fc..2416222989 100644--- a/test/search-alias-fanout.test.ts+++ b/test/search-alias-fanout.test.ts@@ -92,6 +92,26 @@ describe('alias fan-out', () => {expect((await search('Widget Co discount history')).visible).toContain('mention_index');});+ test('match: "keyword" on an entity name lists records filed under any of its names, and pages through them', async () => {+ await account();+ const first = await dispatchToolCall(engine, 'search', { query: 'Widget Co', match: 'keyword', limit: 3 }, remote as never);+ const visible = first.content.map(c => c.text ?? '').join('\n');+ expect(visible).toContain('Keyword matches for any of this entity\'s names ("Widget Co", "Copper Fox", "WGCO"');+ const slugs = new Set((JSON.parse(first.content[0].text!) as Array<{ slug: string }>).map(r => r.slug));+ const next = (first._meta?.retrieval as { next?: Record<string, unknown> }).next!;+ let page: Record<string, unknown> | undefined = next;+ while (page) {+ const r = await dispatchToolCall(engine, 'search', page, remote as never);+ for (const row of JSON.parse(r.content[0].text!) as Array<{ slug: string }>) slugs.add(row.slug);+ page = (r._meta?.retrieval as { next?: Record<string, unknown> }).next;+ }+ expect(slugs).toContain('tickets/t1');+ expect(slugs).toContain('contracts/a1');+ expect(slugs).toContain('notes/n0');+ const plain = await dispatchToolCall(engine, 'search', { query: 'Widget Co weekly', match: 'keyword' }, remote as never);+ expect(plain.content.map(c => c.text ?? '').join('\n')).not.toContain('any of this entity');+ });+test('search.alias_fanout_max=0 turns fan-out off', async () => {await account();await engine.setConfig('search.alias_fanout_max', '0');