Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(query): expansion default follows the search mode (GBRA-81 item 1b)
garrytanb67796e732a3
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 678b303a44..ffe2e9d570 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -289,11 +289,11 @@ Replace a complete canonical Markdown page. Read get_page with include_content:t## `query`-Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged. Rows with `result_type: "fact"` are saved facts, not pages: they have no `slug` or `id`; follow `follow_up` (a `recall` call), or pass `page_slug` to get_page when it is present.+Hybrid search with vector + keyword, plus multi-query expansion when the search mode or the call asks for it (`expand` unset follows the mode: off in conservative and balanced, on in tokenmax; `expand: true` forces it). Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z'); expansion can recover synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (it never expands). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged. Rows with `result_type: "fact"` are saved facts, not pages: they have no `slug` or `id`; follow `follow_up` (a `recall` call), or pass `page_slug` to get_page when it is present.| Parameter | Type | Guidance || --- | --- | --- |-| `query` | string | Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params. |+| `query` | string | Question or topic text for hybrid retrieval (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params. || `image` | string | Base64-encoded image bytes for image-similarity search (CLI: --image <path>). || `image_mime` | string | MIME type for the image bytes (auto-derived from path on CLI; required when calling op directly). || `limit` | number | Max results. Omitted or 0 resolves from the active search mode (10 conservative / 25 balanced / 50 tokenmax by default, or the configured `search.searchLimit` override) — for both text queries and image-similarity queries (`image` param). |@@ -303,7 +303,7 @@ Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for| `return_unit` | string (`chunk`, `window`, `section`, `page`, `auto`) | Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').<br> 'chunk' — the ranked chunk only (~300-450 tokens per result).<br> 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).<br> 'section' — the enclosing markdown section, or the conversation rounds around the hit.<br> 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.<br> 'auto' — the whole page for conversation pages (conversation/transcript/chat/meeting/slack/imessage types, chat/ or conversations/ slugs), the ranked chunk unchanged for everything else. When no hit is a conversation the response is exactly the chunk response.<br>Non-chunk units return one result per page, packed into token_budget (default 6000, auto 24000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated; reason under auto) per result and `delivery` in the response meta. || `return_window` | number | Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1). || `token_budget` | number | Token budget. Chunk mode, and whenever return_unit is omitted: caps the cumulative chunk payload (results that would overflow are skipped). Explicit non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000, auto 24000; remote max search.return_budget_max_remote = 32000). |-| `expand` | boolean | Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used. |+| `expand` | boolean | Multi-query expansion. Unset follows the search mode (`search.expansion`, else off in conservative and balanced, on in tokenmax); true forces it, false skips it. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used. || `detail` | string | Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks) || `mode` | string | Search mode (conservative\|balanced\|tokenmax). Local callers only; remote uses configured mode. || `lang` | string | Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby) |@@ -382,7 +382,7 @@ Fuzzy-resolve a partial slug to matching page slugs## `search`-Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.+Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (it can add multi-query expansion with `expand: true`); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.Every call also reports how many pages match the query's keywords (`keyword_total`, `keyword_truncated`; "10000+" past 10,000) in one line after the rows. That count covers keyword (full-text) matches only, not the ranked rows. To list every one of those pages, pass `match: "keyword"`: rows come one per page in keyword-score order with `total`, `truncated` and `next`, a ready-to-send argument object; keep calling with `next` until it is absent. A page whose text did not fit `token_budget` still gets a row, with `evidence_omitted: true`. If the count times out, the line says it is unavailable (degraded stage `keyword_count_unavailable`), never zero.diff --git a/src/cli/top-help.ts b/src/cli/top-help.tsindex d842103396..202fd476d8 100644--- a/src/cli/top-help.ts+++ b/src/cli/top-help.ts@@ -41,8 +41,8 @@ PAGESSEARCHsearch <query> Keyword search (tsvector)- query <question> [--no-expand] Hybrid search (RRF + expansion)- ask <question> [--no-expand] Alias for query+ query <question> [--expand] Hybrid search (RRF; expansion per search mode)+ ask <question> [--expand] Alias for queryIMPORT/EXPORTimport <dir> [--no-embed] Import markdown directorydiff --git a/src/commands/eval-replay.ts b/src/commands/eval-replay.tsindex 9df0e496eb..a06abff797 100644--- a/src/commands/eval-replay.ts+++ b/src/commands/eval-replay.ts@@ -264,7 +264,9 @@ async function replayRow(engine: BrainEngine, row: CapturedRow, opts: ReplayOptscurrent = await hybridSearch(engine, row.query, {limit,detail: row.detail ?? undefined,- expansion: row.expand_enabled ?? false,+ // A captured `expand` of null means the caller left it unset, so the+ // mode's default decides (query's default follows search.mode).+ expansion: row.expand_enabled ?? undefined,// v0.36 (D16 / CDX-10): replay the SAME column that ran at capture// time so config drift between capture and replay doesn't surface// as "regression." NULL/undefined falls through to resolver default.diff --git a/src/core/eval-capture.ts b/src/core/eval-capture.tsindex 2326119fb3..711d7b9238 100644--- a/src/core/eval-capture.ts+++ b/src/core/eval-capture.ts@@ -64,7 +64,7 @@ export interface CaptureContext {latency_ms: number;/** OperationContext.remote — true for MCP callers, false for local CLI. */remote: boolean;- /** The `expand` flag as requested by the caller (query-only; null for search). */+ /** The raw `expand` param the caller passed (query-only): null when unset (the mode decided) and for search. What ran is `meta.expansion_applied`. */expand_enabled: boolean | null;/** The `detail` flag as requested (query-only). */detail: 'low' | 'medium' | 'high' | null;diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 4ffff38307..e12554b4dd 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -963,7 +963,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "query","idempotent": true,"outputRedaction": "retrieval",- "description": "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",+ "description": "Hybrid search for concept/landscape questions; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.","params": {"query": {"type": "string",@@ -1018,7 +1018,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"expand": {"type": "boolean",- "description": "Default true; false skips the LLM expansion."+ "description": "Default per search mode (tokenmax on)."},"detail": {"type": "string",diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 22c1bfb377..6f58280c4e 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -49,7 +49,7 @@ export const LIST_PAGES_DESCRIPTION ="List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; a full page may be truncated: continue with updated_after + updated_after_slug from the last row.";export const QUERY_DESCRIPTION =- "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.";+ "Hybrid search for concept/landscape questions; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.";export const SEARCH_DESCRIPTION ="Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.";diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex e7560743b0..5d7644023a 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -445,8 +445,8 @@ async function buildRetrievalResponseMeta(): Promise<Record<string, unknown>> {const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;const hint = opts.conceptHint && looksConceptShaped(queryText)- ? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " +- 'synonym-phrased matches this keyword-leaning search can miss.'+ ? "concept-shaped question — the 'query' tool with expand: true adds multi-query expansion, " ++ 'which can recover synonym-phrased matches this keyword-leaning search can miss.': undefined;const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);const excludeSlugPrefixes = resolveHardExcludes();@@ -839,7 +839,7 @@ const query: Operation = {return_unit: RETURN_UNIT_PARAM,return_window: RETURN_WINDOW_PARAM,token_budget: { type: 'number', description: 'Evidence token cap.' },- expand: { type: 'boolean', description: 'Default true; false skips the LLM expansion.' },+ expand: { type: 'boolean', description: 'Default per search mode (tokenmax on).' },detail: { type: 'string', description: 'low (compiled truth), medium (default) or high (all chunks).' },fields: FIELDS_PARAM,mode: { type: 'string', description: 'Local callers only.' },@@ -865,7 +865,7 @@ const query: Operation = {},handler: async (ctx, p) => {const startedAt = Date.now();- const expand = p.expand !== false;+ const expandParam = typeof p.expand === 'boolean' ? p.expand : undefined;const detail = (p.detail as 'low' | 'medium' | 'high') || undefined;const queryText = p.query as string | undefined;// #3985: validated multi-type filter (text path; the image-similarity@@ -986,8 +986,8 @@ const query: Operation = {excludePrivate,requireSafeChunks: ctx.remote !== false, decide: { remote: ctx.remote !== false, answerability: true },takesHoldersAllowList: readHolders(ctx),- expansion: expand,- expandFn: expand ? expandQuery : undefined,+ expansion: expandParam,+ expandFn: expandParam === false ? undefined : expandQuery,// T4/D5 — per-call mode (local/trusted only; remote ignored)....((): { mode?: string } => { const m = resolvePerCallMode(ctx, p.mode); return m ? { mode: m } : {}; })(),detail,@@ -1055,16 +1055,17 @@ const query: Operation = {ctx.engine.getConfig('search.crag_escalation').catch(() => null),ctx.engine.getConfig('search.crag_think').catch(() => null),]);- // #4610: pass the documented guard inputs. `callerExpanded: expand`- // implements the long-documented high-ceiling skip — a first pass that- // already ran with expansion (the default) doesn't pay for a second- // expansion LLM call + rerank over a near-identical query. Escalation- // now fires for callers that explicitly opted out of expansion (the- // shape where the forced-expansion re-run has something new to find).+ // #4610: pass the documented guard inputs. `callerExpanded` reads what+ // the first pass actually did (`expansion_applied`), not what was+ // requested: a first pass that produced expansion variants doesn't pay+ // for a second expansion LLM call + rerank over a near-identical query,+ // while one that ran without expansion (the mode default outside+ // tokenmax, an explicit opt-out, or an expander that produced nothing)+ // can still escalate.if (shouldEscalateRetrieval(grade, {enabled: escalationCfg === 'true',alreadyEscalated: false,- callerExpanded: expand,+ callerExpanded: (capturedMeta as HybridSearchMeta | null)?.expansion_applied === true,})) {try {// The caller's effective row contract (shared with the image@@ -1178,7 +1179,7 @@ const query: Operation = {meta,latency_ms,remote: ctx.remote ?? false,- expand_enabled: expand,+ expand_enabled: expandParam ?? null,detail: detail ?? null,job_id: ctx.jobId ?? null,subagent_id: ctx.subagentId ?? null,diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 3f326e6187..0b9b64e6e4 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -105,10 +105,10 @@ export interface ModeBundle {*/tokenBudget: number | undefined;/**- * LLM multi-query expansion (Haiku call per search).- * Per CLAUDE.md TODOS the corpus eval shows ~97.6% lift relative to no- * expansion — barely measurable. Off for conservative/balanced;- * on for tokenmax to preserve power-user retrieval ceiling.+ * LLM multi-query expansion (one chat call per expanded search). The+ * `query` op's default when a call leaves `expand` unset; `search` and the+ * memory verbs never expand. Off for conservative/balanced, on for+ * tokenmax. Override: per-call `expand` → `search.expansion` → bundle.*/expansion: boolean;/**@@ -125,10 +125,10 @@ export interface ModeBundle {* the config parser AND both per-call seams in hybrid.ts.* Arithmetic: two variants agreeing on a distractor at rank 0 tie* the original's rank-0 vote exactly at `b = 1.0`; legacy with two variants- * is ≈ `b = 2.0`; `b = 0.5` subordinates them. Receipt (LongMemEval strict- * recall_all@5, v0.48.2.0 harness): plain hybrid 93.19% vs hybrid + LLM- * expansion 54.89% (paired +3 / −183) — variant lists fusing at full weight- * outvote the original on small-k recall. No-op when `expansion` is off.+ * is ≈ `b = 2.0`; `b = 0.5` subordinates them. Receipt (LongMemEval-S strict+ * recall_all@5, recorded expansions, reranker off, gbrain-evals 2026-10-04):+ * legacy-weight expansion 436/470 vs plain hybrid 434/470 (+6/−4, p = 0.75)+ * — no measured gain. No-op when `expansion` is off.* Override: per-call → `search.expansion_variant_budget` config → bundle.*/expansion_variant_budget: number | null;diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex bb7ebbfa2e..6f37c2af46 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -26,7 +26,7 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {intentWeighting: 'Zero-LLM intent classifier weight adjustments',keywordOrFallback: 'Keyword-arm AND→OR zero-recall fallback',tokenBudget: 'Per-call token-budget cap (undefined = no cap)',- expansion: 'Core-library default only; query defaults on and search stays off regardless of this row',+ expansion: 'LLM multi-query expansion: the `query` default when `expand` is unset (`search` never expands)',expansion_variant_budget: 'Total RRF weight shared by expansion variant lists (null = legacy weight 1 each; (0, 4])',searchLimit: 'Default `limit` for the operation layer',reranker_enabled: 'Cross-encoder reranker on/off',@@ -94,18 +94,19 @@ export function formatKnobValue(knob: string, value: unknown): string {* the BRAIN-LEVEL planes (config override > mode bundle); per-call* SearchOpts overrides on individual searches are not represented here —* a live search that passes its own knobs can legitimately differ from- * this report for that one call. #4601: the `query` op ALWAYS supplies- * `expand` (default on), so the `expansion` row never governs it — say so- * here, on the surface operators actually read, or the dashboard gives a- * confident wrong answer for the primary agent verb.+ * this report for that one call. The `expansion` row is `query`'s default+ * when a call leaves `expand` unset, and `search` never expands; say so here,+ * on the surface operators actually read, so the dashboard answers for the+ * primary agent verb.*/export const MODES_REPORT_PER_CALL_NOTE ='Resolved from config overrides + the active mode bundle. Per-call SearchOpts ' +'overrides on individual searches are not shown — a call that passes its own ' +'knobs (e.g. expand, autocut, relational) wins for that call only. The `query` ' +- 'op always passes `expand` (default on in every mode; `--no-expand` or ' +- '`expand: false` opts out), while `search` never expands. Neither inherits ' +- '`search.expansion`. Expansion needs configured embedding and expansion ' ++ 'op expands when the resolved `expansion` row below is on (the tokenmax ' ++ 'default; `search.expansion` overrides it) unless the call passes `expand` ' ++ '(`--expand` / `expand: true` forces it, `--no-expand` / `expand: false` ' ++ 'skips it), while `search` never expands. Expansion needs configured embedding and expansion ' +'providers; requested expansion is not proof a provider ran. A configured ' +'cloud expander receives the query and may charge for the call.';diff --git a/src/core/search/query-intent.ts b/src/core/search/query-intent.tsindex a5e6a6c68c..3888b77eeb 100644--- a/src/core/search/query-intent.ts+++ b/src/core/search/query-intent.ts@@ -754,8 +754,8 @@ export function conceptNudge(query: string): string | null {if (!looksConceptShaped(query)) return null;const preview = query.length > 60 ? `${query.slice(0, 57)}...` : query;return (- `hint: concept-shaped question — try \`gbrain query "${preview}"\` ` +- `(adds multi-query expansion; recovers synonym-phrased matches search can miss). ` ++ `hint: concept-shaped question — try \`gbrain query "${preview}" --expand\` ` ++ `(multi-query expansion can recover synonym-phrased matches search can miss). ` +`A nonzero search count is not proof of completeness.`);}diff --git a/src/core/search/tune-recommendations.ts b/src/core/search/tune-recommendations.tsindex 186d03635b..796d09619c 100644--- a/src/core/search/tune-recommendations.ts+++ b/src/core/search/tune-recommendations.ts@@ -84,7 +84,7 @@ export async function buildTuneRecommendations(engine: BrainEngine): Promise<Tunknob: 'search.mode',current: 'tokenmax',suggested: 'balanced',- reason: 'Subagent tier is Haiku but mode is tokenmax. Balanced caps the result payload at 12K tokens by default, reducing downstream input volume. It does not disable query expansion; use query --no-expand to skip that provider call. Semantic result caching is temporarily disabled.',+ reason: 'Subagent tier is Haiku but mode is tokenmax. Balanced caps the result payload at 12K tokens by default, reducing downstream input volume, and turns off query expansion by default (query --expand still requests it). Semantic result caching is temporarily disabled.',apply_command: 'gbrain config set search.mode balanced',});}diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 4a4310b130..e071e14d56 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -40,8 +40,8 @@"","SEARCH"," search <query> Keyword search (tsvector)",- " query <question> [--no-expand] Hybrid search (RRF + expansion)",- " ask <question> [--no-expand] Alias for query",+ " query <question> [--expand] Hybrid search (RRF; expansion per search mode)",+ " ask <question> [--expand] Alias for query","","IMPORT/EXPORT"," import <dir> [--no-embed] Import markdown directory",@@ -254,8 +254,8 @@"","SEARCH"," search <query> Keyword search (tsvector)",- " query <question> [--no-expand] Hybrid search (RRF + expansion)",- " ask <question> [--no-expand] Alias for query",+ " query <question> [--expand] Hybrid search (RRF; expansion per search mode)",+ " ask <question> [--expand] Alias for query","","IMPORT/EXPORT"," import <dir> [--no-embed] Import markdown directory",@@ -468,8 +468,8 @@"","SEARCH"," search <query> Keyword search (tsvector)",- " query <question> [--no-expand] Hybrid search (RRF + expansion)",- " ask <question> [--no-expand] Alias for query",+ " query <question> [--expand] Hybrid search (RRF; expansion per search mode)",+ " ask <question> [--expand] Alias for query","","IMPORT/EXPORT"," import <dir> [--no-embed] Import markdown directory",@@ -685,7 +685,7 @@"stdout": ["Usage: gbrain query <query> [options]","",- "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",+ "Hybrid search for concept/landscape questions; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.","","Options:"," <query> Question or topic (required unless image).",@@ -698,7 +698,7 @@" --return-unit Default auto: whole conversations."," --return-window Window radius 1-3."," --token-budget Evidence token cap.",- " --expand Default true; false skips the LLM expansion.",+ " --expand Default per search mode (tokenmax on)."," --detail low (compiled truth), medium (default) or high (all chunks)."," --fields lean (remote default) or full."," --mode Local callers only.",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c516012960..969d3d9267 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 231140,- "stdoutSha256": "bb979a78c5e89bb88016cc8af97c2215136976a11b8fdba6de37d572d83dc54d",+ "stdoutBytes": 231142,+ "stdoutSha256": "aed45d4035c445e1acd71d88d36ea134c5718a97fe26d90a67e524f158422de7","toolNames": ["remember","entity",@@ -1232,7 +1232,7 @@"scope": "read"},{- "description": "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",+ "description": "Hybrid search for concept/landscape questions; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.","idempotent": true,"local_only": false,"mutating": false,@@ -1300,7 +1300,7 @@"type": "string"},"expand": {- "description": "Default true; false skips the LLM expansion.",+ "description": "Default per search mode (tokenmax on).","type": "boolean"},"explain": {diff --git a/test/search/modes-report-coverage.test.ts b/test/search/modes-report-coverage.test.tsindex ab2aa363d8..cf1db45948 100644--- a/test/search/modes-report-coverage.test.ts+++ b/test/search/modes-report-coverage.test.ts@@ -120,9 +120,8 @@ describe('#4604 buildModesReport — full-bundle knob coverage', () => {const report = await buildModesReport(stubEngine());expect(report.per_call_note).toBe(MODES_REPORT_PER_CALL_NOTE);expect(report.per_call_note).toContain('Per-call');- // #4601: the `query` op always passes `expand` (default on), so the- // bundle's `expansion` row never governs it — the note must say so or the- // dashboard gives a confident wrong answer for the primary agent verb.+ // The bundle's `expansion` row is the `query` op's default when a call+ // leaves `expand` unset — the note must say so for the primary agent verb.expect(report.per_call_note).toContain('`query` op');});});diff --git a/test/search/operation-expansion-contract.serial.test.ts b/test/search/operation-expansion-contract.serial.test.tsindex a92c51ff8d..1371944223 100644--- a/test/search/operation-expansion-contract.serial.test.ts+++ b/test/search/operation-expansion-contract.serial.test.ts@@ -1,16 +1,35 @@+/**+ * The `query` expansion contract: the search mode decides the default+ * (`expansion` off in conservative and balanced, on in tokenmax, overridden+ * by `search.expansion`), an explicit `expand` wins in either direction, the+ * expander stays wired whenever expansion can resolve on (so tokenmax still+ * expands), and `search` never expands. Rewritten from the earlier pin+ * ("query requests expansion in every mode") when the default moved to the+ * mode (GBRA-81 item 1b).+ *+ * Serial: configures the process-global gateway with a stub embedder so the+ * vector path (where expansion runs) is reached without a provider call.+ */import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { operationsByName, type OperationContext } from '../../src/core/operations.ts';import * as hybrid from '../../src/core/search/hybrid.ts';import { buildModesReport } from '../../src/core/search/modes-report.ts';import { _exports_for_test as searchCommand } from '../../src/commands/search.ts';-import { MODE_PICKER_MENU, runModePicker } from '../../src/commands/init-mode-picker.ts';import { buildTuneRecommendations } from '../../src/core/search/tune-recommendations.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';+const DIMS = 1536;+const embedTransport = (async (p: { values: string[] }) => ({+ embeddings: p.values.map(() => Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0.01))), values: p.values, warnings: [], usage: { tokens: p.values.length },+})) as unknown as Parameters<typeof __setEmbedTransportForTests>[0];+let engine: PGLiteEngine;beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests(embedTransport);engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();@@ -22,66 +41,124 @@ beforeAll(async () => {]);});-afterAll(async () => { await engine.disconnect(); });+afterAll(async () => {+ await engine.disconnect();+ __setEmbedTransportForTests(null);+ resetGateway();+});++function makeCtx(meta: Record<string, unknown>): OperationContext {+ return {+ engine, remote: false, sourceId: 'default',+ config: { engine: 'pglite' }, logger: console, dryRun: false,+ emitResponseMeta: (key, value) => { meta[key] = value; },+ };+}++/**+ * Spy on the op's hybrid call: record the options it passed and swap the+ * wired expander for a stub, so "expansion ran" is observable without a chat+ * provider. `variants` decides what the stub returns.+ */+function spyHybrid(variants: (q: string) => string[]) {+ const options: Array<Parameters<typeof hybrid.hybridSearchCached>[2]> = [];+ const expanderCalls: string[] = [];+ const original = hybrid.hybridSearchCached;+ const spy = spyOn(hybrid, 'hybridSearchCached').mockImplementation(async (db, query, opts) => {+ options.push(opts);+ const wired = opts?.expandFn+ ? { ...opts, expandFn: async (q: string) => { expanderCalls.push(q); return variants(q); } }+ : opts;+ return original(db, query, wired);+ });+ return { options, expanderCalls, restore: () => spy.mockRestore() };+}++async function resetSearchConfig(mode: string, expansionOverride: string | undefined): Promise<void> {+ await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'search.%'`);+ await engine.setConfig('search.mode', mode);+ if (expansionOverride !== undefined) await engine.setConfig('search.expansion', expansionOverride);+ await engine.setConfig('search.reranker.enabled', 'false');+}-describe('operation expansion remains independent of mode bundles', () => {+describe('query expansion follows the search mode', () => {for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {- for (const override of ['true', 'false']) {- test(`${mode}, search.expansion=${override}: query default, explicit opt-out and search`, async () => {- await engine.setConfig('search.mode', mode);- await engine.setConfig('search.expansion', override);- await engine.setConfig('search.reranker.enabled', 'false');- const options: Array<Parameters<typeof hybrid.hybridSearchCached>[2]> = [];- const original = hybrid.hybridSearchCached;- const spy = spyOn(hybrid, 'hybridSearchCached').mockImplementation(async (db, query, opts) => {- options.push(opts);- return original(db, query, opts);- });+ for (const override of [undefined, 'true', 'false'] as const) {+ const modeDefault = override === undefined ? mode === 'tokenmax' : override === 'true';+ test(`${mode}, search.expansion=${override ?? 'unset'}: default ${modeDefault ? 'expands' : 'does not expand'}, explicit expand wins, search never expands`, async () => {+ await resetSearchConfig(mode, override);+ const probe = spyHybrid(q => [q, `${q} alternate phrasing`]);const meta: Record<string, unknown> = {};- const ctx: OperationContext = {- engine, remote: false, sourceId: 'default',- config: { engine: 'pglite' }, logger: console, dryRun: false,- emitResponseMeta: (key, value) => { meta[key] = value; },- };+ const ctx = makeCtx(meta);try {- for (const expand of [undefined, false, true]) {+ for (const expand of [undefined, false, true] as const) {+ const before = probe.expanderCalls.length;const results = await operationsByName.query.handler(ctx, {- query: 'Zirconiumneedle', ...(expand === undefined ? {} : { expand }),+ query: 'Zirconiumneedle retrieval', ...(expand === undefined ? {} : { expand }),});expect(JSON.stringify(results)).toContain('notes/expansion-example');- expect(options.at(-1)?.expansion).toBe(expand !== false);- expect(typeof options.at(-1)?.expandFn).toBe(expand === false ? 'undefined' : 'function');- expect(meta.retrieval).toMatchObject({ expansion_applied: false, vector_enabled: false });+ const passed = probe.options.at(-1);+ // The raw param reaches hybrid search; unset stays unset so the mode decides.+ expect(passed?.expansion).toBe(expand);+ // The expander stays wired unless the caller opted out.+ expect(typeof passed?.expandFn).toBe(expand === false ? 'undefined' : 'function');+ const expected = expand ?? modeDefault;+ expect(probe.expanderCalls.length - before).toBe(expected ? 1 : 0);+ expect((meta.retrieval as { expansion_applied?: boolean }).expansion_applied).toBe(expected);}- const count = options.length;- const results = await operationsByName.search.handler(ctx, { query: 'Zirconiumneedle' });+ const count = probe.options.length;+ const results = await operationsByName.search.handler(ctx, { query: 'Zirconiumneedle retrieval' });expect(JSON.stringify(results)).toContain('notes/expansion-example');- for (const opts of options.slice(count)) {+ for (const opts of probe.options.slice(count)) {expect(opts?.expansion).toBe(false);expect(opts?.expandFn).toBeUndefined();}const report = await buildModesReport(engine);- expect(report.resolved.expansion.value).toBe(override === 'true');- expect(report.per_call_note).toContain('default on in every mode');- expect(report.per_call_note).toContain('Neither inherits `search.expansion`');+ expect(report.resolved.expansion.value).toBe(modeDefault);+ expect(report.per_call_note).toContain('op expands when the resolved `expansion` row below is on');+ expect(report.per_call_note).toContain('`search` never expands');const text = searchCommand.formatModesText(report);expect(text.indexOf('`query` op')).toBeLessThan(text.indexOf('Resolved knobs:'));} finally {- spy.mockRestore();+ probe.restore();}});}}+});- test('the install picker does not promise mode-specific expansion or cache savings', () => {- expect(MODE_PICKER_MENU).not.toContain('no LLM expansion');- expect(MODE_PICKER_MENU).not.toContain('LLM query expansion ON');- expect(MODE_PICKER_MENU).not.toContain('cache hits skip downstream');- expect(MODE_PICKER_MENU).toContain('gbrain query requests expansion in every mode');- expect(MODE_PICKER_MENU).toContain('keyless');+describe('CRAG escalation reads what the first pass did', () => {+ test('callerExpanded is expansion_applied, not the requested flag', async () => {+ await resetSearchConfig('balanced', undefined);+ await engine.setConfig('search.crag_escalation', 'true');+ // Variants the store cannot match keep every pass at zero results (a weak grade).+ const noVariants = spyHybrid(q => [q]);+ try {+ // expand: true, but the expander produced no variants: nothing expanded, so escalate.+ await operationsByName.query.handler(makeCtx({}), { query: 'qwertyuiop asdfghjkl nothing', expand: true });+ expect(noVariants.options.length).toBe(2);+ expect(noVariants.options[1]?.expansion).toBe(true);+ } finally {+ noVariants.restore();+ }+ const withVariants = spyHybrid(q => [q, `${q} other words`]);+ try {+ // The first pass expanded: the high-ceiling re-run would repeat it, so no escalation.+ await operationsByName.query.handler(makeCtx({}), { query: 'qwertyuiop asdfghjkl nothing', expand: true });+ expect(withVariants.options.length).toBe(1);+ // Unset in balanced: no expansion ran, so a weak result escalates once.+ await operationsByName.query.handler(makeCtx({}), { query: 'qwertyuiop asdfghjkl nothing' });+ expect(withVariants.options.length).toBe(3);+ } finally {+ withVariants.restore();+ await engine.setConfig('search.crag_escalation', 'false');+ }});+});- test('tuning advice does not promise expansion savings from modes or an unavailable cache', async () => {+describe('tuning advice', () => {+ test('tokenmax with a Haiku subagent: balanced also turns off the expansion default', async () => {+ await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'search.%'`);await engine.setConfig('search.mode', 'tokenmax');await engine.setConfig('models.tier.subagent', 'haiku');await engine.setConfig('search.cache.enabled', 'false');@@ -94,20 +171,7 @@ describe('operation expansion remains independent of mode bundles', () => {expect(report.recommendations.some(row => row.knob.startsWith('search.cache.'))).toBe(false);const mode = report.recommendations.find(row => row.knob === 'search.mode');expect(mode?.suggested).toBe('balanced');- expect(mode?.reason).toContain('does not disable query expansion');+ expect(mode?.reason).toContain('turns off query expansion by default');expect(mode?.reason).toContain('12K tokens');});-- test('keyless noninteractive initialization reports the effective expansion policy', async () => {- const lines: string[] = [];- const output = spyOn(console, 'log').mockImplementation((...args) => { lines.push(args.join(' ')); });- try {- expect(await runModePicker(engine, { force: true })).toBe('conservative');- expect(await engine.getConfig('search.mode')).toBe('conservative');- expect(lines.join('\n')).toContain('query requests expansion in every mode');- expect(lines.join('\n')).toContain('Keyless retrieval skips expansion');- } finally {- output.mockRestore();- }- });});diff --git a/test/search/query-expand-capture-replay.serial.test.ts b/test/search/query-expand-capture-replay.serial.test.tsnew file mode 100644index 0000000000..4b4502f6a2--- /dev/null+++ b/test/search/query-expand-capture-replay.serial.test.ts@@ -0,0 +1,83 @@+/**+ * Eval capture and replay of `query`'s expansion now that the default follows+ * the search mode (GBRA-81 item 1b): capture records the raw `expand` param+ * (null when the caller left it unset) next to `expansion_applied`, and+ * `eval replay` maps a null back to the mode default instead of forcing+ * expansion off. Serial: spies on module exports.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import * as hybrid from '../../src/core/search/hybrid.ts';+import { replayCore } from '../../src/commands/eval-replay.ts';+import type { EvalCandidateInput } from '../../src/core/types.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';++let engine: PGLiteEngine;+const tmp = mkdtempSync(join(tmpdir(), 'query-expand-replay-'));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('notes/capture-example', { type: 'note', title: 'Capture Example', compiled_truth: 'Osmiumfeather capture fixture.' });+ await installFixtureChunks(engine, 'notes/capture-example', [+ { chunk_index: 0, chunk_text: 'Osmiumfeather capture fixture.', chunk_source: 'compiled_truth' },+ ]);+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(tmp, { recursive: true, force: true });+});++describe('eval capture records the raw expand param', () => {+ test('unset → null, explicit true/false recorded as passed, expansion_applied alongside', async () => {+ const captured: EvalCandidateInput[] = [];+ const spy = spyOn(engine, 'logEvalCandidate').mockImplementation(async (input: EvalCandidateInput) => { captured.push(input); return 1; });+ const ctx: OperationContext = {+ engine, remote: false, sourceId: 'default', config: { engine: 'pglite', eval: { capture: true } } as OperationContext['config'],+ logger: console, dryRun: false,+ };+ try {+ for (const expand of [undefined, true, false] as const) {+ await operationsByName.query.handler(ctx, { query: 'Osmiumfeather capture', ...(expand === undefined ? {} : { expand }) });+ }+ for (let i = 0; i < 50 && captured.length < 3; i++) await new Promise(r => setTimeout(r, 10));+ } finally {+ spy.mockRestore();+ }+ expect(captured.map(c => c.expand_enabled)).toEqual([null, true, false]);+ for (const c of captured) {+ expect(c.tool_name).toBe('query');+ expect(typeof c.expansion_applied).toBe('boolean');+ }+ });+});++describe('eval replay maps a null expand to the mode default', () => {+ test('null → undefined (mode decides), true/false passed through', async () => {+ const row = (id: number, expand: boolean | null) => JSON.stringify({+ schema_version: 1, id, tool_name: 'query', query: 'Osmiumfeather capture', retrieved_slugs: ['notes/capture-example'],+ expand_enabled: expand, latency_ms: 5,+ });+ const file = join(tmp, 'captured.ndjson');+ writeFileSync(file, [row(1, null), row(2, true), row(3, false)].join('\n') + '\n');+ const seen: Array<boolean | undefined> = [];+ const original = hybrid.hybridSearch;+ const spy = spyOn(hybrid, 'hybridSearch').mockImplementation(async (db, query, opts) => {+ seen.push(opts?.expansion);+ return original(db, query, opts);+ });+ try {+ const { results } = await replayCore(engine, { against: file });+ expect(results.every(r => !r.errored)).toBe(true);+ } finally {+ spy.mockRestore();+ }+ expect(seen).toEqual([undefined, true, false]);+ });+});