Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(query): every surface states the mode-decided expansion; phrasing guard (GBRA-81 item 1b)

garrytand970ea54dc1a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb9e2da9a2..0a899a9164 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,12 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+### Itemized changes
+
+- **`query` expands only when the search mode says so (GBRA-81 item 1b).** The `query` operation used to send `expand: true` on every call, so every mode, `balanced` included, made one expansion LLM call before retrieval. It now leaves `expand` unset unless the caller passes it, so the resolved mode decides: on in `tokenmax`, off in `balanced` and `conservative`. `expand: true` (CLI `--expand`) forces it and `expand: false` (`--no-expand`) skips it; `gbrain config set search.expansion true` restores it by default for a brain, and a `search.expansion` value set earlier, which `query` ignored, now takes effect. The expander stays wired whenever expansion can resolve on, so `tokenmax` still expands. CRAG's caller-expanded check reads `expansion_applied`; eval capture records the raw `expand` param (null when unset) and `gbrain eval replay` maps null to the mode default. The tool description, the concept-search hint, `gbrain search modes`, `search tune`, top-level help, the picker copy and the docs say the same, and a guard test rejects "in every mode" / "always expands" phrasing in `src/` and `docs/`. `test/search/operation-expansion-contract.serial.test.ts` is rewritten to pin the new contract.
+
## [0.60.178.0] - 2026-10-12
**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.
diff --git a/CLAUDE.md b/CLAUDE.md
index 99e4e224dc..03c863a182 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 in every mode unless explicitly disabled; `search`
-and memory verbs do not. Semantic result reuse is disabled.
+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.
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 43a2bd1d11..e508399192 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -264,11 +264,11 @@ Per-query cost @ 10K queries/mo (typical single-user volume):
> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —
> no budget, 50 chunks. Best for Opus/frontier models.
>
-> Expansion is command-specific, not mode-specific: `gbrain search` and the
-> memory verbs do not expand; `gbrain query` expands in every mode unless you
-> pass `--no-expand` (`expand: false` over MCP). The `search.expansion` bundle
-> setting does not change these shipped command paths. See
-> [search modes](docs/guides/search-modes.md) for the current contract.
+> 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 search` and the memory
+> verbs never expand. See [search modes](docs/guides/search-modes.md) for the
+> current contract.
>
> Cost depends on BOTH the mode AND the downstream model you run. See the
> matrix above for the 9-cell breakdown.
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 7d6123d9b7..afc27240d6 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -218,7 +218,7 @@ Every non-localOnly operation on the MCP surface: 149 tools across 25 areas. **S
|---|---|---|---|---|
| `assemble_evidence` | Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. | read | | |
| `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | |
-| `query` | Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonyms). | read | yes | |
+| `query` | Hybrid search for concept/landscape questions; expand adds multi-query expansion (expansion recovers synonyms). | read | yes | |
| `rate_answer` | Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). | write | | |
| `search` | Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. | read | yes | |
| `search_by_image` | Image-as-query retrieval. | read | | |
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index a255d1fc45..66235e7f86 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -176,12 +176,12 @@ 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 retain a core-library `expansion` default (`tokenmax` true;
-`balanced` and `conservative` false). It applies only when a library caller
-leaves `expansion` unset and supplies an `expandFn`. Shipped operations set
-their own policy: `query` requests expansion in every mode, with
-`expand: false` / `--no-expand` as the explicit opt-out; `search` never
-expands. Neither inherits `search.expansion`. Keyless and image-only paths
+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`;
+`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
[search-mode guide](../guides/search-modes.md) is the authoritative rule for
defaults, overrides and provider costs; `gbrain search modes` prints the
@@ -197,8 +197,8 @@ relational recall arm remains available.
intent classify (query-intent.ts — deterministic, no LLM)
│
▼
-expansion (query: requested by default in every mode; --no-expand opts out;
- search: off; keyless and image-only paths skip it)
+expansion (query: the mode's default, on only in tokenmax; --expand forces,
+ --no-expand skips; search: off; keyless and image-only paths skip it)
│
▼
hybrid recall + fusion:
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index a15332a8ed..788d246fef 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -61,7 +61,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/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` is on in every mode unless explicitly disabled, 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 (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/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 bf2452fa6b..3c6f4ffe92 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -494,7 +494,7 @@ What the arms say:
and autocut off, expansion costs thirteen questions against `balanced`
(+2 / −15: multi-session −7, temporal −5) plus the Haiku call per query.
`gbrain config set search.mode balanced` keeps the reranker and drops
- expansion (`gbrain query` still expands in every mode unless `--no-expand`);
+ expansion (`gbrain query` no longer expands under `balanced` unless `--expand`);
`gbrain config set search.expansion_variant_budget 0.25`
recovers most of the loss if you keep it on.
- **Slot starvation is not the miss class** (from the 2026-09-02 sibling run;
diff --git a/docs/guides/capabilities.md b/docs/guides/capabilities.md
index 71f255deae..b6a6df6ea8 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 in every mode unless `--no-expand` is passed, while `search` and memory verbs do not 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` 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).
**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 9e29cc4f55..8a1148f595 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -41,23 +41,22 @@ and maintenance commands remain available.
| `reranker` (cross-encoder) | off | `voyage:rerank-2.5` | `voyage:rerank-2.5` |
| `autocut` (rerank-cliff cut) | off | off | off |
-The `expansion` row is not decisive for any shipped verb today: `gbrain query`
-(the only verb that can expand) expands by default in every mode — pass
-`--no-expand` / `expand: false` to opt out — while `gbrain search`, the memory
-verbs and the eval harnesses pin expansion per call. The bundle value (and the
-`search.expansion` config key) only reaches a core-library caller that leaves `expansion`
-unset AND wires an `expandFn`; none ship today. `gbrain search modes` reports
-the bundle value and prints the operation-level exception before its knob table.
-
-This preserves the existing query contract: changing modes does not silently
-enable or disable expansion. `query` defaults to `expand: true`; explicit
-`expand: false` (CLI `--no-expand`) wins even in `tokenmax`. `search` never
-expands, even with `search.expansion=true`. Keyless retrieval takes the
-keyword-only path before expansion; configured embedding and expansion
-providers are prerequisites. Image-only retrieval also skips expansion.
-Check response metadata `expansion_applied` for actual variant use, not just
-the requested setting. A configured cloud expander receives the query;
-its model's input/output charges are separate from downstream reading costs.
+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
+`--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.
+
+Keyless retrieval takes the keyword-only path before expansion; configured
+embedding and expansion providers are prerequisites. Image-only retrieval also
+skips expansion. Check response metadata `expansion_applied` for actual
+variant use, not just the requested setting. A configured cloud expander
+receives the query; its model's input/output charges are separate from
+downstream reading costs.
- **`conservative`** — smallest payloads. Pairs naturally with a cheap
downstream model (Haiku-class) or a high query volume.
@@ -70,9 +69,9 @@ Seven of the knobs deserve a sentence:
- **`expansion`** rewrites your query into multiple variants via a cheap
LLM call when available (the historical Haiku estimate is roughly $1.50 per
1K queries; actual charges depend on model and token counts). It can recover
- alternate phrasings but can also hurt precision. `gbrain query` requests
- expansion in every mode unless `--no-expand`;
- this knob does not turn it off (see the caption under the table).
+ alternate phrasings but can also hurt precision. It is `gbrain query`'s
+ default when a call leaves `expand` unset (see the caption under the table);
+ `--expand` / `--no-expand` win per call.
- **`expansion_variant_budget`** (config key
`search.expansion_variant_budget`) is the total RRF weight the expansion
variants share at fusion time (`weight_i = b / n_voting_arms`; the original
diff --git a/llms-full.txt b/llms-full.txt
index d19692b31f..1f0e48be02 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2175,8 +2175,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 in every mode unless explicitly disabled; `search`
-and memory verbs do not. Semantic result reuse is disabled.
+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.
Read `docs/eval/SEARCH_MODE_METHODOLOGY.md` for eval methodology and
`docs/eval/METRIC_GLOSSARY.md` for metric definitions. Eval audit records stay in
@@ -2766,11 +2766,11 @@ Per-query cost @ 10K queries/mo (typical single-user volume):
> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —
> no budget, 50 chunks. Best for Opus/frontier models.
>
-> Expansion is command-specific, not mode-specific: `gbrain search` and the
-> memory verbs do not expand; `gbrain query` expands in every mode unless you
-> pass `--no-expand` (`expand: false` over MCP). The `search.expansion` bundle
-> setting does not change these shipped command paths. See
-> [search modes](docs/guides/search-modes.md) for the current contract.
+> 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 search` and the memory
+> verbs never expand. See [search modes](docs/guides/search-modes.md) for the
+> current contract.
>
> Cost depends on BOTH the mode AND the downstream model you run. See the
> matrix above for the 9-cell breakdown.
diff --git a/src/commands/init-mode-picker.ts b/src/commands/init-mode-picker.ts
index 17fbef9128..47f774d33b 100644
--- a/src/commands/init-mode-picker.ts
+++ b/src/commands/init-mode-picker.ts
@@ -134,7 +134,7 @@ This matrix estimates the downstream agent's input cost for reading retrieved
chunks. Embedding, reranking and expansion can add separate provider charges.
GBrain's semantic result caching is temporarily disabled; budget for fresh retrieval.
When configured, gbrain query adds ~$1.50 per 1K queries under the historical
-Haiku expansion call estimate, in every mode — --no-expand skips it;
+Haiku expansion call estimate when it expands (tokenmax, or --expand) — --no-expand skips it;
gbrain search never expands. Actual expansion cost depends on model and tokens.
Per-query cost @ 10K queries/mo (full search payload, no cache savings):
@@ -164,8 +164,9 @@ it does not skip retrieval or downstream generation.
Best for: Opus/frontier models, broad retrieval,
low-volume high-stakes work.
-gbrain query requests expansion in every mode unless you pass --no-expand.
-gbrain search never expands. Neither inherits search.expansion. Actual
+gbrain query expands only when the mode says so (tokenmax) or with --expand;
+--no-expand skips it.
+gbrain search never expands, even with search.expansion=true. Actual
expansion needs configured embedding and expansion providers; keyless
retrieval sends no expansion request. Cloud expansion sends the query
to the configured provider and may incur its model's input/output charges.
@@ -261,7 +262,7 @@ export async function runModePicker(
console.log('');
console.log(' (scales linearly: ×10 for 100K queries/mo, ÷10 for 1K)');
console.log(' 25x corner-to-corner spread. Natural diagonal pairings span ~4x.');
- console.log(' query requests expansion in every mode; --no-expand opts out. search never expands.');
+ console.log(' query expands only when the mode says so (tokenmax); --expand forces it, --no-expand skips it. search never expands.');
console.log(' Keyless retrieval skips expansion; configured cloud providers may add separate charges.');
console.log('');
console.log('To change later: gbrain config set search.mode <mode>');
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 13077c7ba1..cfd5281b93 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -467,6 +467,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },
// Fix wave 15 group 1 (managed sync authority and data safety).
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
+ // Low-hanging-fruit wave lane A (GBRA-81 items 1 and 1b). `since` is provisional (this branch's VERSION, 0.60.178.0); the integrator restamps it to the release at the merge slot.
+ { since: '0.60.178.0', text: '`query` now expands only when the search mode says so: on in `tokenmax`, off in `balanced` (the default) and `conservative`, so `query` on a `balanced` brain no longer makes an expansion LLM call before retrieval. `expand: true` (CLI `--expand`) expands one call in any mode, and `gbrain config set search.expansion true` restores expansion by default for the brain; `expand: false` (`--no-expand`) still skips it. A `search.expansion` value set earlier, which `query` used to ignore, now takes effect on `query`; `gbrain search modes` shows it. `search` never expands, as before. CRAG escalation now reads whether the first pass actually expanded (`expansion_applied`), and eval capture records the `expand` the caller sent (null when unset) so `gbrain eval replay` replays the mode default.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index cb7cdf1abc..535bf49f53 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/test/mcp-eval-capture.test.ts b/test/mcp-eval-capture.test.ts
index 90c5d564c5..5137970454 100644
--- a/test/mcp-eval-capture.test.ts
+++ b/test/mcp-eval-capture.test.ts
@@ -99,7 +99,8 @@ describe('op-layer capture — query', () => {
expect(row.tool_name).toBe('query');
expect(row.query).toBe('alice');
expect(row.remote).toBe(true);
- expect(row.expand_enabled).toBe(true); // default
+ // The raw `expand` param: unset is null, so replay applies the mode default (GBRA-81 item 1b).
+ expect(row.expand_enabled).toBeNull();
expect(row.vector_enabled).toBe(false); // OPENAI_API_KEY deleted
expect(row.job_id).toBeNull();
expect(row.subagent_id).toBeNull();
diff --git a/test/search/query-expansion-phrasing-guard.test.ts b/test/search/query-expansion-phrasing-guard.test.ts
new file mode 100644
index 0000000000..d20942d1f5
--- /dev/null
+++ b/test/search/query-expansion-phrasing-guard.test.ts
@@ -0,0 +1,47 @@
+/**
+ * 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.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..', '..');
+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;
+
+function files(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) return files(path);
+ return /\.(ts|md)$/.test(name) ? [path] : [];
+ });
+}
+
+describe('query expansion phrasing guard', () => {
+ test('the pattern catches the retired claims and spares unrelated "every mode" text', () => {
+ for (const old of [
+ '`query` expands in every mode unless explicitly disabled',
+ 'gbrain query requests expansion in every mode unless you pass --no-expand.',
+ '(the only verb that can expand) expands by default in every mode',
+ 'the `query` op always expands',
+ ]) expect(old).toMatch(CLAIM);
+ for (const fine of ['autocut is off in every mode since rule R2', 'floor 1 in every mode', '`query` expands only when the mode says so']) {
+ expect(fine).not.toMatch(CLAIM);
+ }
+ });
+
+ 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))];
+ for (const path of paths) {
+ readFileSync(path, 'utf8').split('\n').forEach((line, i) => {
+ if (CLAIM.test(line)) offenders.push(`${relative(ROOT, path)}:${i + 1}: ${line.trim().slice(0, 160)}`);
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+});