Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: question-ranked recall (scorer, op, CLI)
garrytan85e85c6dab30
diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex f5da8d4c61..37236a2736 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -13,6 +13,7 @@* gbrain recall --include-expired* gbrain recall --as-context # prompt-injection-ready markdown* gbrain recall --json # structured output+ * gbrain recall --question "<q>" # facts ranked by relevance to the question** gbrain forget <fact-id> # durable withdrawal (forget_fact / forget verb)* gbrain forget <fact-id> --purge # owner-only purge (src/commands/forget-purge.ts)@@ -72,6 +73,7 @@ interface ParsedFlags {// MEMORY_VERBS v1 [c4]: recall's verb params, routed through the recall OP// (this hand-rolled CLI otherwise ignores unknown flags silently).query: string | null;+ question: string | null;budgetTokens: number | null;budgetPolicy: string | null;sourceExplicit: boolean;@@ -104,6 +106,7 @@ function parseFlags(args: string[]): ParsedFlags {source: 'default',limit: 50,query: null,+ question: null,budgetTokens: null,budgetPolicy: null,sourceExplicit: false,@@ -142,6 +145,8 @@ function parseFlags(args: string[]): ParsedFlags {out.limit = Number(raw); continue;}if (a === '--query') { out.query = args[++i] ?? null; continue; }+ if (a === '--question') { out.question = args[++i] ?? null; continue; }+ if (a.startsWith('--question=')) { out.question = a.slice('--question='.length); continue; }if (a === '--budget-tokens') { rawBudget = args[++i]; continue; }if (a === '--budget-policy') {const next = args[i + 1];@@ -178,10 +183,10 @@ function parseFlags(args: string[]): ParsedFlags {return out;}-/** Only `--query`/`--budget-tokens` without --budget-policy runs the recall op in-process; every other form has a thin-client path. */+/** Only `--query`/`--budget-tokens` without --budget-policy or --question runs the recall op in-process; every other form has a thin-client path. */export function recallNeedsLocalEngine(args: string[]): boolean {const flags = parseFlags(args);- return flags.budgetPolicy === null && (flags.query !== null || flags.budgetTokens !== null);+ return flags.budgetPolicy === null && flags.question === null && (flags.query !== null || flags.budgetTokens !== null);}function parseSinceParam(raw: string): Date | null {@@ -267,16 +272,18 @@ async function resolveSourceForRecall(export async function runRecall(engine: BrainEngine, args: string[]): Promise<void> {const flags = parseFlags(args);- if (flags.budgetPolicy !== null) {+ if (flags.budgetPolicy !== null || flags.question !== null) {const { MEMORY_VERBS_VERSION, operationsByName, verbError } = await import('../core/operations.ts');const { validateParams } = await import('../mcp/validate-params.ts');const { reportPersistenceCliError } = await import('./persistence-delegate.ts');+ const option = flags.budgetPolicy !== null ? '--budget-policy' : '--question';try {- const error = validateParams(operationsByName.recall, { budget_policy: flags.budgetPolicy })+ const error = (flags.budgetPolicy !== null ? validateParams(operationsByName.recall, { budget_policy: flags.budgetPolicy }) : null)?? (flags.watchSeconds !== null || flags.sinceLastRun || flags.rollup || flags.asContext- ? '--budget-policy cannot be combined with --watch, --since-last-run, --rollup, or --as-context.' : null);- if (error) throw verbError('invalid_params', error,- 'Use --budget-policy facts_first or query_first on a one-shot recall, or omit the policy for CLI-only behavior.');+ ? `${option} cannot be combined with --watch, --since-last-run, --rollup, or --as-context.` : null);+ if (error) throw verbError('invalid_params', error, flags.budgetPolicy !== null+ ? 'Use --budget-policy facts_first or query_first on a one-shot recall, or omit the policy for CLI-only behavior.'+ : 'Use --question on a one-shot recall, or drop it for the watch, cursor, rollup and context renders.');const selector = flags.sourceExplicit ? flags.source : process.env.GBRAIN_SOURCE || undefined;if (selector !== undefined && !SOURCE_ID_RE.test(selector)) {throw verbError('invalid_params', 'recall requires a concrete source id matching [a-z0-9-]{1,32}.',@@ -320,7 +327,7 @@ export async function runRecall(engine: BrainEngine, args: string[]): Promise<vo// MEMORY_VERBS v1 [c4]: the verb params route through the recall OP so the// CLI and MCP exercise the same arm (query/budget packing/superset envelope).- if (flags.query !== null || flags.budgetTokens !== null) {+ if (flags.query !== null || flags.budgetTokens !== null || flags.question !== null) {await runRecallVerb(engine, flags, sourceId);return;}@@ -352,26 +359,30 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?:remote: false as const,sourceId: sourceId ?? 'default',};+ const oneShot = flags.budgetPolicy !== null || flags.question !== null;const params = {...(flags.entity ? { entity: flags.entity } : {}),+ ...(flags.question !== null ? { question: flags.question } : {}),...(flags.query ? { query: flags.query } : {}),...(flags.budgetTokens ? { budget_tokens: flags.budgetTokens } : {}),...(flags.since ? { since: flags.since.toISOString() } : {}),...(flags.grep ? { grep: flags.grep } : {}),include_expired: flags.includeExpired,limit: flags.limit,- ...(flags.budgetPolicy !== null ? {- budget_policy: flags.budgetPolicy,+ ...(oneShot ? {+ ...(flags.budgetPolicy !== null ? { budget_policy: flags.budgetPolicy } : {}),...(sourceId !== undefined ? { source_id: sourceId } : {}),...(flags.sessionId ? { session_id: flags.sessionId } : {}),...(flags.supersessions ? { supersessions: true } : {}),...(flags.pending ? { include_pending: true } : {}),} : {}),};- const result = (flags.budgetPolicy !== null && isThinClient(ctx.config)+ const result = (oneShot && isThinClient(ctx.config)? unpackToolResult(await callRemoteTool(ctx.config, 'recall', params, { timeoutMs: 30_000 })): await op.handler(ctx, params)) as {- facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string }>;+ facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string; relevance?: number }>;+ facts_order?: 'relevance' | 'newest';+ facts_degraded?: { reason?: string; unembedded?: number };results?: Array<{ slug: string; title: string | null; evidence: string; chunk: string | null }>;search_degraded?: string;budget_tokens?: number;@@ -379,15 +390,19 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?:dropped_count?: number;};+ // An older server ignores `question` (warn-mode params) and answers without facts_order.+ const unranked = flags.question !== null && result.facts_order !== 'relevance'+ ? 'note: this brain did not rank facts by the question (its server predates question ranking); facts are newest first.' : null;if (flags.json) {process.stdout.write(JSON.stringify(result, null, 2) + '\n');+ if (unranked) process.stderr.write(unranked + '\n');return;}const lines: string[] = [];if (result.facts.length) {- lines.push('Facts:');+ lines.push(result.facts_order === 'relevance' ? 'Facts (ranked by relevance to the question):' : 'Facts:');for (const f of result.facts) {- lines.push(` #${f.fact_id} [${f.kind}]${f.entity_slug ? ` (${f.entity_slug})` : ''} ${f.fact} — ${f.provenance}`);+ lines.push(` #${f.fact_id} [${f.kind}]${f.entity_slug ? ` (${f.entity_slug})` : ''} ${f.fact} — ${f.provenance}${typeof f.relevance === 'number' ? ` (relevance ${f.relevance.toFixed(2)})` : ''}`);}}if (result.results?.length) {@@ -397,7 +412,12 @@ async function runRecallVerb(engine: BrainEngine, flags: ParsedFlags, sourceId?:if (r.chunk) lines.push(` ${r.chunk.replace(/\s+/g, ' ').slice(0, 160)}`);}}- if (!lines.length) lines.push('Nothing recalled.');+ if (!lines.length) lines.push(result.facts_order === 'relevance' ? 'No saved fact matched the question.' : 'Nothing recalled.');+ if (unranked) lines.push(unranked);+ if (result.facts_degraded) {+ const d = result.facts_degraded;+ lines.push(`note: fact ranking degraded (${[d.reason, d.unembedded ? `${d.unembedded} fact(s) without a comparable embedding` : null].filter(Boolean).join('; ')})`);+ }if (result.search_degraded) lines.push(`note: search degraded (${result.search_degraded})`);if (result.budget_tokens !== undefined) {lines.push(`budget: ${result.budget_used}/${result.budget_tokens} tokens used, ${result.dropped_count} dropped`);diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex d8a2109f13..12b7586580 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -731,7 +731,7 @@ export async function getFactsHealth(exec: LegacyUnscopedRead, source_id: string* either a string ("[0.1,...]") or already-parsed array depending on type* codec — we handle both.*/-interface FactRowSqlShape {+export interface FactRowSqlShape {id: number | bigint;source_id: string;entity_slug: string | null;@@ -775,7 +775,7 @@ const normalizeFactRow = compileRowNormalizer<FactRowSqlShape>({consolidated_at: 'date', embedded_at: 'date', created_at: 'date',});-function rowToFact(raw: FactRowSqlShape): FactRow {+export function rowToFact(raw: FactRowSqlShape): FactRow {const row = normalizeFactRow(raw as unknown as Record<string, unknown>);let embedding: Float32Array | null = null;if (row.embedding != null) {diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.tsnew file mode 100644index 0000000000..24623cc927--- /dev/null+++ b/src/core/facts/question-recall.ts@@ -0,0 +1,256 @@+/**+ * recall's `question` ranking (MEMORY_VERBS v1 additive field): active facts+ * ranked by relevance to the question instead of by recency, inside any+ * `entity`, `session_id`, `since` or `grep` filter. The candidate pool and+ * the score are fact-relevance.ts's (shared with the temporal fact reserve);+ * the read policy is recall's own (source scope, trust floor, quarantine and+ * rederive hiding, remote world-only plus the private-provenance filter).+ * Facts below the admission rule are not returned, so an empty list is a+ * valid answer. One query embedding per call, no model call; the brain's+ * embedding opt-out, a missing provider or a failed embed rank by term share+ * alone and say so in `facts_degraded`.+ */+import type { BrainEngine, FactRow } from '../engine.ts';+import type { Action, Notice } from '../agent-output.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { MEMORY_VERBS_VERSION } from '../verbs.ts';+import { isAvailable } from '../ai/gateway.ts';+import { rowToFact, type FactRowSqlShape } from '../engine-sql/facts.ts';+import { loadEmbeddingQueryPrefix } from '../search/query-prefix.ts';+import { embedQueryBounded, makeQueryEmbedDeadline } from '../search/hybrid.ts';+import { resolveHnswIterativeScan } from '../search/hnsw-iterative-scan.ts';+import {+ QUESTION_ADMISSION_RULES, admitted, collectFactCandidates, countUncomparableFacts, poolEntityPairs, queryTerms, scoreFactCandidates,+ type FactPoolFilters, type FactPoolScope, type QuestionAdmissionRule,+} from '../search/fact-relevance.ts';++export const QUESTION_MAX_CHARS = 2000;+/** Candidates per arm, separate from the output `limit`. */+export const QUESTION_POOL_DEPTH = 100;+/** Which preregistered admission rule ranks recall's `question` (dev-tuned): `reserve` (default) or `facts_arm`. */+export const QUESTION_ADMISSION_KEY = 'recall.question_admission';++export interface FactsDegraded {+ /** Why the cosine arm did not run: recall's search_degraded strings, or no_query_terms. */+ reason?: string;+ /** Facts in the authorized pool the cosine arm could not compare (no vector, another model, a stale hash or other dimensions). */+ unembedded?: number;+}++export type EntityCandidate = { source_id: string; entity_slug: string };++/**+ * The identity key is (source_id, slug): an entity name resolved in several+ * granted sources names different entities unless an entity-identity group+ * links their pages. Merging them would hand the caller a stranger's facts,+ * so federated recall refuses unlinked namesakes and names the candidates.+ * Returns null when the per-source fact lists are one entity.+ */+export async function unlinkedNamesakes(engine: BrainEngine, lists: Array<Array<{ source_id: string; entity_slug: string | null }>>): Promise<EntityCandidate[] | null> {+ const candidates = [...new Map(lists.flat().map((r): [string, EntityCandidate] =>+ [`${r.source_id}:${r.entity_slug}`, { source_id: r.source_id, entity_slug: r.entity_slug as string }])).values()];+ if (candidates.length < 2) return null;+ const { identityIdsForPages } = await import('../entity-identity.ts');+ const ids = await identityIdsForPages(engine, candidates.map(c => ({ sourceId: c.source_id, slug: c.entity_slug })));+ const groups = new Set(candidates.map(c => ids.get(`${c.source_id}:${c.entity_slug}`) ?? null));+ return groups.size === 1 && !groups.has(null) ? null : candidates;+}++/** The call's arguments without transport metadata, for retry fixes. */+function callArgs(p: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(p).filter(([k, v]) => !k.startsWith('_') && v !== undefined));+}++const ARGV_FLAGS: Record<string, string> = { question: '--question', query: '--query', entity: '', since: '--since', session_id: '--session-id', grep: '--grep', limit: '--limit', source_id: '--source-id' };++/** The CLI form of a recall call, for the flags the CLI has. */+export function recallArgv(args: Record<string, unknown>): string[] {+ const argv = ['gbrain', 'recall'];+ for (const [k, flag] of Object.entries(ARGV_FLAGS)) {+ const v = args[k];+ if (v === undefined || v === null || v === '') continue;+ if (flag) argv.push(flag);+ argv.push(String(v));+ }+ return argv;+}++/** An `invalid_params` refusal whose fix is the same recall with `retry` arguments. */+function invalidQuestionCall(message: string, suggestion: string, retry: Record<string, unknown>, why: string) {+ const e = opError('invalid_params', message, suggestion, {+ fix: { argv: recallArgv(retry), mcp: { tool: 'recall', arguments: retry }, consent: [], actor: 'agent', requires_exclusive: false, why },+ });+ e.protocolVersion = MEMORY_VERBS_VERSION;+ return e;+}++/**+ * The validated `question`, or null when absent. Refuses the combinations+ * ranking cannot honor (`supersessions`, `include_expired`) and an over-long+ * question, each with the corrected call as its fix.+ */+export function parseQuestionParam(p: Record<string, unknown>): string | null {+ if (p.question === undefined || p.question === null) return null;+ const args = callArgs(p);+ if (typeof p.question !== 'string') {+ const { question: _q, ...rest } = args;+ throw invalidQuestionCall(`question must be a string, got ${typeof p.question}.`, 'Pass question as a string, or omit it to read facts newest first.', rest, 'The same recall without question.');+ }+ const question = p.question.trim();+ if (!question) return null;+ if (p.supersessions === true) {+ const { supersessions: _s, ...rest } = args;+ throw invalidQuestionCall('question cannot be combined with supersessions: the supersession log is ordered by when facts were replaced, not ranked.',+ 'Drop supersessions to rank active facts, or drop question to read the supersession log.', rest, 'The same recall without supersessions.');+ }+ if (p.include_expired === true) {+ const { include_expired: _e, ...rest } = args;+ throw invalidQuestionCall('question cannot be combined with include_expired: ranking runs over active facts only.',+ 'Drop include_expired to rank active facts, or drop question to list expired facts newest first.', rest, 'The same recall without include_expired.');+ }+ if (question.length > QUESTION_MAX_CHARS) {+ throw invalidQuestionCall(`question is ${question.length} characters; the limit is ${QUESTION_MAX_CHARS}.`,+ `Shorten question to at most ${QUESTION_MAX_CHARS} characters.`, { ...args, question: question.slice(0, QUESTION_MAX_CHARS) }, `The same recall with question cut to ${QUESTION_MAX_CHARS} characters.`);+ }+ return question;+}++/** The configured admission rule; the default (`reserve`) on an unset or unreadable key. */+async function admissionRule(engine: BrainEngine): Promise<QuestionAdmissionRule> {+ const raw = (await engine.getConfig(QUESTION_ADMISSION_KEY).catch(() => null))?.trim().toLowerCase();+ return (QUESTION_ADMISSION_RULES as readonly string[]).includes(raw ?? '') ? raw as QuestionAdmissionRule : 'reserve';+}++/** One bounded query embedding for the question, or why there is none. */+async function questionEmbedding(ctx: OperationContext, question: string): Promise<{ embedding: Float32Array | null; reason?: string }> {+ const { factEmbeddingDisabled } = await import('../embedding-disabled.ts');+ if (await factEmbeddingDisabled(ctx.engine, ctx.config)) return { embedding: null, reason: (await import('../interop-notices.ts')).RECALL_KEYWORD_ONLY_OPTED_OUT };+ if (!isAvailable('embedding')) return { embedding: null, reason: 'keyword_only_no_embedding_provider' };+ try {+ const queryPrefix = await loadEmbeddingQueryPrefix(ctx.engine);+ return { embedding: await embedQueryBounded(question, queryPrefix ? { queryPrefix } : undefined, makeQueryEmbedDeadline()) };+ } catch (error) {+ const timedOut = /deadline|timeout|abort/i.test(error instanceof Error ? `${error.name} ${error.message}` : String(error));+ return { embedding: null, reason: timedOut ? 'embed_timeout' : 'embed_unavailable' };+ }+}++/** A database failure while ranking: `unavailable`, never a silent empty list. */+function rankingUnavailable(p: Record<string, unknown>, error: unknown) {+ const args = callArgs(p);+ const verify: Action['verify'] = { argv: ['gbrain', 'doctor', '--json'] };+ const e = opError('unavailable', 'recall could not rank facts for this question: the facts read failed.', 'Retry the same call in a few seconds; if it keeps failing, run `gbrain doctor --json`.', {+ reason: 'facts_read_failed',+ why: `Reading the fact candidates failed (${error instanceof Error ? error.message.slice(0, 160) : 'unknown error'}); an empty list here would read as "no saved facts".`,+ fix: { argv: recallArgv(args), mcp: { tool: 'recall', arguments: args }, consent: [], actor: 'provider', requires_exclusive: false, why: 'Retry the same recall after a few seconds.', verify },+ });+ e.protocolVersion = MEMORY_VERBS_VERSION;+ return e;+}++export interface QuestionRecallInput {+ question: string;+ params: Record<string, unknown>;+ factSources: string[];+ limit: number;+ scope: FactPoolScope;+ entity: string | null;+ sessionId: string | null;+ since: Date | null;+ grep: string | null;+}++export interface QuestionRecall {+ rows: FactRow[];+ /** fact id → relevance (cosine + term share + 0.1 when dated). */+ relevance: Map<number, number>;+ degraded?: FactsDegraded;+ /** The source holding the most uncomparable facts, for the `embed --stale --facts` fix. */+ unembeddedSource?: string;+ ambiguousEntity: EntityCandidate[] | null;+}++/** Active facts ranked by relevance to `question` under recall's read policy and filters. */+export async function rankFactsByQuestion(ctx: OperationContext, input: QuestionRecallInput): Promise<QuestionRecall> {+ const { question, scope } = input;+ const filters: FactPoolFilters = {+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),+ ...(input.since ? { since: input.since } : {}),+ ...(input.grep ? { grep: input.grep } : {}),+ };+ const empty = (degraded?: FactsDegraded, ambiguousEntity: EntityCandidate[] | null = null): QuestionRecall => ({ rows: [], relevance: new Map(), ambiguousEntity, ...(degraded ? { degraded } : {}) });+ try {+ if (input.entity) {+ const { resolveEntitySlug } = await import('../entities/resolve.ts');+ filters.entities = await Promise.all(input.factSources.map(async src => ({ sourceId: src, slug: (await resolveEntitySlug(ctx.engine, src, input.entity!)) ?? input.entity! })));+ const ambiguous = await unlinkedNamesakes(ctx.engine, [await poolEntityPairs(ctx.engine, scope, filters)]);+ if (ambiguous) return empty(undefined, ambiguous);+ }+ } catch (error) {+ throw rankingUnavailable(input.params, error);+ }+ const { embedding, reason } = await questionEmbedding(ctx, question);+ if (!embedding && queryTerms(question).length === 0) return empty({ reason: 'no_query_terms' });+ try {+ const pool = await collectFactCandidates(ctx.engine, question, scope, embedding, {+ depth: { keyword: QUESTION_POOL_DEPTH, cosine: QUESTION_POOL_DEPTH, entity: QUESTION_POOL_DEPTH }, filters, cosineForAll: true,+ hnswIterativeScan: resolveHnswIterativeScan(ctx.config),+ });+ const rule = await admissionRule(ctx.engine);+ const ranked = scoreFactCandidates(question, pool.candidates).filter(s => admitted(s, rule)).slice(0, input.limit);+ const uncomparable = embedding && pool.column ? await countUncomparableFacts(ctx.engine, scope, filters, embedding.length) : [];+ const unembedded = uncomparable.reduce((n, r) => n + r.n, 0);+ const why = reason ?? (embedding && !pool.column ? 'facts_embedding_column_missing' : undefined);+ const degraded: FactsDegraded | undefined = why || unembedded ? { ...(why ? { reason: why } : {}), ...(unembedded ? { unembedded } : {}) } : undefined;+ const ids = ranked.map(s => s.candidate.id);+ const raw = ids.length+ ? await ctx.engine.executeRaw<FactRowSqlShape>('SELECT * FROM facts WHERE source_id = ANY($1::text[]) AND id = ANY($2::bigint[])', [input.factSources, ids])+ : [];+ const byId = new Map(raw.map(r => { const row = rowToFact(r); return [row.id, { ...row, embedding: null }] as const; }));+ return {+ rows: ids.flatMap(id => byId.get(id) ?? []),+ relevance: new Map(ranked.map(s => [s.candidate.id, Math.round(s.score * 1e4) / 1e4])),+ ambiguousEntity: null,+ ...(degraded ? { degraded } : {}),+ ...(uncomparable[0] ? { unembeddedSource: uncomparable[0].source_id } : {}),+ };+ } catch (error) {+ throw rankingUnavailable(input.params, error);+ }+}++/**+ * TC7: a recall that passed `query` but no `question` and no fact filter got+ * its facts newest first; the hint names `question` and carries the same call+ * with it added.+ */+export function recallHintNotice(p: Record<string, unknown>, queryText: string): Notice {+ const retry = { ...callArgs(p), question: queryText };+ return {+ code: 'recall_hint',+ kind: 'info',+ why: 'The facts in this response are the newest saved facts: `query` searches pages and does not rank facts. `question` ranks saved facts by relevance to a question (it does not search pages).',+ fix: { argv: recallArgv(retry), mcp: { tool: 'recall', arguments: retry }, consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The same recall with question set to the query, so saved facts come back ranked by relevance and pages are still searched.' },+ };+}++/** Notices for a question-ranked recall: facts the cosine arm could not compare, with the preview-then-approve embed fix. */+export function questionRecallNotices(ranking: QuestionRecall): Notice[] {+ const n = ranking.degraded?.unembedded ?? 0;+ if (!n || !ranking.unembeddedSource) return [];+ const base = ['gbrain', 'embed', '--stale', '--facts', '--source', ranking.unembeddedSource];+ return [{+ code: 'facts_unembedded',+ kind: 'degraded',+ why: `${n} saved fact(s) in scope have no embedding this brain can compare with the question (none stored, another embedding model, a changed text or other dimensions), so they were ranked by word overlap alone and a relevant one can be missing.`,+ fix: {+ argv: [...base, '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Previews how many facts in source ${ranking.unembeddedSource} need embedding and what it costs; writes nothing.`,+ then: { argv: [...base, '--yes', '--max-cost-usd', '<usd>'], consent: ['paid'], actor: 'agent', requires_exclusive: false,+ inputs: [{ name: 'usd', how: 'The dollar cap the user approved after seeing the preview.' }],+ why: 'Embeds those facts within the approved cost cap.' },+ },+ }];+}diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex f0e69286e0..8d4b3b6551 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -24,7 +24,8 @@ interface StageGuidance { why: string; fix: StageFix }/** Recall-affecting stages: every DEGRADED_STAGES member except the ranking-only ones, plus the verbs' own markers. */export type RecallStage =| Exclude<DegradedStage, 'reranker_skipped'>- | 'keyword_only_no_embedding_provider' | 'deadline' | 'server_budget';+ | 'keyword_only_no_embedding_provider' | 'deadline' | 'server_budget'+ | 'no_query_terms' | 'facts_embedding_column_missing';/*** The closed guidance map: what each recall-affecting stage means for the@@ -55,6 +56,8 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidanceprojection_status_unknown: { why: 'whether recent writes are in the search index could not be checked', fix: 'doctor' },deadline: { why: 'the pack hit its time limit and is partial', fix: null },server_budget: { why: 'the server ran out of time budget for this pack', fix: null },+ no_query_terms: { why: 'the question has no searchable words and semantic search did not run, so no saved fact could be ranked against it', fix: 'embeddings' },+ facts_embedding_column_missing: { why: 'the facts table has no embedding column, so saved facts were ranked by word overlap alone', fix: 'doctor' },};const NOT_ABSENCE = 'Treat a thin or empty result as "not found with a degraded search", never as "the brain has nothing on this".';@@ -201,6 +204,12 @@ export const QUESTION_EMBED_OPTED_OUT = 'QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLexport const RECALL_KEYWORD_ONLY_OPTED_OUT = 'keyword_only_embedding_disabled';const VECTOR_FALLBACK_WARNINGS: ReadonlySet<string> = new Set(['QUESTION_EMBED_FAILED', QUESTION_EMBED_OPTED_OUT]);+/** recall's `facts_degraded.reason` (question ranking without the cosine arm), when present. */+function factsDegradedReason(r: Record<string, unknown>): string | undefined {+ const reason = (r.facts_degraded as { reason?: unknown } | undefined)?.reason;+ return typeof reason === 'string' ? reason : undefined;+}+/** Did this call run keyword-only because the brain opted out of embedding (not a missing or failing provider)? */export function embeddingOptedOutFor(op: string, result: unknown, meta: Record<string, unknown>): boolean {const r = (result && typeof result === 'object' ? result : {}) as Record<string, unknown>;@@ -208,7 +217,7 @@ export function embeddingOptedOutFor(op: string, result: unknown, meta: Record<sconst retrieval = meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined;return (retrieval?.degraded ?? []).some(d => d.reason === 'embedding_disabled');}- if (op === 'recall') return r.search_degraded === RECALL_KEYWORD_ONLY_OPTED_OUT;+ if (op === 'recall') return r.search_degraded === RECALL_KEYWORD_ONLY_OPTED_OUT || factsDegradedReason(r) === RECALL_KEYWORD_ONLY_OPTED_OUT;if (op === 'think') return Array.isArray(r.warnings) && r.warnings.includes(QUESTION_EMBED_OPTED_OUT);return false;}@@ -220,7 +229,13 @@ export function recallStagesFor(op: string, result: unknown, meta: Record<stringconst retrieval = meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined;return (retrieval?.degraded ?? []).filter(affectsRecall).map(d => d.stage as string);}- if (op === 'recall') return typeof r.search_degraded === 'string' ? ['keyword_only_no_embedding_provider'] : [];+ if (op === 'recall') {+ const facts = factsDegradedReason(r);+ return [...new Set([+ ...(typeof r.search_degraded === 'string' ? ['keyword_only_no_embedding_provider'] : []),+ ...(facts ? [facts === RECALL_KEYWORD_ONLY_OPTED_OUT ? 'keyword_only_no_embedding_provider' : facts] : []),+ ])];+ }if (op === 'context_pack') return typeof r.degraded_reason === 'string' ? [r.degraded_reason] : [];if (op === 'think') {const warned = Array.isArray(r.warnings) && r.warnings.some(w => VECTOR_FALLBACK_WARNINGS.has(String(w)));diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex d9a8c2a117..7e46f814a6 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -48,6 +48,7 @@ import { activationSuppressionNotice, suppressionSummary } from '../eligibility/import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';+import { parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';// ============================================================// v0.31 — Hot memory ops: extract_facts / recall / forget_fact@@ -199,6 +200,26 @@ function packingArm<T>(candidates: T[], kept: T[], cost: (item: T) => number) {return { candidates: candidates.length, kept: kept.length, dropped: candidates.length - kept.length, used: kept.reduce((sum, r) => sum + cost(r), 0) };}+/** recall's budget_packing meta: only policy-supplied calls carry it. */+function recallBudgetPacking<F extends { fact: string }>(policy: unknown, queryText: string | null, budgetTokens: number | null,+ arms: { rows: F[]; packedFacts: F[]; searchResults: SearchResult[]; packedResults: SearchResult[] }) {+ if (policy !== 'facts_first' && policy !== 'query_first') return undefined;+ const queryFirst = policy === 'query_first' && queryText !== null && budgetTokens !== null;+ const { rows, packedFacts, searchResults, packedResults } = arms;+ return {+ policy: queryFirst ? 'query_first' : 'facts_first',+ applied: budgetTokens !== null && (queryFirst || (policy === 'facts_first' && budgetTokens > 0)),+ reason: policy === 'query_first' && !queryText ? 'no_query'+ : budgetTokens === null ? 'no_positive_finite_budget'+ : budgetTokens === 0 ? 'budget_below_one'+ : rows.length + searchResults.length === 0 ? 'no_candidates'+ : packedFacts.length + packedResults.length === 0 ? 'first_items_exceed_budget'+ : 'packed',+ facts: packingArm(rows, packedFacts, r => estimateTokens(r.fact)),+ results: packingArm(searchResults, packedResults, resultTokens),+ };+}+/*** recall's evidence plan: budget_tokens budgets the delivered blocks before* recall's own packing. Without return_unit, budget_tokens or budget_policy@@ -218,9 +239,10 @@ const recall: Operation = {mutating: false,idempotent: true,outputRedaction: { retrieval: { localVerbatim: ['facts'] } },- description: 'MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.',+ description: 'MEMORY VERB (v1): read saved facts by entity, since or session_id, newest first, or ranked by `question`; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.',params: {entity: { type: 'string', description: 'Entity slug; its facts, newest first.' },+ question: { type: 'string', description: 'Rank saved facts by relevance to this question instead of recency; does not search pages. Max 2000 chars.' },query: { type: 'string', description: 'Also search pages (results[]).' },budget_tokens: { type: 'number', description: 'Token budget; facts pack first.' },budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'facts_first (default) or query_first.' },@@ -332,8 +354,10 @@ const recall: Operation = {'Pass an ISO 8601 datetime (e.g. "2026-08-11T00:00:00Z"), Unix epoch millis, or a duration such as "8 hours ago" / "2d".',);}+ const question = parseQuestionParam(p);const entityParam = typeof p.entity === 'string' && p.entity.length > 0 ? (p.entity as string) : null;const sessionParam = typeof p.session_id === 'string' && p.session_id.length > 0 ? (p.session_id as string) : null;+ let ranking: QuestionRecall | null = null;// Shared per-source opts for the fact-list arms (visibility, grep and the// audit exclusion all filter at the ENGINE level, before each source's// LIMIT, so a hidden newest row never consumes a slot).@@ -345,7 +369,12 @@ const recall: Operation = {excludeAuditRows: true, eligibility,};- if (p.supersessions === true) {+ if (question !== null) {+ ranking = await rankFactsByQuestion(ctx, { question, params: p, factSources, limit, entity: entityParam, sessionId: sessionParam, since, grep,+ scope: { sourceIds: factSources, remote: ctx.remote !== false, excludePrivate, minTrust: eligibility.floor, suppressFlagged: eligibility.suppressFlagged } });+ ({ rows, ambiguousEntity } = ranking);+ for (const notice of questionRecallNotices(ranking)) ctx.emitNotice?.(notice);+ } else if (p.supersessions === true) {// Visibility filters at the ENGINE level (before each source's LIMIT),// same as the sibling fact-list arms — a post-merge filter would let a// private newest row consume a limit slot and hide an older world row.@@ -443,6 +472,7 @@ const recall: Operation = {? Math.floor(p.budget_tokens): null;+ if (queryText && question === null && !entityParam && !sessionParam && !since && p.supersessions !== true) ctx.emitNotice?.(recallHintNotice(p, queryText));let searchResults: SearchResult[] = [];let searchDegraded: string | undefined;let delivery: DeliveryMeta | undefined;@@ -511,20 +541,7 @@ const recall: Operation = {droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;}- const budgetPacking = p.budget_policy === 'facts_first' || p.budget_policy === 'query_first'- ? {- policy: queryFirst ? 'query_first' : 'facts_first',- applied: budgetTokens !== null && (queryFirst || (p.budget_policy === 'facts_first' && budgetTokens > 0)),- reason: p.budget_policy === 'query_first' && !queryText ? 'no_query'- : budgetTokens === null ? 'no_positive_finite_budget'- : budgetTokens === 0 ? 'budget_below_one'- : rows.length + searchResults.length === 0 ? 'no_candidates'- : packedFacts.length + packedResults.length === 0 ? 'first_items_exceed_budget'- : 'packed',- facts: packingArm(rows, packedFacts, r => estimateTokens(r.fact)),- results: packingArm(searchResults, packedResults, resultTokens),- }- : undefined;+ const budgetPacking = recallBudgetPacking(p.budget_policy, queryText, budgetTokens, { rows, packedFacts, searchResults, packedResults });return {facts: await withFactDateHeaders(ctx.engine, await stampRowTrust(ctx.engine, 'facts', packedFacts.map(r => ({ // #5575 A6: + trust_tier, origin, unconfirmed@@ -557,8 +574,11 @@ const recall: Operation = {// is the protocol name for the stored source attribution.fact_id: String(r.id),provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),+ ...(ranking ? { relevance: ranking.relevance.get(r.id) } : {}),})), f => f.id)),total: packedFacts.length,+ facts_order: ranking ? 'relevance' : 'newest',+ ...(ranking?.degraded ? { facts_degraded: ranking.degraded } : {}),...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),// MEMORY_VERBS v1 envelope (G1B superset — additive on every response).@@ -589,26 +609,8 @@ const recall: Operation = {},};-type EntityCandidate = { source_id: string; entity_slug: string };const AMBIGUOUS_ENTITY_SUGGESTION = 'These are different entities in different sources. Pass source_id to read one, or link them with entity_identity_link if they are the same.';-/**- * The identity key is (source_id, slug): an entity name resolved in several- * granted sources names different entities unless an entity-identity group- * links their pages. Merging them would hand the caller a stranger's facts,- * so federated recall refuses unlinked namesakes and names the candidates.- * Returns null when the per-source fact lists are one entity.- */-async function unlinkedNamesakes(engine: BrainEngine, lists: FactRow[][]): Promise<EntityCandidate[] | null> {- const candidates = [...new Map(lists.flat().map((r): [string, EntityCandidate] =>- [`${r.source_id}:${r.entity_slug}`, { source_id: r.source_id, entity_slug: r.entity_slug as string }])).values()];- if (candidates.length < 2) return null;- const { identityIdsForPages } = await import('../entity-identity.ts');- const ids = await identityIdsForPages(engine, candidates.map(c => ({ sourceId: c.source_id, slug: c.entity_slug })));- const groups = new Set(candidates.map(c => ids.get(`${c.source_id}:${c.entity_slug}`) ?? null));- return groups.size === 1 && !groups.has(null) ? null : candidates;-}-/** Parse an `entities` param (comma-string or array) to a trimmed name list. */function parseEntityList(v: unknown): string[] {if (Array.isArray(v)) return v.filter((x) => typeof x === 'string' && x.trim()).map((x) => (x as string).trim());diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.tsnew file mode 100644index 0000000000..7daea90ba2--- /dev/null+++ b/src/core/search/fact-relevance.ts@@ -0,0 +1,264 @@+/**+ * Question relevance for saved facts, shared by recall's `question` ranking+ * (src/core/facts/question-recall.ts) and the temporal fact reserve+ * (facts-arm.ts `applyTemporalFactReserve`); the `query` facts arm reads the+ * same candidate pool and keeps its own match rule.+ *+ * Candidates: one bounded pool per call under the caller's read policy+ * (source scope, active rows, audit rows excluded, quarantine and rederive+ * hiding, the trust floor, remote world-only plus the private-provenance+ * filter), optionally narrowed by recall's filters (entity pairs, session,+ * event-time since, escaped grep) inside the SQL. Three arms fill it: keyword+ * (FTS over fact text and entity), cosine (nearest by the question embedding,+ * cast to the facts column type) and the facts of the one entity page the+ * question names, constrained to that page's source.+ *+ * Score: cosine + term share + DATED_BONUS when the writer supplied the date.+ * Term share counts whole words, and its denominator grows with a long fact's+ * own term count, so a fact stuffed with common words cannot match most+ * questions. Order: score, then newest valid_from, then id.+ *+ * Errors: a missing embedding column or a dimension mismatch skips the cosine+ * arm (expected on old or migrating brains); any other database error throws,+ * and each caller picks its policy.+ */+import type { BrainEngine } from '../engine.ts';+import type { TrustTier } from '../trust/tier.ts';+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 { projectionEligibleSql } from '../eligibility/sql.ts';+import { escapeLikePattern } from '../cjk.ts';+import { supportsHnswIterativeScan } from '../vector-index.ts';+import { VECTOR_EXTENSION_VERSION_SQL } from './vector-statement.ts';+import { withVectorSettings } from './vector-settings.ts';+import type { HnswIterativeScanMode } from './hnsw-iterative-scan.ts';++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']);+const WORD_RE = /[\p{L}\p{N}][\p{L}\p{N}'-]+/gu;++/** The question's content terms: distinct words of 3+ characters, stopwords dropped, at most 12. */+export function queryTerms(query: string): string[] {+ return [...new Set(query.toLowerCase().match(WORD_RE) ?? [])].filter(t => t.length >= 3 && !STOPWORDS.has(t)).slice(0, 12);+}++export const DATED_BONUS = 0.1;+/** valid_from this far from created_at means the writer supplied the date. */+const DATED_MIN_MS = 24 * 60 * 60 * 1000;+/** A fact with more content terms than this many times the question's has its term share scaled down (term stuffing). */+export const TERM_STUFFING_RATIO = 3;++/** The two preregistered admission rules; dev picks one (`recall.question_admission`). */+export const QUESTION_ADMISSION_RULES = ['reserve', 'facts_arm'] as const;+export type QuestionAdmissionRule = (typeof QUESTION_ADMISSION_RULES)[number];+const RESERVE_COSINE_MIN = 0.5;+const RESERVE_TERM_SHARE_MIN = 0.34;+const FACTS_ARM_COSINE_MIN = 0.6;++export interface FactPoolScope {+ sourceId?: string; sourceIds?: string[]; remote: boolean;+ /** #5575 read floor and activation control, applied in the pool SQL like every retrieval arm. */+ minTrust?: TrustTier; suppressFlagged?: boolean;+ /** Hide facts whose provenance page is private (resolveExcludePrivatePages for the caller). */+ excludePrivate: boolean;+}++/** recall's fact filters, applied inside every arm before its LIMIT. */+export interface FactPoolFilters {+ /** (source_id, entity_slug) pairs the entity resolved to, one per source. */+ entities?: Array<{ sourceId: string; slug: string }>;+ sessionId?: string;+ /** Event time, COALESCE(valid_from, created_at). */+ since?: Date;+ grep?: string;+}++export interface FactPoolOpts {+ depth: { keyword: number; cosine: number; entity: number };+ filters?: FactPoolFilters;+ /** Score every candidate's cosine, whichever arm found it (recall and the reserve); the facts arm keeps cosine-arm-only similarity. */+ cosineForAll?: boolean;+ /** Set for filtered recall pools: hnsw.ef_search sized to the depth plus pgvector's iterative scan when supported. */+ hnswIterativeScan?: HnswIterativeScanMode;+}++export interface FactCandidate {+ id: number; fact: string; kind: string; entity_slug: string | null; source_id: string; source: string;+ valid_from: Date | string; valid_until: Date | string | null; created_at?: Date | string | null; claim_metric: string | null; claim_period: string | null;+ similarity?: number;+ /** Found by the named-entity arm. */+ entity: boolean;+}++export interface FactPool {+ candidates: FactCandidate[];+ /** Whether the cosine arm ran (an embedding was given and the facts column can be compared with it). */+ cosine: boolean;+ /** Whether the facts table has an embedding column (probed only when an embedding was given). */+ column: boolean;+}++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';++/** The facts embedding column's type and declared dimensions, or null when there is none. */+async function factsEmbeddingColumn(engine: BrainEngine): Promise<{ type: string; dims: number } | null> {+ const [row] = await engine.executeRaw<{ type: string; dims: number }>(+ `SELECT t.typname AS type, a.atttypmod AS dims FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid+ WHERE a.attrelid = to_regclass('facts') AND a.attname = 'embedding' AND NOT a.attisdropped`);+ return row && (row.type === 'vector' || row.type === 'halfvec') ? { type: row.type, dims: Number(row.dims) } : null;+}++/**+ * The pool's WHERE clause and its bound params ($1.. in order): the caller's+ * read policy plus the filters. Arms append their own params after these.+ */+function poolPredicate(scope: FactPoolScope, filters: FactPoolFilters | undefined): { where: string; params: unknown[] } {+ const params: unknown[] = [scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'], [...AUDIT_ROW_SOURCES]];+ const bind = (v: unknown) => { params.push(v); return `$${params.length}`; };+ const clauses = [+ 'f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL',+ '(f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])',+ quarantinedProvenanceFilterFragment('f'),+ ...(scope.remote ? [`f.visibility = 'world'`] : []),+ ...(scope.excludePrivate ? [privateProvenanceFilterFragment('f')] : []),+ projectionEligibleSql('facts', 'f', { floor: scope.minTrust, suppressFlagged: scope.suppressFlagged }),+ ];+ if (filters?.entities) {+ clauses.push(`(f.source_id, f.entity_slug) IN (SELECT * FROM unnest(${bind(filters.entities.map(e => e.sourceId))}::text[], ${bind(filters.entities.map(e => e.slug))}::text[]))`);+ }+ if (filters?.sessionId) clauses.push(`f.source_session = ${bind(filters.sessionId)}`);+ if (filters?.since) clauses.push(`COALESCE(f.valid_from, f.created_at) >= ${bind(filters.since.toISOString())}::text::timestamptz`);+ if (filters?.grep?.trim()) clauses.push(`f.fact ILIKE ${bind(`%${escapeLikePattern(filters.grep.trim())}%`)} ESCAPE '\\'`);+ return { where: clauses.join(' AND '), params };+}++/** The comparable-embedding predicate: same model, current text hash, same dimensions. */+const comparable = (model: string, dims: string) =>+ `f.embedding IS NOT NULL AND f.embedding_model = ${model} AND f.embedded_text_hash = md5(f.fact) AND vector_dims(f.embedding) = ${dims}`;++/**+ * The bounded candidate pool for `question`. Throws on a database error+ * (callers choose fail-open or `unavailable`).+ */+export async function collectFactCandidates(engine: BrainEngine, question: string, scope: FactPoolScope, queryEmbedding: Float32Array | null | undefined,+ opts: FactPoolOpts): Promise<FactPool> {+ const terms = queryTerms(question);+ const { where, params } = poolPredicate(scope, opts.filters);+ const column = queryEmbedding?.length ? await factsEmbeddingColumn(engine) : null;+ const cosine = !!column && (column.dims <= 0 || column.dims === queryEmbedding!.length);+ const armParams = (extra: unknown[]) => [...params, ...extra];+ const vec = cosine ? { lit: `[${Array.from(queryEmbedding!).join(',')}]`, cast: column!.type === 'halfvec' ? '::halfvec' : '::vector' } : null;+ const n = params.length;+ const simParams = vec ? [vec.lit, getEmbeddingModel(), queryEmbedding!.length] : [];+ const simSql = vec ? `CASE WHEN ${comparable(`$${n + 2}`, `$${n + 3}`)} THEN 1 - (f.embedding <=> $${n + 1}${vec.cast}) END AS similarity` : 'NULL::float8 AS similarity';+ const allSim = vec && opts.cosineForAll;+ const found = new Map<number, FactCandidate>();+ const add = (rows: Array<FactCandidate & { similarity?: number | null }>, entity = false) => {+ for (const r of rows) {+ const prev = found.get(Number(r.id));+ const sim = r.similarity === null || r.similarity === undefined ? prev?.similarity : Number(r.similarity);+ found.set(Number(r.id), { ...r, id: Number(r.id), similarity: sim, entity: entity || !!prev?.entity });+ }+ };++ if (terms.length) {+ const p = armParams(allSim ? simParams : []);+ const lang = `$${p.length + 1}`;+ const q = `$${p.length + 2}`;+ const doc = `to_tsvector(${lang}::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' '))`;+ add(await engine.executeRaw(+ `WITH q AS (SELECT NULLIF(replace(plainto_tsquery(${lang}::regconfig, ${q})::text, ' & ', ' | '), '')::tsquery AS q)+ SELECT ${COLS}, ${allSim ? simSql : 'NULL::float8 AS similarity'} FROM facts f, q WHERE ${where} AND q.q IS NOT NULL AND ${doc} @@ q.q+ ORDER BY ts_rank_cd(${doc}, q.q) DESC, f.valid_from DESC, f.id DESC LIMIT $${p.length + 3}`,+ [...p, getFtsLanguage(), terms.join(' '), opts.depth.keyword]));+ }+ if (vec) {+ const p = armParams(simParams);+ const sql = `SELECT ${COLS}, ${simSql} FROM facts f WHERE ${where} AND ${comparable(`$${n + 2}`, `$${n + 3}`)}+ ORDER BY f.embedding <=> $${n + 1}${vec.cast}, f.id DESC LIMIT $${p.length + 1}`;+ const bound = [...p, opts.depth.cosine];+ add(opts.hnswIterativeScan+ ? await engine.transaction(async tx => {+ const iterative = opts.hnswIterativeScan !== 'off'+ && supportsHnswIterativeScan((await tx.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL))[0]?.extversion);+ return withVectorSettings((s, v) => tx.executeRaw(s, v), iterative, opts.depth.cosine, 20_000,+ () => tx.executeRaw<FactCandidate & { similarity: number }>(sql, bound), undefined, opts.hnswIterativeScan);+ })+ : await engine.executeRaw<FactCandidate & { similarity: number }>(sql, bound));+ }+ const sourceIds = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];+ const named = await namedEntity(engine, question, { sourceIds, excludePrivate: scope.excludePrivate });+ if (named) {+ const p = armParams(allSim ? simParams : []);+ add(await engine.executeRaw(+ `SELECT ${COLS}, ${allSim ? simSql : 'NULL::float8 AS similarity'} FROM facts f WHERE ${where} AND f.source_id = $${p.length + 1} AND f.entity_slug = $${p.length + 2}+ ORDER BY f.valid_from DESC, f.id DESC LIMIT $${p.length + 3}`,+ [...p, named.source_id, named.slug, opts.depth.entity]), true);+ }+ return { candidates: [...found.values()], cosine, column: !!column };+}++/**+ * Facts in the same authorized, filtered pool that the cosine arm cannot+ * compare (no vector, another model, a stale text hash or other+ * dimensions), per source. Only meaningful when an embedding was compared.+ */+export async function countUncomparableFacts(engine: BrainEngine, scope: FactPoolScope, filters: FactPoolFilters | undefined, dims: number): Promise<Array<{ source_id: string; n: number }>> {+ const { where, params } = poolPredicate(scope, filters);+ const rows = await engine.executeRaw<{ source_id: string; n: number | string }>(+ `SELECT f.source_id, count(*) AS n FROM facts f WHERE ${where} AND NOT (${comparable(`$${params.length + 1}`, `$${params.length + 2}`)})+ GROUP BY f.source_id ORDER BY count(*) DESC, f.source_id`, [...params, getEmbeddingModel(), dims]);+ return rows.map(r => ({ source_id: r.source_id, n: Number(r.n) }));+}++/** The distinct (source_id, entity_slug) pairs with a fact in the authorized, filtered pool (the namesake check runs on these before any ranking). */+export async function poolEntityPairs(engine: BrainEngine, scope: FactPoolScope, filters: FactPoolFilters): Promise<Array<{ source_id: string; entity_slug: string }>> {+ const { where, params } = poolPredicate(scope, filters);+ return engine.executeRaw<{ source_id: string; entity_slug: string }>(+ `SELECT DISTINCT f.source_id, f.entity_slug FROM facts f WHERE ${where} AND f.entity_slug IS NOT NULL ORDER BY f.source_id, f.entity_slug`, params);+}++export interface ScoredFact {+ candidate: FactCandidate;+ cosine: number;+ /** Whole-word content terms of the question the fact holds. */+ matched: number;+ /** The question's content-term count. */+ terms: number;+ termShare: number;+ score: number;+}++const wordsOf = (c: FactCandidate) => {+ const slug = c.entity_slug ?? '';+ return new Set(`${c.fact} ${slug} ${slug.replace(/-/g, ' ')}`.toLowerCase().match(WORD_RE) ?? []);+};++export const isDatedFact = (f: Pick<FactCandidate, 'valid_from' | 'created_at'>) =>+ !!f.created_at && Math.abs(new Date(f.valid_from).getTime() - new Date(f.created_at).getTime()) > DATED_MIN_MS;++/** Score every candidate (cosine + term share + DATED_BONUS when dated), ordered by score, newest valid_from, then id. */+export function scoreFactCandidates(question: string, candidates: FactCandidate[]): ScoredFact[] {+ const terms = queryTerms(question);+ return candidates.map(c => {+ const words = wordsOf(c);+ const matched = terms.filter(t => words.has(t)).length;+ const factTerms = [...words].filter(w => w.length >= 3 && !STOPWORDS.has(w)).length;+ const termShare = terms.length ? matched / Math.max(terms.length, Math.ceil(factTerms / TERM_STUFFING_RATIO)) : 0;+ const cosine = c.similarity ?? 0;+ return { candidate: c, cosine, matched, terms: terms.length, termShare, score: cosine + termShare + (isDatedFact(c) ? DATED_BONUS : 0) };+ }).sort((a, b) => b.score - a.score+ || new Date(b.candidate.valid_from).getTime() - new Date(a.candidate.valid_from).getTime()+ || b.candidate.id - a.candidate.id);+}++/** Whether a scored fact passes the admission rule. */+export function admitted(s: ScoredFact, rule: QuestionAdmissionRule): boolean {+ if (rule === 'reserve') return s.cosine >= RESERVE_COSINE_MIN || s.termShare >= RESERVE_TERM_SHARE_MIN;+ return s.candidate.entity || s.cosine >= FACTS_ARM_COSINE_MIN+ || (s.terms > 0 && s.matched >= Math.max(Math.min(2, s.terms), Math.ceil(s.terms / 2)));+}diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 3da28c8a7d..955d31e376 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -1,8 +1,8 @@/**- * Facts arm for `query` (`search.query_facts_arm`, default off; gates in+ * Facts arm for `query` (`search.query_facts_arm`, default on; gates in* docs/eval/decisions/query-facts-arm/). A correction saved with `remember`* lives in the facts table, which page search never ranks, so the stale page- * text answers instead. With the key on, `query` adds the active facts that+ * text answers instead. Unless the key is off, `query` adds the active facts that* match the question as rows of their own, inside the caller's row count and* token budget, and stamps a page row `superseded_claim` when a newer active* fact covers the same entity and typed claim slot as a fact taken from that@@ -11,25 +11,23 @@* Matching: query terms against the fact text and entity (at least half of* the content terms), cosine against the query embedding hybrid search* already computed (no extra model call; skipped when there is none), and the- * facts of the one entity page the query names. Matches are ordered newest+ * facts of the one entity page the query names (in that page's source); the+ * candidate pool is fact-relevance.ts's. Matches are ordered newest* valid_from first. Read policy is recall's: source scope, active rows only,* audit rows excluded, and world-visible facts with non-private provenance* for remote callers.*/import type { BrainEngine } from '../engine.ts';import type { PageReadScope, SearchResult } from '../types.ts';-import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';-import { getFtsLanguage } from '../fts-language.ts';-import { getEmbeddingModel } from '../ai/gateway.ts';-import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from './private-visibility.ts';-import { quarantinedProvenanceFilterFragment } from '../quarantine.ts';-import { namedEntity } from './entity-anchor.ts';+import { resolveExcludePrivatePages } from './private-visibility.ts';+import { admitted, collectFactCandidates, queryTerms, scoreFactCandidates, type FactCandidate as PoolCandidate, type FactPoolScope } from './fact-relevance.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 { queryTerms } from './fact-relevance.ts';+export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';/** Fact rows added per query at most. */export const MAX_FACT_ROWS = 3;@@ -45,11 +43,6 @@ export const TEMPORAL_RESERVE_SHARE = 0.15;export const MAX_RESERVE_ROWS = 20;/** Share of the caller's row count reserved facts may take (at least one row). */export const TEMPORAL_RESERVE_ROW_SHARE = 0.3;-const RESERVE_COSINE_MIN = 0.5;-const RESERVE_TERM_SHARE_MIN = 0.34;-const DATED_BONUS = 0.1;-/** valid_from this far from created_at means the writer supplied the date. */-const DATED_MIN_MS = 24 * 60 * 60 * 1000;const MONTHS = 'january|february|march|april|may|june|july|august|september|october|november|december';const TEMPORAL_CUE = new RegExp(`\\b(when|before|after|since|until|till|during|ago|earlier|later|earliest|latest|first|last|previous|next|dates?|day|week|month|year|order|sequence|${MONTHS})\\b`+ `|\\bhow (long|many (days|weeks|months|years))\\b|\\bwhat time\\b|\\b\\d{4}-\\d{2}-\\d{2}\\b`, 'i');@@ -59,87 +52,27 @@ export function hasTemporalCue(query: string): boolean {return TEMPORAL_CUE.test(query);}-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;/** #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;- valid_from: Date | string; valid_until: Date | string | null; created_at?: Date | string | null; claim_metric: string | null; claim_period: string | null;-}+type FactCandidate = PoolCandidate;-export function queryTerms(query: string): string[] {- return [...new Set(query.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}'-]+/gu) ?? [])].filter(t => t.length >= 3 && !STOPWORDS.has(t)).slice(0, 12);+async function poolScope(engine: BrainEngine, scope: FactsArmScope): Promise<FactPoolScope> {+ return { ...scope, excludePrivate: await resolveExcludePrivatePages(engine, scope.remote) };}const day = (v: Date | string | null) => (v ? new Date(v).toISOString().slice(0, 10) : null);-type ScoredCandidate = FactCandidate & { similarity?: number; matched: number; terms: number; entity: boolean };--/**- * Active facts near `query` under the caller's read policy: the keyword- * matches (with how many query terms each holds), the `cosineLimit` nearest by- * the query embedding (with their similarity), and the named entity's newest- * `entityLimit` facts.- */-async function collectFactCandidates(engine: BrainEngine, query: string, scope: FactsArmScope, queryEmbedding: Float32Array | null | undefined,- limits: { cosine: number; entity: number }): Promise<ScoredCandidate[]> {- const terms = queryTerms(query);- const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];- const params: unknown[] = [sources, [...AUDIT_ROW_SOURCES]];- const excludePrivate = await resolveExcludePrivatePages(engine, scope.remote);- 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 ${quarantinedProvenanceFilterFragment('f')}- ${scope.remote ? `AND f.visibility = 'world'` : ''} ${excludePrivate ? `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) => {- const prev = found.get(Number(r.id));- const haystack = r.haystack ?? `${r.fact} ${r.entity_slug ?? ''}`.toLowerCase();- found.set(Number(r.id), { ...r, similarity: r.similarity !== undefined ? Number(r.similarity) : prev?.similarity,- matched: terms.filter(t => haystack.includes(t)).length, terms: terms.length, entity: entity || !!prev?.entity });- };- if (terms.length) {- const rows = await engine.executeRaw<FactCandidate & { haystack: string }>(- `WITH q AS (SELECT NULLIF(replace(plainto_tsquery($3::regconfig, $4)::text, ' & ', ' | '), '')::tsquery AS q)- SELECT ${cols}, lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack- FROM facts f, q WHERE ${base} AND q.q IS NOT NULL- AND to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')) @@ q.q- ORDER BY ts_rank_cd(to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')), q.q) DESC, f.valid_from DESC- LIMIT 50`, [...params, getFtsLanguage(), terms.join(' ')]);- for (const r of rows) add(r);- }- if (queryEmbedding && queryEmbedding.length) {- const model = getEmbeddingModel();- const lit = `[${Array.from(queryEmbedding).join(',')}]`;- const rows = await engine.executeRaw<FactCandidate & { similarity: number }>(- `SELECT ${cols}, 1 - (f.embedding <=> $3::vector) AS similarity FROM facts f- WHERE ${base} AND f.embedding IS NOT NULL AND f.embedding_model = $4 AND f.embedded_text_hash = md5(f.fact)- AND vector_dims(f.embedding) = $5- ORDER BY f.embedding <=> $3::vector LIMIT ${limits.cosine}`, [...params, lit, model, queryEmbedding.length]).catch(() => []);- for (const r of rows) add(r);- }- const entity = await namedEntity(engine, query, { sourceIds: sources, excludePrivate }).catch(() => null);- if (entity) {- const rows = await engine.executeRaw<FactCandidate>(- `SELECT ${cols} FROM facts f WHERE ${base} AND f.entity_slug = $3 ORDER BY f.valid_from DESC, f.id DESC LIMIT ${limits.entity}`,- [...params, entity.slug]);- for (const r of rows) add(r, true);- }- return [...found.values()];-}-/** The active facts that match `query`, newest valid_from first (at most MAX_FACT_ROWS). */export async function matchQueryFacts(engine: BrainEngine, query: string, scope: FactsArmScope, queryEmbedding?: Float32Array | null): Promise<FactCandidate[]> {- const candidates = await collectFactCandidates(engine, query, scope, queryEmbedding, { cosine: 10, entity: MAX_FACT_ROWS });+ const { candidates } = await collectFactCandidates(engine, query, await poolScope(engine, scope), queryEmbedding, { depth: { keyword: 50, cosine: 10, entity: MAX_FACT_ROWS } });+ const terms = queryTerms(query);+ const matched = (c: FactCandidate) => { const haystack = `${c.fact} ${c.entity_slug ?? ''}`.toLowerCase(); return terms.filter(t => haystack.includes(t)).length; };return candidates- .filter(c => c.entity || (c.similarity ?? -1) >= FACT_COSINE_MIN || (c.terms > 0 && c.matched >= Math.max(Math.min(2, c.terms), Math.ceil(c.terms * TERM_SHARE_MIN))))+ .filter(c => c.entity || (c.similarity ?? -1) >= FACT_COSINE_MIN || (terms.length > 0 && matched(c) >= Math.max(Math.min(2, terms.length), Math.ceil(terms.length * TERM_SHARE_MIN)))).sort((a, b) => new Date(b.valid_from).getTime() - new Date(a.valid_from).getTime() || Number(b.id) - Number(a.id)).slice(0, MAX_FACT_ROWS);}@@ -241,12 +174,11 @@ export async function applyFactsArm(engine: BrainEngine, query: string, results:}}-const isDated = (f: FactCandidate) => !!f.created_at && Math.abs(new Date(f.valid_from).getTime() - new Date(f.created_at).getTime()) > DATED_MIN_MS;-/*** Temporal fact reserve: for a query with a temporal cue and a token budget,- * the facts that best match the question (cosine + term share, +0.1 when the- * fact carries a real date) take up to TEMPORAL_RESERVE_SHARE of the budget and+ * the facts that best match the question (the shared scorer in+ * fact-relevance.ts: cosine + term share, +0.1 when the fact carries a real+ * date, admitted by the reserve rule) take up to TEMPORAL_RESERVE_SHARE of the budget and* TEMPORAL_RESERVE_ROW_SHARE of the row count (1 to MAX_RESERVE_ROWS rows), rendered with their date header and ordered oldest* first after the pages. The row count never grows (a fact takes a free row,* else the lowest page row) and pages fill the rest of the budget. No match or@@ -254,12 +186,9 @@ const isDated = (f: FactCandidate) => !!f.created_at && Math.abs(new Date(f.vali*/export async function applyTemporalFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {try {- const candidates = await collectFactCandidates(engine, query, opts, opts.queryEmbedding, { cosine: 50, entity: MAX_RESERVE_ROWS });- const scored = candidates- .map(c => ({ c, share: c.terms ? c.matched / c.terms : 0, cos: c.similarity ?? 0 }))- .filter(x => x.cos >= RESERVE_COSINE_MIN || x.share >= RESERVE_TERM_SHARE_MIN)- .map(x => ({ c: x.c, score: x.cos + x.share + (isDated(x.c) ? DATED_BONUS : 0) }))- .sort((a, b) => b.score - a.score || Number(b.c.id) - Number(a.c.id));+ const { candidates } = await collectFactCandidates(engine, query, await poolScope(engine, opts), opts.queryEmbedding,+ { depth: { keyword: 50, cosine: 50, entity: MAX_RESERVE_ROWS }, cosineForAll: true });+ const scored = scoreFactCandidates(query, candidates).filter(s => admitted(s, 'reserve')).map(s => ({ c: s.candidate }));if (!scored.length) return results;const rowCap = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0);const pageSlugs = await readableEntityPages(engine, scored.map(x => x.c), opts.readScope).catch(() => new Set<string>());