Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search: explain — per-arm RRF attribution, score_details, explain/explain_target on search and query

garrytan772bd21dddf9
diff --git a/src/cli.ts b/src/cli.ts
index a8396d1fae..9ea51b1cf0 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1646,6 +1646,8 @@ export function formatResult(
if (answerId && results.length > 0) process.stderr.write(`answer: ${answerId} (rate with: gbrain rate ${answerId} 1-5)\n`);
if (params.json === true) {
if (incompleteNotice) process.stderr.write(incompleteNotice);
+ // --explain --json: the same per-row score_details object MCP `explain: true` returns.
+ if (getCliOptions().explain) for (const r of results) r.score_details ??= require('./core/search/explain-formatter.ts').buildScoreDetails(r);
return JSON.stringify(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, null, 2) + '\n';
}
// T15/FOV-1: an empty result names its cause when the pipeline told us
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 33b1a75108..76106b21b2 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -29,6 +29,9 @@ import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
+import { buildScoreDetails } from '../search/explain-formatter.ts';
+import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
+import type { Notice } from '../agent-output.ts';
import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
@@ -83,6 +86,8 @@ type SourceScope = { sourceId?: string; sourceIds?: string[] };
function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,
evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {
const rows = resultRowsFor(ctx, p.fields);
+ // `explain: true` — every row carries its score breakdown (kept in lean rows).
+ if (p.explain === true) for (const r of results) r.score_details = buildScoreDetails(r);
// The shape is reported where it can vary: remote callers, or an explicit `fields`.
const shown = ctx.remote !== false || p.fields !== undefined ? { rows } : {};
if (!evidence) {
@@ -500,6 +505,66 @@ const TYPES_PARAM_DESCRIPTION = "Page types, e.g. ['person'].";
const SOURCE_ID_PARAM_DESCRIPTION = "One source, or '__all__'.";
const SALIENCE_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: 'Boost emotional pages (default: auto).' };
+
+/** Ranking explanation params shared by `search` and `query`. */
+const EXPLAIN_PARAMS = {
+ explain: { type: 'boolean' as const, description: 'true: each row gets score_details (which retrieval arms found it, at what rank, and every ranking factor). Use when a result looks wrong.' },
+ explain_target: { type: 'string' as const, description: 'Slug of a page you expected but did not get; the response meta explain_target says which stage lost it and what to do next.' },
+ explain_target_source: { type: 'string' as const, description: 'Source id of explain_target when the slug exists in several sources.' },
+};
+
+/**
+ * explain_target, before the search: resolve the target among the pages this
+ * caller can read (one probe under the same scope and visibility the search
+ * uses). Returns the trace to thread into the search, or an early diagnosis
+ * (not visible / ambiguous) that needs no trace.
+ */
+async function prepareExplainTarget(
+ ctx: OperationContext, p: Record<string, unknown>, scope: SourceScope, excludePrivate: boolean, tool: 'search' | 'query',
+): Promise<{ trace?: TargetTrace; early?: ExplainTargetDiagnosis } | null> {
+ if (typeof p.explain_target !== 'string' || p.explain_target.trim() === '') return null;
+ const slug = p.explain_target.trim();
+ const sourceId = typeof p.explain_target_source === 'string' && p.explain_target_source ? p.explain_target_source : undefined;
+ const retry = { tool, arguments: explainRetryArgs(p) };
+ let probe;
+ try {
+ probe = await probeTarget((sql, params) => ctx.engine.executeRaw(sql, params), slug,
+ { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false });
+ } catch {
+ return { trace: new TargetTrace({ slug, sourceId }) };
+ }
+ const early = diagnoseProbe({ slug, sourceId }, probe, { requireSafeChunks: ctx.remote !== false, retry });
+ if (early && (early.code === 'target_not_found_or_not_visible' || early.code === 'target_ambiguous')) return { early };
+ const resolvedSource = sourceId ?? (probe.length === 1 ? probe[0].source_id : undefined);
+ return { trace: new TargetTrace({ slug, sourceId: resolvedSource }), ...(early ? { early } : {}) };
+}
+
+/** The caller's search arguments, minus explain params, so every fix is a complete retry call. */
+function explainRetryArgs(p: Record<string, unknown>): Record<string, unknown> {
+ const { explain: _e, explain_target: _t, explain_target_source: _s, ...rest } = p;
+ return rest;
+}
+
+/** explain_target, after the search: diagnose, refine an unretrieved target with the probe, and emit the fix as a notice. */
+function finishExplainTarget(
+ ctx: OperationContext, p: Record<string, unknown>, prep: { trace?: TargetTrace; early?: ExplainTargetDiagnosis } | null,
+ results: SearchResult[], tool: 'search' | 'query',
+): ExplainTargetDiagnosis | undefined {
+ if (!prep) return undefined;
+ let diag = prep.early;
+ if (prep.trace) {
+ const traced = diagnoseTrace(prep.trace, results, { tool, arguments: explainRetryArgs(p) });
+ // A probe finding (no chunks / stale projection / unsealed) explains an unretrieved page better than "no arm found it".
+ diag = traced.state === 'not_retrieved' && prep.early ? { ...prep.early, stages: traced.stages } : traced;
+ }
+ if (diag?.fix) {
+ const notice: Notice = { code: diag.code, kind: 'info', why: diag.why, fix: diag.fix };
+ ctx.emitNotice?.(notice);
+ }
+ if (!diag) return undefined;
+ const { fix: _fix, ...wire } = diag;
+ return wire as ExplainTargetDiagnosis;
+}
const RECENCY_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'], description: "Boost recent pages (default: auto)." };
const SNIPPET_CHARS_PARAM_DESCRIPTION = 'Max chars per chunk_text (0 = full).';
@@ -554,6 +619,7 @@ const search: Operation = {
salience: SALIENCE_PARAM,
recency: RECENCY_PARAM,
fields: FIELDS_PARAM,
+ ...EXPLAIN_PARAMS,
},
handler: async (ctx, p) => {
const startedAt = Date.now();
@@ -621,6 +687,7 @@ const search: Operation = {
// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
// expansion OFF (no per-call LLM cost). `query` op is the full-control variant.
let capturedMeta: HybridSearchMeta | null = null;
+ const explainPrep = await prepareExplainTarget(ctx, p, scope, excludePrivate, 'search');
const searchOpts = {
limit,
offset,
@@ -636,7 +703,9 @@ const search: Operation = {
recency: p.recency as 'off' | 'on' | 'strong' | undefined,
decide: { remote: ctx.remote !== false },
};
- const primary = await hybridSearchCached(ctx.engine, queryText, { ...searchOpts, onMeta: (m) => { capturedMeta = m; } });
+ const primary = await hybridSearchCached(ctx.engine, queryText, {
+ ...searchOpts, onMeta: (m) => { capturedMeta = m; }, ...(explainPrep?.trace ? { explainTarget: explainPrep.trace } : {}),
+ });
const declarations = new DeclarationMemo();
const results = (await withDeclaredNameFanOut(primary, queryText, declarations,
(alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 }))).map(r => ({ ...r }));
@@ -645,8 +714,12 @@ const search: Operation = {
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
+ const explainTarget = finishExplainTarget(ctx, p, explainPrep, results, 'search');
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
- rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' }));
+ async rows => ({
+ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' })),
+ ...(explainTarget ? { explain_target: explainTarget } : {}),
+ }));
},
scope: 'read', mutating: false,
cliHints: { name: 'search', positional: ['query'] },
@@ -715,6 +788,7 @@ const query: Operation = {
adaptive_return: { type: 'boolean', description: 'true when one answer is wanted (fewer rows; never returns empty); omit for breadth.' },
autocut: { type: 'boolean', description: 'Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return.' },
relational: { type: 'boolean', description: 'Relationship-graph arm (default on).' },
+ ...EXPLAIN_PARAMS,
},
handler: async (ctx, p) => {
const startedAt = Date.now();
@@ -822,6 +896,7 @@ const query: Operation = {
const typeFilter = await reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types);
types = typeFilter.types;
let capturedMeta: HybridSearchMeta | null = null;
+ const explainPrep = await prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query');
// v0.32.x search-lite: route the query op through hybridSearchCached so
// token budget and intent weighting apply at the operation boundary.
// Semantic cache reuse is suspended in the wrapper.
@@ -879,6 +954,7 @@ const query: Operation = {
autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : undefined,
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
+ ...(explainPrep?.trace ? { explainTarget: explainPrep.trace } : {}),
});
const declarations = new DeclarationMemo();
results = await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
@@ -1043,8 +1119,13 @@ const query: Operation = {
// #1663: the CRAG grade rides the same retrieval meta channel.
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
+ const explainTarget = finishExplainTarget(ctx, p, explainPrep, results, 'query');
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
- async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag }));
+ async rows => ({
+ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })),
+ crag,
+ ...(explainTarget ? { explain_target: explainTarget } : {}),
+ }));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.ts
index 2be4c1cc08..3278827f7c 100644
--- a/src/core/search/explain-formatter.ts
+++ b/src/core/search/explain-formatter.ts
@@ -48,6 +48,12 @@ export function formatResultExplain(
// (result wasn't routed through runPostFusionStages), fall back to
// final score and label "no boosts applied" downstream.
const base = result.base_score ?? result.score;
+ // Which retrieval arm instances found this row, at what rank, and their
+ // RRF contribution (page votes on the lead chunk, own votes otherwise).
+ if (result.rrf && result.rrf.arms.length > 0) {
+ const found = result.rrf.arms.map(v => `${v.arm} #${v.rank + 1} (+${fmt(v.contribution)})`).join(', ');
+ lines.push(` found by: ${found}`);
+ }
lines.push(` base=${fmt(base)} (rrf+cosine)`);
// v0.46.15: raw query↔chunk cosine (the calibrated semantic signal evidence
// keys off). Absent on keyword-only / no-embedding paths.
@@ -59,7 +65,8 @@ export function formatResultExplain(
if (result.backlink_boost !== undefined && result.backlink_boost !== 1.0) {
anyBoost = true;
- lines.push(` + backlink ×${fmt(result.backlink_boost)}`);
+ const inbound = result.backlink_count !== undefined ? ` (${result.backlink_count} inbound${result.backlink_hub_weight !== undefined ? `, hub weight ${fmt(result.backlink_hub_weight)}` : ''})` : '';
+ lines.push(` + backlink ×${fmt(result.backlink_boost)}${inbound}`);
}
if (result.salience_boost !== undefined && result.salience_boost !== 1.0) {
anyBoost = true;
@@ -189,6 +196,63 @@ export function formatResultsExplain(
return head.length > 0 ? `${head.join('\n')}\n\n${body}` : body;
}
+/** A ranking stage's state in score_details: it ran, was skipped (with why), or never ran on this path. */
+export type StageState<T> = ({ state: 'applied' } & T) | { state: 'skipped' | 'not_run'; reason: string };
+
+/** Stable per-result score breakdown returned by `search`/`query` with `explain: true`. */
+export interface ScoreDetails {
+ /** The row's final score. */
+ final: number;
+ /** Arm-instance votes; `rank` is 1-based for display, `fusion_rank` the 0-based rank RRF used. */
+ arms: Array<{ arm: string; rank: number; fusion_rank: number; k: number; weight: number; contribution: number; vote: 'page' | 'chunk'; chunk_id?: number }>;
+ rrf: StageState<{ raw: number; normalized: number; compiled_truth_boost: number }>;
+ blend: StageState<{ rrf_weight: number; norm_rrf: number; cosine_weight: number; cosine: number }>;
+ /** Score entering the post-fusion boost stages. */
+ base_score: number | null;
+ /** Multiplicative factors applied after fusion, by stage (only stages that changed this row). */
+ boosts: Record<string, { factor: number } & Record<string, unknown>>;
+ rerank: StageState<{ score: number; delta: number | null; pinned: boolean }>;
+}
+
+/**
+ * Pure projection of the stamps every ranking stage leaves on a row into one
+ * stable object. Absent stamps become `not_run`/`skipped` states rather than
+ * invented values, so the breakdown never claims a stage it did not observe.
+ */
+export function buildScoreDetails(result: SearchResult): ScoreDetails {
+ const arms = (result.rrf?.arms ?? []).map(v => ({
+ arm: v.arm, rank: v.rank + 1, fusion_rank: v.rank, k: v.k, weight: v.weight,
+ contribution: v.contribution, vote: v.vote, ...(v.chunk_id !== undefined ? { chunk_id: v.chunk_id } : {}),
+ }));
+ const rrf: ScoreDetails['rrf'] = result.rrf
+ ? { state: 'applied', raw: result.rrf.raw, normalized: result.rrf.normalized, compiled_truth_boost: result.rrf.compiled_truth_boost }
+ : { state: 'not_run', reason: 'single_arm_path' };
+ const blend: ScoreDetails['blend'] = result.blend_norm_rrf !== undefined && typeof result.cosine === 'number'
+ ? { state: 'applied', rrf_weight: 0.7, norm_rrf: result.blend_norm_rrf, cosine_weight: 0.3, cosine: result.cosine }
+ : { state: 'not_run', reason: 'no_query_embedding' };
+ const boosts: ScoreDetails['boosts'] = {};
+ const add = (name: string, factor: number | undefined, detail: Record<string, unknown> = {}) => {
+ if (factor === undefined || factor === 1) return;
+ const clean = Object.fromEntries(Object.entries(detail).filter(([, v]) => v !== undefined));
+ boosts[name] = { factor, ...clean };
+ };
+ add('backlink', result.backlink_boost, { inbound: result.backlink_count, hub_weight: result.backlink_hub_weight });
+ add('salience', result.salience_boost);
+ add('recency', result.recency_boost);
+ add('chronicle', result.chronicle_boost);
+ add('title', result.title_match_boost);
+ add('adjacency', result.graph_adjacency_boost, { hits: result.graph_adjacency_hits, hub_weight: result.graph_hub_weight });
+ add('cross_source', result.graph_cross_source_boost, { other_sources: result.graph_cross_source_hits, hub_weight: result.graph_hub_weight });
+ add('session_demote', result.session_demote_factor, { prefix: result.graph_session_prefix });
+ add('alias_resolved', result.alias_resolved_boost);
+ add('supersede', result.supersede_penalty, { superseded_by: result.superseded_by });
+ add('exact_match', result.exact_match_boost);
+ const rerank: ScoreDetails['rerank'] = result.rerank_score !== undefined
+ ? { state: 'applied', score: result.rerank_score, delta: result.reranker_delta ?? null, pinned: result.relational_pinned === true }
+ : { state: 'not_run', reason: 'reranker_off_or_outside_head' };
+ return { final: result.score, arms, rrf, blend, base_score: result.base_score ?? null, boosts, rerank };
+}
+
/**
* Compact number formatter. Drops trailing zeros for readability; 4
* decimal places of precision is plenty for ranking scores (RRF lands
diff --git a/src/core/search/explain-target.ts b/src/core/search/explain-target.ts
new file mode 100644
index 0000000000..2802b46858
--- /dev/null
+++ b/src/core/search/explain-target.ts
@@ -0,0 +1,234 @@
+/**
+ * explain-target.ts — "why is this page missing from my results?"
+ *
+ * A `TargetTrace` rides one hybridSearch call (HybridSearchOpts.explainTarget)
+ * and records, at each pipeline stage, whether the target page was present
+ * and at what rank: every retrieval arm instance, the keyword arm before and
+ * after relaxed-row demotion, fusion, dedup, rerank, return sizing (autocut,
+ * adaptive return, identity tiers, relational evidence slot), the limit slice
+ * and the token budget. `diagnoseTrace` turns those observations into one
+ * state — retrieved / dropped / reinjected / not_retrieved / not_recorded —
+ * naming the first stage that lost the page. It never claims a cause it did
+ * not observe: boost stages only re-order (they are reported through
+ * score_details, never as a drop), and a stage the path never ran is absent
+ * from the observations rather than guessed.
+ *
+ * When no arm retrieved the page, `probeTarget` runs ONE read under the
+ * caller's read policy to tell "not indexed" from "not retrieved". A page the
+ * caller cannot read and a page that does not exist return the same
+ * `target_not_found_or_not_visible`, so the diagnosis never leaks existence.
+ *
+ * Tracking runs only when a target is set; normal searches pay nothing.
+ */
+
+import type { SearchResult, PageReadPolicy } from '../types.ts';
+import type { Action } from '../agent-output.ts';
+import { pageReadFilter } from './read-policy-sql.ts';
+import { belowSafeChunkFence } from './safe-chunks.ts';
+
+export interface ExplainTargetRef {
+ slug: string;
+ /** Required when the slug exists in more than one readable source. */
+ sourceId?: string;
+}
+
+export interface TargetObservation {
+ /** Pipeline stage, or `arm:<instance>` for one retrieval arm's list. */
+ stage: string;
+ present: boolean;
+ /** 1-based rank within that stage's list when present. */
+ rank?: number;
+}
+
+export class TargetTrace {
+ readonly observations: TargetObservation[] = [];
+ constructor(readonly target: ExplainTargetRef) {}
+
+ matches(r: SearchResult): boolean {
+ if (r.slug !== this.target.slug) return false;
+ return this.target.sourceId === undefined || (r.source_id ?? 'default') === this.target.sourceId;
+ }
+
+ /** Record presence (page-level: the first matching row's rank) in one stage's list. */
+ observe(stage: string, rows: readonly SearchResult[]): void {
+ const i = rows.findIndex(r => this.matches(r));
+ this.observations.push(i >= 0 ? { stage, present: true, rank: i + 1 } : { stage, present: false });
+ }
+
+ arms(): TargetObservation[] {
+ return this.observations.filter(o => o.stage.startsWith('arm:'));
+ }
+
+ last(stage: string): TargetObservation | undefined {
+ for (let i = this.observations.length - 1; i >= 0; i--) if (this.observations[i].stage === stage) return this.observations[i];
+ return undefined;
+ }
+}
+
+/** The ordered post-arm stages a target can be lost at, with the code each loss maps to. */
+const LOSS_STAGES: ReadonlyArray<{ stage: string; code: string; why: string }> = [
+ { stage: 'fused', code: 'target_dropped_relaxed_keyword', why: 'Only the relaxed (OR-of-terms) keyword match found the page, and relaxed rows do not vote while the semantic arm is healthy.' },
+ { stage: 'deduped', code: 'target_dropped_dedup', why: 'Result dedup removed the page (per-page chunk cap, near-duplicate text, or type-diversity cap) in favor of a higher-ranked row.' },
+ { stage: 'reranked', code: 'target_dropped_rerank', why: 'The page fell out during reranking.' },
+ { stage: 'return_pool', code: 'target_dropped_return_sizing', why: 'Return sizing cut the page: autocut found a relevance cliff above it, or adaptive return sizing trimmed the tail.' },
+ { stage: 'limit_slice', code: 'target_beyond_limit', why: 'The page ranked below the requested result limit (or before the offset).' },
+ { stage: 'token_budget', code: 'target_dropped_token_budget', why: 'The token budget filled before the page was reached.' },
+];
+
+export type TargetState = 'retrieved' | 'dropped' | 'reinjected' | 'not_retrieved' | 'not_recorded';
+
+export interface ExplainTargetDiagnosis {
+ target: { slug: string; source_id?: string };
+ state: TargetState;
+ code: string;
+ why: string;
+ /** 1-based rank in the returned rows, when returned. */
+ rank?: number;
+ /** Arm instances that retrieved the page, with their 1-based list rank. */
+ arms: Array<{ arm: string; rank: number }>;
+ /** The stage that last held the page, and the first that lost it. */
+ last_seen?: TargetObservation;
+ lost_at?: string;
+ /** Rank the page held at the last stage that had it (for limit retries). */
+ last_rank?: number;
+ stages: TargetObservation[];
+ fix?: Action;
+}
+
+function armsOf(trace: TargetTrace): ExplainTargetDiagnosis['arms'] {
+ return trace.arms().filter(o => o.present).map(o => ({ arm: o.stage.slice(4), rank: o.rank! }));
+}
+
+/**
+ * Turn the observations into one state. `returned` is the final row list the
+ * caller receives. `retry` holds the original search arguments so every fix
+ * is a complete call.
+ */
+export function diagnoseTrace(
+ trace: TargetTrace,
+ returned: readonly SearchResult[],
+ retry: { tool: 'search' | 'query'; arguments: Record<string, unknown> },
+): ExplainTargetDiagnosis {
+ const target = { slug: trace.target.slug, ...(trace.target.sourceId ? { source_id: trace.target.sourceId } : {}) };
+ const stages = trace.observations;
+ const arms = armsOf(trace);
+ const getPage: Action = {
+ mcp: { tool: 'get_page', arguments: { slug: trace.target.slug, ...(trace.target.sourceId ? { source_id: trace.target.sourceId } : {}) } },
+ argv: ['gbrain', 'get', trace.target.slug],
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read the page directly; search ranking does not limit a direct read.',
+ };
+ const idx = returned.findIndex(r => trace.matches(r));
+ if (idx >= 0) {
+ const reinjected = stages.some(o => o.stage === 'reranked' && !o.present) && trace.last('return_pool')?.present === true;
+ return reinjected
+ ? { target, state: 'reinjected', code: 'target_reinjected', rank: idx + 1, arms, stages,
+ why: 'The page was cut earlier and put back on page 1 by the relational evidence slot or an identity tier (exact slug/title, declared alias).' }
+ : { target, state: 'retrieved', code: 'target_returned', rank: idx + 1, arms, stages,
+ why: `The page is result #${idx + 1}; score_details on that row shows how its score was formed.` };
+ }
+ if (stages.length === 0) {
+ return { target, state: 'not_recorded', code: 'target_not_recorded', arms, stages,
+ why: 'This search path did not record stage observations for the target.' };
+ }
+ if (arms.length === 0) {
+ return { target, state: 'not_retrieved', code: 'target_not_retrieved', arms, stages,
+ why: 'No retrieval arm (semantic, keyword, title, relational) returned the page for this query.',
+ fix: { mcp: { tool: 'query', arguments: { ...retry.arguments, query: retry.arguments.query } }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The query tool adds multi-query expansion, which recovers pages phrased differently from the question; or read the page directly with get_page.' } };
+ }
+ // The page reached at least one arm: find the first post-arm stage that lost it.
+ const keywordRaw = trace.last('arm:keyword_raw');
+ const keyword = trace.last('arm:keyword');
+ if (keywordRaw?.present && keyword && !keyword.present && arms.every(a => a.arm === 'keyword_raw')) {
+ const loss = LOSS_STAGES[0];
+ return { target, state: 'dropped', code: loss.code, why: loss.why, arms, stages, lost_at: 'fused', last_seen: keywordRaw, last_rank: keywordRaw.rank, fix: getPage };
+ }
+ let lastSeen: TargetObservation | undefined = trace.arms().filter(o => o.present).pop();
+ for (const loss of LOSS_STAGES) {
+ const o = trace.last(loss.stage);
+ if (!o) continue;
+ if (o.present) { lastSeen = o; continue; }
+ const base = { target, state: 'dropped' as const, code: loss.code, why: loss.why, arms, stages, lost_at: loss.stage, last_seen: lastSeen, last_rank: lastSeen?.rank };
+ if (loss.code === 'target_beyond_limit' && lastSeen?.rank) {
+ return { ...base, fix: { mcp: { tool: retry.tool, arguments: { ...retry.arguments, limit: Math.min(100, lastSeen.rank + 5) } },
+ consent: [], actor: 'agent', requires_exclusive: false, why: `Repeat the same search with a limit that reaches rank ${lastSeen.rank}.` } };
+ }
+ if (loss.code === 'target_dropped_token_budget') {
+ return { ...base, fix: { mcp: { tool: retry.tool, arguments: { ...retry.arguments, token_budget: 12000 } },
+ consent: [], actor: 'agent', requires_exclusive: false, why: 'Repeat the same search with a larger evidence token budget, or read the page directly with get_page.' } };
+ }
+ return { ...base, fix: getPage };
+ }
+ return { target, state: 'not_recorded', code: 'target_not_recorded', arms, stages, last_seen: lastSeen,
+ why: 'The page reached the pipeline but the stage that removed it was not observed (evidence delivery or an output filter after the traced stages).', fix: getPage };
+}
+
+/** One readable copy of the target page. */
+export interface TargetProbeRow {
+ source_id: string;
+ chunks: number;
+ current: boolean;
+ chunker_version: number | null;
+}
+
+type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
+
+/** Every readable live copy of `slug` under the caller's policy (one query). */
+export async function probeTarget(query: ReadQuery, slug: string, policy: PageReadPolicy): Promise<TargetProbeRow[]> {
+ const params: unknown[] = [slug];
+ const filter = pageReadFilter('p', policy, params, true);
+ const rows = await query<{ source_id: string; chunks: number; current: boolean; chunker_version: number | null }>(
+ `SELECT p.source_id,
+ (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id) AS chunks,
+ ((p.text_projection_revision = p.knowledge_revision) IS TRUE) AS current,
+ p.chunker_version
+ FROM pages p WHERE p.slug = $1 AND ${filter} ORDER BY p.source_id`, params);
+ return rows.map(r => ({ source_id: r.source_id, chunks: Number(r.chunks), current: r.current === true, chunker_version: r.chunker_version == null ? null : Number(r.chunker_version) }));
+}
+
+/**
+ * Refine a `not_retrieved` diagnosis (or resolve the target before search)
+ * from the probe. `requireSafeChunks` mirrors the remote read legs.
+ */
+export function diagnoseProbe(
+ ref: ExplainTargetRef,
+ rows: readonly TargetProbeRow[],
+ opts: { requireSafeChunks: boolean; retry: { tool: 'search' | 'query'; arguments: Record<string, unknown> } },
+): ExplainTargetDiagnosis | null {
+ const target = { slug: ref.slug, ...(ref.sourceId ? { source_id: ref.sourceId } : {}) };
+ const scoped = ref.sourceId ? rows.filter(r => r.source_id === ref.sourceId) : rows;
+ if (scoped.length === 0) {
+ return { target, state: 'not_retrieved', code: 'target_not_found_or_not_visible', arms: [], stages: [],
+ why: 'No page with this slug is readable by this caller in the searched sources: it may not exist, may be private, or may live in a source outside this search.',
+ fix: { consent: [], actor: 'user', requires_exclusive: false, why: 'Ask the user whether the page exists and which source holds it; a private or out-of-scope page cannot be diagnosed from here.',
+ user_message: `I could not find a readable page "${ref.slug}" in the searched sources. Does it exist, and in which source?` } };
+ }
+ if (scoped.length > 1) {
+ return { target, state: 'not_retrieved', code: 'target_ambiguous', arms: [], stages: [],
+ why: `The slug exists in ${scoped.length} readable sources (${scoped.map(r => r.source_id).join(', ')}); name one with explain_target_source.`,
+ fix: { mcp: { tool: opts.retry.tool, arguments: { ...opts.retry.arguments, explain: true, explain_target: ref.slug, explain_target_source: scoped[0].source_id } },
+ consent: [], actor: 'agent', requires_exclusive: false, why: `Repeat with explain_target_source set to one of: ${scoped.map(r => r.source_id).join(', ')}.` } };
+ }
+ const row = scoped[0];
+ const withSource = { ...target, source_id: row.source_id };
+ if (row.chunks === 0) {
+ return { target: withSource, state: 'not_retrieved', code: 'target_not_indexed', arms: [], stages: [],
+ why: 'The page has no indexed chunks, so no search arm can return it.',
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Doctor reports pages missing chunks or embeddings and the command that re-indexes them.' } };
+ }
+ if (!row.current) {
+ return { target: withSource, state: 'not_retrieved', code: 'target_projection_stale', arms: [], stages: [],
+ why: 'The page changed and its searchable text has not been rebuilt yet; search reads only the current revision.',
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Doctor shows the projection backlog and whether a worker is draining it; retry the search after it catches up.' } };
+ }
+ if (opts.requireSafeChunks && belowSafeChunkFence(row.chunker_version)) {
+ return { target: withSource, state: 'not_retrieved', code: 'target_safe_chunks_uncertified', arms: [], stages: [],
+ why: 'The page was indexed before the current safe-chunk format; remote reads withhold it until it is re-sealed.',
+ fix: { argv: ['gbrain', 'repair', 'safe-chunks'], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'The brain host operator re-seals older pages; the page becomes searchable remotely afterwards.' } };
+ }
+ return null;
+}
diff --git a/src/core/search/fusion-lists.ts b/src/core/search/fusion-lists.ts
index d3936ded9c..f8c4c61a16 100644
--- a/src/core/search/fusion-lists.ts
+++ b/src/core/search/fusion-lists.ts
@@ -67,6 +67,12 @@ export interface FusionListEntry {
list: SearchResult[];
k: number;
weight?: number;
+ /**
+ * Arm INSTANCE label for explain attribution (`vector`, `vector_variant#2`,
+ * `vector_clause#1`, `image`, `keyword`, `title`, `relational`). Labels
+ * never affect fusion math.
+ */
+ arm?: string;
}
/** Tag-and-append helper: the single way hybrid.ts adds a vector arm. */
@@ -180,13 +186,17 @@ export function composeFusionLists(input: ComposeFusionListsInput): FusionListEn
budget === null || votingExpansionArms === 0 ? undefined : budget / votingExpansionArms;
const out: FusionListEntry[] = [];
+ const seenByRole = new Map<VectorArmRole, number>();
for (const arm of arms) {
+ const n = (seenByRole.get(arm.role) ?? 0) + 1;
+ seenByRole.set(arm.role, n);
+ const label = arm.role === 'original' ? 'vector' : arm.role === 'image' ? 'image' : `vector_${arm.role}#${n}`;
if (arm.role === 'image') {
- out.push({ list: arm.list, k: imageK });
+ out.push({ list: arm.list, k: imageK, arm: label });
} else if (isExpansionRole(arm.role) && expansionWeight !== undefined && arm.list.length > 0) {
- out.push({ list: arm.list, k: textK, weight: expansionWeight });
+ out.push({ list: arm.list, k: textK, weight: expansionWeight, arm: label });
} else {
- out.push({ list: arm.list, k: textK });
+ out.push({ list: arm.list, k: textK, arm: label });
}
}
// Arm-confidence weighting (arm-confidence.ts): the keyword AND title
@@ -204,12 +214,12 @@ export function composeFusionLists(input: ComposeFusionListsInput): FusionListEn
// Meta stamping must never break fusion.
}
const lexicalWeight = lexical.weight === undefined ? {} : { weight: lexical.weight };
- out.push({ list: keywordFusionList, k: ks.keywordK, ...lexicalWeight });
+ out.push({ list: keywordFusionList, k: ks.keywordK, ...lexicalWeight, arm: 'keyword' });
if (titleFusionList.length > 0) {
- out.push({ list: titleFusionList, k: ks.keywordK, ...lexicalWeight });
+ out.push({ list: titleFusionList, k: ks.keywordK, ...lexicalWeight, arm: 'title' });
}
if (includeRelational && relationalList.length > 0) {
- out.push({ list: relationalList, k: ks.baseRrfK });
+ out.push({ list: relationalList, k: ks.baseRrfK, arm: 'relational' });
}
return out;
}
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index db8503c216..4833ef9ade 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -28,7 +28,8 @@ import { registerBackgroundWorkDrainer } from '../background-work.ts';
import { applyAliasHop, isExcludedIdentity, type IdentityTierOpts } from './alias-hop.ts';
export { applyAliasHop, isExcludedIdentity, type IdentityTierOpts };
import { dedupResults } from './dedup.ts';
-import { accumulateRrf } from './rrf-page-fusion.ts';
+import { accumulateRrf, type RrfEntry } from './rrf-page-fusion.ts';
+import type { RrfAttribution } from '../types.ts';
import {
isAmbiguousModalityQuery,
} from './query-intent.ts';
@@ -946,6 +947,12 @@ export interface HybridSearchOpts extends SearchOpts {
* hash `hd=`); eval A/B runs drive it here.
*/
hubDampening?: HubDampening | string;
+ /**
+ * explain_target (explain-target.ts): when set, each pipeline stage records
+ * whether the target page was present and at what rank. Observation only —
+ * never changes ranking.
+ */
+ explainTarget?: import('./explain-target.ts').TargetTrace;
/** Override default RRF K constant (default: 60). Lower values boost top-ranked results more. */
rrfK?: number;
/** Override dedup pipeline parameters. */
@@ -1174,6 +1181,7 @@ export async function hybridSearch(
// Dedup
const deduped = dedupResults(fused, dedupOpts);
+ opts?.explainTarget?.observe('deduped', deduped);
// Auto-escalate: if detail=low returned 0, retry with high. The inner
// call's onMeta fires with the escalated detail_resolved; do NOT also
@@ -1183,9 +1191,11 @@ export async function hybridSearch(
}
const { rerankPinned, relationalRerankPin } = await rerankAndPin(req, deduped, relationalList, effectiveModality);
+ opts?.explainTarget?.observe('reranked', rerankPinned);
const { returnPool, adaptiveDecision, autocutDecision, relationalSlotDecision } = await sizeReturnPool(req, {
rerankPinned, deduped, exactLookupOpts: lexical.exactLookupOpts, relationalList, effectiveModality,
});
+ opts?.explainTarget?.observe('return_pool', returnPool);
return finalizeHybridResults(req, returnPool, {
relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision,
relationalRerankPin, keywordArmConfidence, metadataBoostGate, hubDampening,
@@ -1470,25 +1480,33 @@ export function rrfFusionWeighted(
const entries = accumulateRrf(lists);
if (entries.length === 0) return [];
+ // Explain attribution (score_details): the raw summed vote, the normalized
+ // score and the compiled-truth factor, stamped once per fused row.
+ const attribution = new Map<RrfEntry, RrfAttribution>();
const maxScore = Math.max(...entries.map(e => e.score));
if (maxScore > 0) {
for (const e of entries) {
+ const raw = e.score;
e.score = e.score / maxScore;
// issue #160 + #3695: unverified stubs and synthetic chunkless title
// rows never get the compiled-truth authority boost. Numeric = factor.
const boost = typeof applyBoost === 'number'
? compiledTruthBoost(e.result, true, applyBoost)
: compiledTruthBoost(e.result, applyBoost);
+ attribution.set(e, { raw, normalized: e.score, compiled_truth_boost: boost, arms: e.arms });
e.score *= boost;
}
}
return entries
.sort((a, b) => b.score - a.score || b.own - a.own)
- .map(({ result, score, keywordHit }) =>
- keywordHit && result.keyword_hit !== true
- ? { ...result, score, keyword_hit: true }
- : { ...result, score });
+ .map((e) => {
+ const { result, score, keywordHit } = e;
+ const rrf = attribution.get(e) ?? { raw: e.score, normalized: e.score, compiled_truth_boost: 1, arms: e.arms };
+ return keywordHit && result.keyword_hit !== true
+ ? { ...result, score, keyword_hit: true, rrf }
+ : { ...result, score, rrf };
+ });
}
/**
@@ -1611,7 +1629,7 @@ export async function cosineReScore(
// v0.46.15: stamp the raw cosine — evidence + --explain read it (the
// hydration map is already paid for; zero extra probes).
- return { ...r, score: blended, cosine };
+ return { ...r, score: blended, cosine, blend_norm_rrf: normRrf };
}).sort((a, b) => b.score - a.score);
}
diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.ts
index 3341af3181..fdb1c8f00c 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -10,6 +10,7 @@ import { type PostFusionOpts, RRF_K, rrfFusionWeighted, runPostFusionStages, sta
import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';
import type { SearchResult } from '../../types.ts';
import type { HubDampeningMeta } from '../hub-dampening.ts';
+import type { FusionListEntry } from '../fusion-lists.ts';
import { applyAliasHop } from '../alias-hop.ts';
import { applyExactLookupTier } from '../exact-lookup.ts';
import { dedupResults } from '../dedup.ts';
@@ -38,11 +39,17 @@ export async function searchWithoutEmbeddings(
await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);
let noEmbedResults = keywordResults;
let hubDampening: HubDampeningMeta | undefined;
+ const trace = opts?.explainTarget;
+ if (trace) {
+ trace.observe('arm:keyword', keywordResults);
+ trace.observe('arm:title', titleResults);
+ trace.observe('arm:relational', relationalList);
+ }
if (relationalList.length > 0 || titleResults.length > 0) {
const fk = opts?.rrfK ?? RRF_K;
- const noEmbedLists = [{ list: keywordResults, k: fk }];
- if (titleResults.length > 0) noEmbedLists.push({ list: titleResults, k: fk });
- if (relationalList.length > 0) noEmbedLists.push({ list: relationalList, k: fk });
+ const noEmbedLists: FusionListEntry[] = [{ list: keywordResults, k: fk, arm: 'keyword' }];
+ if (titleResults.length > 0) noEmbedLists.push({ list: titleResults, k: fk, arm: 'title' });
+ if (relationalList.length > 0) noEmbedLists.push({ list: relationalList, k: fk, arm: 'relational' });
noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost);
}
if (noEmbedResults.length > 0) {
@@ -53,7 +60,10 @@ export async function searchWithoutEmbeddings(
}
// T3/T4 — alias hop + evidence stamp even without an embedding provider
// (the named-thing fix is most valuable exactly when vector is unavailable).
- const noEmbedPreExact = await applyAliasHop(engine, dedupResults(noEmbedResults), query, aliasHopOpts);
+ trace?.observe('fused', noEmbedResults);
+ const noEmbedDeduped = dedupResults(noEmbedResults);
+ trace?.observe('deduped', noEmbedDeduped);
+ const noEmbedPreExact = await applyAliasHop(engine, noEmbedDeduped, query, aliasHopOpts);
// #1663 — structural exact-lookup tier (slug / exact-title identity).
const noEmbedHopped = await applyExactLookupTier(engine, noEmbedPreExact, query, exactLookupOpts);
stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
@@ -72,9 +82,12 @@ export async function searchWithoutEmbeddings(
noEmbedPool = r.pool;
noEmbedRelSlot = r.decision;
}
+ trace?.observe('return_pool', noEmbedPool);
const noEmbedSliced = noEmbedPool.slice(offset, offset + limit);
+ trace?.observe('limit_slice', noEmbedSliced);
// v0.32.3 search-lite: budget enforcement on the no-embedding-provider path.
const { results: noEmbedBudgeted, meta: noEmbedBudgetMeta } = enforceTokenBudget(noEmbedSliced, resolvedMode.tokenBudget);
+ trace?.observe('token_budget', noEmbedBudgeted);
await stampContentFlags(engine, noEmbedBudgeted, opts);
req.lastResultsCount = noEmbedBudgeted.length;
req.lastRank1Score = noEmbedBudgeted[0] ? (noEmbedBudgeted[0].base_score ?? noEmbedBudgeted[0].score) : undefined;
@@ -144,11 +157,17 @@ export async function searchVectorFallback(
await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);
let fallbackResults = keywordResults;
let hubDampening: HubDampeningMeta | undefined;
+ const trace = opts?.explainTarget;
+ if (trace) {
+ trace.observe('arm:keyword', keywordResults);
+ trace.observe('arm:title', titleResults);
+ trace.observe('arm:relational', relationalList);
+ }
if (relationalList.length > 0 || titleResults.length > 0) {
const fk = opts?.rrfK ?? RRF_K;
- const fallbackLists = [{ list: keywordResults, k: fk }];
- if (titleResults.length > 0) fallbackLists.push({ list: titleResults, k: fk });
- if (relationalList.length > 0) fallbackLists.push({ list: relationalList, k: fk });
+ const fallbackLists: FusionListEntry[] = [{ list: keywordResults, k: fk, arm: 'keyword' }];
+ if (titleResults.length > 0) fallbackLists.push({ list: titleResults, k: fk, arm: 'title' });
+ if (relationalList.length > 0) fallbackLists.push({ list: relationalList, k: fk, arm: 'relational' });
fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost);
}
if (fallbackResults.length > 0) {
@@ -157,7 +176,10 @@ export async function searchVectorFallback(
fallbackResults.sort((a, b) => b.score - a.score);
fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });
}
- const kwPreExact = await applyAliasHop(engine, dedupResults(fallbackResults), query, aliasHopOpts);
+ trace?.observe('fused', fallbackResults);
+ const kwDeduped = dedupResults(fallbackResults);
+ trace?.observe('deduped', kwDeduped);
+ const kwPreExact = await applyAliasHop(engine, kwDeduped, query, aliasHopOpts);
// #1663 — structural exact-lookup tier (slug / exact-title identity).
const kwHopped = await applyExactLookupTier(engine, kwPreExact, query, exactLookupOpts);
stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
@@ -172,9 +194,12 @@ export async function searchVectorFallback(
kwPool = r.pool;
kwRelSlot = r.decision;
}
+ trace?.observe('return_pool', kwPool);
const kwSliced = kwPool.slice(offset, offset + limit);
+ trace?.observe('limit_slice', kwSliced);
// v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.
const { results: kwBudgeted, meta: kwBudgetMeta } = enforceTokenBudget(kwSliced, resolvedMode.tokenBudget);
+ trace?.observe('token_budget', kwBudgeted);
await stampContentFlags(engine, kwBudgeted, opts);
req.lastResultsCount = kwBudgeted.length;
req.lastRank1Score = kwBudgeted[0] ? (kwBudgeted[0].base_score ?? kwBudgeted[0].score) : undefined;
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index 0e751806aa..ddb25dc706 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -130,6 +130,14 @@ export async function fuseArms(
},
});
+ // explain_target: per-arm presence (keyword before and after relaxed-row demotion).
+ const trace = opts?.explainTarget;
+ if (trace) {
+ trace.observe('arm:keyword_raw', keywordResults);
+ trace.observe('arm:title_raw', titleResults);
+ for (const entry of allLists) trace.observe(`arm:${entry.arm ?? 'list'}`, entry.list);
+ }
+
// issue #160: stamp unverified auto-extracted stubs across ALL candidate
// arms BEFORE fusion so the compiled-truth authority boost skips them.
await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list), opts);
@@ -174,6 +182,7 @@ export async function fuseArms(
await applyIdentityBoosts(req, fused);
fused.sort((a, b) => b.score - a.score);
}
+ trace?.observe('fused', fused);
return { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate, hubDampening };
}
@@ -446,11 +455,13 @@ export async function finalizeHybridResults(
): Promise<SearchResult[]> {
const { engine, opts, resolvedMode, resolvedCol, limit, offset, suggestions, detailResolved, degraded } = req;
const sliced = returnPool.slice(offset, offset + limit);
+ opts?.explainTarget?.observe('limit_slice', sliced);
// v0.32.3 search-lite: budget enforcement at the main return path.
// hybridSearchCached used to be the only place this fired; now bare
// hybridSearch enforces it too so eval-replay + eval-longmemeval see
// the same budget behavior as the production query op.
const { results: budgeted, meta: budgetMeta } = enforceTokenBudget(sliced, resolvedMode.tokenBudget);
+ opts?.explainTarget?.observe('token_budget', budgeted);
await stampContentFlags(engine, budgeted, opts);
req.lastResultsCount = budgeted.length;
req.lastRank1Score = budgeted[0] ? (budgeted[0].base_score ?? budgeted[0].score) : undefined;
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
index 61d4b13b86..920b2333e2 100644
--- a/src/core/search/lean-rows.ts
+++ b/src/core/search/lean-rows.ts
@@ -28,6 +28,8 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set([
'evidence', 'create_safety',
'injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',
'message_id', 'thread_id', 'source_subject', 'relational',
+ // Present only when the caller asked for `explain: true`.
+ 'score_details',
]);
/** Explicit `fields` wins; then trusted local callers get full rows; then the transport's choice (default lean). */
diff --git a/src/core/search/rrf-page-fusion.ts b/src/core/search/rrf-page-fusion.ts
index ba701e6b49..050f3c1b24 100644
--- a/src/core/search/rrf-page-fusion.ts
+++ b/src/core/search/rrf-page-fusion.ts
@@ -37,7 +37,24 @@ function rrfPageKey(r: SearchResult): string {
return `${r.source_id ?? 'default'}:${r.slug}`;
}
-export type RrfEntry = { result: SearchResult; score: number; own: number; keywordHit: boolean };
+/**
+ * One fusion vote, for explain attribution: which arm instance voted, at
+ * which 0-based list rank, with what k / weight and contribution
+ * (`weight / (k + rank)`). `vote: 'page'` = the page-level vote the lead chunk
+ * carries (the page's best-ranked chunk in that list, `chunk_id` names it);
+ * `vote: 'chunk'` = this chunk's own vote.
+ */
+export interface RrfArmVote {
+ arm: string;
+ rank: number;
+ k: number;
+ weight: number;
+ contribution: number;
+ vote: 'page' | 'chunk';
+ chunk_id?: number;
+}
+
+export type RrfEntry = { result: SearchResult; score: number; own: number; keywordHit: boolean; arms: RrfArmVote[] };
/**
* Shared accumulation for both RRF fusers: chunk entries (identity and
@@ -45,23 +62,30 @@ export type RrfEntry = { result: SearchResult; score: number; own: number; keywo
* first-seen order; each page's lead scores the page total, the rest their
* own vote.
*/
-export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: number; weight?: number }>): RrfEntry[] {
+export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: number; weight?: number; arm?: string }>): RrfEntry[] {
const chunks = new Map<string, RrfEntry>();
const pages = new Map<string, number>();
// Graph evidence is page-level: the relational arm may surface a page's
// canonical chunk while keyword/vector pick another chunk of the same page,
// so the evidence rides on whichever of the page's rows survives.
const graphEvidence = new Map<string, Partial<SearchResult>>();
- for (const { list, k, weight } of lists) {
+ const pageVotes = new Map<string, RrfArmVote[]>();
+ for (let li = 0; li < lists.length; li++) {
+ const { list, k, weight } = lists[li];
+ const arm = lists[li].arm ?? `list#${li + 1}`;
const w = weight ?? 1;
const votedPages = new Set<string>();
for (let rank = 0; rank < list.length; rank++) {
const r = list[rank];
const rrfScore = w / (k + rank);
const page = rrfPageKey(r);
+ const vote: RrfArmVote = { arm, rank, k, weight: w, contribution: rrfScore, vote: 'chunk' };
if (!votedPages.has(page)) {
votedPages.add(page);
pages.set(page, (pages.get(page) ?? 0) + rrfScore);
+ const pv = pageVotes.get(page) ?? [];
+ pv.push({ ...vote, vote: 'page', ...(typeof r.chunk_id === 'number' ? { chunk_id: r.chunk_id } : {}) });
+ pageVotes.set(page, pv);
}
if (!graphEvidence.has(page) && (r.relational !== undefined || r.relational_seed !== undefined)) {
graphEvidence.set(page, pickGraphEvidence(r));
@@ -70,6 +94,7 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
const existing = chunks.get(key);
if (existing) {
existing.own += rrfScore;
+ existing.arms.push(vote);
// #3783 — OR-propagate lexical-arm membership: a row that fusion
// first saw via a vector list must still read keyword_hit when the
// keyword arm ALSO surfaced it.
@@ -81,7 +106,7 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
existing.result = strict;
}
} else {
- chunks.set(key, { result: r, score: 0, own: rrfScore, keywordHit: r.keyword_hit === true });
+ chunks.set(key, { result: r, score: 0, own: rrfScore, keywordHit: r.keyword_hit === true, arms: [vote] });
}
}
}
@@ -99,7 +124,10 @@ export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: nu
const lead = leads.get(page);
if (!lead || e.own > lead.own) leads.set(page, e);
}
- for (const [page, lead] of leads) lead.score = pages.get(page) ?? lead.own;
+ for (const [page, lead] of leads) {
+ lead.score = pages.get(page) ?? lead.own;
+ lead.arms = pageVotes.get(page) ?? lead.arms;
+ }
return entries;
}
diff --git a/src/core/types.ts b/src/core/types.ts
index 8c9b7bfe4b..faa190067c 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -799,6 +799,13 @@ export interface ChunkInput {
}
// Search
+export interface RrfAttribution {
+ raw: number;
+ normalized: number;
+ compiled_truth_boost: number;
+ arms: import('./search/rrf-page-fusion.ts').RrfArmVote[];
+}
+
export interface SearchResult {
slug: string;
page_id: number;
@@ -945,6 +952,18 @@ export interface SearchResult {
*/
/** RRF + cosine score BEFORE any boost stage mutated it. */
base_score?: number;
+ /**
+ * Explain attribution from weighted RRF fusion: the summed vote (`raw`),
+ * the score after max-normalization (`normalized`), the compiled-truth
+ * factor, and every arm-instance vote behind it (0-based ranks). Absent on
+ * rows that never went through `rrfFusionWeighted` (keyword-only single-arm
+ * paths). Lean MCP rows strip it; `explain` renders it as score_details.
+ */
+ rrf?: RrfAttribution;
+ /** Cosine blend input: the max-normalized RRF score the 0.7/0.3 blend used. */
+ blend_norm_rrf?: number;
+ /** Per-row ranking breakdown, set by the `search`/`query` ops only when the caller passes `explain: true`. */
+ score_details?: import('./search/explain-formatter.ts').ScoreDetails;
/**
* v0.46.15 — RAW query↔chunk cosine similarity from cosineReScore's
* hydration (the active embedding column's space). Absent on keyword-only
diff --git a/test/search/explain.test.ts b/test/search/explain.test.ts
new file mode 100644
index 0000000000..41a5ff8b95
--- /dev/null
+++ b/test/search/explain.test.ts
@@ -0,0 +1,199 @@
+/**
+ * Explainable ranking: per-arm RRF attribution, score_details, the `explain`
+ * op param, and explain_target diagnosis.
+ *
+ * Protects: every fused row says which arm instances voted for it at which
+ * rank, and those votes sum to its raw RRF score; score_details reports a
+ * stage it did not observe as not_run instead of inventing values; `explain`
+ * survives the lean MCP projection; explain_target names the first stage
+ * that lost a page, and a remote caller asking about a private page gets the
+ * same answer as for a page that does not exist.
+ * Seams: none for the pure parts; in-memory PGLite (keyless) for the op tests.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { SearchResult } from '../../src/core/types.ts';
+import { accumulateRrf } from '../../src/core/search/rrf-page-fusion.ts';
+import { rrfFusionWeighted } from '../../src/core/search/hybrid.ts';
+import { buildScoreDetails } from '../../src/core/search/explain-formatter.ts';
+import { TargetTrace, diagnoseProbe, diagnoseTrace } from '../../src/core/search/explain-target.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';
+
+function row(slug: string, chunk_id: number, page_id = chunk_id): SearchResult {
+ return {
+ slug, page_id, title: slug, type: 'note', chunk_text: slug, chunk_source: 'compiled_truth',
+ chunk_id, chunk_index: 0, score: 0, stale: false, source_id: 'default',
+ } as SearchResult;
+}
+
+describe('RRF arm attribution', () => {
+ test('page votes on the lead chunk sum to its raw score; other chunks keep their own votes', () => {
+ const a1 = row('notes/a', 1, 10);
+ const a2 = row('notes/a', 2, 10);
+ const b = row('notes/b', 3, 20);
+ const entries = accumulateRrf([
+ { list: [a1, b], k: 60, arm: 'vector' },
+ { list: [b, a2], k: 60, weight: 0.5, arm: 'vector_variant#1' },
+ { list: [a2], k: 60, arm: 'keyword' },
+ ]);
+ // a2 has the larger own vote (variant 0.5/61 + keyword 1/60 > vector 1/60), so it leads page a.
+ const lead = entries.find(e => e.result.chunk_id === 2)!;
+ const second = entries.find(e => e.result.chunk_id === 1)!;
+ const sum = (e: typeof lead) => e.arms.reduce((t, v) => t + v.contribution, 0);
+ expect(lead.arms.every(v => v.vote === 'page')).toBe(true);
+ expect(lead.arms.map(v => [v.arm, v.chunk_id])).toEqual([['vector', 1], ['vector_variant#1', 2], ['keyword', 2]]);
+ expect(sum(lead)).toBeCloseTo(lead.score, 12);
+ expect(second.arms.every(v => v.vote === 'chunk')).toBe(true);
+ expect(sum(second)).toBeCloseTo(second.score, 12);
+ });
+
+ test('rrfFusionWeighted stamps raw / normalized / compiled-truth factor without changing order', () => {
+ const lists = [{ list: [row('notes/a', 1), row('notes/b', 2)], k: 60, arm: 'vector' }, { list: [row('notes/b', 2)], k: 60, arm: 'keyword' }];
+ const fused = rrfFusionWeighted(lists, false);
+ expect(fused.map(r => r.slug)).toEqual(['notes/b', 'notes/a']);
+ const b = fused[0];
+ expect(b.rrf!.raw).toBeCloseTo(1 / 61 + 1 / 60, 12);
+ expect(b.rrf!.normalized).toBe(1);
+ expect(b.rrf!.compiled_truth_boost).toBe(1);
+ expect(b.rrf!.arms.map(v => [v.arm, v.rank])).toEqual([['vector', 1], ['keyword', 0]]);
+ });
+});
+
+describe('buildScoreDetails', () => {
+ test('unobserved stages are not_run, applied boosts carry their factors, ranks are 1-based', () => {
+ const r = { ...row('notes/a', 1), score: 1.2, base_score: 1, backlink_boost: 1.1, backlink_count: 40, backlink_hub_weight: 0.25,
+ rrf: { raw: 0.03, normalized: 1, compiled_truth_boost: 1, arms: [{ arm: 'keyword', rank: 0, k: 60, weight: 1, contribution: 1 / 60, vote: 'page' as const, chunk_id: 1 }] } };
+ const d = buildScoreDetails(r);
+ expect(d.final).toBe(1.2);
+ expect(d.arms[0]).toMatchObject({ arm: 'keyword', rank: 1, fusion_rank: 0 });
+ expect(d.rrf).toMatchObject({ state: 'applied', raw: 0.03 });
+ expect(d.blend).toEqual({ state: 'not_run', reason: 'no_query_embedding' });
+ expect(d.rerank.state).toBe('not_run');
+ expect(d.boosts.backlink).toEqual({ factor: 1.1, inbound: 40, hub_weight: 0.25 });
+ expect(Object.keys(d.boosts)).toEqual(['backlink']);
+ });
+
+ test('a single-arm row says rrf did not run', () => {
+ expect(buildScoreDetails(row('notes/a', 1)).rrf).toEqual({ state: 'not_run', reason: 'single_arm_path' });
+ });
+});
+
+describe('diagnoseTrace', () => {
+ const retry = { tool: 'search' as const, arguments: { query: 'q', limit: 2 } };
+ test('returned rows report their rank', () => {
+ const t = new TargetTrace({ slug: 'notes/a' });
+ t.observe('arm:keyword', [row('notes/a', 1)]);
+ t.observe('limit_slice', [row('notes/a', 1)]);
+ const d = diagnoseTrace(t, [row('notes/a', 1)], retry);
+ expect(d).toMatchObject({ state: 'retrieved', code: 'target_returned', rank: 1 });
+ });
+
+ test('the first stage that lost the page is named, with a complete retry for the limit', () => {
+ const t = new TargetTrace({ slug: 'notes/c' });
+ const pool = [row('notes/a', 1), row('notes/b', 2), row('notes/c', 3)];
+ t.observe('arm:vector', pool);
+ t.observe('fused', pool);
+ t.observe('deduped', pool);
+ t.observe('return_pool', pool);
+ t.observe('limit_slice', pool.slice(0, 2));
+ const d = diagnoseTrace(t, pool.slice(0, 2), retry);
+ expect(d).toMatchObject({ state: 'dropped', code: 'target_beyond_limit', lost_at: 'limit_slice', last_rank: 3 });
+ expect(d.fix?.mcp).toEqual({ tool: 'search', arguments: { query: 'q', limit: 8 } });
+ });
+
+ test('a page only the relaxed keyword arm found is attributed to relaxed-row demotion', () => {
+ const t = new TargetTrace({ slug: 'notes/x' });
+ t.observe('arm:keyword_raw', [row('notes/x', 9)]);
+ t.observe('arm:vector', [row('notes/a', 1)]);
+ t.observe('arm:keyword', []);
+ t.observe('fused', [row('notes/a', 1)]);
+ expect(diagnoseTrace(t, [row('notes/a', 1)], retry)).toMatchObject({ state: 'dropped', code: 'target_dropped_relaxed_keyword' });
+ });
+
+ test('no arm → not_retrieved with an expansion retry; no observations → not_recorded', () => {
+ const t = new TargetTrace({ slug: 'notes/x' });
+ t.observe('arm:vector', [row('notes/a', 1)]);
+ expect(diagnoseTrace(t, [], retry)).toMatchObject({ state: 'not_retrieved', code: 'target_not_retrieved' });
+ expect(diagnoseTrace(new TargetTrace({ slug: 'notes/x' }), [], retry).state).toBe('not_recorded');
+ });
+});
+
+describe('diagnoseProbe', () => {
+ const retry = { tool: 'query' as const, arguments: { query: 'q' } };
+ const ok = { source_id: 'default', chunks: 2, current: true, chunker_version: 99 };
+ test('absent, ambiguous, unindexed, stale and unsealed pages', () => {
+ expect(diagnoseProbe({ slug: 's' }, [], { requireSafeChunks: false, retry })!.code).toBe('target_not_found_or_not_visible');
+ const amb = diagnoseProbe({ slug: 's' }, [ok, { ...ok, source_id: 'team' }], { requireSafeChunks: false, retry })!;
+ expect(amb.code).toBe('target_ambiguous');
+ expect(amb.fix?.mcp?.arguments).toMatchObject({ query: 'q', explain_target: 's', explain_target_source: 'default' });
+ expect(diagnoseProbe({ slug: 's' }, [{ ...ok, chunks: 0 }], { requireSafeChunks: false, retry })!.code).toBe('target_not_indexed');
+ expect(diagnoseProbe({ slug: 's' }, [{ ...ok, current: false }], { requireSafeChunks: false, retry })!.code).toBe('target_projection_stale');
+ expect(diagnoseProbe({ slug: 's' }, [{ ...ok, chunker_version: 1 }], { requireSafeChunks: true, retry })!.code).toBe('target_safe_chunks_uncertified');
+ expect(diagnoseProbe({ slug: 's' }, [ok], { requireSafeChunks: true, retry })).toBeNull();
+ });
+});
+
+describe('search / query ops with explain (PGLite, keyless)', () => {
+ let engine: PGLiteEngine;
+ const notices: unknown[] = [];
+ const metas: Record<string, unknown>[] = [];
+ const ctx = (remote: boolean) => ({
+ engine, remote, sourceId: 'default', config: { engine: 'pglite', embedding_disabled: true }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} },
+ emitNotice: (n: unknown) => { notices.push(n); },
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') metas.push(value as Record<string, unknown>); },
+ }) as unknown as OperationContext;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ __resetPrivateVisibilityCacheForTests();
+ await importFromContent(engine, 'notes/quokka-habitat', '# Quokka habitat\nQuokka quokka island habitat notes.', { noEmbed: true });
+ await importFromContent(engine, 'notes/quokka-diet', '# Quokka diet\nQuokka eats leaves; quokka diet notes.', { noEmbed: true });
+ await importFromContent(engine, 'notes/unrelated', '# Ferries\nFerry timetable.', { noEmbed: true });
+ await importFromContent(engine, 'notes/secret-quokka', '---\nvisibility: private\n---\n# Secret\nQuokka secret.', { noEmbed: true });
+ }, 120_000);
+ afterAll(async () => { if (engine) await engine.disconnect(); });
+
+ test('explain: true keeps score_details on lean remote rows; without it rows stay lean', async () => {
+ const lean = await operationsByName.search.handler(ctx(true), { query: 'quokka' }) as Array<Record<string, unknown>>;
+ expect(lean.length).toBeGreaterThan(0);
+ expect(lean.every(r => r.score_details === undefined)).toBe(true);
+ const explained = await operationsByName.search.handler(ctx(true), { query: 'quokka', explain: true }) as Array<Record<string, unknown>>;
+ expect(explained.every(r => typeof r.score_details === 'object')).toBe(true);
+ expect((explained[0].score_details as { final: number }).final).toBe(explained[0].score as number);
+ });
+
+ test('explain_target: a returned page reports its rank; a page cut by the limit says so', async () => {
+ metas.length = 0;
+ await operationsByName.search.handler(ctx(false), { query: 'quokka', explain: true, explain_target: 'notes/quokka-diet' });
+ expect(metas.at(-1)?.explain_target).toMatchObject({ state: 'retrieved', code: 'target_returned' });
+ const all = await operationsByName.search.handler(ctx(false), { query: 'quokka' }) as SearchResult[];
+ expect(all.length).toBeGreaterThan(1);
+ metas.length = 0; notices.length = 0;
+ await operationsByName.search.handler(ctx(false), { query: 'quokka', limit: 1, explain_target: all[1].slug });
+ expect(metas.at(-1)?.explain_target).toMatchObject({ state: 'dropped', code: 'target_beyond_limit', last_rank: 2 });
+ expect(notices).toContainEqual(expect.objectContaining({ code: 'target_beyond_limit' }));
+ });
+
+ test('a private page and a nonexistent page look identical to a remote caller', async () => {
+ metas.length = 0;
+ await operationsByName.search.handler(ctx(true), { query: 'quokka', explain_target: 'notes/secret-quokka' });
+ const priv = metas.at(-1)?.explain_target as Record<string, unknown>;
+ metas.length = 0;
+ await operationsByName.search.handler(ctx(true), { query: 'quokka', explain_target: 'notes/does-not-exist' });
+ const none = metas.at(-1)?.explain_target as Record<string, unknown>;
+ expect(priv.code).toBe('target_not_found_or_not_visible');
+ expect({ ...priv, target: null }).toEqual({ ...none, target: null });
+ });
+
+ test('query op threads explain_target too', async () => {
+ metas.length = 0;
+ await operationsByName.query.handler(ctx(false), { query: 'quokka', expand: false, explain_target: 'notes/unrelated' });
+ expect((metas.at(-1)?.explain_target as { state: string }).state).toBe('not_retrieved');
+ });
+});
diff --git a/test/search/fusion-lists.test.ts b/test/search/fusion-lists.test.ts
index 2cc72af01c..c16f967df4 100644
--- a/test/search/fusion-lists.test.ts
+++ b/test/search/fusion-lists.test.ts
@@ -119,10 +119,10 @@ describe('composeFusionLists — expansion variant budget (the 38-point gap)', (
arms, keywordFusionList: [], titleFusionList: [], relationalList: [],
includeRelational: true, ks: KS, knobs: { expansionVariantBudget: 1.0 },
});
- expect(lists[0]).toEqual({ list: [gold], k: 60 });
- expect(lists[1]).toEqual({ list: [distractor], k: 60, weight: 0.5 });
- expect(lists[2]).toEqual({ list: [], k: 60 });
- expect(lists[3]).toEqual({ list: [distractor], k: 60, weight: 0.5 });
+ expect(lists[0]).toEqual({ list: [gold], k: 60, arm: 'vector' });
+ expect(lists[1]).toEqual({ list: [distractor], k: 60, weight: 0.5, arm: 'vector_variant#1' });
+ expect(lists[2]).toEqual({ list: [], k: 60, arm: 'vector_variant#2' });
+ expect(lists[3]).toEqual({ list: [distractor], k: 60, weight: 0.5, arm: 'vector_clause#1' });
});
test('original missing (its embed or searchVector failed) → survivors are variants sharing the budget', () => {
@@ -160,11 +160,14 @@ describe('composeFusionLists — null deep-equals the pre-role allLists mapping'
// Today's mapping, verbatim (hybrid.ts pre-wave):
// [...vectorLists.map(list => ({ list, k: vectorK })), { list: keywordFusionList, k: keywordK }]
// + title (keywordK) if non-empty + relational (baseRrfK) if non-empty && modality !== 'image'
+ // Plus the explain-only `arm` instance label (never read by fusion math).
const legacy: FusionListEntry[] = [
- ...[orig, v1, v2].map((list) => ({ list, k: KS.vectorK })),
- { list: kw, k: KS.keywordK },
- { list: title, k: KS.keywordK },
- { list: rel, k: KS.baseRrfK },
+ { list: orig, k: KS.vectorK, arm: 'vector' },
+ { list: v1, k: KS.vectorK, arm: 'vector_variant#1' },
+ { list: v2, k: KS.vectorK, arm: 'vector_variant#2' },
+ { list: kw, k: KS.keywordK, arm: 'keyword' },
+ { list: title, k: KS.keywordK, arm: 'title' },
+ { list: rel, k: KS.baseRrfK, arm: 'relational' },
];
expect(got).toEqual(legacy);
// No `weight` key anywhere in legacy mode (byte-identical shape).
@@ -178,7 +181,7 @@ describe('composeFusionLists — null deep-equals the pre-role allLists mapping'
arms, keywordFusionList: kw, titleFusionList: [], relationalList: rel,
includeRelational: false, ks: KS, knobs: { expansionVariantBudget: null },
});
- expect(got).toEqual([{ list: orig, k: KS.vectorK }, { list: kw, k: KS.keywordK }]);
+ expect(got).toEqual([{ list: orig, k: KS.vectorK, arm: 'vector' }, { list: kw, k: KS.keywordK, arm: 'keyword' }]);
});
test('both mode (image arm present): text arms at textRrfK, image arm at imageRrfK', () => {
@@ -191,10 +194,10 @@ describe('composeFusionLists — null deep-equals the pre-role allLists mapping'
includeRelational: true, ks: KS, knobs: { expansionVariantBudget: null },
});
expect(got).toEqual([
- { list: orig, k: KS.textRrfK },
- { list: v1, k: KS.textRrfK },
- { list: img, k: KS.imageRrfK },
- { list: kw, k: KS.keywordK },
+ { list: orig, k: KS.textRrfK, arm: 'vector' },
+ { list: v1, k: KS.textRrfK, arm: 'vector_variant#1' },
+ { list: img, k: KS.imageRrfK, arm: 'image' },
+ { list: kw, k: KS.keywordK, arm: 'keyword' },
]);
});
@@ -207,9 +210,9 @@ describe('composeFusionLists — null deep-equals the pre-role allLists mapping'
arms, keywordFusionList: kw, titleFusionList: [], relationalList: [],
includeRelational: true, ks: KS, knobs: { expansionVariantBudget: 0.5 },
});
- expect(got[2]).toEqual({ list: img, k: KS.imageRrfK });
- expect(got[1]).toEqual({ list: v1, k: KS.textRrfK, weight: 0.5 });
- expect(got[0]).toEqual({ list: orig, k: KS.textRrfK });
+ expect(got[2]).toEqual({ list: img, k: KS.imageRrfK, arm: 'image' });
+ expect(got[1]).toEqual({ list: v1, k: KS.textRrfK, weight: 0.5, arm: 'vector_variant#1' });
+ expect(got[0]).toEqual({ list: orig, k: KS.textRrfK, arm: 'vector' });
});
test('image-only mode (sole image arm): fuses at vectorK, exactly as the single-list mapping did', () => {
@@ -219,7 +222,7 @@ describe('composeFusionLists — null deep-equals the pre-role allLists mapping'
arms, keywordFusionList: [], titleFusionList: [], relationalList: rel,
includeRelational: false, ks: KS, knobs: { expansionVariantBudget: null },
});
- expect(got).toEqual([{ list: img, k: KS.vectorK }, { list: [], k: KS.keywordK }]);
+ expect(got).toEqual([{ list: img, k: KS.vectorK, arm: 'image' }, { list: [], k: KS.keywordK, arm: 'keyword' }]);
});
test('CORRECTED corner: both mode whose image branch fell open with two text lists → no list gets imageRrfK', () => {