Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): skip the saved-facts scan and the declared-name scan when there is nothing to find (cat40 cost wave C5)

garrytandf025f16b74f
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index eb75e0e3b7..e91a5195db 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -246,6 +246,8 @@ function indexOfName(text: string, word: string, wholeWord: boolean): number {
}
const ALIAS_DECLARATION = /\b(?:account code|also known as|a\.k\.a\.|aka|short name|ticker|code name)\b\s*[:(]?\s*["\u201c']?([A-Z0-9][A-Za-z0-9&.-]{1,24})/gi;
+/** Every ALIAS_DECLARATION keyword, lowercased: a row containing none of them cannot match the regex. */
+const DECLARATION_KEYWORDS = ['account code', 'also known as', 'a.k.a', 'aka', 'short name', 'ticker', 'code name'];
/**
* Pages often declare another name for their subject ("Account code: MULI",
@@ -262,7 +264,10 @@ export function aliasDeclarations(rows: Array<{ slug: string; title?: string; ch
for (const row of rows.slice(0, 10)) {
const name = (row.title ?? '').split(':').pop()!.trim();
if (!name) continue;
- for (const m of (row.chunk_text ?? '').matchAll(ALIAS_DECLARATION)) {
+ const text = row.chunk_text ?? '';
+ const lower = text.toLowerCase();
+ if (!DECLARATION_KEYWORDS.some(k => lower.includes(k))) continue;
+ for (const m of text.matchAll(ALIAS_DECLARATION)) {
const alias = m[1].replace(/[.,;]+$/, '');
if (!/[A-Z0-9]/.test(alias) || alias.toLowerCase() === name.toLowerCase()) continue;
const hasName = q.includes(name.toLowerCase());
@@ -274,6 +279,27 @@ export function aliasDeclarations(rows: Array<{ slug: string; title?: string; ch
return [...out.values()].slice(0, 5);
}
+type DeclarationRow = { slug: string; title?: string; chunk_text?: string };
+
+/**
+ * One declaration scan per search: the fan-out and the response meta share
+ * this memo, and the meta reuses the fan-out's scan whenever it reads the
+ * same top rows (no fan-out pages spliced in, chunk text unchanged by
+ * evidence delivery); otherwise it scans its own rows, so the result never
+ * differs from scanning them directly.
+ */
+export class DeclarationMemo {
+ private rows: DeclarationRow[] | null = null;
+ private found: AliasDeclaration[] = [];
+ scan(rows: DeclarationRow[], queryText: string): AliasDeclaration[] {
+ const top = rows.slice(0, 10);
+ const same = this.rows !== null && this.rows.length === top.length
+ && top.every((r, i) => r.slug === this.rows![i].slug && r.title === this.rows![i].title && r.chunk_text === this.rows![i].chunk_text);
+ if (!same) { this.rows = top; this.found = aliasDeclarations(top, queryText); }
+ return this.found;
+ }
+}
+
/**
* When the evidence declares another name for the entity the query names,
* also search under that name and splice the new pages in after the top two
@@ -282,9 +308,9 @@ export function aliasDeclarations(rows: Array<{ slug: string; title?: string; ch
* dropped: cutting the tail to make room lost the page that answered
* (gbrain-evals Cat 40, family B).
*/
-async function withDeclaredNameFanOut(results: SearchResult[], queryText: string,
+async function withDeclaredNameFanOut(results: SearchResult[], queryText: string, memo: DeclarationMemo,
run: (query: string, limit: number) => Promise<SearchResult[]>): Promise<SearchResult[]> {
- const [first] = aliasDeclarations(results, queryText);
+ const [first] = memo.scan(results, queryText);
if (!first) return results;
const nameAt = indexOfName(queryText, first.name, false);
const [from, to, at] = nameAt >= 0
@@ -316,7 +342,20 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
if (terms.length === 0 || !ctx.emitResponseMeta) return [];
const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'];
const remote = ctx.remote !== false;
+ const visibility = remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : '';
try {
+ // Most searches have no saved fact to find: one indexed probe (idx_facts_since) with the
+ // same active-fact and visibility predicates skips the LIKE ANY scan when no fact qualifies.
+ const any = await ctx.engine.executeRaw(
+ `SELECT 1 FROM facts f
+ WHERE f.source_id = ANY($1::text[])
+ AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
+ AND f.source != ALL($2::text[])
+ ${visibility}
+ LIMIT 1`,
+ [sources, [...AUDIT_ROW_SOURCES]],
+ );
+ if (any.length === 0) return [];
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
@@ -325,7 +364,7 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
AND f.source != ALL($2::text[])
AND lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE ANY($3::text[])
- ${remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : ''}
+ ${visibility}
ORDER BY f.valid_from DESC, f.id DESC
LIMIT 200`,
[sources, [...AUDIT_ROW_SOURCES], terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`)],
@@ -362,7 +401,7 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string } = {},
+ opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo } = {},
): Promise<Record<string, unknown>> {
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
@@ -379,7 +418,7 @@ async function buildRetrievalResponseMeta(
types: opts.types,
excludeSlugPrefixes,
});
- const aliases = aliasDeclarations(results as Array<{ slug: string; title?: string; chunk_text?: string }>, queryText);
+ const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);
const savedFacts = await matchingSavedFacts(ctx, scope, queryText, aliases);
const degraded = [...(m?.degraded ?? [])];
if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });
@@ -592,7 +631,8 @@ const search: Operation = {
decide: { remote: ctx.remote !== false },
};
const primary = await hybridSearchCached(ctx.engine, queryText, { ...searchOpts, onMeta: (m) => { capturedMeta = m; } });
- const results = (await withDeclaredNameFanOut(primary, queryText,
+ const declarations = new DeclarationMemo();
+ const results = (await withDeclaredNameFanOut(primary, queryText, declarations,
(alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 }))).map(r => ({ ...r }));
stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
@@ -600,7 +640,7 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
- rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice }));
+ rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations }));
},
scope: 'read', mutating: false,
cliHints: { name: 'search', positional: ['query'] },
@@ -832,7 +872,8 @@ const query: Operation = {
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
});
- results = await withDeclaredNameFanOut(results, queryText, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
+ const declarations = new DeclarationMemo();
+ results = await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
limit: altLimit, excludePrivate, requireSafeChunks: ctx.remote !== false, takesHoldersAllowList: readHolders(ctx),
expansion: false, types, ...querySourceScope,
}));
@@ -995,7 +1036,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
- async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice })), crag }));
+ async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations })), crag }));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/test/fixtures/goldens/search-c5/notices.json b/test/fixtures/goldens/search-c5/notices.json
new file mode 100644
index 0000000000..dccc1af926
--- /dev/null
+++ b/test/fixtures/goldens/search-c5/notices.json
@@ -0,0 +1,437 @@
+{
+ "with": {
+ "search NULA billing contact": {
+ "content": [
+ "[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.9836065573770493,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4838709677419355,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in contracts/numbat-labs-msa).",
+ "Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]"
+ ],
+ "retrieval": {
+ "returned_count": 4,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 49,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "saved_facts": [
+ {
+ "id": 1,
+ "fact": "The billing contact for Numbat Labs is New Person.",
+ "entity_slug": "numbat-labs",
+ "kind": "fact",
+ "valid_from": "2026-09-01 00:00:00+00",
+ "source": "user update"
+ }
+ ],
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "contracts/numbat-labs-msa"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs)."
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "crm/numbat-labs"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search OCFR renewal": {
+ "content": [
+ "[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight).",
+ "Saved facts (remember) matching this query, newest first; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]"
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 59,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "saved_facts": [
+ {
+ "id": 2,
+ "fact": "Ocelot Freight renewal moves to the platform team.",
+ "entity_slug": "ocelot-freight",
+ "kind": "fact",
+ "valid_from": "2026-09-02 00:00:00+00",
+ "source": "user update"
+ }
+ ],
+ "other_names": [
+ {
+ "name": "Ocelot Freight",
+ "alias": "OCFR",
+ "slug": "crm/ocelot-freight"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search renewal quote": {
+ "content": [
+ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 1,
+ "retrieved_count": 1,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 30,
+ "dropped": 0,
+ "kept": 1
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "query Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs)."
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "crm/numbat-labs"
+ }
+ ],
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ },
+ "query OCFR renewal owner": {
+ "content": [
+ "[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight)."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 59,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Ocelot Freight",
+ "alias": "OCFR",
+ "slug": "crm/ocelot-freight"
+ }
+ ],
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ }
+ },
+ "without": {
+ "search NULA billing contact": {
+ "content": [
+ "[{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5081967213114754,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4998656275194841,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 3,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 74,
+ "dropped": 0,
+ "kept": 3
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 44,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search OCFR renewal": {
+ "content": [
+ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search renewal quote": {
+ "content": [
+ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 1,
+ "retrieved_count": 1,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 30,
+ "dropped": 0,
+ "kept": 1
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "query Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 44,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ },
+ "query OCFR renewal owner": {
+ "content": [
+ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]"
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "crag": {
+ "confidence": "weak",
+ "reason": "keyword_relaxed_top",
+ "query_shape": "factual",
+ "escalate_to_think": true
+ },
+ "rows": "lean"
+ }
+ }
+ }
+}
diff --git a/test/search-c5-identical.test.ts b/test/search-c5-identical.test.ts
new file mode 100644
index 0000000000..903ef7a275
--- /dev/null
+++ b/test/search-c5-identical.test.ts
@@ -0,0 +1,161 @@
+/**
+ * C5 (cost wave): search skips the saved-facts scan and the declared-name
+ * scan cheaply when there is nothing to find, and changes nothing when there
+ * is. The golden below was captured on the build before C5 (the cost wave's
+ * C3+C4 commit) with GBRAIN_TEST_UPDATE_GOLDENS=1; it holds the full MCP
+ * result (content[0], every notice block and _meta.retrieval) for searches
+ * and queries on a brain with active saved facts and declared other names,
+ * including one that fans out to the other name, plus the same searches on a
+ * brain with neither. Regenerate only on a build whose search output is meant
+ * to change, and say why in the commit.
+ *
+ * Also: a fact saved with `remember` is found by the next search in the same
+ * process, and by a search after another process saved it (no per-process
+ * cache can hide a fresh fact).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { aliasDeclarations } from '../src/core/ops/search.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const GOLDEN = join(import.meta.dir, 'fixtures/goldens/search-c5/notices.json');
+const REMOTE = { remote: true, transport: 'http' as const, sourceId: 'default' };
+
+const PAGES: Array<[string, string, string]> = [
+ ['crm/numbat-labs', 'CRM record: Numbat Labs', 'Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.'],
+ ['contracts/numbat-labs-msa', 'MSA: Numbat Labs', 'Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.'],
+ ['contracts/amendment-one', 'Amendment No. 1: NULA', 'Executed amendment for NULA: payment terms change to Net 30.'],
+ ['crm/ocelot-freight', 'CRM record: Ocelot Freight', 'Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.'],
+ ['notes/renewal-playbook', 'Renewal playbook', 'Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.'],
+];
+const FACTS = `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from) VALUES
+ ('default', 'numbat-labs', 'The billing contact for Numbat Labs is New Person.', 'fact', 'world', 'user update', '2026-09-01'),
+ ('default', 'ocelot-freight', 'Ocelot Freight renewal moves to the platform team.', 'fact', 'world', 'user update', '2026-09-02'),
+ ('default', 'numbat-labs', 'Numbat Labs payment terms are disputed.', 'fact', 'private', 'user update', '2026-09-03')`;
+const CALLS: Array<[string, Record<string, unknown>]> = [
+ ['search', { query: 'NULA billing contact' }],
+ ['search', { query: 'Numbat Labs payment terms' }],
+ ['search', { query: 'OCFR renewal' }],
+ ['search', { query: 'renewal quote' }],
+ ['query', { query: 'Numbat Labs payment terms', expand: false }],
+ ['query', { query: 'OCFR renewal owner', expand: false }],
+];
+
+/** Opens an engine; assigned in beforeAll (the canonical PGLite lifecycle, test/helpers/reset-pglite.ts). */
+let open: (dataDir?: string) => Promise<PGLiteEngine>;
+
+async function brain(withFactsAndNames: boolean): Promise<PGLiteEngine> {
+ const engine = await open();
+ for (const [slug, title, body] of PAGES) {
+ const text = withFactsAndNames ? body : body.replace(/\(?account code NULA\)?|Account code: NULA\.|, also known as OCFR/g, '');
+ await importFromContent(engine, slug, serializeMarkdown({}, text, '', { type: 'note', title, tags: [] }), { noEmbed: true, forceRechunk: true });
+ }
+ if (withFactsAndNames) await engine.executeRaw(FACTS);
+ return engine;
+}
+
+async function capture(engine: PGLiteEngine): Promise<Record<string, unknown>> {
+ const out: Record<string, unknown> = {};
+ for (const [name, args] of CALLS) {
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name, args, REMOTE));
+ out[`${name} ${args.query}`] = { content: res.content.map(c => c.text), retrieval: res._meta?.retrieval };
+ }
+ return out;
+}
+
+/** Dates the importer stamps from today are the only run-to-run variance. */
+const stable = (v: unknown) => JSON.parse(JSON.stringify(v).replace(/\d{4}-\d{2}-\d{2}(?=\\?")/g, 'DATE'));
+
+let withBoth: PGLiteEngine;
+let withNeither: PGLiteEngine;
+const opened: PGLiteEngine[] = [];
+beforeAll(async () => {
+ open = async (dataDir?: string) => {
+ const engine = new PGLiteEngine();
+ await engine.connect(dataDir ? { database_path: dataDir } : {});
+ await engine.initSchema();
+ opened.push(engine);
+ return engine;
+ };
+ withBoth = await brain(true);
+ withNeither = await brain(false);
+}, 180_000);
+afterAll(async () => { for (const engine of opened) await engine.disconnect().catch(() => {}); });
+
+describe('byte-identical results before and after C5', () => {
+ test('a brain with saved facts and declared names, and one with neither', async () => {
+ const got = stable({ with: await capture(withBoth), without: await capture(withNeither) });
+ if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1') {
+ mkdirSync(dirname(GOLDEN), { recursive: true });
+ writeFileSync(GOLDEN, JSON.stringify(got, null, 2) + '\n');
+ }
+ const want = JSON.parse(readFileSync(GOLDEN, 'utf8'));
+ expect(got).toEqual(want);
+ // The fixture exercises what C5 must not change: a saved fact, a declared
+ // name in both directions, and a fan-out that splices a page in.
+ const w = got.with as Record<string, { content: string[] }>;
+ expect(w['search NULA billing contact'].content.join('\n')).toContain('New Person');
+ expect(w['search NULA billing contact'].content.join('\n')).toContain('NULA = Numbat Labs');
+ expect(w['search Numbat Labs payment terms'].content[0]).toContain('contracts/amendment-one');
+ expect(JSON.stringify(got.without)).not.toContain('Saved facts');
+ });
+});
+
+describe('declaration keyword precheck', () => {
+ test('a row without any declaration keyword yields nothing; one with a keyword still parses', () => {
+ expect(aliasDeclarations([{ slug: 'x', title: 'Note: Thing', chunk_text: 'No other name here. THING-2 is a code.' }], 'Thing')).toEqual([]);
+ for (const label of ['Account code:', 'also known as', 'aka', 'Short name:', 'Ticker:', 'Code name:', 'TICKER']) {
+ expect(aliasDeclarations([{ slug: 'x', title: 'Co: Widget Co', chunk_text: `Widget Co ${label} WDGT` }], 'Widget Co pricing'), label)
+ .toEqual([{ name: 'Widget Co', alias: 'WDGT', slug: 'x' }]);
+ }
+ });
+});
+
+describe('a fresh fact is never hidden', () => {
+ test('remember then search in the same process', async () => {
+ const engine = await brain(false);
+ try {
+ const before = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'Numbat Labs escalation owner' }, REMOTE));
+ expect(before.content.map(c => c.text).join('\n')).not.toContain('Saved facts');
+ const saved = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'remember',
+ { fact: 'The Numbat Labs escalation owner is Alice Example.', provenance: 'test', entity: 'numbat-labs' }, { ...REMOTE, writeWaitMs: 30_000 }));
+ expect(saved.isError, saved.content[0].text).not.toBe(true);
+ const after = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'Numbat Labs escalation owner' }, REMOTE));
+ expect(after.content.map(c => c.text).join('\n')).toContain('escalation owner is Alice Example');
+ } finally {
+ await engine.disconnect();
+ }
+ }, 60_000);
+
+ test('a fact saved by another process is found by the next search', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c5-'));
+ const dataDir = join(dir, 'brain.pglite');
+ try {
+ let engine = await open(dataDir);
+ await importFromContent(engine, 'crm/numbat-labs', serializeMarkdown({}, 'Account record for Numbat Labs.', '', { type: 'note', title: 'CRM record: Numbat Labs', tags: [] }), { noEmbed: true, forceRechunk: true });
+ const before = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'Numbat Labs escalation owner' }, REMOTE));
+ expect(before.content.map(c => c.text).join('\n')).not.toContain('Saved facts');
+ await engine.disconnect();
+ const child = spawnSync('bun', ['-e', `
+ const engines = await import(${JSON.stringify(join(import.meta.dir, '../src/core/pglite-engine.ts'))});
+ const e = new engines.PGLiteEngine();
+ await e.connect({ database_path: ${JSON.stringify(dataDir)} });
+ await e.executeRaw("INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES ('default', 'numbat-labs', 'The Numbat Labs escalation owner is Alice Example.', 'fact', 'world', 'other process')");
+ await e.disconnect();`], { encoding: 'utf8', env: { ...process.env, GBRAIN_HOME: dir } });
+ expect(child.status, child.stderr).toBe(0);
+ engine = await open(dataDir);
+ const after = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'Numbat Labs escalation owner' }, REMOTE));
+ expect(after.content.map(c => c.text).join('\n')).toContain('escalation owner is Alice Example');
+ await engine.disconnect();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 120_000);
+});