Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): tokenmax query no longer expands by default (GBRA-94)

garrytand5861ac6f74d
diff --git a/CLAUDE.md b/CLAUDE.md
index 03c863a182..9154fb428b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -197,8 +197,8 @@ from recurring:
Confirm the user's mode choice during installation; relay the matrix in
`INSTALL_FOR_AGENTS.md` Step 3.5. The current command-level expansion and cost
contract lives in [search modes](docs/guides/search-modes.md), not a second knob
-table here. `query` expands only when the mode says so (on in `tokenmax`;
-`--expand` / `--no-expand` win); `search` and memory verbs never do. Semantic result reuse is disabled.
+table here. `query` does not expand by default in any mode (`search.expansion true`
+turns it on; `--expand` / `--no-expand` win); `search` and memory verbs never do. Semantic result reuse is disabled.
Read `docs/eval/SEARCH_MODE_METHODOLOGY.md` for eval methodology and
`docs/eval/METRIC_GLOSSARY.md` for metric definitions. Eval audit records stay in
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index ff31d28270..57d3185d67 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -289,13 +289,13 @@ Estimated downstream input cost of the retrieved payload @ 10K queries/mo:
>
> 2) balanced — 12K budget, 25 chunks, reranked.
>
-> 3) tokenmax (recommended with a chat key) — no budget, 50 chunks, reranked,
-> `gbrain query` expands by default. The widest retrieval.
+> 3) tokenmax (recommended with a chat key) — no budget, 50 chunks, reranked.
+> The widest retrieval.
>
-> Expansion follows the mode for `gbrain query` only: on in `tokenmax`, off in
-> `balanced` and `conservative`; `--expand` (`expand: true` over MCP) forces it
-> and `--no-expand` (`expand: false`) skips it. `gbrain config set search.expansion false`
-> turns the default off for the brain in any mode. `gbrain search` and the memory
+> `gbrain query` does not expand by default in any mode; `--expand`
+> (`expand: true` over MCP) forces it and `--no-expand` (`expand: false`) skips
+> it. `gbrain config set search.expansion true` turns the default on for the
+> brain in any mode. `gbrain search` and the memory
> verbs never expand. See [search modes](docs/guides/search-modes.md) for the
> current contract.
>
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 46ae5a60b3..57aec9b69f 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -176,10 +176,11 @@ outvote it on small-k retrieval.
Budget-normalized weighted RRF, composed in `src/core/search/fusion-lists.ts`. Every vector list is a role-tagged arm (`original` | `variant` | `clause` | `image`) — tagged objects, never a positional convention, so a failed arm or a fell-open image branch can't mis-tag a list. The `original` arm always fuses at weight 1; the non-empty `variant`/`clause` arms share ONE total weight budget, `search.expansion_variant_budget` (`weight_i = b / n_voting_arms`, each row scored `weight / (k + rank)`), so total expansion influence is exactly `b` however many variants the LLM produced. `null`, the default in all three mode bundles, is equal-weight fusion (every list weight 1). A budget in (0, 4] is set with `gbrain config set search.expansion_variant_budget <b>`, per call via `HybridSearchOpts.expansionVariantBudget`, or pinned per eval arm with `gbrain eval longmemeval --expansion-variant-budget <b>` (sweep it against frozen `--expansion-replay` variants so cells differ only in `b`). Arithmetic: two variants agreeing on a distractor at rank 0 tie the original's rank-0 vote exactly at `b = 1.0`; equal weighting with two variants is ≈ `b = 2.0`; `b = 0.5` subordinates them. The knob is a no-op when expansion is off and folds into the query-cache key (`evb=`). Measured 2026-09-06 with recorded Haiku variants replayed at every budget: the mechanism is real — strict `recall_all@5` rises from 255/470 at equal weighting to 394/470 at budget 0.25 — but its pre-registered rule (≥ plain hybrid − 2 on the 430-question decision set, no type losing > 1) failed at every budget (0.25: −43; plain hybrid 439/470), so every bundle sets `expansion_variant_budget: null` and the knob is an operator lever. The receipts point at a trigger rather than a weight (expand only when the original query's evidence is weak) as the next mechanism to pre-register.
-The mode bundles carry an `expansion` default (`tokenmax` true; `balanced`
-and `conservative` false). It applies when a caller leaves `expansion` unset
-and supplies an `expandFn`. The `query` operation leaves it unset unless the
-caller passes `expand`, so `query` expands by default only in `tokenmax`;
+The mode bundles carry an `expansion` default, false in all three (`tokenmax`
+turned it off after the 2026-10-14 expansion-latency eval: `query` p50 fell
+from 2,022 to 227 ms with retrieval unchanged). It applies when a caller leaves
+`expansion` unset and supplies an `expandFn`. The `query` operation leaves it
+unset unless the caller passes `expand`, so `query` does not expand by default;
`expand: true` / `--expand` forces it and `expand: false` / `--no-expand`
skips it. `search` never expands; `search.expansion` overrides the mode default for `query` only. Keyless and image-only paths
skip expansion, and `expansion_applied` reports actual variant use. The
@@ -197,7 +198,7 @@ relational recall arm remains available.
intent classify (query-intent.ts — deterministic, no LLM)
│
▼
-expansion (query: the mode's default, on only in tokenmax; --expand forces,
+expansion (query: the mode's default, off in all three; --expand forces,
--no-expand skips; search: off; keyless and image-only paths skip it)
│
▼
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index d14b5716b7..25d1a56998 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -63,7 +63,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds registered search knobs into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `KNOB_CONFIG_KEY` (a `Record<keyof ModeBundle, string>`, so every knob names the `search.*` key `loadOverridesFromConfig` reads it from) is the single knob→key map: `SEARCH_MODE_CONFIG_KEYS` derives from it, `attributeKnob` prints it as the override `source_detail`, and `KNOWN_CONFIG_KEYS` in `config.ts` hand-mirrors it (config.ts stays import-light; `test/config-search-registry.test.ts` pins the two equal), and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.
- `src/core/search/mode-advice.ts` — the one source of the search-mode recommendation (`RECOMMENDED_SEARCH_MODE`, `MODE_REASONS`) and the copy that states it: the downstream-input cost matrix priced from `model-pricing.ts` (`costMatrixLines`, `costMatrixSentence` for init's first-run decision), the picker's `[AGENT]` banner, the post-upgrade banner and `QUERY_EXPANSION_LINE`; `search.mode_source` (`auto` | `operator`). `INSTALL_FOR_AGENTS.md` Step 3.5 carries the matrix verbatim (pinned by `test/init-mode-picker.test.ts`).
-- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (on in `tokenmax`) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.
+- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all three modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.
- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`source_markdown_slug`) is private; the fact-list reads in `engine-sql/facts.ts` (by entity, since, keyset, session, supersessions, trajectory) apply it behind `FactListOpts.excludePrivate` / `TrajectoryOpts.excludePrivate`, which every remote fact surface resolves with `resolveExcludePrivatePages` (`test/remote-fact-list-private-provenance.test.ts`, both engines). Remote fact writes apply the same predicate behind an `excludePrivate` option: `forget` (`guardRemoteForget`, the row lock in `persistence/memory-mutations.ts`, `recordFactWithdrawal`, `similarActiveAfterForget`) and `remember` (`decideSingleFact`'s exact and cosine arms, `decideReplacement`), so a fact remote reads hide is `not_found` to a remote write and never matched as its duplicate (`test/remote-fact-write-private-provenance.test.ts`, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
diff --git a/docs/eval-bench.md b/docs/eval-bench.md
index 9ccc57b6c0..3d50bdfe0d 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -567,7 +567,7 @@ gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \
# runs each question as an agent's stdio MCP call would (remote, stdio, source
# `default`), at the operation's own default limit and under the brain's resolved
# search mode, so a receipt reproduces from a tagged gbrain. `query` expands by the
-# mode (on only in tokenmax) unless --op-expand on|off says otherwise. Each row's
+# mode (off by default in all three modes) unless --op-expand on|off says otherwise. Each row's
# `via_operation` records the context, the `expand` sent, model calls per
# touchpoint, latency, the CRAG grade and the expansion outcome;
# run_config.via_operation_summary has the tree, p50/p95 latency and model calls
diff --git a/docs/eval/METRIC_GLOSSARY.md b/docs/eval/METRIC_GLOSSARY.md
index adb25e07a8..892c571bdf 100644
--- a/docs/eval/METRIC_GLOSSARY.md
+++ b/docs/eval/METRIC_GLOSSARY.md
@@ -138,7 +138,7 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli
**Key:** `cost_per_query_usd`
-**Plain English:** Sum of LLM + embedding API charges for one search call. Includes Haiku expansion call (tokenmax mode only) + embedding cost + downstream answer-model cost if measured.
+**Plain English:** Sum of LLM + embedding API charges for one search call. Includes the expansion call when expansion is on (off by default) + embedding cost + downstream answer-model cost if measured.
**Range:** 0..unbounded. Conservative mode is typically <\$0.001 per call; tokenmax with answer-gen can exceed \$0.01.
@@ -148,7 +148,7 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli
**Plain English:** 99th percentile wall-clock time per search call. The latency that 1% of users see — long-tail experience, not the average.
-**Range:** 0..unbounded. Warm-cache hits should be <50ms; tokenmax with expansion can exceed 200ms due to the Haiku call.
+**Range:** 0..unbounded. Warm-cache hits should be <50ms; a query with expansion on can exceed 1s due to the expansion call.
## Result-Sizing Metrics
diff --git a/docs/guides/capabilities.md b/docs/guides/capabilities.md
index b6a6df6ea8..cd1033d559 100644
--- a/docs/guides/capabilities.md
+++ b/docs/guides/capabilities.md
@@ -28,7 +28,7 @@ The command is idempotent (re-running with the same language is a no-op for vect
**Say to your agent — the phrasebook.** You never invoke a skill by name; you say what you want and your agent routes it. Every skill declares its trigger phrases in its frontmatter, and [`skills/RESOLVER.md`](../../skills/RESOLVER.md) is the full human-readable phrasebook — one table of "when you say this, this skill fires." A taste: *"Ingest this PDF"* (media-ingest) — *"What's happening today?"* (briefing) — *"Fill my brain"* (cold-start) — *"Brain health"* / *"check backlinks"* (maintain — either phrase routes there) — *"Is my brain set up right?"* (gbrain-advisor) — *"Did the restart break anything?"* (smoke-test) — *"Run this as a background task"* (minion-orchestrator). If you're ever unsure what to say, ask your agent: *"What can my brain do?"* and have it read the resolver back to you.
-**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. Measured 2026-09-06 at gbrain v0.48.4.0 by this command on LongMemEval-S (cleaned Sept-2025 revision, 500 questions, 470 scored after the 30 abstention questions are dropped as the official scorer does), k=5, single run: on the release default path (`balanced`: `voyage:rerank-2.5` on, autocut off) strict session-level `recall_all@5` of **95.53%** (449/470), meaning every gold session landed inside the top-5 distinct retrieved sessions, retrieval only, no reader model; with the reranker off, the like-for-like row against systems that run no reranker, **93.40%** (439/470). The looser any-hit `recall_any@5` was 99.79% / 98.72% and is reported as a diagnostic, not a headline. The reranker-off row reproduces the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) runner's 2026-09-02 receipt (438/470; 469 of 470 rows agree per question), where the per-row receipts live. Paired against reranker-off hybrid the reranker gains 18 questions and loses 8; the default that shipped before v0.48.4.0 (reranker on with autocut) scored 379/470, because autocut kept the best session and dropped the rest on multi-part questions, which is why autocut is now off. One warning that the ranker wave re-measured rather than removed: an explicit LLM multi-query expansion experiment performed worse at k=5 — 255/470 `recall_all@5` (paired +3 / −187 vs hybrid) at the legacy weighting, 394/470 with the new `search.expansion_variant_budget` knob at its smallest pre-registered value, still 43 questions behind plain hybrid on the held-out decision set — so the bundles keep the legacy weighting, these results describe the expanded experiment rather than every call in a named mode. `gbrain query` expands only when the mode says so (on in `tokenmax`, off in `balanced` and `conservative`; `--expand` / `--no-expand` win), while `search` and memory verbs never expand; see [search modes](search-modes.md). `gbrain eval export` + `gbrain eval replay` capture real queries and replay them against code changes (set `GBRAIN_CONTRIBUTOR_MODE=1`). `gbrain eval cross-modal` cross-checks an output against the task using three different-provider frontier models. `gbrain eval retrieval-quality` runs NamedThingBench, which hard-gates the named-thing retrieval families (title-substring, alias-synonym, generic-to-named, multi-chunk-dilution) so a regression in "find the page this query names" fails CI loudly. `gbrain eval brainbench` runs the cross-harness memory conformance suite: know-to-ask, push precision/recall, write-back fidelity, and cross-session continuity, scored per harness seam (your OpenClaw's production pipeline plus Claude Code and Codex injection contracts) against a committed 141-fixture synthetic corpus — hermetic by default (in-memory PGLite, no keys, seconds), and CI gates every PR against master's committed baseline. Methodology in [`docs/eval/BRAINBENCH.md`](../eval/BRAINBENCH.md); search-mode methodology in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). **Say to your agent:** *"Run a regression check on retrieval"* (your agent runs `gbrain eval brainbench`); *"Run the public LongMemEval benchmark like-for-like"* (no skill backs this one; your agent runs `gbrain eval longmemeval <longmemeval_s_cleaned.json> --retrieval-only --top-k 5 --by-type --no-trajectory --mode balanced --reranker off --autocut off`. That in-repo command is the reproduction path for the 93.40% row (and the 2026-09-02 receipt's 93.19%): its `--by-type` summary reports strict `recall_all@5` with any-hit as the diagnostic, joins on the dataset's raw session ids, and drops the 30 abstention questions as the official scorer does; `--reranker on --autocut off` runs the shipped default path instead — autocut is off in every mode since rule R2 — and `--reranker on --autocut on --capture-pool` reproduces the capture the autocut replay was scored from).
+**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. Measured 2026-09-06 at gbrain v0.48.4.0 by this command on LongMemEval-S (cleaned Sept-2025 revision, 500 questions, 470 scored after the 30 abstention questions are dropped as the official scorer does), k=5, single run: on the release default path (`balanced`: `voyage:rerank-2.5` on, autocut off) strict session-level `recall_all@5` of **95.53%** (449/470), meaning every gold session landed inside the top-5 distinct retrieved sessions, retrieval only, no reader model; with the reranker off, the like-for-like row against systems that run no reranker, **93.40%** (439/470). The looser any-hit `recall_any@5` was 99.79% / 98.72% and is reported as a diagnostic, not a headline. The reranker-off row reproduces the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) runner's 2026-09-02 receipt (438/470; 469 of 470 rows agree per question), where the per-row receipts live. Paired against reranker-off hybrid the reranker gains 18 questions and loses 8; the default that shipped before v0.48.4.0 (reranker on with autocut) scored 379/470, because autocut kept the best session and dropped the rest on multi-part questions, which is why autocut is now off. One warning that the ranker wave re-measured rather than removed: an explicit LLM multi-query expansion experiment performed worse at k=5 — 255/470 `recall_all@5` (paired +3 / −187 vs hybrid) at the legacy weighting, 394/470 with the new `search.expansion_variant_budget` knob at its smallest pre-registered value, still 43 questions behind plain hybrid on the held-out decision set — so the bundles keep the legacy weighting, these results describe the expanded experiment rather than every call in a named mode. `gbrain query` does not expand by default in any mode (`search.expansion true` turns it on; `--expand` / `--no-expand` win), while `search` and memory verbs never expand; see [search modes](search-modes.md). `gbrain eval export` + `gbrain eval replay` capture real queries and replay them against code changes (set `GBRAIN_CONTRIBUTOR_MODE=1`). `gbrain eval cross-modal` cross-checks an output against the task using three different-provider frontier models. `gbrain eval retrieval-quality` runs NamedThingBench, which hard-gates the named-thing retrieval families (title-substring, alias-synonym, generic-to-named, multi-chunk-dilution) so a regression in "find the page this query names" fails CI loudly. `gbrain eval brainbench` runs the cross-harness memory conformance suite: know-to-ask, push precision/recall, write-back fidelity, and cross-session continuity, scored per harness seam (your OpenClaw's production pipeline plus Claude Code and Codex injection contracts) against a committed 141-fixture synthetic corpus — hermetic by default (in-memory PGLite, no keys, seconds), and CI gates every PR against master's committed baseline. Methodology in [`docs/eval/BRAINBENCH.md`](../eval/BRAINBENCH.md); search-mode methodology in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). **Say to your agent:** *"Run a regression check on retrieval"* (your agent runs `gbrain eval brainbench`); *"Run the public LongMemEval benchmark like-for-like"* (no skill backs this one; your agent runs `gbrain eval longmemeval <longmemeval_s_cleaned.json> --retrieval-only --top-k 5 --by-type --no-trajectory --mode balanced --reranker off --autocut off`. That in-repo command is the reproduction path for the 93.40% row (and the 2026-09-02 receipt's 93.19%): its `--by-type` summary reports strict `recall_all@5` with any-hit as the diagnostic, joins on the dataset's raw session ids, and drops the 30 abstention questions as the official scorer does; `--reranker on --autocut off` runs the shipped default path instead — autocut is off in every mode since rule R2 — and `--reranker on --autocut on --capture-pool` reproduces the capture the autocut replay was scored from).
**How it measures up.** One distinction decides every memory-benchmark comparison: strict `recall_all@5` counts a question only when every gold session lands in the top 5, while loose any-hit counts it when a single one does, and 300 of LongMemEval-S's 470 scored questions need two or more sessions. On the strict metric, on this dataset, gbrain scores 93.40% with the reranker off (v0.48.4.0, 2026-09-06, 470 scored; 93.19% on the 2026-09-02 sibling receipt) and 95.53% on the release default path with `voyage:rerank-2.5` on (same run, same 470); the k=5 ceiling is 99.4% because 3 questions carry 6 gold sessions. The closest strict comparisons we could find: MemPalace publishes only any-hit (96.6% / 98.4%), but rescoring its committed per-question rankings against the official gold labels gives 85.7% for its raw vector setup and 90.0% with an LLM reranker in the loop (our recomputation, their data); ContextFit publishes an All@5 of 87.45% (411/470) whose rerank layer reads gold labels during the run, so we mark it loosely comparable. The 94 to 96% figures quoted for Mastra, Mem0, MemCog, Supermemory and others are LLM-judged answer accuracy, a different race that scores the reader and judge as much as the memory. gbrain's first judged number, published with v0.48.4.0: 86.6% (433/500; 95% CI 83.6–89.6) with the default `anthropic:claude-sonnet-4-6` reader over the full text of the retrieved sessions and a gpt-4o judge running the official prompts; 449 of the 470 non-abstention questions had every gold session retrieved and the reader converted 396 of them, so the gap to those vendor numbers is in the answering layer and the protocols differ, so no comparison is claimed in either direction. Pure vector on the same corpus scored 93.8% (v0.48.0.0 receipt), so the hybrid layer is roughly neutral on this benchmark and earns its keep elsewhere. Full table with sources and our read of each: [gbrain-evals `docs/comparison-systems.md`](https://github.com/garrytan/gbrain-evals/blob/main/docs/comparison-systems.md).
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index adf4b798c9..6d19834dc7 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -31,7 +31,7 @@ and maintenance commands remain available.
| `cache.ttl_seconds` | 3600 | 3600 | 3600 |
| `intentWeighting` | true | true | true |
| `tokenBudget` | **4000** | **12000** | **off** |
-| `expansion` (LLM multi-query) | false | false | **true** |
+| `expansion` (LLM multi-query) | false | false | false |
| `expansion_variant_budget` | `null` (legacy) | `null` (legacy) | `null` (legacy) |
| `relationalRetrieval` | false | **true** | **true** |
| `relational_rerank_pin` | 3 | 3 | 3 |
@@ -44,19 +44,23 @@ and maintenance commands remain available.
The `expansion` row is `gbrain query`'s default: `query` (the only verb that
can expand) expands when a call leaves `expand` unset and the resolved row is
-on, so it expands by default in `tokenmax` and not in `balanced` or
-`conservative`. `--expand` / `expand: true` forces expansion in any mode and
+on. The row is off in all three modes, so `query` does not expand by default.
+`tokenmax` turned it off after the 2026-10-14 expansion-latency eval: on 300 LongMemEval-S questions with
+the reranker, `query` without expansion kept retrieval within the noise floor
+(strict recall@10 298 vs 299 of 300; the reference's own re-run scored 298)
+and its p50 fell from 2,022 to 227 ms (gbrain-evals GBRA-94 report,
+2026-10-14). `--expand` / `expand: true` forces expansion in any mode and
`--no-expand` / `expand: false` skips it in any mode. The `search.expansion`
config key overrides the row like any other knob. `gbrain search`, the memory
verbs and the eval harnesses pin expansion per call, so `search` never
expands, even with `search.expansion=true`. `gbrain search modes` reports the
resolved row.
-To turn expansion off for one brain without changing its mode, run
-`gbrain config set search.expansion false` on the brain host. Every `query`
-call that leaves `expand` unset then skips it: the CLI, MCP over stdio and
+To turn expansion on for one brain without changing its mode, run
+`gbrain config set search.expansion true` on the brain host (`false` pins it
+off). Every `query` call that leaves `expand` unset then follows the key: the CLI, MCP over stdio and
`gbrain serve --http` all resolve the same row. A call that passes
-`--expand` / `expand: true` still expands. `gbrain config unset search.expansion`
+`--expand` / `expand: true` or `--no-expand` / `expand: false` still wins. `gbrain config unset search.expansion`
returns to the mode default. The key is per brain and lives in its database,
so a thin client (`gbrain init --mcp-only`) can't set it; whoever runs the
brain host sets it, and the host needs gbrain v0.60.188.0 or later, because
@@ -373,15 +377,14 @@ on user_asks_about(topic):
full_page = gbrain get <slug_from_chunk>
elif topic.is_semantic_question or topic.is_concept_or_landscape:
- # MODE 2: Full hybrid -- adds multi-query LLM expansion on top of
- # vector + keyword + RRF. Owns concept / landscape / "all-of-X"
- # questions: expansion recovers synonym- and outcome-phrased
- # matches a single embedding misses. Costs one LLM expansion call
- # per query -- worth it for these question shapes.
+ # MODE 2: Full hybrid -- vector + keyword + RRF + reranking. Owns
+ # concept / landscape / "all-of-X" questions. Pass --expand to add
+ # one LLM expansion call when the original wording is weak; it is
+ # off by default because it measured no retrieval gain (GBRA-94).
results = gbrain query "{natural language question}"
# e.g., "Who do I know at fintech companies?" -> gbrain query "fintech contacts"
# e.g., "all the companies doing offshore wind" -> gbrain query "..."
- # Returns ranked chunks via vector + keyword + expansion + RRF
+ # Returns ranked chunks via vector + keyword + RRF (+ expansion with --expand)
# Same rule: chunks first, then get full page if needed
if chunk.confirms_relevance:
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index c58a9fa4cc..4a09359e8f 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -303,7 +303,7 @@ Replace a complete canonical Markdown page. Read get_page with include_content:t
## `query`
-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.
+Hybrid search with vector + keyword, plus multi-query expansion when the search mode or the call asks for it (`expand` unset follows `search.expansion`, off by default in all three modes; `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 |
| --- | --- | --- |
@@ -317,7 +317,7 @@ Hybrid search with vector + keyword, plus multi-query expansion when the search
| `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 | 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. |
+| `expand` | boolean | Multi-query expansion. Unset follows `search.expansion` (off by default in all three modes); 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) |
diff --git a/llms-full.txt b/llms-full.txt
index 80a763e644..3d9cd7aa37 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2242,8 +2242,8 @@ from recurring:
Confirm the user's mode choice during installation; relay the matrix in
`INSTALL_FOR_AGENTS.md` Step 3.5. The current command-level expansion and cost
contract lives in [search modes](docs/guides/search-modes.md), not a second knob
-table here. `query` expands only when the mode says so (on in `tokenmax`;
-`--expand` / `--no-expand` win); `search` and memory verbs never do. Semantic result reuse is disabled.
+table here. `query` does not expand by default in any mode (`search.expansion true`
+turns it on; `--expand` / `--no-expand` win); `search` and memory verbs never do. Semantic result reuse is disabled.
Read `docs/eval/SEARCH_MODE_METHODOLOGY.md` for eval methodology and
`docs/eval/METRIC_GLOSSARY.md` for metric definitions. Eval audit records stay in
@@ -2859,12 +2859,12 @@ Estimated downstream input cost of the retrieved payload @ 10K queries/mo:
> 2) balanced — 12K budget, 25 chunks, reranked.
>
> 3) tokenmax (recommended with a chat key) — no budget, 50 chunks, reranked,
-> `gbrain query` expands by default. The widest retrieval.
+> per-chunk synopsis context. The widest retrieval.
>
-> Expansion follows the mode for `gbrain query` only: on in `tokenmax`, off in
-> `balanced` and `conservative`; `--expand` (`expand: true` over MCP) forces it
-> and `--no-expand` (`expand: false`) skips it. `gbrain config set search.expansion false`
-> turns the default off for the brain in any mode. `gbrain search` and the memory
+> `gbrain query` does not expand by default in any mode; `--expand`
+> (`expand: true` over MCP) forces it and `--no-expand` (`expand: false`) skips
+> it. `gbrain config set search.expansion true` turns the default on for the
+> brain in any mode. `gbrain search` and the memory
> verbs never expand. See [search modes](docs/guides/search-modes.md) for the
> current contract.
>
diff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
index 9b27f86659..cadb44bdc8 100644
--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
@@ -126,7 +126,7 @@ Before using ANY external API to research a person, company, or topic:
1. `gbrain entity "<name>"` (v0.43+) — ONE known person/company/project → full card (description, aliases, open threads, recent events, edges, backlink/fact counts). Zero LLM calls, sub-100ms. This one call replaces steps 2–6 for known-entity lookups; near-misses return suggestions.
2. `gbrain search "name"` — exact-token lookup for existing pages (cheap hybrid, no expansion)
-3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (expansion recovers synonym phrasings; a nonzero `search` count is not proof of completeness)
+3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (meaning-match plus reranking recovers synonym phrasings; `--expand` adds LLM rewrites when results look thin; a nonzero `search` count is not proof of completeness)
4. `gbrain get <slug>` — if you know the slug, read the full page
5. Check backlinks: who references this entity?
6. Check timeline: recent events involving this entity
@@ -274,7 +274,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
## Tools Used
- `search` — cheap hybrid search (vector + keyword, no expansion)
-- `query` — hybrid search + LLM multi-query expansion (concept/landscape questions)
+- `query` — hybrid search for concept/landscape questions (`--expand` adds LLM multi-query expansion)
- `get_page` — read a brain page
- `put_page` — create/update brain pages
- `add_link` — cross-reference entities
diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
index eecda4b95d..844840fbad 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
@@ -12,7 +12,7 @@ Your tool inventory includes these (prefixed `gbrain__` in OpenClaw):
| Tool | Use for |
|------|---------|
| `gbrain__search` / `search` | Exact tokens / known names — cheap hybrid, no expansion |
-| `gbrain__query` / `query` | Concept / landscape questions — hybrid + LLM expansion |
+| `gbrain__query` / `query` | Concept / landscape questions — hybrid; `expand: true` adds LLM expansion |
| `gbrain__get_page` / `get_page` | Direct page read when you know the slug |
| `gbrain__get_links` / `get_links` | Outgoing links from a page |
| `gbrain__get_backlinks` / `get_backlinks` | Who references this entity |
@@ -33,9 +33,9 @@ Route by the SHAPE of the question, then escalate:
1. **Exact known token / name / structured field** → **`search`** — cheap
hybrid (vector + keyword, no expansion; embedding-only cost).
2. **Concept / landscape / synonym-phrased question** ("all the X that do Y",
- "the landscape of Z") → **`query`** FIRST — multi-query expansion recovers
- phrasings `search` misses. Costs one extra LLM expansion call; worth it
- for these.
+ "the landscape of Z") → **`query`** FIRST — meaning-match and reranking recover
+ phrasings `search` misses. `expand: true` adds one LLM expansion call
+ when the results look thin.
3. **`get_page`** if you found a slug — read the full compiled truth.
4. **External APIs only after steps 1-2 return nothing useful.**
diff --git a/plugin-variants/gbrain-coding/skills/conventions/search-modes.md b/plugin-variants/gbrain-coding/skills/conventions/search-modes.md
index 0b663dbc9b..e57ea865db 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/search-modes.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/search-modes.md
@@ -36,7 +36,7 @@ The canonical knob table (with cost anchors) lives in
| `cache.ttl_seconds` | 3600 | 3600 | 3600 |
| `intentWeighting` | true | true | true |
| `tokenBudget` | **4000** | **12000** | **off** |
-| `expansion` (LLM multi-query) | false | false | **true** |
+| `expansion` (LLM multi-query) | false | false | false |
| `relationalRetrieval` | false | **true** | **true** |
| `searchLimit` default | 10 | 25 | 50 |
@@ -74,8 +74,8 @@ and prints a paste-ready revert command.
## Cache contamination guard
The retained `query_cache.knobs_hash` machinery separates mode settings:
-tokenmax (expansion=on, limit=50) has a different hash from conservative
-(no expansion, limit=10). Its stored lookup filter is:
+tokenmax (limit=50, no token budget) has a different hash from conservative
+(limit=10). Its stored lookup filter is:
WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $
diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.md
index dace517f2b..6469a19517 100644
--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md
@@ -67,7 +67,7 @@ This skill guarantees:
- Structured queries (list by type, backlinks) for relational questions
2. **Execute searches:**
- Cheap-hybrid search gbrain for exact tokens / known names (search)
- - Full-hybrid search gbrain with multi-query expansion for concept questions (query)
+ - Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)
- List pages in gbrain by type or check backlinks for structural queries
3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.
4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
index eecda4b95d..844840fbad 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
@@ -12,7 +12,7 @@ Your tool inventory includes these (prefixed `gbrain__` in OpenClaw):
| Tool | Use for |
|------|---------|
| `gbrain__search` / `search` | Exact tokens / known names — cheap hybrid, no expansion |
-| `gbrain__query` / `query` | Concept / landscape questions — hybrid + LLM expansion |
+| `gbrain__query` / `query` | Concept / landscape questions — hybrid; `expand: true` adds LLM expansion |
| `gbrain__get_page` / `get_page` | Direct page read when you know the slug |
| `gbrain__get_links` / `get_links` | Outgoing links from a page |
| `gbrain__get_backlinks` / `get_backlinks` | Who references this entity |
@@ -33,9 +33,9 @@ Route by the SHAPE of the question, then escalate:
1. **Exact known token / name / structured field** → **`search`** — cheap
hybrid (vector + keyword, no expansion; embedding-only cost).
2. **Concept / landscape / synonym-phrased question** ("all the X that do Y",
- "the landscape of Z") → **`query`** FIRST — multi-query expansion recovers
- phrasings `search` misses. Costs one extra LLM expansion call; worth it
- for these.
+ "the landscape of Z") → **`query`** FIRST — meaning-match and reranking recover
+ phrasings `search` misses. `expand: true` adds one LLM expansion call
+ when the results look thin.
3. **`get_page`** if you found a slug — read the full compiled truth.
4. **External APIs only after steps 1-2 return nothing useful.**
diff --git a/plugin-variants/gbrain-daily/skills/conventions/search-modes.md b/plugin-variants/gbrain-daily/skills/conventions/search-modes.md
index 0b663dbc9b..e57ea865db 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/search-modes.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/search-modes.md
@@ -36,7 +36,7 @@ The canonical knob table (with cost anchors) lives in
| `cache.ttl_seconds` | 3600 | 3600 | 3600 |
| `intentWeighting` | true | true | true |
| `tokenBudget` | **4000** | **12000** | **off** |
-| `expansion` (LLM multi-query) | false | false | **true** |
+| `expansion` (LLM multi-query) | false | false | false |
| `relationalRetrieval` | false | **true** | **true** |
| `searchLimit` default | 10 | 25 | 50 |
@@ -74,8 +74,8 @@ and prints a paste-ready revert command.
## Cache contamination guard
The retained `query_cache.knobs_hash` machinery separates mode settings:
-tokenmax (expansion=on, limit=50) has a different hash from conservative
-(no expansion, limit=10). Its stored lookup filter is:
+tokenmax (limit=50, no token budget) has a different hash from conservative
+(limit=10). Its stored lookup filter is:
WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $
diff --git a/plugin-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.md
index dace517f2b..6469a19517 100644
--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md
@@ -67,7 +67,7 @@ This skill guarantees:
- Structured queries (list by type, backlinks) for relational questions
2. **Execute searches:**
- Cheap-hybrid search gbrain for exact tokens / known names (search)
- - Full-hybrid search gbrain with multi-query expansion for concept questions (query)
+ - Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)
- List pages in gbrain by type or check backlinks for structural queries
3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.
4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.
diff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.md
index 9b27f86659..cadb44bdc8 100644
--- a/plugin/skills/brain-ops/SKILL.md
+++ b/plugin/skills/brain-ops/SKILL.md
@@ -126,7 +126,7 @@ Before using ANY external API to research a person, company, or topic:
1. `gbrain entity "<name>"` (v0.43+) — ONE known person/company/project → full card (description, aliases, open threads, recent events, edges, backlink/fact counts). Zero LLM calls, sub-100ms. This one call replaces steps 2–6 for known-entity lookups; near-misses return suggestions.
2. `gbrain search "name"` — exact-token lookup for existing pages (cheap hybrid, no expansion)
-3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (expansion recovers synonym phrasings; a nonzero `search` count is not proof of completeness)
+3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (meaning-match plus reranking recovers synonym phrasings; `--expand` adds LLM rewrites when results look thin; a nonzero `search` count is not proof of completeness)
4. `gbrain get <slug>` — if you know the slug, read the full page
5. Check backlinks: who references this entity?
6. Check timeline: recent events involving this entity
@@ -274,7 +274,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
## Tools Used
- `search` — cheap hybrid search (vector + keyword, no expansion)
-- `query` — hybrid search + LLM multi-query expansion (concept/landscape questions)
+- `query` — hybrid search for concept/landscape questions (`--expand` adds LLM multi-query expansion)
- `get_page` — read a brain page
- `put_page` — create/update brain pages
- `add_link` — cross-reference entities
diff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.md
index eecda4b95d..844840fbad 100644
--- a/plugin/skills/conventions/brain-first.md
+++ b/plugin/skills/conventions/brain-first.md
@@ -12,7 +12,7 @@ Your tool inventory includes these (prefixed `gbrain__` in OpenClaw):
| Tool | Use for |
|------|---------|
| `gbrain__search` / `search` | Exact tokens / known names — cheap hybrid, no expansion |
-| `gbrain__query` / `query` | Concept / landscape questions — hybrid + LLM expansion |
+| `gbrain__query` / `query` | Concept / landscape questions — hybrid; `expand: true` adds LLM expansion |
| `gbrain__get_page` / `get_page` | Direct page read when you know the slug |
| `gbrain__get_links` / `get_links` | Outgoing links from a page |
| `gbrain__get_backlinks` / `get_backlinks` | Who references this entity |
@@ -33,9 +33,9 @@ Route by the SHAPE of the question, then escalate:
1. **Exact known token / name / structured field** → **`search`** — cheap
hybrid (vector + keyword, no expansion; embedding-only cost).
2. **Concept / landscape / synonym-phrased question** ("all the X that do Y",
- "the landscape of Z") → **`query`** FIRST — multi-query expansion recovers
- phrasings `search` misses. Costs one extra LLM expansion call; worth it
- for these.
+ "the landscape of Z") → **`query`** FIRST — meaning-match and reranking recover
+ phrasings `search` misses. `expand: true` adds one LLM expansion call
+ when the results look thin.
3. **`get_page`** if you found a slug — read the full compiled truth.
4. **External APIs only after steps 1-2 return nothing useful.**
diff --git a/plugin/skills/conventions/search-modes.md b/plugin/skills/conventions/search-modes.md
index 0b663dbc9b..e57ea865db 100644
--- a/plugin/skills/conventions/search-modes.md
+++ b/plugin/skills/conventions/search-modes.md
@@ -36,7 +36,7 @@ The canonical knob table (with cost anchors) lives in
| `cache.ttl_seconds` | 3600 | 3600 | 3600 |
| `intentWeighting` | true | true | true |
| `tokenBudget` | **4000** | **12000** | **off** |
-| `expansion` (LLM multi-query) | false | false | **true** |
+| `expansion` (LLM multi-query) | false | false | false |
| `relationalRetrieval` | false | **true** | **true** |
| `searchLimit` default | 10 | 25 | 50 |
@@ -74,8 +74,8 @@ and prints a paste-ready revert command.
## Cache contamination guard
The retained `query_cache.knobs_hash` machinery separates mode settings:
-tokenmax (expansion=on, limit=50) has a different hash from conservative
-(no expansion, limit=10). Its stored lookup filter is:
+tokenmax (limit=50, no token budget) has a different hash from conservative
+(limit=10). Its stored lookup filter is:
WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $
diff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.md
index dace517f2b..6469a19517 100644
--- a/plugin/skills/query/SKILL.md
+++ b/plugin/skills/query/SKILL.md
@@ -67,7 +67,7 @@ This skill guarantees:
- Structured queries (list by type, backlinks) for relational questions
2. **Execute searches:**
- Cheap-hybrid search gbrain for exact tokens / known names (search)
- - Full-hybrid search gbrain with multi-query expansion for concept questions (query)
+ - Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)
- List pages in gbrain by type or check backlinks for structural queries
3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.
4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.
diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.md
index d85259cf21..e64e6507f3 100644
--- a/skills/brain-ops/SKILL.md
+++ b/skills/brain-ops/SKILL.md
@@ -125,7 +125,7 @@ Before using ANY external API to research a person, company, or topic:
1. `gbrain entity "<name>"` (v0.43+) — ONE known person/company/project → full card (description, aliases, open threads, recent events, edges, backlink/fact counts). Zero LLM calls, sub-100ms. This one call replaces steps 2–6 for known-entity lookups; near-misses return suggestions.
2. `gbrain search "name"` — exact-token lookup for existing pages (cheap hybrid, no expansion)
-3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (expansion recovers synonym phrasings; a nonzero `search` count is not proof of completeness)
+3. `gbrain query "natural question about name"` — concept/landscape questions go here FIRST (meaning-match plus reranking recovers synonym phrasings; `--expand` adds LLM rewrites when results look thin; a nonzero `search` count is not proof of completeness)
4. `gbrain get <slug>` — if you know the slug, read the full page
5. Check backlinks: who references this entity?
6. Check timeline: recent events involving this entity
@@ -273,7 +273,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
## Tools Used
- `search` — cheap hybrid search (vector + keyword, no expansion)
-- `query` — hybrid search + LLM multi-query expansion (concept/landscape questions)
+- `query` — hybrid search for concept/landscape questions (`--expand` adds LLM multi-query expansion)
- `get_page` — read a brain page
- `put_page` — create/update brain pages
- `add_link` — cross-reference entities
diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.md
index eecda4b95d..844840fbad 100644
--- a/skills/conventions/brain-first.md
+++ b/skills/conventions/brain-first.md
@@ -12,7 +12,7 @@ Your tool inventory includes these (prefixed `gbrain__` in OpenClaw):
| Tool | Use for |
|------|---------|
| `gbrain__search` / `search` | Exact tokens / known names — cheap hybrid, no expansion |
-| `gbrain__query` / `query` | Concept / landscape questions — hybrid + LLM expansion |
+| `gbrain__query` / `query` | Concept / landscape questions — hybrid; `expand: true` adds LLM expansion |
| `gbrain__get_page` / `get_page` | Direct page read when you know the slug |
| `gbrain__get_links` / `get_links` | Outgoing links from a page |
| `gbrain__get_backlinks` / `get_backlinks` | Who references this entity |
@@ -33,9 +33,9 @@ Route by the SHAPE of the question, then escalate:
1. **Exact known token / name / structured field** → **`search`** — cheap
hybrid (vector + keyword, no expansion; embedding-only cost).
2. **Concept / landscape / synonym-phrased question** ("all the X that do Y",
- "the landscape of Z") → **`query`** FIRST — multi-query expansion recovers
- phrasings `search` misses. Costs one extra LLM expansion call; worth it
- for these.
+ "the landscape of Z") → **`query`** FIRST — meaning-match and reranking recover
+ phrasings `search` misses. `expand: true` adds one LLM expansion call
+ when the results look thin.
3. **`get_page`** if you found a slug — read the full compiled truth.
4. **External APIs only after steps 1-2 return nothing useful.**
diff --git a/skills/conventions/search-modes.md b/skills/conventions/search-modes.md
index 0b663dbc9b..e57ea865db 100644
--- a/skills/conventions/search-modes.md
+++ b/skills/conventions/search-modes.md
@@ -36,7 +36,7 @@ The canonical knob table (with cost anchors) lives in
| `cache.ttl_seconds` | 3600 | 3600 | 3600 |
| `intentWeighting` | true | true | true |
| `tokenBudget` | **4000** | **12000** | **off** |
-| `expansion` (LLM multi-query) | false | false | **true** |
+| `expansion` (LLM multi-query) | false | false | false |
| `relationalRetrieval` | false | **true** | **true** |
| `searchLimit` default | 10 | 25 | 50 |
@@ -74,8 +74,8 @@ and prints a paste-ready revert command.
## Cache contamination guard
The retained `query_cache.knobs_hash` machinery separates mode settings:
-tokenmax (expansion=on, limit=50) has a different hash from conservative
-(no expansion, limit=10). Its stored lookup filter is:
+tokenmax (limit=50, no token budget) has a different hash from conservative
+(limit=10). Its stored lookup filter is:
WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $
diff --git a/skills/query/SKILL.md b/skills/query/SKILL.md
index 12e699626f..5aefe9116d 100644
--- a/skills/query/SKILL.md
+++ b/skills/query/SKILL.md
@@ -66,7 +66,7 @@ This skill guarantees:
- Structured queries (list by type, backlinks) for relational questions
2. **Execute searches:**
- Cheap-hybrid search gbrain for exact tokens / known names (search)
- - Full-hybrid search gbrain with multi-query expansion for concept questions (query)
+ - Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)
- List pages in gbrain by type or check backlinks for structural queries
3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.
4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.
diff --git a/src/commands/eval-run-all.ts b/src/commands/eval-run-all.ts
index c72bba7429..b6765f6f50 100644
--- a/src/commands/eval-run-all.ts
+++ b/src/commands/eval-run-all.ts
@@ -30,7 +30,7 @@
import { writeFileSync, mkdirSync, appendFileSync, existsSync } from 'fs';
import { dirname, join } from 'path';
import type { BrainEngine } from '../core/engine.ts';
-import { SEARCH_MODES, type SearchMode } from '../core/search/mode.ts';
+import { MODE_BUNDLES, SEARCH_MODES, type SearchMode } from '../core/search/mode.ts';
import { redactSecrets } from '../eval/longmemeval/run-config.ts';
import { OperationError, opError } from '../core/ops/contract.ts';
import type { Action } from '../core/agent-output.ts';
@@ -292,7 +292,7 @@ export function estimateRunCost(opts: { suites: string[]; modes: SearchMode[]; l
for (const suite of opts.suites) {
for (const mode of opts.modes) {
// Retrieval side: 1 embed + (optional Haiku) per query.
- const expansionCalls = mode === 'tokenmax' ? Qper : 0;
+ const expansionCalls = MODE_BUNDLES[mode].expansion ? Qper : 0;
const retCost = Qper * 0.00001 + expansionCalls * 0.001;
// Answer side: 1 Sonnet/Opus call per query for longmemeval; 0 for replay/brainbench.
const answerCost = suite === 'longmemeval' ? Qper * 0.015 : 0;
diff --git a/src/commands/init-mode-picker.ts b/src/commands/init-mode-picker.ts
index 6f21f0c0a8..defce0ba8a 100644
--- a/src/commands/init-mode-picker.ts
+++ b/src/commands/init-mode-picker.ts
@@ -139,8 +139,7 @@ retrieval or downstream generation.
2) balanced 12K-token cap, 25 results by default, reranked.
Best for: mixed workloads, a reranker without a chat key.
- 3) tokenmax no token cap, 50 results by default, reranked,
- query expansion on by default.
+ 3) tokenmax no token cap, 50 results by default, reranked.
Best for: the widest retrieval, low-volume high-stakes work.
${QUERY_EXPANSION_LINE}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1d6359f1e2..b563f07815 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -642,6 +642,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
{ since: '0.60.250.0', text: 'Remote agents and token-floor connections now get stored contradiction findings from `find_contradictions` instead of an availability note or a refusal: only findings whose two sides they can read now, each side re-read live with its `source_id` and `trust_tier`, never the stored report text; `min_trust` and the token floor filter instead of refusing. A local `gbrain find-contradictions --source <id>` (or `GBRAIN_SOURCE`) now gets that scoped view instead of the note; the bare command still reads the whole stored run.' },
+ // LHF wave 2 item 1 (GBRA-94): tokenmax `query` no longer expands by default.
+ { since: '0.60.251.0', text: '`gbrain query` no longer runs LLM query expansion by default on `tokenmax`, so no search mode expands by default. On 300 LongMemEval-S questions with the reranker, `query` without expansion kept retrieval within noise (298 vs 299 of 300) and its p50 fell from about 2 s to about 230 ms (gbrain-evals expansion-latency report, 2026-10-14). To keep expanding: `gbrain config set search.expansion true` for the brain, or pass `--expand` / `expand: true` per call.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/eval/metric-glossary.ts b/src/core/eval/metric-glossary.ts
index bba4b71ae9..36fda681e3 100644
--- a/src/core/eval/metric-glossary.ts
+++ b/src/core/eval/metric-glossary.ts
@@ -125,13 +125,13 @@ export const METRIC_GLOSSARY: Readonly<Record<string, Readonly<MetricGlossEntry>
}),
'cost_per_query_usd': Object.freeze({
industry_term: 'Cost per query (USD)',
- eli10: 'Sum of LLM + embedding API charges for one search call. Includes Haiku expansion call (tokenmax mode only) + embedding cost + downstream answer-model cost if measured.',
+ eli10: 'Sum of LLM + embedding API charges for one search call. Includes the expansion call when expansion is on (off by default) + embedding cost + downstream answer-model cost if measured.',
range: '0..unbounded. Conservative mode is typically <\\$0.001 per call; tokenmax with answer-gen can exceed \\$0.01.',
}),
'p99_latency_ms': Object.freeze({
industry_term: 'p99 latency (ms)',
eli10: '99th percentile wall-clock time per search call. The latency that 1% of users see — long-tail experience, not the average.',
- range: '0..unbounded. Warm-cache hits should be <50ms; tokenmax with expansion can exceed 200ms due to the Haiku call.',
+ range: '0..unbounded. Warm-cache hits should be <50ms; a query with expansion on can exceed 1s due to the expansion call.',
}),
// ────────────────────────────────────────────────────────────────────────
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index cce35425f8..7e9a2464f1 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -1153,7 +1153,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"expand": {
"type": "boolean",
- "description": "Default per search mode (tokenmax on)."
+ "description": "Default off; search.expansion overrides."
},
"detail": {
"type": "string",
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 453798c191..77e12bc696 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -857,7 +857,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 per search mode (tokenmax on).' },
+ expand: { type: 'boolean', description: 'Default off; search.expansion overrides.' },
detail: { type: 'string', description: 'low (compiled truth), medium (default) or high (all chunks).' },
fields: FIELDS_PARAM,
mode: { type: 'string', description: 'Local callers only.' },
@@ -1083,8 +1083,8 @@ const query: Operation = {
// 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)
+ // while one that ran without expansion (the default, an explicit
+ // opt-out, or an expander that produced nothing)
// can still escalate.
if (shouldEscalateRetrieval(grade, {
enabled: escalationCfg === 'true',
diff --git a/src/core/search/mode-advice.ts b/src/core/search/mode-advice.ts
index 763c0c30e2..036c8fd1b6 100644
--- a/src/core/search/mode-advice.ts
+++ b/src/core/search/mode-advice.ts
@@ -85,9 +85,9 @@ export function costMatrixSentence(): string {
/** How `query` and `search` expand, stated once. */
export const QUERY_EXPANSION_LINE =
- '`gbrain query` expands only when the mode says so (off in conservative and balanced, on in tokenmax); ' +
- '--expand forces it and --no-expand skips it. `gbrain config set search.expansion false` turns the default off for ' +
- 'the brain in any mode (true turns it on; an explicit --expand still wins). `gbrain search` never expands. An expansion is one call to the ' +
+ '`gbrain query` does not expand by default in any mode; --expand forces it and --no-expand skips it. ' +
+ '`gbrain config set search.expansion true` turns the default on for the brain in any mode (false turns it off; ' +
+ 'an explicit --expand or --no-expand still wins). `gbrain search` never expands. An expansion is one call to the ' +
'configured chat model, a separate provider charge; keyless brains never expand.';
/** The picker's reason for each recommendation branch. */
diff --git a/src/core/search/mode-switch-ux.ts b/src/core/search/mode-switch-ux.ts
index 8798843162..9eddf37878 100644
--- a/src/core/search/mode-switch-ux.ts
+++ b/src/core/search/mode-switch-ux.ts
@@ -135,8 +135,7 @@ export function summarizeTransition(
}
// Narrowing: dropping a feature (e.g. balanced → conservative drops the
- // reranker; tokenmax → balanced drops default expansion and synopsis
- // context). Semantic result caching is off, so nothing refills; no backfill.
+ // reranker; tokenmax → balanced drops synopsis context). Semantic result caching is off, so nothing refills; no backfill.
if (oldMode && narrowness(newMode) < narrowness(oldMode)) {
return {
kind: 'narrowing',
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index a6fe8d388f..9a58db766c 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -116,8 +116,9 @@ export interface ModeBundle {
/**
* 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.
+ * memory verbs never expand. Off in every bundle: on `tokenmax` it cut
+ * `query` p50 from 2,022 to 227 ms with retrieval unchanged (gbrain-evals
+ * GBRA-94, 2026-10-14). Override: per-call `expand` → `search.expansion` → bundle.
*/
expansion: boolean;
/**
@@ -602,11 +603,16 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
intentWeighting: true,
keywordOrFallback: true,
tokenBudget: undefined,
- expansion: true,
+ // Expansion OFF (gbrain-evals 2026-10-14 expansion latency, GBRA-94): on
+ // 300 LongMemEval-S questions with the reranker, no expansion kept strict
+ // recall@10 within the noise floor (298 vs 299; the reference's own re-run
+ // also scored 298) and cut `query` p50 from 2,022 to 227 ms.
+ // `search.expansion true` or per-call `expand: true` turns it back on.
+ expansion: false,
expansion_variant_budget: null,
searchLimit: 50,
- // tokenmax is the high-cost-tolerant tier that already pays for LLM
- // expansion + 50-result payloads. Reranker is the natural capstone:
+ // tokenmax is the high-cost-tolerant tier that already pays for
+ // 50-result payloads. Reranker is the natural capstone:
// better ordering of a large candidate set is where rerankers earn
// their fee. ~$0.0006/query at this shape (rerank-3-lite); rounding error vs the
// tier's $700/mo @ Opus pairing per CLAUDE.md cost matrix.
diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.ts
index 508e07e5ce..65684b6dda 100644
--- a/src/core/search/modes-report.ts
+++ b/src/core/search/modes-report.ts
@@ -107,8 +107,8 @@ 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 expands when the resolved `expansion` row below is on (the tokenmax ' +
- 'default; `search.expansion` overrides it) unless the call passes `expand` ' +
+ 'op expands when the resolved `expansion` row below is on (off in every ' +
+ 'mode by 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 ' +
diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.ts
index 4c7c3bd9ed..6a4b789f3d 100644
--- a/src/core/search/query-cache.ts
+++ b/src/core/search/query-cache.ts
@@ -72,8 +72,8 @@ export interface QueryCacheConfig {
* hit_count and created_at rather than inserting duplicates.
*
* v0.32.3 [CDX-4]: knobsHash is now part of the key to prevent cross-mode
- * cache contamination. A tokenmax write (expansion=on, limit=50) and a
- * conservative write (no expansion, limit=10) for the same query+source
+ * cache contamination. A tokenmax write (limit=50, no token budget) and a
+ * conservative write (limit=10) for the same query+source
* land in distinct rows. Empty-string knobsHash is accepted (preserves
* existing test setups) but production calls always pass the resolved hash.
*/
@@ -223,8 +223,8 @@ export class SemanticQueryCache {
// ttl_seconds > now) so we never return a stale row.
//
// v0.32.3 [CDX-4]: knobs_hash filter prevents cross-mode contamination.
- // A tokenmax write (expansion=on, limit=50) and a conservative read
- // (no expansion, limit=10) have distinct knobs hashes and miss each
+ // A tokenmax write (limit=50, no token budget) and a conservative read
+ // (limit=10) have distinct knobs hashes and miss each
// other. Rows with NULL knobs_hash (pre-v0.32.3) are excluded.
// v0.40.3.0: query_cache row aliased `qc` so the two-layer gate
// fragment in CACHE_GATE_WHERE_CLAUSE can reference qc.max_generation_at_store
diff --git a/src/core/search/tune-recommendations.ts b/src/core/search/tune-recommendations.ts
index 796d09619c..bbcd371111 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<Tun
knob: '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, and turns off query expansion by default (query --expand still requests it). 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. Semantic result caching is temporarily disabled.',
apply_command: 'gbrain config set search.mode balanced',
});
}
diff --git a/test/eval-longmemeval-via-operation.serial.test.ts b/test/eval-longmemeval-via-operation.serial.test.ts
index acab37ec0f..cd08f00287 100644
--- a/test/eval-longmemeval-via-operation.serial.test.ts
+++ b/test/eval-longmemeval-via-operation.serial.test.ts
@@ -175,13 +175,13 @@ describe('eval longmemeval --via-operation', () => {
expect(via.summary.run_config.via_operation_summary.model_calls_per_query.expansion).toBe(1);
}, 120_000);
- test('query under tokenmax with no --op-expand: the mode turns expansion on', async () => {
+ test('query under tokenmax with no --op-expand: the mode default no longer expands (GBRA-94)', async () => {
expansionTransport('variants');
const via = await run(['--via-operation', 'query', '--mode', 'tokenmax', ...NO_SYNOPSIS]);
expect(via.failed).toBe(false);
- expect(expansionCalls).toBe(QUESTIONS);
- expect(via.summary.run_config.expansion).toBe(true);
- expect(via.rows.every(r => r.via_operation.expansion.outcome === 'applied')).toBe(true);
+ expect(expansionCalls).toBe(0);
+ expect(via.summary.run_config.expansion).toBe(false);
+ expect(via.rows.every(r => r.via_operation.expansion.outcome === 'not_expected')).toBe(true);
}, 120_000);
test('a throwing expansion provider invalidates the arm: every row says failed and the run fails', async () => {
diff --git a/test/eval-run-all.test.ts b/test/eval-run-all.test.ts
index 62d1dbf20e..e1dfea0cdf 100644
--- a/test/eval-run-all.test.ts
+++ b/test/eval-run-all.test.ts
@@ -110,10 +110,10 @@ describe('estimateRunCost', () => {
expect(est.retrieval_usd).toBeGreaterThan(0);
});
- test('tokenmax incurs expansion cost (Haiku per query)', () => {
+ test('expansion cost follows the mode bundle: no mode expands by default since GBRA-94', () => {
const bal = estimateRunCost({ suites: ['replay'], modes: ['balanced'], limit: 100 });
const tok = estimateRunCost({ suites: ['replay'], modes: ['tokenmax'], limit: 100 });
- expect(tok.retrieval_usd).toBeGreaterThan(bal.retrieval_usd);
+ expect(tok.retrieval_usd).toBe(bal.retrieval_usd);
});
test('replay suite has zero answer cost', () => {
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 1573b226fa..db7b8316a8 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -728,7 +728,7 @@
" --return-unit Default auto: whole conversations.",
" --return-window Window radius 1-3.",
" --token-budget Evidence token cap.",
- " --expand Default per search mode (tokenmax on).",
+ " --expand Default off; search.expansion overrides.",
" --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.json
index 70f5c970bf..c89e601569 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": 238925,
- "stdoutSha256": "48e1395287f6d7cc7418aa35788642033780fadcdfc344e549c04be6740a6e47",
+ "stdoutBytes": 238927,
+ "stdoutSha256": "ab5b53bb28c47d3e7f4228c7f8f2326679a81ab4872659ea9e81b7a54d41da1d",
"toolNames": [
"remember",
"entity",
@@ -1446,7 +1446,7 @@
"type": "string"
},
"expand": {
- "description": "Default per search mode (tokenmax on).",
+ "description": "Default off; search.expansion overrides.",
"type": "boolean"
},
"explain": {
diff --git a/test/init-mode-picker.test.ts b/test/init-mode-picker.test.ts
index 0be03b2407..aae8c5ed04 100644
--- a/test/init-mode-picker.test.ts
+++ b/test/init-mode-picker.test.ts
@@ -215,9 +215,9 @@ describe('cost matrix: newest models, priced from model-pricing', () => {
test('the menu states the query expansion rule and no cache refill', () => {
const flat = MODE_PICKER_MENU.replace(/\s+/g, ' ');
- expect(flat).toContain('`gbrain query` expands only when the mode says so');
+ expect(flat).toContain('`gbrain query` does not expand by default in any mode');
expect(flat).toContain('`gbrain search` never expands');
- expect(flat).toContain('`gbrain config set search.expansion false` turns the default off for the brain');
+ expect(flat).toContain('`gbrain config set search.expansion true` turns the default on for the brain');
expect(flat).not.toMatch(/in every mode/);
expect(MODE_PICKER_MENU).toContain('semantic result caching is temporarily disabled');
expect(MODE_PICKER_MENU).toContain('gbrain search tune');
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index 0cf3a30140..be3430fded 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -158,7 +158,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
intentWeighting: true,
keywordOrFallback: true,
tokenBudget: undefined,
- expansion: true,
+ // GBRA-94 (2026-10-14): off, like the other two bundles.
+ expansion: false,
expansion_variant_budget: null,
searchLimit: 50,
reranker_enabled: true,
@@ -292,19 +293,19 @@ describe('resolveSearchMode resolution chain', () => {
test('per-call false-y values (false / 0) still beat fallback', () => {
const r = resolveSearchMode({
mode: 'tokenmax',
- perCall: { expansion: false, cache_enabled: false },
+ perCall: { reranker_enabled: false, cache_enabled: false },
});
- expect(r.expansion).toBe(false); // beat tokenmax's true
+ expect(r.reranker_enabled).toBe(false); // beat tokenmax's true
expect(r.cache_enabled).toBe(false); // beat tokenmax's true
});
test('undefined fields in perCall fall through (not coerced to false)', () => {
const r = resolveSearchMode({
mode: 'tokenmax',
- perCall: { tokenBudget: undefined, expansion: undefined },
+ perCall: { tokenBudget: undefined, reranker_enabled: undefined },
});
expect(r.tokenBudget).toBeUndefined(); // from tokenmax bundle
- expect(r.expansion).toBe(true); // from tokenmax bundle, NOT overridden
+ expect(r.reranker_enabled).toBe(true); // from tokenmax bundle, NOT overridden
});
});
diff --git a/test/search/mode-receipt.serial.test.ts b/test/search/mode-receipt.serial.test.ts
index a2345df768..46cddd6205 100644
--- a/test/search/mode-receipt.serial.test.ts
+++ b/test/search/mode-receipt.serial.test.ts
@@ -3,8 +3,8 @@
* the provider calls one `put_page`, one `search` and one `query` make in
* each mode, with every provider stubbed (embedding, rerank, expansion). It
* pins what choosing a mode at init actually changes on the agent read and
- * write paths: `query` expands by default only in tokenmax, `search` never
- * does, conservative never reranks, and `put_page` makes no provider call in
+ * write paths: `query` does not expand by default in any mode (GBRA-94),
+ * `search` never does, conservative never reranks, and `put_page` makes no provider call in
* any mode (it queues the page's embedding; per-chunk synopses come only from
* the separate contextual-retrieval backfill).
*
@@ -90,11 +90,11 @@ const RECEIPTS: Record<SearchMode, {
query: { embed: 1, rerank: 1, expand: 0, chat: 0 },
},
tokenmax: {
- settings: { searchLimit: 50, tokenBudget: null, reranker_enabled: true, reranker_top_n_in: 50, expansion: true, contextual_retrieval: 'per_chunk_synopsis' },
+ settings: { searchLimit: 50, tokenBudget: null, reranker_enabled: true, reranker_top_n_in: 50, expansion: false, contextual_retrieval: 'per_chunk_synopsis' },
put_page: { embed: 0, rerank: 0, expand: 0, chat: 0 },
search: { embed: 1, rerank: 1, expand: 0, chat: 0 },
- // The original question plus the expander's two variants.
- query: { embed: 3, rerank: 1, expand: 1, chat: 0 },
+ // No expansion call and no variant embeds since GBRA-94 (was embed 3, expand 1).
+ query: { embed: 1, rerank: 1, expand: 0, chat: 0 },
},
};
diff --git a/test/search/operation-expansion-contract.serial.test.ts b/test/search/operation-expansion-contract.serial.test.ts
index c3cf006c9e..8ab6ea8a0f 100644
--- a/test/search/operation-expansion-contract.serial.test.ts
+++ b/test/search/operation-expansion-contract.serial.test.ts
@@ -1,11 +1,12 @@
/**
* 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).
+ * (`expansion` off in all three bundles since GBRA-94, overridden by
+ * `search.expansion`), an explicit `expand` wins in either direction, the
+ * expander stays wired whenever expansion can resolve on (so
+ * `search.expansion true` 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); tokenmax's default
+ * turned off on the 2026-10-14 expansion-latency eval (GBRA-94).
*
* Serial: configures the process-global gateway with a stub embedder so the
* vector path (where expansion runs) is reached without a provider call.
@@ -86,7 +87,7 @@ async function resetSearchConfig(mode: string, expansionOverride: string | undef
describe('query expansion follows the search mode', () => {
for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {
for (const override of [undefined, 'true', 'false'] as const) {
- const modeDefault = override === undefined ? mode === 'tokenmax' : override === 'true';
+ const modeDefault = 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`]);
@@ -129,30 +130,36 @@ describe('query expansion follows the search mode', () => {
}
});
-describe('per-brain off switch: `gbrain config set search.expansion false`', () => {
+describe('per-brain switch: `gbrain config set search.expansion true|false`', () => {
async function runQueryCli(argv: string[], probe: ReturnType<typeof spyHybrid>): Promise<number> {
const before = probe.expanderCalls.length;
await operationsByName.query.handler(makeCtx({}), parseOpArgs(operationsByName.query, argv));
return probe.expanderCalls.length - before;
}
- test('unset expands in tokenmax, false stops it, an explicit --expand still wins, unset again restores it', async () => {
+ test('unset does not expand in tokenmax, true turns it on, false pins it off, explicit flags still win, unset restores the default', async () => {
await resetSearchConfig('tokenmax', undefined);
const probe = spyHybrid(q => [q, `${q} alternate phrasing`]);
const log = spyOn(console, 'log').mockImplementation(() => {});
try {
expect(parseOpArgs(operationsByName.query, ['Zirconiumneedle retrieval'])).not.toHaveProperty('expand');
+ expect((await buildModesReport(engine)).resolved.expansion).toMatchObject({ value: false });
+ expect(await runQueryCli(['Zirconiumneedle retrieval'], probe)).toBe(0);
+ expect(await runQueryCli(['Zirconiumneedle retrieval', '--expand'], probe)).toBe(1);
+
+ await runConfig(engine, ['set', 'search.expansion', 'true']);
+ expect(await engine.getConfig('search.expansion')).toBe('true');
+ expect((await buildModesReport(engine)).resolved.expansion).toMatchObject({ value: true, source: 'override' });
expect(await runQueryCli(['Zirconiumneedle retrieval'], probe)).toBe(1);
+ expect(await runQueryCli(['Zirconiumneedle retrieval', '--no-expand'], probe)).toBe(0);
await runConfig(engine, ['set', 'search.expansion', 'false']);
- expect(await engine.getConfig('search.expansion')).toBe('false');
expect((await buildModesReport(engine)).resolved.expansion).toMatchObject({ value: false, source: 'override' });
expect(await runQueryCli(['Zirconiumneedle retrieval'], probe)).toBe(0);
expect(await runQueryCli(['Zirconiumneedle retrieval', '--expand'], probe)).toBe(1);
- expect(await runQueryCli(['Zirconiumneedle retrieval', '--no-expand'], probe)).toBe(0);
await runConfig(engine, ['unset', 'search.expansion']);
- expect(await runQueryCli(['Zirconiumneedle retrieval'], probe)).toBe(1);
+ expect(await runQueryCli(['Zirconiumneedle retrieval'], probe)).toBe(0);
} finally {
log.mockRestore();
probe.restore();
@@ -206,7 +213,7 @@ describe('CRAG escalation reads what the first pass did', () => {
});
describe('tuning advice', () => {
- test('tokenmax with a Haiku subagent: balanced also turns off the expansion default', async () => {
+ test('tokenmax with a Haiku subagent: balanced caps the payload (no expansion claim: neither mode expands by 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');
@@ -220,7 +227,7 @@ describe('tuning advice', () => {
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('turns off query expansion by default');
+ expect(mode?.reason).not.toContain('expansion');
expect(mode?.reason).toContain('12K tokens');
});
});
diff --git a/test/search/query-expansion-phrasing-guard.test.ts b/test/search/query-expansion-phrasing-guard.test.ts
index d20942d1f5..4b09144b10 100644
--- a/test/search/query-expansion-phrasing-guard.test.ts
+++ b/test/search/query-expansion-phrasing-guard.test.ts
@@ -1,7 +1,10 @@
/**
* Guard: `query` expands only when the search mode says so (GBRA-81 item 1b),
* so no source file or doc may claim it expands "in every mode" or "always".
- * Scans src/, docs/ and the root agent docs; CHANGELOG history is exempt.
+ * Since the expansion-latency eval (GBRA-94) no mode expands by default, so no
+ * file may say `tokenmax` expands by default either.
+ * Scans src/, docs/, skills/ and the root agent docs; CHANGELOG history and the
+ * dated BEHAVIOR_CHANGES rows are exempt from the tokenmax check.
*/
import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
@@ -13,6 +16,9 @@ const ROOT_DOCS = ['INSTALL_FOR_AGENTS.md', 'CLAUDE.md', 'AGENTS.md', 'README.md
/** An expansion word and "in every mode" in one clause, or "always expands". */
const CLAIM = /\b(?:expands?|expansion|expanding)\b[^.;\n]{0,40}\bin every mode\b|\bin every mode\b[^.;\n]{0,20}\bexpan(?:ds?|sion)\b|\balways (?:expands?|requests expansion)\b/i;
+/** A claim that `tokenmax` turns expansion on by default. */
+const TOKENMAX_CLAIM = /\bexpan\w*\b[^.\n]{0,80}\bon (?:in|for|only in) `?tokenmax`?|`?tokenmax`?[^.\n]{0,30}\bexpansion ?[=:]? ?on\b|`?tokenmax`?[^.\n]{0,80}\bexpands by default\b/i;
+
function files(dir: string): string[] {
return readdirSync(dir).flatMap(name => {
const path = join(dir, name);
@@ -34,6 +40,30 @@ describe('query expansion phrasing guard', () => {
}
});
+ test('the tokenmax pattern catches the retired claims and spares the current wording', () => {
+ for (const old of [
+ 'Expansion follows the mode for `gbrain query` only: on in `tokenmax`, off in',
+ 'expand unset follows the mode: off in conservative and balanced, on in tokenmax',
+ 'tokenmax (expansion=on, limit=50) has a different hash',
+ '3) tokenmax — no budget, 50 chunks, reranked, `gbrain query` expands by default.',
+ ]) expect(old).toMatch(TOKENMAX_CLAIM);
+ for (const fine of ['`gbrain query` does not expand by default in any mode', 'tokenmax (limit=50, no token budget)', 'reranker on for balanced and tokenmax']) {
+ expect(fine).not.toMatch(TOKENMAX_CLAIM);
+ }
+ });
+
+ test('no file in src/, docs/, skills/ or the root agent docs says tokenmax expands by default', () => {
+ const offenders: string[] = [];
+ const paths = [...files(join(ROOT, 'src')), ...files(join(ROOT, 'docs')), ...files(join(ROOT, 'skills')), ...ROOT_DOCS.map(f => join(ROOT, f))];
+ for (const path of paths) {
+ if (relative(ROOT, path) === 'src/core/behavior-change-notice.ts') continue;
+ readFileSync(path, 'utf8').split('\n').forEach((line, i) => {
+ if (TOKENMAX_CLAIM.test(line)) offenders.push(`${relative(ROOT, path)}:${i + 1}: ${line.trim().slice(0, 160)}`);
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+
test('no file in src/, docs/ or the root agent docs says query expands in every mode', () => {
const offenders: string[] = [];
const paths = [...files(join(ROOT, 'src')), ...files(join(ROOT, 'docs')), ...ROOT_DOCS.map(f => join(ROOT, f))];