Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): saved-fact matching applies the term threshold before the cut

garrytancac9f041de81
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 5f8d0302f1..03155eca03 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -394,25 +394,31 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
// fact's own columns only: every row the scan returns passes it, so it never changes the
// result, and the page-eligibility filters stay on the scan, where they cost an index
// lookup per candidate. In the probe the planner joined them to the whole pages index.
- const rows = await ctx.engine.executeRaw<SavedFactMatch & { haystack: string }>(
- `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source,
- lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack
- FROM facts f
- WHERE ${active}
- ${eligible}
- AND lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE ANY($3::text[])
- AND EXISTS (SELECT 1 FROM facts f WHERE ${active} LIMIT 1)
- ORDER BY f.valid_from DESC, f.id DESC
+ // The term threshold is applied before the cut: a fact matching every term is never crowded
+ // out by newer facts that match only one.
+ const need = Math.max(Math.min(2, terms.length), Math.ceil(terms.length * 0.75));
+ const rows = await ctx.engine.executeRaw<SavedFactMatch & { haystack: string; at: unknown; hits: unknown }>(
+ `SELECT * FROM (
+ SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source, f.valid_from AS at,
+ lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack,
+ (SELECT count(*) FROM unnest($3::text[]) AS t(pattern) WHERE lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE t.pattern) AS hits
+ FROM facts f
+ WHERE ${active}
+ ${eligible}
+ AND lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE ANY($3::text[])
+ AND EXISTS (SELECT 1 FROM facts f WHERE ${active} LIMIT 1)
+ ) m
+ WHERE m.hits >= $4::int
+ ORDER BY m.hits DESC, m.at DESC, m.id DESC
LIMIT 200`,
- [sources, [...AUDIT_ROW_SOURCES], terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`)],
+ [sources, [...AUDIT_ROW_SOURCES], terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`), need],
);
- const need = Math.max(Math.min(2, terms.length), Math.ceil(terms.length * 0.75));
return rows
.map(r => ({ r, hits: terms.filter(t => r.haystack.includes(t)).length }))
.filter(x => x.hits >= need)
.sort((a, b) => b.hits - a.hits)
.slice(0, 5)
- .map(({ r: { haystack: _h, ...fact } }) => ({ ...fact, id: Number(fact.id) }));
+ .map(({ r: { haystack: _h, at: _a, hits: _n, ...fact } }) => ({ ...fact, id: Number(fact.id) }));
} catch {
return [];
}
diff --git a/test/search-saved-facts.test.ts b/test/search-saved-facts.test.ts
index cb748a27dd..37bc60efac 100644
--- a/test/search-saved-facts.test.ts
+++ b/test/search-saved-facts.test.ts
@@ -38,6 +38,17 @@ describe('search surfaces remembered facts', () => {
const text = extra(await call('search', { query: 'Numbat Labs invoices email' }));
expect(text).not.toContain('prefers invoices by email');
});
+ test('an older fact matching every term is not crowded out by newer facts matching one', async () => {
+ // 250 newer world facts share only "lanternfish"; the one fact naming all three terms is the oldest.
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from)
+ VALUES ('default', 'notes/ledger-example', 'The lanternfish quibble ledger was reconciled by Example Person.', 'fact', 'world', 'user update', now() - interval '400 days')`);
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from)
+ SELECT 'default', 'notes/school-' || g, 'A lanternfish school was sighted on survey ' || g || '.', 'fact', 'world', 'user update', now() - (g || ' minutes')::interval
+ FROM generate_series(1, 250) AS g`);
+ const text = extra(await call('search', { query: 'lanternfish quibble ledger' }));
+ expect(text).toContain('reconciled by Example Person');
+ expect(text).not.toContain('school was sighted');
+ });
test('a query sharing too few words returns no facts block', async () => {
const text = extra(await call('search', { query: 'Numbat roadmap webinar dashboard filters' }));
expect(text).not.toContain('Saved facts');