Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(questions, search): quarantined pages and facts projected from them are never pinned-question evidence or facts-arm rows (#6284)
garrytan745a77155314
diff --git a/docs/guides/pinned-questions.md b/docs/guides/pinned-questions.mdindex 7dbee72a9e..366ca033f0 100644--- a/docs/guides/pinned-questions.md+++ b/docs/guides/pinned-questions.md@@ -92,6 +92,7 @@ sentence is stale when its evidence:- was edited, renamed away or made private (the page's revision changed);- was soft-deleted or hard-deleted, or its source was archived;- was forgotten, superseded, or expired because its `valid_until` passed;+- is a fact whose source page the content-quality gate has since quarantined;- is a take that was deactivated or changed, or a timeline entry that was removed;- can't be found or verified (a sentence with no citation is always stale).@@ -114,8 +115,9 @@ JSON-only reminder (both calls count toward spend); if that also fails, therefresh fails with `refresh_failed:model_output_not_json`. A failed refreshnever removes the previous answer.-Question pages, synthesis pages and pages that copy a published answer are-never used as evidence.+Question pages, synthesis pages, pages that copy a published answer, and+quarantined pages (with the facts extracted from them) are never used as+evidence.## Your own notesdiff --git a/src/core/quarantine.ts b/src/core/quarantine.tsindex 0cb580bf42..45fd81f90a 100644--- a/src/core/quarantine.ts+++ b/src/core/quarantine.ts@@ -56,6 +56,12 @@ export function quarantineFilterFragment(pageAlias: string): string {* and for any future stale/orphan-chunk query that needs it. */export const QUARANTINE_FILTER_FRAGMENT = quarantineFilterFragment('p');+/** Fact-row twin: excludes facts whose source page (same source, `source_markdown_slug`) is quarantined. */+export function quarantinedProvenanceFilterFragment(factAlias: string): string {+ return `NOT EXISTS (SELECT 1 FROM pages qp WHERE qp.source_id = ${factAlias}.source_id `+ + `AND qp.slug = ${factAlias}.source_markdown_slug AND NOT ${quarantineFilterFragment('qp')})`;+}+export interface QuarantineMarker {/** Why the page was quarantined. The high-confidence junk reasons. */reason: 'junk_pattern' | 'literal_substring';diff --git a/src/core/questions/freshness.ts b/src/core/questions/freshness.tsindex c542351959..1170629992 100644--- a/src/core/questions/freshness.ts+++ b/src/core/questions/freshness.ts@@ -8,17 +8,18 @@*/import type { BrainEngine } from '../engine.ts';import type { AnswerSentence, PinRow } from './store.ts';+import { quarantinedProvenanceFilterFragment } from '../quarantine.ts';export type StaleReason =| 'page_missing' | 'page_deleted' | 'page_changed' | 'source_archived'- | 'fact_missing' | 'fact_withdrawn' | 'fact_expired' | 'fact_superseded' | 'fact_changed'+ | 'fact_missing' | 'fact_withdrawn' | 'fact_expired' | 'fact_superseded' | 'fact_changed' | 'fact_source_quarantined'| 'timeline_missing' | 'timeline_changed' | 'take_missing' | 'take_inactive' | 'take_changed'| 'owner_edited' | 'unverifiable';/** Reasons that remove or contradict evidence: an incremental edit can't recover from them, so refresh recomputes. */const FULL_RECOMPUTE_REASONS: ReadonlySet<StaleReason> = new Set(['page_missing', 'page_deleted', 'source_archived', 'fact_missing', 'fact_withdrawn', 'fact_expired',- 'fact_superseded', 'fact_changed', 'timeline_missing', 'take_missing', 'take_inactive', 'take_changed', 'unverifiable',+ 'fact_superseded', 'fact_changed', 'fact_source_quarantined', 'timeline_missing', 'take_missing', 'take_inactive', 'take_changed', 'unverifiable',]);export type EvidenceKind = 'page' | 'fact' | 'timeline' | 'take' | 'owner';@@ -63,6 +64,7 @@ interface EvidenceJoinRow {f_valid_until_passed: boolean | null;f_superseded: string | number | null;f_hash: string | null;+ f_source_quarantined: boolean | null;t_id: number | null;t_hash: string | null;k_id: string | number | null;@@ -95,6 +97,7 @@ export function evidenceReasons(r: EvidenceJoinRow): StaleReason[] {if (r.f_superseded !== null && r.f_superseded !== undefined) return ['fact_superseded'];if (r.f_valid_until_passed) return ['fact_expired'];if (r.f_hash !== r.content_hash) return ['fact_changed'];+ if (r.f_source_quarantined) return ['fact_source_quarantined'];return [];}case 'timeline': {@@ -128,6 +131,7 @@ export async function evaluateAnswer(s.archived AS p_source_archived, md5(p.compiled_truth) AS p_body_hash,f.id AS f_id, f.expired_at AS f_expired, (f.valid_until IS NOT NULL AND f.valid_until <= now()) AS f_valid_until_passed,f.superseded_by AS f_superseded, ${FACT_HASH_SQL('f')} AS f_hash,+ (f.id IS NOT NULL AND NOT ${quarantinedProvenanceFilterFragment('f')}) AS f_source_quarantined,t.id AS t_id, ${TIMELINE_HASH_SQL('t')} AS t_hash,k.id AS k_id, k.active AS k_active, k.superseded_by AS k_superseded, ${TAKE_HASH_SQL('k')} AS k_hashFROM question_evidence ediff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.tsindex d1493c5e1c..9fb38e1387 100644--- a/src/core/questions/refresh.ts+++ b/src/core/questions/refresh.ts@@ -28,6 +28,7 @@ import { chat as gatewayChat, probeChatModel } from '../ai/gateway.ts';import { classifyLlmCallFailure } from '../think/index.ts';import { PINNED_QUESTION_MARKER, normalizeQuestion, sentenceId } from './identity.ts';import { entityAnchoredPages, prefixAnchoredPages } from '../search/entity-anchor.ts';+import { quarantinedProvenanceFilterFragment, quarantineFilterFragment } from '../quarantine.ts';import { FACT_HASH_SQL, TAKE_HASH_SQL, TIMELINE_HASH_SQL, evaluateAnswer, type EvidenceKind } from './freshness.ts';import { ownerClaims, readQuestionPage } from './pages.ts';import { acquireLease, getPin, pinId, releaseLease, type AnswerSentence, type PinRow } from './store.ts';@@ -170,7 +171,7 @@ export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promisconst candidates = slugs.size === 0 ? [] : await engine.executeRaw<CandidatePage>(`SELECT id, slug, source_id, generation, knowledge_revision::text AS revision, type, compiled_truth, updated_at,(frontmatter ? '${PINNED_QUESTION_MARKER}') AS marker- FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [pin.source_id, [...slugs]]);+ FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL AND ${quarantineFilterFragment('pages')}`, [pin.source_id, [...slugs]]);const laundered = launderingIndex(await engine.executeRaw<PublishedAnswer>(`SELECT q.answer, q.last_refresh_at AS published_at,COALESCE(array_agg(e.page_id) FILTER (WHERE e.page_id IS NOT NULL), ARRAY[]::integer[]) AS cited@@ -199,7 +200,7 @@ export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promisconst facts = await engine.executeRaw<{ id: string | number; fact: string; entity_slug: string | null; valid_from: unknown; hash: string }>(`SELECT f.id, f.fact, f.entity_slug, f.valid_from, ${FACT_HASH_SQL('f')} AS hash FROM facts fWHERE f.source_id = $1 AND f.entity_slug = ANY($2::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL- AND (f.valid_until IS NULL OR f.valid_until > now())+ AND (f.valid_until IS NULL OR f.valid_until > now()) AND ${quarantinedProvenanceFilterFragment('f')}AND NOT EXISTS (SELECT 1 FROM pages fp WHERE fp.source_id = f.source_id AND fp.slug = f.source_markdown_slugAND (fp.type IN ('question', 'synthesis') OR fp.frontmatter ? '${PINNED_QUESTION_MARKER}'))ORDER BY f.valid_from DESC, f.id DESC LIMIT ${MAX_FACTS}`, [pin.source_id, entitySlugs]);diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 46f18facd2..8ae160fd10 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -22,6 +22,7 @@ import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';import { getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { privateProvenanceFilterFragment } from './private-visibility.ts';+import { quarantinedProvenanceFilterFragment } from '../quarantine.ts';import { namedEntity } from './entity-anchor.ts';import { pageReadFilter } from './read-policy-sql.ts';import { enforceTokenBudget, resultTokens } from './token-budget.ts';@@ -86,7 +87,7 @@ async function collectFactCandidates(engine: BrainEngine, query: string, scope:const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];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 NULL- AND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])+ AND (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')}` : ''}`;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>();diff --git a/test/helpers/pinned-questions-scenarios.ts b/test/helpers/pinned-questions-scenarios.tsindex e7789438b7..29481c75b4 100644--- a/test/helpers/pinned-questions-scenarios.ts+++ b/test/helpers/pinned-questions-scenarios.ts@@ -7,7 +7,8 @@* Protects: restricted grants never see a question page or answer on any* read surface; answer text never enters pages, chunks, versions or export;* every evidence change (edit, soft and hard delete, forget, clock expiry,- * supersession, visibility, take, timeline, owner edit) marks the dependent+ * supersession, visibility, take, timeline, owner edit, a fact's source page+ * quarantined) marks the dependent* sentence stale on the next read with no cycle; refresh never publishes over* a concurrent change, a duplicate worker, a crash between publication* stages, or a failure; consent, keyless, budget and worker states carry an@@ -229,6 +230,11 @@ export function registerPinnedQuestionSuite(label: string, getEngine: () => BraiputPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan for acme-example ships in March.', 'visibility: private\n'), await revisionOf(engine, s.sourceId, 'notes/widget-plan')) },{ name: 'deactivated take', needle: 'take on people/alice-example', reason: 'take_inactive', mutate: async (engine, s) => { await engine.executeRaw('UPDATE takes SET active = false WHERE id = $1', [s.takeId]); } },{ name: 'removed timeline entry', needle: 'timeline people/alice-example', reason: 'timeline_missing', mutate: async (engine, s) => { await engine.executeRaw('DELETE FROM timeline_entries WHERE id = $1', [s.timelineId]); } },+ { name: 'fact whose source page was quarantined after it was projected', needle: '40 employees', reason: 'fact_source_quarantined', mutate: async (engine, s) => {+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $2 WHERE id = $1', [s.factId, 'notes/widget-plan']);+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"quarantine": {"reason": "junk_pattern", "detail": "test"}}'::jsonb+ WHERE source_id = $1 AND slug = 'notes/widget-plan'`, [s.sourceId]);+ } },];for (const c of cases) {run(`${c.name} makes the dependent sentence stale on read, and context_pack withholds it`, async (engine) => {@@ -377,6 +383,26 @@ export function registerPinnedQuestionSuite(label: string, getEngine: () => Braifor (const banned of ['synthesis/acme-widgets', 'notes/retyped-question', 'notes/copied-answer']) expect(chat.calls.join('\n')).not.toContain(banned);});+ run('a quarantined page, and facts projected from it before it was quarantined, are never evidence (#6284)', async (engine) => {+ const s = await seedBrain(engine);+ await putPage(engine, s.sourceId, 'notes/widget-scrape', page('note', 'Widget scrape', 'Scraped listing: acme-example widgets are built in Lisbon by Alice example.'));+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $2 WHERE id = $1', [s.factId, 'notes/widget-scrape']);+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"quarantine": {"reason": "junk_pattern", "detail": "test"}}'::jsonb+ WHERE source_id = $1 AND slug = ANY($2::text[])`, [s.sourceId, ['notes/widget-scrape', 'notes/widget-plan']]);+ const pinned = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { slug_prefix: 'notes/' } }, { chat: stubChat().fn });+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const chat = stubChat();+ await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: chat.fn, leaseOwner: 't', full: true });+ const scoped = await pinQuestion(localCtx(engine, s.sourceId), { question: 'How many employees does acme-example have?', scope: { entity: ENTITY } }, { chat: chat.fn });+ const cited = await engine.executeRaw<{ page_slug: string | null; item_id: string | number | null; kind: string }>(+ 'SELECT page_slug, item_id, kind FROM question_evidence WHERE question_id IN (SELECT id FROM pinned_questions WHERE source_id = $1)', [s.sourceId]);+ expect(cited.map(r => r.page_slug)).not.toContain('notes/widget-scrape');+ expect(cited.map(r => r.page_slug)).not.toContain('notes/widget-plan');+ expect(cited.filter(r => r.kind === 'fact').map(r => Number(r.item_id))).not.toContain(s.factId);+ expect(scoped.receipt.answer!.some(x => x.text.includes('widget sale'))).toBe(true);+ for (const banned of ['notes/widget-scrape', 'notes/widget-plan', '40 employees']) expect(chat.calls.join('\n')).not.toContain(banned);+ });+run('the first answer is a bounded wait: a slow model leaves awaiting_refresh and releases the lease', async (engine) => {const s = await seedBrain(engine);const chat = stubChat();diff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsindex e059b27d04..4d8c8b80d9 100644--- a/test/search-facts-arm.test.ts+++ b/test/search-facts-arm.test.ts@@ -5,7 +5,8 @@* 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;- * the key is on when unset, and with it off the rows are unchanged. PGLite, keyword-only, no network.+ * 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.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -140,4 +141,18 @@ describe('facts arm', () => {expect(stamped[0]!.superseded_claim!.fact_id).toBe(newer.id);} finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }});++ test('a fact whose source page is quarantined is never a facts-arm row, local or remote (#6284)', async () => {+ const lq = 'Where is the Lantern retreat held?';+ await putPage(engine, sourceId, 'notes/lantern-scrape', page('note', 'Lantern scrape', 'Scraped listing about the Lantern retreat venue and its rooms.'));+ const scraped = await engine.insertFact({ fact: 'The Lantern retreat is held in Boise.', kind: 'fact', entity_slug: 'lantern', source: 'extracted', visibility: 'world', valid_from: new Date('2025-08-01T00:00:00Z') }, { source_id: sourceId });+ await engine.executeRaw(`UPDATE facts SET source_markdown_slug = 'notes/lantern-scrape' WHERE id = $1`, [scraped.id]);+ const ids = async (remote: boolean) => (await matchQueryFacts(engine, lq, { sourceId, remote })).map(f => Number(f.id));+ expect(await ids(false)).toContain(Number(scraped.id));+ expect(await ids(true)).toContain(Number(scraped.id));+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"quarantine": {"reason": "junk_pattern", "detail": "test"}}'::jsonb+ WHERE source_id = $1 AND slug = 'notes/lantern-scrape'`, [sourceId]);+ expect(await ids(false)).not.toContain(Number(scraped.id));+ expect(await ids(true)).not.toContain(Number(scraped.id));+ });});