Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts-arm): saved-fact rows honor the #5575 read contract: the arm applies the read floor, activation control and the purge/quarantine holds in its candidate SQL, and each fact row carries its own trust tier; pinned_questions and question_evidence join the deletion inventory, questions_list/status declare labeled read trust; query result-size ceiling re-pinned to 3303 (measured 3145 x 1.05)
garrytan19358c1d9bc4
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 9c55a51a2e..23d0357831 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -122,9 +122,11 @@ const ROWS: readonly Row[] = [['persistence_topology_changes', 'out_of_scope', 'probed_reported', 'digest operation source_id state recovery outcome', 'recovery outcome'],['persistence_worktree_refreshes', 'out_of_scope', 'probed_reported', 'source_ids state old_head target_head upstream_ref preserved_uncommitted outcome', 'outcome'],['persistence_worktrees', 'out_of_scope', 'no_memory_text', 'state manifest'],+ ['pinned_questions', 'out_of_scope', 'probed_reported', 'source_id slug question scope_slug_prefix scope_entity state inactive_reason publish_mode model origin created_by answer answer_model last_error lease_token lease_owner', 'question answer last_error'],['planner_stats_deltas', 'out_of_scope', 'no_memory_text', 'table_name'],['planner_stats_state', 'out_of_scope', 'no_memory_text', 'table_name'],['query_cache', 'swept', 'query_cache', 'id query_text source_id embedding results meta knobs_hash page_generations'],+ ['question_evidence', 'out_of_scope', 'text_free_ledger', 'sentence_id kind source_id page_slug page_revision content_hash'],['raw_data', 'out_of_scope', 'probed_reported', 'source data', 'source data'],['retrieval_event_links', 'out_of_scope', 'no_memory_text', 'event_id source_id edge_key to_slug'],['retrieval_event_pages', 'out_of_scope', 'no_memory_text', 'event_id source_id slug content_hash'],diff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.tsindex a79fd0d00a..5b6cb57740 100644--- a/src/core/eligibility/registry.ts+++ b/src/core/eligibility/registry.ts@@ -40,6 +40,7 @@ export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {extraction_pending: 'labeled', entity_identity_list: 'labeled', find_contradictions: 'labeled',find_experts: 'labeled', find_trajectory: 'labeled', takes_scorecard: 'labeled', takes_calibration: 'labeled',open_loops: 'labeled', schema_review_orphans: 'labeled',+ questions_list: 'labeled', questions_status: 'labeled',code_callers: 'labeled', code_callees: 'labeled', code_def: 'labeled', code_refs: 'labeled', code_blast: 'labeled', code_flow: 'labeled',// no stored memory textsearch_modes: 'text_free', list_link_sources: 'text_free', get_brain_identity: 'text_free',diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 1b2c78dd79..7da14fe857 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -18,6 +18,8 @@ const withFlag = (fields: TrustFields, flagged: unknown): TrustFields => (flaggeinterface PageRef {page_id?: number | null; source_id?: string | null; slug: string; chunk_text?: string | null;trust_tier?: string; origin?: string; unconfirmed?: true; contested?: Contested;+ /** A saved-fact row (search/facts-arm.ts): labeled with the fact's own tier, not a page's. */+ fact_row?: { id: number };}type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -59,9 +61,13 @@ export async function loadPageTrust(engine: Exec, refs: readonly PageRef[]): Pro*/export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[], floor?: TrustTier): Promise<T[]> {if (rows.length === 0) return rows;+ const factRows = rows.filter(row => typeof row.fact_row?.id === 'number');+ const factTrust = factRows.length ? await stampRowTrust(engine, 'facts', factRows, row => row.fact_row!.id) : [];+ factRows.forEach((row, i) => Object.assign(row, factTrust[i]));+ const pageRows = rows.filter(row => typeof row.fact_row?.id !== 'number');let found: Awaited<ReturnType<typeof loadPageTrust>> | null = null;- try { found = await loadPageTrust(engine, rows); } catch { found = null; }- for (const row of rows) {+ try { found = pageRows.length ? await loadPageTrust(engine, pageRows) : null; } catch { found = null; }+ for (const row of pageRows) {const fields = (typeof row.page_id === 'number' ? found?.byId.get(row.page_id) : undefined)?? found?.byKey.get(key(row.source_id, row.slug))?? { trust_tier: 'unknown' as const, origin: 'unrecorded' };@@ -71,7 +77,7 @@ export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[],row.origin = lowered ? FENCE_TRUST_ORIGIN : fields.origin;if (fields.unconfirmed) row.unconfirmed = true;}- await applyFenceRowTrust(engine, rows);+ await applyFenceRowTrust(engine, pageRows);return floor ? rows.filter(row => admitsTrust(row.trust_tier as TrustTier, floor)) : rows;}diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 8ae160fd10..ab9060c13e 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -27,6 +27,8 @@ import { namedEntity } from './entity-anchor.ts';import { pageReadFilter } from './read-policy-sql.ts';import { enforceTokenBudget, resultTokens } from './token-budget.ts';import { factDateHeader } from './evidence-date.ts';+import { projectionEligibleSql } from '../eligibility/sql.ts';+import type { TrustTier } from '../trust/tier.ts';export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';/** Fact rows added per query at most. */@@ -60,7 +62,11 @@ export function hasTemporalCue(query: string): boolean {const STOPWORDS = new Set(['the', 'and', 'for', 'who', 'what', 'when', 'where', 'which', 'with', 'from', 'that', 'this', 'are', 'was', 'were', 'our', 'your', 'their','now', 'current', 'currently', 'should', 'does', 'did', 'has', 'have', 'how', 'any', 'all', 'about', 'into', 'its', 'next', 'use', 'uses', 'tell']);-export interface FactsArmScope { sourceId?: string; sourceIds?: string[]; remote: boolean }+export interface FactsArmScope {+ sourceId?: string; sourceIds?: string[]; remote: boolean;+ /** #5575 read floor and activation control, applied in the candidate SQL like every retrieval arm. */+ minTrust?: TrustTier; suppressFlagged?: boolean;+}interface FactCandidate {id: number; fact: string; kind: string; entity_slug: string | null; source_id: string; source: string;@@ -88,7 +94,8 @@ async function collectFactCandidates(engine: BrainEngine, query: string, scope:const params: unknown[] = [sources, [...AUDIT_ROW_SOURCES]];const base = `f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULLAND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[]) AND ${quarantinedProvenanceFilterFragment('f')}- ${scope.remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : ''}`;+ ${scope.remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : ''}+ AND ${projectionEligibleSql('facts', 'f', { floor: scope.minTrust, suppressFlagged: scope.suppressFlagged })}`;const cols = 'f.id, f.fact, f.kind, f.entity_slug, f.source_id, f.source, f.valid_from, f.valid_until, f.created_at, f.claim_metric, f.claim_period';const found = new Map<number, ScoredCandidate>();const add = (r: FactCandidate & { haystack?: string; similarity?: number }, entity = false) => {diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsindex 86a3467c42..c3fa4f162b 100644--- a/src/core/search/query-arms.ts+++ b/src/core/search/query-arms.ts@@ -17,7 +17,7 @@ export async function applyQueryArms(engine: BrainEngine, p: Record<string, unknconst anchored = await anchorOpResults(engine, p, query, results, scope);if (p.offset || scope.filtered || p.since || p.until || p.lang || p.symbol_kind || p.near_symbol) return anchored;const tokenBudget = !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined;- const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };+ const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, minTrust: scope.minTrust, suppressFlagged: scope.suppressFlagged, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };const budget = scope.evidencePlan ? scope.evidenceBudget : tokenBudget;if (budget && hasTemporalCue(query) && await temporalFactReserveEnabled(engine)) return applyTemporalFactReserve(engine, query, anchored, { ...opts, budget });if (!await queryFactsArmEnabled(engine)) return anchored;diff --git a/test/mcp-result-size-ceiling.test.ts b/test/mcp-result-size-ceiling.test.tsindex 85da816078..a570cf57d8 100644--- a/test/mcp-result-size-ceiling.test.ts+++ b/test/mcp-result-size-ceiling.test.ts@@ -25,7 +25,7 @@ import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';import { withEnv } from './helpers/with-env.ts';/** ceil(measured x 1.05) on the fixture below. */-const CEILINGS = { search: 2756, query: 3024 };+const CEILINGS = { search: 2756, query: 3303 };/*** The keyless fixture also gets the operator contract's degraded_recall* notice (F3) on every HTTP call. It is bounded on its own so the ceilingsdiff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsindex 4d8c8b80d9..2ce339b5df 100644--- a/test/search-facts-arm.test.ts+++ b/test/search-facts-arm.test.ts@@ -6,7 +6,9 @@* 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;* the key is on when unset, and with it off the rows are unchanged; a fact- * whose source page is quarantined never comes back. PGLite, keyword-only, no network.+ * whose source page is quarantined never comes back; a fact row carries its+ * own trust tier, and the read floor and purge's rederive hold apply inside+ * the arm. PGLite, keyword-only, no network.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -16,6 +18,8 @@ import { QUERY_FACTS_ARM_KEY, matchQueryFacts, queryTerms } from '../src/core/seimport { 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';+import { withTrustPromotion } from '../src/core/persistence/context.ts';+import type { TrustTier } from '../src/core/trust/tier.ts';let engine: PGLiteEngine;let sourceId: string;@@ -155,4 +159,31 @@ describe('facts arm', () => {expect(await ids(false)).not.toContain(Number(scraped.id));expect(await ids(true)).not.toContain(Number(scraped.id));});++ test('trust (#5575): a fact row carries its own tier; the floor and the rederive hold apply inside the arm', async () => {+ const tq = 'Where is the Quarry summit held?';+ const setTier = (id: number, tier: TrustTier) => engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed',+ () => tx.executeRaw('UPDATE facts SET trust_tier = $1 WHERE id = $2', [tier, id])));+ const curated = Number((await engine.insertFact({ fact: 'The Quarry summit is held in Tulsa.', kind: 'fact', entity_slug: 'quarry', source: 'owner note', visibility: 'world', valid_from: new Date('2025-09-01T00:00:00Z') }, { source_id: sourceId })).id);+ const external = Number((await engine.insertFact({ fact: 'The Quarry summit is held in Reno.', kind: 'fact', entity_slug: 'quarry', source: 'web page', visibility: 'world', valid_from: new Date('2025-09-02T00:00:00Z') }, { source_id: sourceId })).id);+ await setTier(curated, 'operator_curated');+ await setTier(external, 'external_untrusted');+ const ids = async (minTrust?: TrustTier) => (await matchQueryFacts(engine, tq, { sourceId, remote: false, minTrust })).map(f => Number(f.id));+ expect(await ids()).toEqual([external, curated]);+ expect(await ids('unknown')).toEqual([curated]);++ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const tiers = (rows: SearchResult[]) => Object.fromEntries(rows.filter(r => r.result_type === 'fact').map(r => [Number(r.fact_id), (r as { trust_tier?: string }).trust_tier]));+ expect(tiers(await query({ query: tq, limit: 10 }))).toEqual({ [curated]: 'operator_curated', [external]: 'external_untrusted' });+ expect(tiers(await query({ query: tq, limit: 10, min_trust: 'unknown' }))).toEqual({ [curated]: 'operator_curated' });++ await engine.executeRaw(`INSERT INTO needs_rederive (derived_table, derived_id, source_id, reason) VALUES ('facts', $1, $2, 'test')`, [String(curated), sourceId]);+ expect(await ids()).toEqual([external]);+ expect(tiers(await query({ query: tq, limit: 10 }))).toEqual({ [external]: 'external_untrusted' });+ } finally {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');+ await engine.executeRaw(`DELETE FROM needs_rederive WHERE derived_table = 'facts' AND derived_id = $1`, [String(curated)]);+ }+ });});