Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): grade a corroborated OR-relaxed keyword top moderate, not weak (#5919)
garrytanc991f60bf9a3
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 6c297d1908..b4529f36a6 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -267,7 +267,13 @@ Two cross-cutting seams sit around the pipeline rather than inside it:- **CRAG-style confidence gate.** `src/core/search/crag.ts` grades every`query` op result (`strong`/`moderate`/`weak`) from the already-stampedhonesty signals — zero LLM, zero added latency — and attaches the grade to- response meta. Config-gated and default OFF: `search.crag_escalation=true`+ response meta. An OR-relaxed keyword top (no chunk matched every query+ term) grades `weak` (`keyword_relaxed_top`) unless the top five rows+ corroborate it: at most one query content term appears in none of them,+ that term is not a name, and one row holds every other matched term. Then+ it grades `moderate` (`keyword_relaxed_corroborated`): the question used a+ framing word the corpus never writes, not an attribute or entity the+ evidence lacks. Config-gated and default OFF: `search.crag_escalation=true`re-runs a weak retrieval once at a higher ceiling (expansion + relationalon, autocut off, limit = the caller's explicit `limit` or the mode-deriveddefault — never a hardcoded row count — floored at 50) and keeps thediff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex cc5dde0e9c..59170cb66b 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -913,7 +913,7 @@ const query: Operation = {// search.crag_think=true → still weak + LOCAL caller → run think and// attach its synthesis to the meta (spend-gated by config + trust).const queryShape = classifyQueryShape(queryText);- let grade = gradeRetrievalConfidence(results);+ let grade = gradeRetrievalConfidence(results, { query: queryText });const crag: CragMetaBlock = {confidence: grade.level,reason: grade.reason,@@ -977,7 +977,7 @@ const query: Operation = {// caller's row contract — pre-fix, an adopted escalation handed the// whole uncut sweep back (14-18 rows for a limit:10 request), and// bumpLastRetrievedAt + eval capture recorded the oversized set.- const regraded = gradeRetrievalConfidence(escalated);+ const regraded = gradeRetrievalConfidence(escalated, { query: queryText });crag.escalated = true;crag.escalated_confidence = regraded.level;if (confidenceRank(regraded.level) > confidenceRank(grade.level)) {diff --git a/src/core/search/crag.ts b/src/core/search/crag.tsindex 61ecc36d52..5553b076be 100644--- a/src/core/search/crag.ts+++ b/src/core/search/crag.ts@@ -12,11 +12,12 @@* exact_lookup, exact_title_match, high_vector_match) or the* reranker scored the top at/above the weak-top floor.* moderate — lexically verified top (keyword_exact) but no identity or- * calibrated-semantic signal.+ * calibrated-semantic signal; or an OR-relaxed keyword top whose+ * evidence is corroborated (see `relaxedTopCorroborated`).* weak — zero results, a reranked top BELOW the weak-top floor* (the #1863 "whole list is low-confidence" shape), an- * OR-relaxed keyword top (keyword_relaxed), or an unverified- * weak_semantic top.+ * uncorroborated OR-relaxed keyword top (keyword_relaxed), or an+ * unverified weak_semantic top.** Consumers: the `query` op attaches the grade (+ query shape) to its* retrieval response meta on every call, and — config-gated, default OFF —@@ -51,6 +52,7 @@ export interface ConfidenceGrade {| 'rerank_top_below_floor'| 'keyword_exact_top'| 'keyword_relaxed_top'+ | 'keyword_relaxed_corroborated'| 'weak_semantic_top'| 'decide_evidence';/** Rank-1 evidence label when present (auditability). */@@ -66,10 +68,107 @@ export interface ConfidenceGrade {*/export const DEFAULT_CRAG_MIN_TOP = 0.2;+/** Rows a relaxed top is corroborated against: the top five a reader is handed. */+export const RELAXED_CORROBORATION_DEPTH = 5;++// PostgreSQL's `english` text-search stopwords. The keyword arm drops them,+// so they never decide whether the strict AND query matched.+const ENGLISH_STOPWORDS = new Set(('i me my myself we our ours ourselves you your yours yourself yourselves he him his himself '+ + 'she her hers herself it its itself they them their theirs themselves what which who whom this that these those am is are '+ + 'was were be been being have has had having do does did doing a an the and but if or because as until while of at by for '+ + 'with about against between into through during before after above below to from up down in out on off over under again '+ + 'further then once here there when where why how all any both each few more most other some such no nor not only own same '+ + 'so than too very s t can will just don should now').split(' '));++/**+ * Inflectional stem, applied identically to query and text, so "founded" and+ * "founding" or "headquarters" and "headquartered" compare equal. Lighter+ * than the engine's Snowball stemmer: a miss reads as an unmatched term,+ * which only ever keeps a grade weak.+ */+function stem(word: string): string {+ if (word.length > 4 && word.endsWith('ies')) return `${word.slice(0, -3)}y`;+ if (word.length > 4 && /(ss|x|z|ch|sh)es$/.test(word)) return word.slice(0, -2);+ if (word.length > 3 && word.endsWith('s') && !word.endsWith('ss')) word = word.slice(0, -1);+ if (word.length > 5 && word.endsWith('ing')) return word.slice(0, -3);+ if (word.length > 4 && word.endsWith('ed')) return word.slice(0, -2);+ return word;+}++function words(text: string): string[] {+ return text.normalize('NFKC').split(/[^\p{L}\p{N}]+/u).filter(Boolean);+}++function contentTerms(text: string): Set<string> {+ const out = new Set<string>();+ for (const w of words(text)) {+ const lower = w.toLowerCase();+ if (!ENGLISH_STOPWORDS.has(lower)) out.add(stem(lower));+ }+ return out;+}++/**+ * Name terms: content words written with a capital past the query's first+ * word (a name such as "Acme Example") or an interior capital ("ARR",+ * "McKinsey"). Sentence-initial capitalization is not a name signal.+ */+function nameTerms(query: string): Set<string> {+ const out = new Set<string>();+ words(query).forEach((w, i) => {+ const lower = w.toLowerCase();+ if (ENGLISH_STOPWORDS.has(lower)) return;+ if (/\p{Lu}/u.test(w.slice(1)) || (i > 0 && /^\p{Lu}/u.test(w))) out.add(stem(lower));+ });+ return out;+}++/**+ * An OR-relaxed keyword top means no single chunk matched every query term.+ * That happens for two different reasons, and the grade must tell them apart+ * (gbrain-evals A4, #5919):+ *+ * - the question uses a word the corpus never writes ("Which CITY is Acme+ * Example headquartered in?" against "Acme Example is headquartered in+ * ..."), while the rest of the question is matched by one chunk; or+ * - the asked-about thing is not in the evidence: the entity is matched in+ * one chunk and the attribute only in others (a missing attribute), or+ * a name in the question appears nowhere (an absent entity).+ *+ * Corroborated (graded moderate, not weak) when, over the top+ * RELAXED_CORROBORATION_DEPTH rows, all of these hold:+ *+ * 1. at most one query content term appears in none of the rows;+ * 2. that unmatched term is not a name term (an unmatched name means the+ * question is about something the evidence does not mention);+ * 3. one row (title plus chunk text) contains every query term matched+ * anywhere in the window, and at least two of them, so the matched+ * evidence sits together instead of being split across pages.+ *+ * Purely lexical by design: relaxed rows only reach fusion when every vector+ * list is empty, so no cosine or rerank score exists on this path. A+ * question whose attribute is phrased with words the evidence never uses+ * ("annual recurring revenue" against "ARR") stays weak: lexically it is+ * indistinguishable from the attribute being absent.+ */+export function relaxedTopCorroborated(results: readonly SearchResult[], query: string): boolean {+ const asked = contentTerms(query);+ const rows = results.slice(0, RELAXED_CORROBORATION_DEPTH).map(r => contentTerms(`${r.title ?? ''} ${r.chunk_text ?? ''}`));+ const matched = [...asked].filter(t => rows.some(row => row.has(t)));+ const unmatched = [...asked].filter(t => !matched.includes(t));+ if (unmatched.length > 1 || matched.length < 2) return false;+ const names = nameTerms(query);+ if (unmatched.some(t => names.has(t))) return false;+ return rows.some(row => matched.every(t => row.has(t)));+}+export function gradeRetrievalConfidence(results: SearchResult[],- /** `ignoreDecideEvidence`: the deterministic grade (S4's agreement rule excludes the S3-derived input). */- opts: { minTopScore?: number; ignoreDecideEvidence?: boolean } = {},+ /**+ * `ignoreDecideEvidence`: the deterministic grade (S4's agreement rule excludes the S3-derived input).+ * `query`: the query text; without it an OR-relaxed top is never corroborated.+ */+ opts: { minTopScore?: number; ignoreDecideEvidence?: boolean; query?: string } = {},): ConfidenceGrade {if (results.length === 0) return { level: 'weak', reason: 'zero_results' };const top = results[0];@@ -103,9 +202,12 @@ export function gradeRetrievalConfidence(// No reranker: fall back to the T4 evidence contract. An OR-relaxed// lexical top matched some query terms, not the query (gbrain-evals A4-2:- // 120 of 120 unanswerable questions had one at rank 1).+ // 120 of 120 unanswerable questions had one at rank 1); it is moderate+ // only when the top rows corroborate it (#5919).if (top.keyword_relaxed === true) {- return { level: 'weak', reason: 'keyword_relaxed_top', top_evidence: top.evidence };+ return opts.query !== undefined && relaxedTopCorroborated(results, opts.query)+ ? { level: 'moderate', reason: 'keyword_relaxed_corroborated', top_evidence: top.evidence }+ : { level: 'weak', reason: 'keyword_relaxed_top', top_evidence: top.evidence };}if (top.evidence === 'keyword_exact') {return { level: 'moderate', reason: 'keyword_exact_top', top_evidence: top.evidence };diff --git a/test/search/crag-relaxed-corroboration.test.ts b/test/search/crag-relaxed-corroboration.test.tsnew file mode 100644index 0000000000..c5502731ed--- /dev/null+++ b/test/search/crag-relaxed-corroboration.test.ts@@ -0,0 +1,87 @@+/**+ * #5919, end to end on the keyword path (hermetic PGLite, no embedding+ * provider, the `query` op's retrieval meta): a fixture shaped like the+ * gbrain-evals A4 world. Every question below reaches only the OR-relaxed+ * keyword fallback. Answerable questions, whose answer row matches all but+ * one framing word ("city", "many"), grade moderate; a missing attribute, a+ * sibling company's attribute and an absent company grade weak.+ *+ * Protects: the grade the query op reports for relaxed tops. Fails if the op+ * stops passing the query text to the grader, or if corroboration accepts+ * split or absent evidence. crag.test.ts covers the pure rule; this covers+ * real fallback rows and the op wiring.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { resetGateway } from '../../src/core/ai/gateway.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import type { CragMetaBlock } from '../../src/core/search/crag.ts';++let engine: PGLiteEngine;++const PAGES = [+ ['companies/vessra-example', 'company', 'Vessra Example', 'Vessra Example is a fictional company. Vessra Example is headquartered in Dunmere. Vessra Example was founded in April 1987.'],+ ['notes/a4-vessra-example-runway', 'note', 'Diligence note: Vessra Example', 'Diligence note on Vessra Example. Vessra Example has 31 months of runway at current burn. The remaining questions go to the next partner meeting.'],+ ['companies/orlak-example', 'company', 'Orlak Example', 'Orlak Example is a fictional company. Orlak Example has 140 employees. Orlak Example was founded in May 1990.'],+ ['companies/tamsk-labs-example', 'company', 'Tamsk Labs Example', 'Tamsk Labs Example is a fictional company. Tamsk Labs Example has 52 months of runway at current burn.'],+ ['companies/tamsk-freight-example', 'company', 'Tamsk Freight Example', 'Tamsk Freight Example is a fictional company. Tamsk Freight Example is headquartered in Elmira.'],+ ['companies/brisk-example', 'company', 'Brisk Example', 'Brisk Example is a fictional company. Brisk Example is headquartered in Ostrel. Brisk Example has 18 months of runway at current burn.'],+] as const;++beforeAll(async () => {+ resetGateway();+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const [slug, type, title, text] of PAGES) {+ await engine.putPage(slug, { type, title, compiled_truth: text, timeline: '' });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }]);+ }+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ resetGateway();+});++async function grade(query: string): Promise<{ crag: CragMetaBlock; slugs: string[] }> {+ const meta: Record<string, unknown> = {};+ const ctx = {+ engine, remote: false, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },+ } as unknown as OperationContext;+ const results = await operationsByName.query.handler(ctx, { query, expand: false, limit: 5 }) as Array<{ slug: string; keyword_relaxed?: boolean }>;+ expect(results[0]?.keyword_relaxed).toBe(true);+ return { crag: (meta.retrieval as { crag: CragMetaBlock }).crag, slugs: results.map(r => r.slug) };+}++describe('#5919: A4-style relaxed tops through the query op', () => {+ test('answerable, answer on the profile page → moderate', async () => {+ const { crag, slugs } = await grade('Which city is Vessra Example headquartered in?');+ expect(slugs).toContain('companies/vessra-example');+ expect(crag).toMatchObject({ confidence: 'moderate', reason: 'keyword_relaxed_corroborated' });+ });++ test('answerable, answer only in a diligence note → moderate', async () => {+ const { crag, slugs } = await grade('How many months of runway does Vessra Example have?');+ expect(slugs).toContain('notes/a4-vessra-example-runway');+ expect(crag).toMatchObject({ confidence: 'moderate', reason: 'keyword_relaxed_corroborated' });+ });++ test('missing attribute: the company exists, the attribute is written only for others → weak', async () => {+ const { crag } = await grade('Which city is Orlak Example headquartered in?');+ expect(crag).toMatchObject({ confidence: 'weak', reason: 'keyword_relaxed_top' });+ });++ test('sibling attribute: a company sharing the head word has it → weak', async () => {+ const { crag } = await grade('Which city is Tamsk Labs Example headquartered in?');+ expect(crag).toMatchObject({ confidence: 'weak', reason: 'keyword_relaxed_top' });+ });++ test('absent entity: no page names the company → weak', async () => {+ const { crag } = await grade('How many months of runway does Corvane Example have?');+ expect(crag).toMatchObject({ confidence: 'weak', reason: 'keyword_relaxed_top' });+ });+});diff --git a/test/search/crag.test.ts b/test/search/crag.test.tsindex beb1b7cda4..270961f99b 100644--- a/test/search/crag.test.ts+++ b/test/search/crag.test.ts@@ -8,6 +8,8 @@ import {shouldEscalateRetrieval,confidenceRank,DEFAULT_CRAG_MIN_TOP,+ RELAXED_CORROBORATION_DEPTH,+ relaxedTopCorroborated,} from '../../src/core/search/crag.ts';import type { SearchResult } from '../../src/core/types.ts';@@ -111,3 +113,60 @@ describe('A4-2: an OR-relaxed keyword top is weak', () => {expect(gradeRetrievalConfidence([r({ keyword_relaxed: true, rerank_score: 0.9 })]).reason).toBe('rerank_top');});});++// #5919: a relaxed top is moderate only when the top rows corroborate it.+describe('#5919: corroborating an OR-relaxed keyword top', () => {+ const relaxed = (title: string, chunk_text: string) => r({ keyword_relaxed: true, evidence: 'weak_semantic', title, chunk_text });+ const profile = relaxed('Quillon Example', 'Quillon Example is headquartered in Varnholt. Quillon Example has 212 employees.');+ const note = relaxed('Diligence note: Pellar Example', 'Diligence note on Pellar Example. Pellar Example was founded in March 1998.');+ const other = relaxed('Brisk Example', 'Brisk Example is headquartered in Ostrel.');++ test('one framing word the corpus never writes, rest co-located in one row → moderate', () => {+ const query = 'Which city is Quillon Example headquartered in?';+ expect(relaxedTopCorroborated([profile, other], query)).toBe(true);+ expect(gradeRetrievalConfidence([profile, other], { query })).toEqual({+ level: 'moderate', reason: 'keyword_relaxed_corroborated', top_evidence: 'weak_semantic',+ });+ });++ test('the corroborating row may sit lower in the top five', () => {+ const query = 'How many employees does Quillon Example have?';+ expect(gradeRetrievalConfidence([other, note, profile], { query }).level).toBe('moderate');+ });++ test('inflections compare equal ("headquarters" vs "headquartered")', () => {+ expect(relaxedTopCorroborated([profile], 'Which city has the Quillon Example headquarters?')).toBe(true);+ });++ test('entity in one row, attribute only in others (missing attribute) → weak', () => {+ const query = 'Which city is Pellar Example headquartered in?';+ expect(relaxedTopCorroborated([note, other], query)).toBe(false);+ expect(gradeRetrievalConfidence([note, other], { query })).toMatchObject({ level: 'weak', reason: 'keyword_relaxed_top' });+ });++ test('a name in the question that no row mentions (absent entity) → weak', () => {+ const query = 'When was Corvane Example founded?';+ expect(relaxedTopCorroborated([note], query)).toBe(false);+ expect(relaxedTopCorroborated([note], 'when was corvane example founded?')).toBe(true);+ });++ test('more than one unmatched content term (attribute phrased in words the evidence never uses) → weak', () => {+ const arr = relaxed('Quillon Example', 'Quillon Example reports $4.2M ARR.');+ expect(relaxedTopCorroborated([arr], 'What is the annual recurring revenue of Quillon Example?')).toBe(false);+ });++ test('a framing word written in another window row is treated like an attribute written elsewhere → weak', () => {+ const cityRow = relaxed('Brisk Example', 'Brisk Example is headquartered in a coastal city.');+ expect(relaxedTopCorroborated([profile, cityRow], 'Which city is Quillon Example headquartered in?')).toBe(false);+ });++ test('only rows inside the top five count', () => {+ const query = 'Which city is Quillon Example headquartered in?';+ const filler = Array.from({ length: RELAXED_CORROBORATION_DEPTH }, () => relaxed('Brisk Example', 'Brisk Example sells kites.'));+ expect(relaxedTopCorroborated([...filler, profile], query)).toBe(false);+ });++ test('without the query text a relaxed top stays weak', () => {+ expect(gradeRetrievalConfidence([profile]).reason).toBe('keyword_relaxed_top');+ });+});