Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/ranking-wave-b
garrytan269665737332
diff --cc src/cli/main.tsindex 586920ca19,cd39ec2996..058dc4116c--- a/src/cli/main.ts+++ b/src/cli/main.ts@@@ -76,7 -77,8 +77,8 @@@ importtype 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';+ import { searchTimingsDocument, searchTimingsLine, timeCliPhase } from './search-timings.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 -1666,7 +1666,7 @@@ export function formatResultif (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(withExplainTargetJson(params, meta, answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results), null, 2) + '\n';- return JSON.stringify(searchTimingsDocument(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, meta), null, 2) + '\n';++ return JSON.stringify(withExplainTargetJson(params, meta, searchTimingsDocument(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, meta)), 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 --cc src/cli/op-notices.tsindex dda9ba947d,a1bf9792ea..d2f2d9d989--- a/src/cli/op-notices.ts+++ b/src/cli/op-notices.ts@@@ -37,18 -37,6 +37,19 @@@ export function captureRetrievalNoticespending.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 {++export function withExplainTargetJson(params: Record<string, unknown>, meta: Record<string, unknown> | null | undefined, doc: 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;++ if (!diag || typeof diag !== 'object') return doc;+ const { fix, ...rest } = diag;- return { results: rows, explain_target: fix && typeof fix === 'object' && 'why' in fix ? { ...rest, fix: renderAction(fix, cliRenderContext()) } : rest };++ const explain_target = fix && typeof fix === 'object' && 'why' in fix ? { ...rest, fix: renderAction(fix, cliRenderContext()) } : rest;++ return Array.isArray(doc) ? { results: doc, explain_target } : { ...(doc as Record<string, unknown>), explain_target };+}+/** 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 --cc src/core/ops/search.tsindex 5b35652471,7b1a987b8a..b59491d43c--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@@ -790,7 -795,7 +800,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', capturedMeta?.degraded)),- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, filterHintFor: { op: 'search', p } })), ...(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, filterHintFor: { op: 'search', p } })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search', capturedMeta?.degraded)),keywordCountMeta(await keywordCount, offset + limit)));},scope: 'read', mutating: false,@@@ -1199,7 -1205,7 +1210,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', capturedMeta?.degraded)));- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, filterHintFor: { op: 'query', p } })), 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, filterHintFor: { op: 'query', p } })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query', capturedMeta?.degraded)));},scope: 'read', mutating: false,cliHints: { name: 'query', positional: ['query'] },diff --cc test/search/explain-target-cli-json-7192.test.tsindex b5d02ae9c7,0000000000..37bf34add6mode 100644,000000..100644--- a/test/search/explain-target-cli-json-7192.test.ts+++ b/test/search/explain-target-cli-json-7192.test.ts@@@ -1,51 -1,0 +1,57 @@@+/**+ * #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 { withExplainTargetJson } from '../../src/cli/op-notices.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('with --timings the diagnosis joins the timings document instead of replacing it', () => {++ const doc = withExplainTargetJson({ explain_target: 'notes/x' }, { explain_target: { code: 'target_returned', rank: 1 } }, { results: [], timings_ms: { total: 5 } });++ expect(doc).toEqual({ results: [], timings_ms: { total: 5 }, explain_target: { code: 'target_returned', rank: 1 } });++ });+++ 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);+ });+});