Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): facts arm takes spare capacity only: fact rows fill free slots under the row count and whole rows into the budget the pages leave, never displacing a page; regression harness reports pass_with_facts_diagnostics
garrytan947536f4c7e6
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 509fd7ae0d..c26c1d49b6 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -301,7 +301,9 @@ Two cross-cutting seams sit around the pipeline rather than inside it:- **Facts arm in `query` (default off).** With `search.query_facts_arm=true`,`query` adds up to three active saved facts that match the question (by thequery embedding it already computed, by shared terms or by a named entity)- as fact rows inside the caller's row count and token budget, and marks a+ as fact rows in spare capacity only (free slots under the caller's row+ count, and what the page rows leave of the token budget; a page row is+ never displaced), and marks apage row `superseded_claim` when a newer fact covers its typed claim(`src/core/search/facts-arm.ts`). No model call. It stays off: in the B2corrections suite the facts surfaced but the reader kept the old value,diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 843c1ce540..47d7802a9c 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default off; gate 1 failed as preregistered). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows inside the caller's row count and token budget (free slots first; the lowest page rows give way only when the count is full) and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`.+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default off; see its decision record). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`.- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own default-off key; with both keys off it returns the rows untouched.- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.diff --git a/evals/entity-anchoring/regression.ts b/evals/entity-anchoring/regression.tsindex 8d88d273cb..64203f5910 100644--- a/evals/entity-anchoring/regression.ts+++ b/evals/entity-anchoring/regression.ts@@ -114,7 +114,9 @@ if (import.meta.main) {const lme = new URL('../../test/fixtures/longmemeval-nightly.jsonl', import.meta.url).pathname;reports.push(await longMemEval(lme, false), await longMemEval(lme, true));const asWritten = reports.filter(r => !r.corpus.endsWith('+now') && !r.corpus.endsWith('+facts'));- const out = { mode: 'hermetic', keyword_only: true, key: KEY, pass: asWritten.every(r => r.recall10_lower.length === 0), reports };+ const withFacts = reports.filter(r => !r.corpus.endsWith('+now'));+ const out = { mode: 'hermetic', keyword_only: true, key: KEY, pass: asWritten.every(r => r.recall10_lower.length === 0),+ pass_with_facts_diagnostics: withFacts.every(r => r.recall10_lower.length === 0), reports };const dumpPath = flag('--dump-off');if (dumpPath) writeFileSync(dumpPath, JSON.stringify(dump, null, 2));console.log(args.includes('--json') ? JSON.stringify(out, null, 2) : JSON.stringify(out));diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 80c3e2c183..c92f5e95a6 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -23,7 +23,7 @@ import { getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { privateProvenanceFilterFragment } from './private-visibility.ts';import { namedEntity } from './entity-anchor.ts';-import { enforceTokenBudget } from './token-budget.ts';+import { enforceTokenBudget, resultTokens } from './token-budget.ts';export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';/** Fact rows added per query at most. */@@ -134,21 +134,25 @@ export interface FactsArmOpts extends FactsArmScope {}/**- * The facts arm: matched facts appended as rows (in free slots, else the- * last ones, so the row count never grows), superseded page claims stamped,- * and the token budget re-applied. No match or any error: the results unchanged.+ * The facts arm: matched facts appended as rows in spare capacity only (free+ * slots under the caller's row count, and what the pages leave of the token+ * budget), so no page row is ever displaced; superseded page claims stamped.+ * No match, no spare capacity or any error: the results unchanged.*/export async function applyFactsArm(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts): Promise<SearchResult[]> {try {const facts = await matchQueryFacts(engine, query, opts, opts.queryEmbedding);if (!facts.length) return results;- // Facts fill free slots first; they displace the lowest page rows only when the pages already fill the row count.- const rowCount = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0, facts.length);- let pages = results.slice(0, Math.min(results.length, rowCount - facts.length)).map(r => ({ ...r }));+ const free = ((await opts.rowCap?.().catch(() => 0)) ?? 0) - results.length;+ if (free <= 0) return results;+ const pages = results.map(r => ({ ...r }));const floor = pages.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), pages[0]?.score ?? 1);- const rows = facts.map((f, i) => factRow(f, floor - (i + 1) * 1e-6));- // Facts are paid for first inside the budget; the pages share the rest.- if (opts.tokenBudget) pages = enforceTokenBudget(pages, Math.max(1, opts.tokenBudget - enforceTokenBudget(rows, opts.tokenBudget).meta.used)).results;+ let rows = facts.slice(0, free).map((f, i) => factRow(f, floor - (i + 1) * 1e-6));+ if (opts.tokenBudget) {+ let left = opts.tokenBudget - enforceTokenBudget(pages, opts.tokenBudget).meta.used;+ rows = rows.filter(r => { const cost = resultTokens(r); if (cost > left) return false; left -= cost; return true; });+ }+ if (!rows.length) return results;const merged = [...pages, ...rows];await stampSupersededClaims(engine, merged, facts).catch(() => undefined);return merged;diff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsindex d936b50301..fc68367bf3 100644--- a/test/search-facts-arm.test.ts+++ b/test/search-facts-arm.test.ts@@ -1,7 +1,8 @@/*** Facts arm for `query` (`search.query_facts_arm`, search/facts-arm.ts): with* the key on, an active fact that matches the question comes back as a row of- * its own inside the row count and budget; a remote caller never sees a+ * its own in spare capacity only (free slots under the row count, what the+ * pages leave of the token budget), never displacing a page; a remote caller never sees a* private fact; page-unit delivery passes the fact row through as written;* a page whose typed claim a newer fact covers is stamped superseded_claim;* with the key off the rows are unchanged. PGLite, keyword-only, no network.@@ -11,6 +12,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { handleToolCall } from '../src/mcp/server.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { QUERY_FACTS_ARM_KEY, matchQueryFacts, queryTerms } from '../src/core/search/facts-arm.ts';+import { resultTokens } from '../src/core/search/token-budget.ts';import type { SearchResult } from '../src/core/types.ts';import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';@@ -50,13 +52,14 @@ describe('facts arm', () => {expect(unset.some(r => r.fact_row)).toBe(false);});- test('on: the matching fact is a row of its own, newest first, inside the same row count', async () => {+ test('on: the matching fact is a row of its own, newest first, in free slots after every page row', async () => {await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');- const off = await query();+ const off = await query({ limit: 10 });await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');try {- const on = await query();- expect(on).toHaveLength(off.length);+ const on = await query({ limit: 10 });+ expect(on.length).toBeLessThanOrEqual(10);+ expect(on.slice(0, off.length).map(r => [r.slug, r.chunk_id])).toEqual(off.map(r => [r.slug, r.chunk_id]));const facts = on.filter(r => r.fact_row);expect(facts.map(r => r.fact_row!.valid_from.slice(0, 10))).toEqual(['2025-07-13', '2025-07-12']);expect(facts[1]!.chunk_text).toContain('Missoula');@@ -65,6 +68,19 @@ describe('facts arm', () => {} finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }});+ test('on, no spare capacity: a full row count or a spent token budget returns the page rows unchanged', async () => {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');+ const full = await query();+ const budget = resultTokens(full[0]!);+ const spent = await query({ limit: 10, token_budget: budget });+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ expect(full).toHaveLength(6);+ expect(JSON.stringify(await query())).toBe(JSON.stringify(full));+ expect(JSON.stringify(await query({ limit: 10, token_budget: budget }))).toBe(JSON.stringify(spent));+ } finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }+ });+test('on, remote: a private fact never comes back; the world fact does', async () => {await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');try {@@ -78,7 +94,7 @@ describe('facts arm', () => {test('on, return_unit page: the fact row passes through as written and counts in the budget', async () => {await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');try {- const rows = await query({ return_unit: 'page', token_budget: 2000 }) as Array<SearchResult & { delivered?: { reason?: string } }>;+ const rows = await query({ return_unit: 'page', token_budget: 2000, limit: 10 }) as Array<SearchResult & { delivered?: { reason?: string } }>;const fact = rows.find(r => r.fact_row && r.chunk_text.includes('Missoula'))!;expect(fact.delivered?.reason).toBe('saved_fact');expect(fact.chunk_text.startsWith('Saved fact')).toBe(true);