Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

explain: attribution only for explain callers; explain params on query only; CLI --explain stays bare-only

garrytan875fd88b076b
diff --git a/docs/guides/search-explain.md b/docs/guides/search-explain.md
index cdbf616fe1..2a13e836de 100644
--- a/docs/guides/search-explain.md
+++ b/docs/guides/search-explain.md
@@ -64,7 +64,7 @@ the next step:
| `target_not_indexed` | The page has no indexed chunks. | `gbrain doctor --json` names the re-index command. |
| `target_projection_stale` | The page changed and its searchable text is still being rebuilt. | Retry after `gbrain doctor` shows the backlog drained. |
| `target_safe_chunks_uncertified` | Remote reads withhold pages indexed before the current safe-chunk format. | The brain host runs `gbrain repair safe-chunks`. |
-| `target_ambiguous` | The slug exists in several sources. | Repeat with `explain_target_source`. |
+| `target_ambiguous` | The slug exists in several sources. | Repeat with `explain_target` as `source:slug`. |
| `target_not_found_or_not_visible` | No page with that slug is readable here. | Ask the user whether it exists and where; private pages are never confirmed. |
Agents on the default seven-verb memory surface do not have `search` or
diff --git a/src/cli.ts b/src/cli.ts
index 9ea51b1cf0..8fc813f52e 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1013,7 +1013,8 @@ export function resolveQueryImage(
}
export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
- const params: Record<string, unknown> = {};
+ // `gbrain search --explain`: the CLI-local formatter flag also asks the op for score attribution.
+ const params: Record<string, unknown> = op.name === 'search' && args.includes('--explain') ? { explain: true } : {};
const positional = op.cliHints?.positional || [];
let posIdx = 0;
@@ -1327,7 +1328,8 @@ export function findUnknownOpFlag(op: Operation, args: string[]): string | null
if (m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
continue;
}
- if ((rawKey === 'explain' || rawKey === 'help') && m[2] === undefined) continue;
+ // Bare-only even where an op also declares `explain` (search/query): the `=` form is refused, never parsed as a value.
+ if (rawKey === 'explain' || rawKey === 'help') { if (m[2] === undefined) continue; return `--${rawKey}`; }
if (rawKey === 'source' || rawKey === 'dry-run') {
// Non-boolean-style CLI-locals consume the next token as their value
// in parseOpArgs (source does; dry-run is boolean-read) — mirror the
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 6858e69563..4ead882457 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -506,13 +506,22 @@ 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`. */
+/**
+ * Ranking explanation params, declared on `query` only: every declared param
+ * is re-sent to the model on each turn, so the cheap `search` tool stays
+ * lean. The local CLI passes them to `search` too (`gbrain search --explain`).
+ */
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: { type: 'boolean' as const, description: 'Per-row score_details.' },
+ explain_target: { type: 'string' as const, description: 'Expected page (slug or source:slug): why it is missing.' },
};
+/** `explain_target` is `slug` or `source_id:slug` (slugs never contain ':'). */
+function parseExplainTarget(raw: string): { slug: string; sourceId?: string } {
+ const at = raw.indexOf(':');
+ return at > 0 ? { sourceId: raw.slice(0, at), slug: raw.slice(at + 1) } : { slug: raw };
+}
+
/**
* 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
@@ -523,8 +532,7 @@ 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 { slug, sourceId } = parseExplainTarget(p.explain_target.trim());
const retry = { tool, arguments: explainRetryArgs(p) };
let probe;
try {
@@ -541,7 +549,7 @@ async function prepareExplainTarget(
/** 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;
+ const { explain: _e, explain_target: _t, ...rest } = p;
return rest;
}
@@ -624,7 +632,6 @@ const search: Operation = {
salience: SALIENCE_PARAM,
recency: RECENCY_PARAM,
fields: FIELDS_PARAM,
- ...EXPLAIN_PARAMS,
},
handler: async (ctx, p) => {
const startedAt = Date.now();
@@ -709,7 +716,7 @@ const search: Operation = {
decide: { remote: ctx.remote !== false },
};
const primary = await hybridSearchCached(ctx.engine, queryText, {
- ...searchOpts, onMeta: (m) => { capturedMeta = m; }, ...(explainPrep?.trace ? { explainTarget: explainPrep.trace } : {}),
+ ...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,
});
const declarations = new DeclarationMemo();
const results = (await withDeclaredNameFanOut(primary, queryText, declarations,
@@ -955,7 +962,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,
- explainTarget: explainPrep?.trace,
+ explain: p.explain === true, explainTarget: explainPrep?.trace,
});
const declarations = new DeclarationMemo();
results = await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
diff --git a/src/core/search/explain-target.ts b/src/core/search/explain-target.ts
index 2802b46858..3a99f656c7 100644
--- a/src/core/search/explain-target.ts
+++ b/src/core/search/explain-target.ts
@@ -206,9 +206,9 @@ export function diagnoseProbe(
}
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(', ')}.` } };
+ why: `The slug exists in ${scoped.length} readable sources (${scoped.map(r => r.source_id).join(', ')}); name one as source:slug.`,
+ fix: { mcp: { tool: opts.retry.tool, arguments: { ...opts.retry.arguments, explain_target: `${scoped[0].source_id}:${ref.slug}` } },
+ consent: [], actor: 'agent', requires_exclusive: false, why: `Repeat with explain_target as <source>:${ref.slug}, source one of: ${scoped.map(r => r.source_id).join(', ')}.` } };
}
const row = scoped[0];
const withSource = { ...target, source_id: row.source_id };
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 4833ef9ade..c7418caac7 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -953,6 +953,8 @@ export interface HybridSearchOpts extends SearchOpts {
* never changes ranking.
*/
explainTarget?: import('./explain-target.ts').TargetTrace;
+ /** Stamp fusion attribution (`rrf`, `blend_norm_rrf`) for score_details; off keeps rows byte-identical. */
+ explain?: boolean;
/** Override default RRF K constant (default: 60). Lower values boost top-ranked results more. */
rrfK?: number;
/** Override dedup pipeline parameters. */
@@ -1476,6 +1478,7 @@ export function filterResultsByCallerScope(
export function rrfFusionWeighted(
lists: FusionListEntry[],
applyBoost: boolean | number = true,
+ attribute = false,
): SearchResult[] {
const entries = accumulateRrf(lists);
if (entries.length === 0) return [];
@@ -1502,10 +1505,11 @@ export function rrfFusionWeighted(
.sort((a, b) => b.score - a.score || b.own - a.own)
.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 };
+ // Stamped only for explain callers, so ordinary rows stay byte-identical.
+ const rrf = attribute ? { 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 };
+ ? { ...result, score, keyword_hit: true, ...rrf }
+ : { ...result, score, ...rrf };
});
}
@@ -1572,6 +1576,7 @@ export async function cosineReScore(
queryEmbedding: Float32Array,
column: string = 'embedding',
imageSpace?: { queryEmbedding: Float32Array; column: string },
+ attribute = false,
): Promise<SearchResult[]> {
// 'both' mode: image-arm rows live in the image space (image column,
// multimodal query vector); everything else in the text space.
@@ -1629,7 +1634,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, blend_norm_rrf: normRrf };
+ return { ...r, score: blended, cosine, ...(attribute ? { 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 fdb1c8f00c..041f143f50 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -50,7 +50,7 @@ export async function searchWithoutEmbeddings(
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);
+ noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost, opts?.explain === true || trace !== undefined);
}
if (noEmbedResults.length > 0) {
await runPostFusionStages(engine, noEmbedResults, { ...postFusionOpts, onHubDampening: (m) => { hubDampening = m; } });
@@ -168,7 +168,7 @@ export async function searchVectorFallback(
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);
+ fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost, opts?.explain === true || trace !== undefined);
}
if (fallbackResults.length > 0) {
await runPostFusionStages(engine, fallbackResults, { ...postFusionOpts, onHubDampening: (m) => { hubDampening = m; } });
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index ddb25dc706..63b42ebc12 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -142,7 +142,8 @@ export async function fuseArms(
// arms BEFORE fusion so the compiled-truth authority boost skips them.
await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list), opts);
- let fused = rrfFusionWeighted(allLists, ctBoost);
+ const attribute = opts?.explain === true || trace !== undefined;
+ let fused = rrfFusionWeighted(allLists, ctBoost, attribute);
// Cosine re-scoring before dedup so semantically better chunks survive.
// v0.36 (D9): hydrate from the active embedding column so rescore happens
@@ -154,6 +155,7 @@ export async function fuseArms(
fused = await cosineReScore(
engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name,
imageQueryEmbedding && !unifiedDone ? { queryEmbedding: imageQueryEmbedding, column: 'embedding_image' } : undefined,
+ attribute,
);
}
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 0d2d457e9a..8c634f2633 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -989,6 +989,18 @@
"name": "loop_facts_drift",
"status": "ok"
},
+ {
+ "category": "brain",
+ "message": "inbound links per page p50 0, p90 0, p99 0, max 0 over 0 pages; hub dampening is off (search.hub_dampening). To see whether hub pages crowd a query, run gbrain search \"<query>\" --explain and read each row's backlink inbound count and hub weight.",
+ "name": "hub_degree_shape",
+ "status": "ok"
+ },
+ {
+ "category": "brain",
+ "message": "extraction.date_grounding is off: extraction prompts keep relative dates (\"last week\") as written. Dated pages still store their facts at the page date.",
+ "name": "extraction_date_grounding",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
@@ -1710,7 +1722,7 @@
},
{
"category": "brain",
- "message": "No retrieval-affecting files changed in working tree.",
+ "message": "4 retrieval-affecting file(s) changed since HEAD: src/core/search/explain-target.ts, src/core/search/hybrid.ts, src/core/search/hybrid/keyword-only.ts, …. Re-run `gbrain eval run-all` after committing these changes.",
"name": "eval_drift",
"status": "ok"
},
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index f769567eb8..e8c4924cd0 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -38,6 +38,8 @@
* disclosure), get_write_request (poll cadence and final states),
* add_timeline_entry (when no call is needed) and the instructions (write
* guidance); the served list still fits 25,000 model-visible characters.
+ * query +175 (P2): the `explain` and `explain_target` params (score_details
+ * and missing-page diagnosis), declared on query only so search stays lean.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -64,7 +66,7 @@ const TOOL_BUDGETS: Record<string, number> = {
get_backlinks: 770, get_ingest_log: 280, get_page: 930, get_recent_salience: 660, get_skill: 910,
get_skill_asset: 790, get_write_request: 360, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 1060, list_skills: 670, list_write_requests: 450, put_page: 1460,
- mute_notice: 460, put_skill: 1420, query: 3100, recall: 1540, remember: 1330, request_tools: 560, resolve_slugs: 410, search: 1670,
+ mute_notice: 460, put_skill: 1420, query: 3280, recall: 1540, remember: 1330, request_tools: 560, resolve_slugs: 410, search: 1670,
submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 810, whoami: 230,
};
diff --git a/test/search/arm-confidence.test.ts b/test/search/arm-confidence.test.ts
index 206f1f93d1..2999917862 100644
--- a/test/search/arm-confidence.test.ts
+++ b/test/search/arm-confidence.test.ts
@@ -229,11 +229,12 @@ describe('composeFusionLists — arm-confidence weighting of the keyword + title
test('floor null / unset → byte-identical entries: no `weight` key anywhere', () => {
for (const floor of [null, undefined]) {
const lists = compose({ floor });
+ // `arm` is the explain-only instance label; fusion never reads it.
expect(lists).toEqual([
- { list: [gold], k: KS.vectorK },
- { list: [d1, d2], k: KS.keywordK },
- { list: [d1, d2], k: KS.keywordK },
- { list: [rel], k: KS.baseRrfK },
+ { list: [gold], k: KS.vectorK, arm: 'vector' },
+ { list: [d1, d2], k: KS.keywordK, arm: 'keyword' },
+ { list: [d1, d2], k: KS.keywordK, arm: 'title' },
+ { list: [rel], k: KS.baseRrfK, arm: 'relational' },
]);
for (const e of lists) expect(e).not.toHaveProperty('weight');
}
@@ -243,10 +244,10 @@ describe('composeFusionLists — arm-confidence weighting of the keyword + title
let decision: KeywordArmConfidenceDecision | undefined;
const lists = compose({ floor: 0.6, onDecision: (d) => { decision = d; } });
expect(lists).toEqual([
- { list: [gold], k: KS.vectorK },
- { list: [d1, d2], k: KS.keywordK, weight: 0.5 },
- { list: [d1, d2], k: KS.keywordK, weight: 0.5 },
- { list: [rel], k: KS.baseRrfK },
+ { list: [gold], k: KS.vectorK, arm: 'vector' },
+ { list: [d1, d2], k: KS.keywordK, weight: 0.5, arm: 'keyword' },
+ { list: [d1, d2], k: KS.keywordK, weight: 0.5, arm: 'title' },
+ { list: [rel], k: KS.baseRrfK, arm: 'relational' },
]);
expect(lists[0]).not.toHaveProperty('weight');
expect(lists[3]).not.toHaveProperty('weight');
@@ -256,8 +257,8 @@ describe('composeFusionLists — arm-confidence weighting of the keyword + title
test('strong arm (single keyword row) → unchanged; callback reports downweighted false', () => {
let decision: KeywordArmConfidenceDecision | undefined;
const lists = compose({ floor: 0.6, keyword: [d1], onDecision: (d) => { decision = d; } });
- expect(lists[1]).toEqual({ list: [d1], k: KS.keywordK });
- expect(lists[2]).toEqual({ list: [d1, d2], k: KS.keywordK });
+ expect(lists[1]).toEqual({ list: [d1], k: KS.keywordK, arm: 'keyword' });
+ expect(lists[2]).toEqual({ list: [d1, d2], k: KS.keywordK, arm: 'title' });
expect(decision).toEqual({ margin_ratio: 1, top_score: 0.2, downweighted: false });
});
@@ -280,7 +281,7 @@ describe('composeFusionLists — arm-confidence weighting of the keyword + title
const variantOnly: VectorArm[] = [];
pushVectorList(variantOnly, [], 'original');
pushVectorList(variantOnly, [gold], 'variant');
- expect(compose({ floor: 0.6, arms: variantOnly })[2]).toEqual({ list: [d1, d2], k: KS.keywordK, weight: 0.5 });
+ expect(compose({ floor: 0.6, arms: variantOnly })[2]).toEqual({ list: [d1, d2], k: KS.keywordK, weight: 0.5, arm: 'keyword' });
});
test('empty keyword list → unchanged; the empty title list is still omitted', () => {
@@ -293,7 +294,7 @@ describe('composeFusionLists — arm-confidence weighting of the keyword + title
ks: KS,
knobs: { expansionVariantBudget: null, keywordArmConfidenceFloor: 0.6 },
});
- expect(lists).toEqual([{ list: [gold], k: KS.vectorK }, { list: [], k: KS.keywordK }]);
+ expect(lists).toEqual([{ list: [gold], k: KS.vectorK, arm: 'vector' }, { list: [], k: KS.keywordK, arm: 'keyword' }]);
});
test('the callback fires exactly once per composition, even with the knob off; a throwing callback never breaks fusion', () => {
diff --git a/test/search/explain.test.ts b/test/search/explain.test.ts
index 41a5ff8b95..754d050788 100644
--- a/test/search/explain.test.ts
+++ b/test/search/explain.test.ts
@@ -52,7 +52,8 @@ describe('RRF arm attribution', () => {
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);
+ const fused = rrfFusionWeighted(lists, false, true);
+ expect(rrfFusionWeighted(lists, false).every(r => r.rrf === undefined)).toBe(true);
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);
@@ -128,7 +129,7 @@ describe('diagnoseProbe', () => {
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(amb.fix?.mcp?.arguments).toMatchObject({ query: 'q', explain_target: 'default:s' });
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');