Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): an OR-relaxed keyword top grades weak, not moderate (A4-2)

garrytana590e19de06b
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 5c99feca76..1a68f76a81 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The `vector` strategy runs the production query path: `embedQuery` (query-side `input_type` on asymmetric providers) in the resolved embedding column's model, searched on that column — `embed()` is the document side and would handicap the vector baseline.
-- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so an agent never reads one blended score, decides "no strong match, safe to create", and writes a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.
+- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so an agent never reads one blended score, decides "no strong match, safe to create", and writes a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent. A `keyword_relaxed` row never earns `keyword_exact`; `crag.ts` grades a relaxed rank-1 `weak` (`keyword_relaxed_top`, gbrain-evals A4-2).
- `src/core/search/expansion.ts` — Multi-query expansion via Haiku. Exports `sanitizeQueryForPrompt` + `sanitizeExpansionOutput` (prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search. `expandQuery` returns the original first plus 2-3 variants; `hybridSearch` re-enforces `queries[0]` = the caller's query and dedupes repeats, then fuses each variant's vector list as a role `variant` arm through `src/core/search/fusion-lists.ts` (see that entry), where the variant arms share `search.expansion_variant_budget` as total RRF weight — `null` (every bundle's default) is legacy equal weight, the configuration under which the LongMemEval receipt shows expansion halving strict `recall_all@5` (93.19% plain hybrid vs 54.89% with expansion, paired +3 / -183; `docs/architecture/RETRIEVAL.md` "Multi-query expansion"). The harness records `expansion_variants` per row and `--expansion-replay` serves them back so a budget sweep changes only the budget.
@@ -74,4 +74,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.
-- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit`, and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.
+- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` survives only if every list holding the chunk was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.
diff --git a/src/core/search/crag.ts b/src/core/search/crag.ts
index dbcfb44de4..61ecc36d52 100644
--- a/src/core/search/crag.ts
+++ b/src/core/search/crag.ts
@@ -14,8 +14,9 @@
* moderate — lexically verified top (keyword_exact) but no identity or
* calibrated-semantic signal.
* weak — zero results, a reranked top BELOW the weak-top floor
- * (the #1863 "whole list is low-confidence" shape), or an
- * unverified weak_semantic top.
+ * (the #1863 "whole list is low-confidence" shape), an
+ * 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 —
@@ -49,6 +50,7 @@ export interface ConfidenceGrade {
| 'rerank_top'
| 'rerank_top_below_floor'
| 'keyword_exact_top'
+ | 'keyword_relaxed_top'
| 'weak_semantic_top'
| 'decide_evidence';
/** Rank-1 evidence label when present (auditability). */
@@ -99,7 +101,12 @@ export function gradeRetrievalConfidence(
: { level: 'weak', reason: 'rerank_top_below_floor', top_evidence: top.evidence, top_rerank_score: top.rerank_score };
}
- // No reranker: fall back to the T4 evidence contract.
+ // 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).
+ if (top.keyword_relaxed === true) {
+ return { 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/src/core/search/evidence.ts b/src/core/search/evidence.ts
index 5f31214ed6..4b3dad065b 100644
--- a/src/core/search/evidence.ts
+++ b/src/core/search/evidence.ts
@@ -17,9 +17,10 @@
* alias_hit — query exactly matched the page's declared chosen name
* exact_title_match — query is a phrase in the page title (title boost fired)
* high_vector_match — base (pre-boost) score >= HIGH_MATCH_FLOOR
- * keyword_exact — surfaced by a lexical arm (keyword/title FTS,
- * keyword_hit=true) with a solid score (#3783 — a solid
- * blended score alone no longer earns this label)
+ * keyword_exact — surfaced by a strict lexical arm (keyword/title FTS,
+ * keyword_hit=true, not keyword_relaxed) with a solid
+ * score (#3783 — a solid blended score alone no longer
+ * earns this label)
* weak_semantic — everything else (low-confidence tail)
*
* create_safety:
@@ -80,8 +81,11 @@ export function classifyEvidence(r: SearchResult, opts: EvidenceOpts = {}): Evid
// a solid blended score lied to the agent about WHY it matched. Rows
// without the flag (incl. legacy cached rows) honestly degrade to
// weak_semantic — create_safety 'unknown', the safe look-closer direction.
+ // gbrain-evals A4-2: an OR-relaxed lexical row (keyword_relaxed, the
+ // zero-strict-recall fallback) matched some query terms, not the query, so
+ // it is not lexically verified.
const base = typeof r.base_score === 'number' ? r.base_score : r.score;
- if (r.keyword_hit === true && Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) {
+ if (r.keyword_hit === true && r.keyword_relaxed !== true && Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) {
return 'keyword_exact';
}
return 'weak_semantic';
diff --git a/src/core/search/rrf-page-fusion.ts b/src/core/search/rrf-page-fusion.ts
index b004ea0733..b25cd2625e 100644
--- a/src/core/search/rrf-page-fusion.ts
+++ b/src/core/search/rrf-page-fusion.ts
@@ -67,6 +67,12 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
// first saw via a vector list must still read keyword_hit when the
// keyword arm ALSO surfaced it.
if (r.keyword_hit === true) existing.keywordHit = true;
+ // A strict appearance in any list outranks the OR-relaxed fallback:
+ // the fused row is relaxed only when every list that held it was.
+ if (existing.result.keyword_relaxed === true && r.keyword_relaxed !== true) {
+ const { keyword_relaxed: _relaxed, ...strict } = existing.result;
+ existing.result = strict;
+ }
} else {
chunks.set(key, { result: r, score: 0, own: rrfScore, keywordHit: r.keyword_hit === true });
}
diff --git a/test/search/crag-keyword-relaxed.test.ts b/test/search/crag-keyword-relaxed.test.ts
new file mode 100644
index 0000000000..95167a3eb4
--- /dev/null
+++ b/test/search/crag-keyword-relaxed.test.ts
@@ -0,0 +1,49 @@
+/**
+ * gbrain-evals A4-2, end to end on the keyword path (hermetic PGLite, no
+ * embedding provider): a question about a company no page names only
+ * reaches the OR-relaxed fallback, and CRAG must grade that weak instead of
+ * moderate. A question the corpus answers strictly stays moderate.
+ */
+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 { hybridSearch } from '../../src/core/search/hybrid.ts';
+import { gradeRetrievalConfidence } from '../../src/core/search/crag.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ resetGateway();
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, title, text] of [
+ ['companies/talzarra-example', 'Talzarra Example', 'Talzarra Example headcount is 41 people. The company sells payroll software.'],
+ ['companies/kelvane-example', 'Kelvane Example', 'Kelvane Example has 18 months of runway and is headquartered in a coastal city.'],
+ ] as const) {
+ await engine.putPage(slug, { type: 'company', 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();
+});
+
+describe('A4-2: CRAG on the keyword path', () => {
+ test('a question about an unnamed company reaches only relaxed rows and grades weak', async () => {
+ const results = await hybridSearch(engine, 'What is the headcount of Morvane Example?', { limit: 5 });
+ expect(results.length).toBeGreaterThan(0);
+ expect(results[0].keyword_relaxed).toBe(true);
+ expect(gradeRetrievalConfidence(results)).toMatchObject({ level: 'weak', reason: 'keyword_relaxed_top' });
+ });
+
+ test('a question the corpus matches strictly is not graded by the relaxed rule', async () => {
+ const results = await hybridSearch(engine, 'Talzarra headcount', { limit: 5 });
+ expect(results[0]?.slug).toBe('companies/talzarra-example');
+ expect(results[0].keyword_relaxed).toBeUndefined();
+ expect(gradeRetrievalConfidence(results).reason).not.toBe('keyword_relaxed_top');
+ });
+});
diff --git a/test/search/crag.test.ts b/test/search/crag.test.ts
index e8d75dfcd0..beb1b7cda4 100644
--- a/test/search/crag.test.ts
+++ b/test/search/crag.test.ts
@@ -96,3 +96,18 @@ describe('shouldEscalateRetrieval / confidenceRank (#1663)', () => {
expect(confidenceRank('moderate')).toBeGreaterThan(confidenceRank('weak'));
});
});
+
+// gbrain-evals A4-2: on the keyword path every natural question graded
+// moderate, although the rank-1 row was an OR-relaxed match for 120 of 120
+// unanswerable questions (and 80 of 120 answerable ones).
+describe('A4-2: an OR-relaxed keyword top is weak', () => {
+ test('keyword_relaxed top → weak / keyword_relaxed_top, even when labelled keyword_exact upstream', () => {
+ const g = gradeRetrievalConfidence([r({ keyword_relaxed: true, evidence: 'keyword_exact' })]);
+ expect(g).toEqual({ level: 'weak', reason: 'keyword_relaxed_top', top_evidence: 'keyword_exact' });
+ });
+ test('a strict keyword top stays moderate; identity and rerank signals still win over relaxed', () => {
+ expect(gradeRetrievalConfidence([r({ evidence: 'keyword_exact' })]).reason).toBe('keyword_exact_top');
+ expect(gradeRetrievalConfidence([r({ keyword_relaxed: true, evidence: 'exact_title_match' })]).level).toBe('strong');
+ expect(gradeRetrievalConfidence([r({ keyword_relaxed: true, rerank_score: 0.9 })]).reason).toBe('rerank_top');
+ });
+});
diff --git a/test/search/evidence.test.ts b/test/search/evidence.test.ts
index 46986ba151..4bf997b1a2 100644
--- a/test/search/evidence.test.ts
+++ b/test/search/evidence.test.ts
@@ -122,3 +122,10 @@ describe('stampEvidence', () => {
expect(fixed.create_safety).toBe('exists');
});
});
+
+describe('A4-2: OR-relaxed lexical rows are not lexically verified', () => {
+ test('a relaxed keyword hit with a solid score is weak_semantic, not keyword_exact', () => {
+ expect(classifyEvidence(r({ keyword_hit: true, keyword_relaxed: true, base_score: 0.9 }))).toBe('weak_semantic');
+ expect(classifyEvidence(r({ keyword_hit: true, base_score: 0.9 }))).toBe('keyword_exact');
+ });
+});
diff --git a/test/search/rrf-page-grain.test.ts b/test/search/rrf-page-grain.test.ts
index 9e76d2974b..a26c13ed06 100644
--- a/test/search/rrf-page-grain.test.ts
+++ b/test/search/rrf-page-grain.test.ts
@@ -34,6 +34,14 @@ describe('rrf page-grain fusion (pure)', () => {
expect(out[2].score).toBeCloseTo((1 / 60) / (2 / 60), 12);
});
+ test('A4-2: a chunk is OR-relaxed after fusion only when every list that held it was relaxed', () => {
+ const relaxedKeyword = [row('a', 1, { keyword_relaxed: true, keyword_hit: true }), row('b', 10, { keyword_relaxed: true, keyword_hit: true })];
+ const strictTitle = [row('a', 1, { keyword_hit: true })];
+ const out = rrfFusion([relaxedKeyword, strictTitle], 60, false);
+ expect(out.find(r => r.slug === 'a')?.keyword_relaxed).toBeUndefined();
+ expect(out.find(r => r.slug === 'b')?.keyword_relaxed).toBe(true);
+ });
+
test('a page\'s second chunk never crowds out another page\'s lead', () => {
const vector = [row('a', 1), row('b', 10), row('c', 20)];
const keyword = [row('a', 2), row('b', 10), row('c', 20)];