Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search/query: explain_target diagnosis and its cause in CLI --json (#7192)

garrytan21008fd66967
diff --git a/docs/guides/search-explain.md b/docs/guides/search-explain.md
index 5cf51479ce..a764af64ec 100644
--- a/docs/guides/search-explain.md
+++ b/docs/guides/search-explain.md
@@ -72,17 +72,23 @@ MCP:
```
The response meta `explain_target` holds the diagnosis, and a notice carries
-the next step:
+the next step. On the command line, `gbrain search|query "<q>" --explain-target
+<source>:<slug> --json` prints `{ "results": [...], "explain_target": {...} }`
+instead of the bare array, with the fix rendered as a command (`next`, `argv`,
+`command`); without `--explain-target` the output stays an array. When an arm
+failed on the call, `why` names it, since a failed arm is not evidence of absence:
| `code` | What happened | Next step |
|---|---|---|
| `target_returned` | The page is in the results at `rank`. | Read its `score_details`. |
-| `target_beyond_limit` | It ranked below the requested limit. | The notice repeats the search with a limit that reaches it. |
+| `target_collapsed` | It is a copy folded into the result at `rank`, which lists it in `collapsed`. | Read that row, or set `search.collapse false` to return every copy. |
+| `target_beyond_limit` | It ranked below the requested limit; `arms` and `why` give each arm's rank. | The notice repeats the search with a limit that reaches it. |
| `target_dropped_dedup` | Dedup kept a higher-ranked row from the same page or a near-duplicate. | Read the page directly with `get_page`. |
| `target_dropped_return_sizing` | Autocut or adaptive return trimmed it. | `get_page`, or repeat with `autocut: false` (query). |
| `target_dropped_token_budget` | The evidence budget filled first. | Repeat with a larger `token_budget`. |
| `target_dropped_relaxed_keyword` | Only a loose keyword match found it. | `get_page`, or rephrase with the page's own terms. |
| `target_not_retrieved` | No arm returned it for this query. | `query --expand` (`expand: true`; one call to the configured expansion model) or rephrase. |
+| `target_not_embedded` | Its chunks have no vectors (held from embedding or not embedded yet), so only a keyword or title match can return it. | `gbrain doctor --json` names the held pages and the embed command. |
| `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`. |
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 0aa2960272..586920ca19 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -76,7 +76,7 @@ import {
type CliDispatchContext,
} from './command-table.ts';
import { formatRememberResult } from './remember-format.ts';
-import { applyCliOpNotices, captureCapacityNotices, captureOpNotice, captureRetrievalNotices } from './op-notices.ts';
+import { applyCliOpNotices, captureCapacityNotices, captureOpNotice, captureRetrievalNotices, withExplainTargetJson } from './op-notices.ts';
// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,
// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as a
@@ -1667,7 +1667,7 @@ export function formatResult(
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';
+ return JSON.stringify(withExplainTargetJson(params, meta, 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
// (degradation stages from _meta.retrieval / the local meta capture) —
diff --git a/src/cli/op-notices.ts b/src/cli/op-notices.ts
index a1bf9792ea..dda9ba947d 100644
--- a/src/cli/op-notices.ts
+++ b/src/cli/op-notices.ts
@@ -6,7 +6,7 @@
* gets stderr lines on a TTY and an `[AGENT]` block otherwise (stdout is data).
* One op per CLI process, so module state is safe.
*/
-import { cliRenderContext, renderNotice, type Notice } from '../core/agent-output.ts';
+import { cliRenderContext, renderAction, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { renderCliNotices } from '../core/agent-markers.ts';
import { isInteractive } from '../core/interaction.ts';
import { processNoticeLedger, mutedNoticeCodes } from '../core/notice-ledger.ts';
@@ -37,6 +37,18 @@ export function captureRetrievalNotices(
pending.push(...recallInteropNotices(op, result, { retrieval: retrieval ?? {} }, params, { config, transport: 'cli' }));
}
+/**
+ * #7192: `search|query --explain-target … --json` prints `{ results, explain_target }` so the diagnosis and its cause
+ * reach stdout (a bare array has nowhere to put them); a local run's fix renders as a command (next + argv).
+ * Without the flag, or when the run recorded no diagnosis, the rows stay a bare array.
+ */
+export function withExplainTargetJson(params: Record<string, unknown>, meta: Record<string, unknown> | null | undefined, rows: unknown[]): unknown {
+ const diag = params.explain_target ? meta?.explain_target as (Record<string, unknown> & { fix?: Action }) | undefined : undefined;
+ if (!diag || typeof diag !== 'object') return rows;
+ const { fix, ...rest } = diag;
+ return { results: rows, explain_target: fix && typeof fix === 'object' && 'why' in fix ? { ...rest, fix: renderAction(fix, cliRenderContext()) } : rest };
+}
+
/** Drain the captured notices into the result (`--json` objects) and/or a stderr string. */
export function applyCliOpNotices(result: unknown, json: boolean): { result: unknown; stderr?: string } {
const captured = [...pending, ...takeChatFallbackHopNotices()];
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 07bfa8c057..5b35652471 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -591,20 +591,25 @@ function withExplainTarget(meta: Record<string, unknown>, diagnosis: ExplainTarg
/** 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',
+ results: SearchResult[], tool: 'search' | 'query', degraded?: HybridSearchMeta['degraded'],
): 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;
+ const traced = diagnoseTrace(prep.trace, results, { tool, arguments: explainRetryArgs(p) }, degraded);
+ // A probe finding (no chunks / no vectors / stale projection / unsealed) explains an unretrieved page better than
+ // "no arm found it", except "no vectors" when the semantic arm did not run on this call at all (keyless, embed failure).
+ const vectorArmOff = (degraded ?? []).some(d => ['embed_unavailable', 'embed_timeout', 'vector_arm_failed'].includes(d.stage));
+ const probeWins = prep.early && !(prep.early.code === 'target_not_embedded' && vectorArmOff);
+ diag = traced.state === 'not_retrieved' && probeWins ? { ...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;
+ // #7192: the local CLI renders the fix into its --json object; MCP callers read it from the notice.
+ if (ctx.remote === false) return diag;
const { fix: _fix, ...wire } = diag;
return wire as ExplainTargetDiagnosis;
}
@@ -785,7 +790,7 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap, timings,
- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search', capturedMeta?.degraded)),
keywordCountMeta(await keywordCount, offset + limit)));
},
scope: 'read', mutating: false,
@@ -1194,7 +1199,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap, timings,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query', capturedMeta?.degraded)));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/search/explain-target.ts b/src/core/search/explain-target.ts
index 705ea2f446..d4a1375e88 100644
--- a/src/core/search/explain-target.ts
+++ b/src/core/search/explain-target.ts
@@ -99,6 +99,29 @@ function armsOf(trace: TargetTrace): ExplainTargetDiagnosis['arms'] {
return trace.arms().filter(o => o.present).map(o => ({ arm: o.stage.slice(4), rank: o.rank! }));
}
+type Retry = { tool: 'search' | 'query'; arguments: Record<string, unknown> };
+
+/** A complete retry: the MCP call and the CLI argv for the same arguments (#7192: a fix always names its command). */
+function retryAction(tool: 'search' | 'query', args: Record<string, unknown>, why: string): Action {
+ const { json, ...mcpArgs } = args;
+ const argv = ['gbrain', tool, String(args.query ?? '')];
+ for (const [key, value] of Object.entries(mcpArgs)) {
+ if (key === 'query' || value === undefined || value === null || typeof value === 'object') continue;
+ const flag = key.replace(/_/g, '-');
+ if (typeof value === 'boolean') argv.push(value ? `--${flag}` : `--no-${flag}`);
+ else argv.push(`--${flag}`, String(value));
+ }
+ if (json === true) argv.push('--json');
+ return { mcp: { tool, arguments: mcpArgs }, argv, consent: [], actor: 'agent', requires_exclusive: false, why };
+}
+
+/** Recall-affecting arm failures on this call, as one clause (#7171): an arm that did not answer is not evidence of absence. */
+function degradedClause(degraded: ReadonlyArray<{ stage?: string; reason?: string }> | undefined): string {
+ const arms = (degraded ?? []).filter(d => /_arm_failed$|^embed_(timeout|unavailable)$/.test(d.stage ?? ''))
+ .map(d => `${d.stage}${d.reason ? ` (${d.reason})` : ''}`);
+ return arms.length ? ` On this call ${arms.join(', ')}, so that arm returned nothing.` : '';
+}
+
/**
* Turn the observations into one state. `returned` is the final row list the
* caller receives. `retry` holds the original search arguments so every fix
@@ -107,7 +130,8 @@ function armsOf(trace: TargetTrace): ExplainTargetDiagnosis['arms'] {
export function diagnoseTrace(
trace: TargetTrace,
returned: readonly SearchResult[],
- retry: { tool: 'search' | 'query'; arguments: Record<string, unknown> },
+ retry: Retry,
+ degraded?: ReadonlyArray<{ stage?: string; reason?: string }>,
): ExplainTargetDiagnosis {
const target = { slug: trace.target.slug, ...(trace.target.sourceId ? { source_id: trace.target.sourceId } : {}) };
const stages = trace.observations;
@@ -127,15 +151,21 @@ export function diagnoseTrace(
: { 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.` };
}
+ const into = returned.findIndex(r => r.collapsed?.some(c => c.slug === trace.target.slug && (trace.target.sourceId === undefined || (c.source_id ?? 'default') === trace.target.sourceId)));
+ if (into >= 0) {
+ const kept = returned[into];
+ const reason = kept.collapsed!.find(c => c.slug === trace.target.slug)!.reason;
+ return { target, state: 'retrieved', code: 'target_collapsed', rank: into + 1, arms, stages,
+ why: `The page was folded into result #${into + 1} (${kept.source_id ?? 'default'}:${kept.slug}) as a ${reason}; that row lists it in \`collapsed\`. \`search.collapse false\` returns every copy.` };
+ }
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.' } };
+ why: `No retrieval arm (semantic, keyword, title, relational) returned the page for this query.${degradedClause(degraded)}`,
+ fix: retryAction('query', { ...retry.arguments, expand: true }, 'Expansion (one LLM call) 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');
@@ -151,12 +181,11 @@ export function diagnoseTrace(
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}.` } };
+ const armRanks = arms.map(a => a.arm + ' #' + a.rank).join(', ');
+ return { ...base, why: loss.why + ' It was #' + lastSeen.rank + ' after ranking' + (armRanks ? ' (arm ranks: ' + armRanks + ')' : '') + '.', fix: retryAction(retry.tool, { ...retry.arguments, limit: Math.min(100, lastSeen.rank + 5) }, `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: retryAction(retry.tool, { ...retry.arguments, token_budget: 12000 }, 'Repeat the same search with a larger evidence token budget, or read the page directly with get_page.') };
}
return { ...base, fix: getPage };
}
@@ -168,6 +197,8 @@ export function diagnoseTrace(
export interface TargetProbeRow {
source_id: string;
chunks: number;
+ /** Chunks with a vector; 0 with chunks > 0 means only the keyword and title arms can return the page. */
+ embedded: number;
current: boolean;
chunker_version: number | null;
}
@@ -178,13 +209,14 @@ type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[])
export async function probeTarget(query: ReadQuery, slug: string, policy: PageReadPolicy, chunkManifest = true): 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 }>(
+ const rows = await query<{ source_id: string; chunks: number; embedded: number; current: boolean; chunker_version: number | null }>(
`SELECT p.source_id,
(SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc', chunkManifest)}) AS chunks,
+ (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedding IS NOT NULL AND ${chunkGenerationFilter('p', 'cc', chunkManifest)}) AS embedded,
((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) }));
+ return rows.map(r => ({ source_id: r.source_id, chunks: Number(r.chunks), embedded: Number(r.embedded), current: r.current === true, chunker_version: r.chunker_version == null ? null : Number(r.chunker_version) }));
}
/**
@@ -194,7 +226,7 @@ export async function probeTarget(query: ReadQuery, slug: string, policy: PageRe
export function diagnoseProbe(
ref: ExplainTargetRef,
rows: readonly TargetProbeRow[],
- opts: { requireSafeChunks: boolean; retry: { tool: 'search' | 'query'; arguments: Record<string, unknown> } },
+ opts: { requireSafeChunks: boolean; retry: Retry },
): 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;
@@ -207,8 +239,7 @@ 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 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(', ')}.` } };
+ fix: retryAction(opts.retry.tool, { ...opts.retry.arguments, explain_target: `${scoped[0].source_id}:${ref.slug}` }, `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 };
@@ -224,6 +255,12 @@ export function diagnoseProbe(
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 (row.embedded === 0) {
+ return { target: withSource, state: 'not_retrieved', code: 'target_not_embedded', arms: [], stages: [],
+ why: `None of the page's ${row.chunks} chunks has a vector (held from embedding or not embedded yet), so the semantic arm cannot return it; only an exact keyword or title match can.`,
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Doctor reports pages held from embedding or missing vectors and the command that embeds them.' } };
+ }
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.',
diff --git a/test/search/explain-target-cli-json-7192.test.ts b/test/search/explain-target-cli-json-7192.test.ts
new file mode 100644
index 0000000000..b5d02ae9c7
--- /dev/null
+++ b/test/search/explain-target-cli-json-7192.test.ts
@@ -0,0 +1,51 @@
+/**
+ * #7192: \`gbrain search|query --explain-target <source>:<slug> --json\` puts the
+ * diagnosis and its cause in stdout JSON (it used to ride only stderr), with the
+ * fix rendered as a runnable command. Without --explain-target the output stays
+ * a bare array.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { captureRetrievalMeta, formatResult, resetRetrievalMetaForTests } from '../../src/cli/main.ts';
+import { diagnoseTrace, TargetTrace } from '../../src/core/search/explain-target.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+
+const row = (slug: string, score: number) => ({ slug, score, page_id: 1, title: slug, type: 'note', chunk_text: 't', chunk_source: 'compiled_truth', stale: false, source_id: 'default' }) as SearchResult;
+
+afterEach(() => resetRetrievalMetaForTests());
+
+describe('#7192 explain_target in CLI --json', () => {
+ test('a target cut by the limit: object form with the cause, per-arm ranks and a runnable retry', () => {
+ const t = new TargetTrace({ slug: 'notes/x', sourceId: 'default' });
+ const pool = [row('notes/a', 0.9), row('notes/b', 0.8), row('notes/x', 0.7)];
+ t.observe('arm:vector', [row('notes/x', 0.7), row('notes/a', 0.9)]);
+ t.observe('arm:keyword', pool);
+ for (const stage of ['fused', 'deduped', 'return_pool'] as const) t.observe(stage, pool);
+ t.observe('limit_slice', pool.slice(0, 2));
+ const diag = diagnoseTrace(t, pool.slice(0, 2), { tool: 'search', arguments: { query: 'acme-example terms', limit: 2, expand: false, json: true } });
+ captureRetrievalMeta('retrieval', { explain_target: diag });
+ const out = JSON.parse(formatResult('search', pool.slice(0, 2), { json: true, explain_target: 'default:notes/x' }));
+ expect(out.results.map((r: SearchResult) => r.slug)).toEqual(['notes/a', 'notes/b']);
+ expect(out.explain_target).toMatchObject({ code: 'target_beyond_limit', state: 'dropped', last_rank: 3 });
+ expect(out.explain_target.arms).toEqual([{ arm: 'vector', rank: 1 }, { arm: 'keyword', rank: 3 }]);
+ expect(out.explain_target.why).toContain('arm ranks: vector #1, keyword #3');
+ expect(out.explain_target.fix).toMatchObject({ next: 'run', argv: ['gbrain', 'search', 'acme-example terms', '--limit', '8', '--no-expand', '--json'] });
+ expect(diag.fix?.mcp).toEqual({ tool: 'search', arguments: { query: 'acme-example terms', limit: 8, expand: false } });
+ expect(out.explain_target.fix.command).toContain('--limit 8');
+ });
+
+ test('no arm found it: the retry is a concrete command, not a bare tell_user_to_run', () => {
+ const t = new TargetTrace({ slug: 'notes/x' });
+ t.observe('arm:vector', [row('notes/a', 1)]);
+ const diag = diagnoseTrace(t, [], { tool: 'search', arguments: { query: 'q' } }, [{ stage: 'keyword_arm_failed', reason: 'timeout' }] as never);
+ expect(diag.why).toContain('keyword_arm_failed (timeout)');
+ captureRetrievalMeta('retrieval', { explain_target: diag });
+ const out = JSON.parse(formatResult('search', [], { json: true, explain_target: 'notes/x' }));
+ expect(out.results).toEqual([]);
+ expect(out.explain_target.fix).toMatchObject({ next: 'run', argv: ['gbrain', 'query', 'q', '--expand'] });
+ });
+
+ test('without --explain-target the --json output is still a bare array', () => {
+ captureRetrievalMeta('retrieval', { explain_target: { code: 'target_returned' } });
+ expect(JSON.parse(formatResult('search', [row('notes/a', 1)], { json: true }))).toHaveLength(1);
+ });
+});
diff --git a/test/search/explain.test.ts b/test/search/explain.test.ts
index 8c7571a0ed..baabb25577 100644
--- a/test/search/explain.test.ts
+++ b/test/search/explain.test.ts
@@ -114,6 +114,13 @@ describe('diagnoseTrace', () => {
expect(diagnoseTrace(t, [row('notes/a', 1)], retry)).toMatchObject({ state: 'dropped', code: 'target_dropped_relaxed_keyword' });
});
+ test('#7192: a page folded into a kept row is retrieved as target_collapsed at that row', () => {
+ const t = new TargetTrace({ slug: 'notes/x-copy' });
+ t.observe('arm:keyword', [row('notes/x', 2), row('notes/x-copy', 2)]);
+ const kept = { ...row('notes/x', 2), collapsed: [{ slug: 'notes/x-copy', source_id: 'default', reason: 'twin' }] } as SearchResult;
+ expect(diagnoseTrace(t, [row('notes/a', 3), kept], retry)).toMatchObject({ state: 'retrieved', code: 'target_collapsed', rank: 2 });
+ });
+
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)]);
@@ -124,7 +131,7 @@ describe('diagnoseTrace', () => {
describe('diagnoseProbe', () => {
const retry = { tool: 'query' as const, arguments: { query: 'q' } };
- const ok = { source_id: 'default', chunks: 2, current: true, chunker_version: 99 };
+ const ok = { source_id: 'default', chunks: 2, embedded: 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 })!;
@@ -134,6 +141,8 @@ describe('diagnoseProbe', () => {
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();
+ expect(diagnoseProbe({ slug: 's' }, [{ ...ok, embedded: 0 }], { requireSafeChunks: false, retry })!.code).toBe('target_not_embedded');
+ expect(amb.fix?.argv).toEqual(['gbrain', 'query', 'q', '--explain-target', 'default:s']);
});
});
@@ -179,6 +188,12 @@ describe('search / query ops with explain (PGLite, keyless)', () => {
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' }));
+ // #7192: the local CLI keeps the fix (rendered into its --json object); a remote caller reads it from the notice only.
+ expect((metas.at(-1)?.explain_target as { fix?: { argv?: string[] } }).fix?.argv).toEqual(['gbrain', 'search', 'quokka', '--limit', '7']);
+ metas.length = 0;
+ await operationsByName.search.handler(ctx(true), { query: 'quokka', limit: 1, explain_target: all[1].slug });
+ expect(metas.at(-1)?.explain_target).toMatchObject({ code: 'target_beyond_limit' });
+ expect((metas.at(-1)?.explain_target as { fix?: unknown }).fix).toBeUndefined();
});
test('a private page and a nonexistent page look identical to a remote caller', async () => {
@@ -196,5 +211,7 @@ describe('search / query ops with explain (PGLite, keyless)', () => {
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');
+ // #7192: a keyless brain has no vectors anywhere; with the semantic arm off on this call, "no vectors" is not the cause.
+ expect((metas.at(-1)?.explain_target as { code: string }).code).toBe('target_not_retrieved');
});
});