Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(init): one source for search-mode advice, init --search-mode, search.mode_source (GBRA-81 item 1)
garrytana7115763ba52
diff --git a/AGENTS.md b/AGENTS.mdindex de3cb2cf65..98944aded9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -33,7 +33,7 @@ start here.default but printed a 9-cell cost matrix (mode × downstream model)preceded by `[AGENT]` markers. You MUST relay the matrix to the operatorand confirm their choice before continuing. Cost spread between corners- is 25x — silent acceptance is the wrong default. See+ is about 200x — silent acceptance is the wrong default. See[`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) Step 3.5 for theexact ask-the-user protocol. The same banner fires on `gbrain post-upgrade`for a brain created before v0.32.3, when search modes arrived.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a899a9164..38ba3de259 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,9 @@ identifiers and attribution are available in the pre-removal Git revision### 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.+- **`gbrain init` reads keys the way the gateway does.** Provider keys are read through `mergedProviderEnv`, so a key saved in `~/.gbrain/config.json` counts, and a brain with a ready reranker but no chat key gets `balanced` instead of `conservative` (the reranker branch uses `rerankerReadiness`, not a key name); `conservative` stays for a Haiku subagent or when neither a chat key nor a ready reranker exists.+- **`gbrain init --search-mode <mode>` and `search.mode_source`.** An agent that knows the operator's choice records it at install time: no recommendation, no first-run `search_mode` ask, `search.mode_source: operator`. On a brain with a different mode it refuses unless `--force`. Picker choices record `auto`; `gbrain config set search.mode` records `operator`.+- **One source for the mode advice.** `src/core/search/mode-advice.ts` holds the recommendation, its reasons and evidence, the `[AGENT]` and upgrade banners, init's first-run decision text and the cost matrix, now priced for Haiku 5.5, Sonnet 5.5 and Opus 5.5 from `src/core/model-pricing.ts` (about a 200x corner-to-corner spread). `INSTALL_FOR_AGENTS.md` Step 3.5 carries the generated matrix, kept in sync by a test. Switching modes no longer promises a cache refill while semantic result caching is off.## [0.60.178.0] - 2026-10-12diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex e508399192..0456b89124 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -228,26 +228,33 @@ loop; full reference in `docs/ENGINES.md` ("Engine detection and access repair")## Step 3.5: Confirm search mode with the user (DO NOT SKIP)This is the `search_mode` decision from the first-run bundle.-`gbrain init` auto-applied a default search mode (`tokenmax` unless your subagent-tier is Haiku-class or no expansion-capable API key — Anthropic, OpenAI, or-Google — is configured). The init output included the cost matrix below preceded-by `[AGENT]` markers. You must NOT silently accept the default. Stop and ask the-operator.+`gbrain init` auto-applied a default search mode: `tokenmax` with a chat key+(Anthropic, OpenAI or Google), `balanced` with a ready reranker but no chat key,+and `conservative` when your subagent tier is Haiku-class or neither exists. The init output+included the cost matrix below preceded by `[AGENT]` markers. You must NOT+silently accept the default. Stop and ask the operator.++If you already know the operator's choice, record it at install time instead:+`gbrain init --search-mode <conservative|balanced|tokenmax>` stores it as the+operator's (`search.mode_source: operator`) and init asks no `search_mode`+question. On an existing brain with a different mode it refuses unless you pass+`--force`.**Present this matrix verbatim:**-<!-- Cost matrix: keep this block aligned with src/commands/init-mode-picker.ts; CLAUDE.md links here rather than duplicating it. -->+<!-- Cost matrix: generated by costMatrixLines() in src/core/search/mode-advice.ts (prices from src/core/model-pricing.ts); test/init-mode-picker.test.ts keeps this block in sync. -->```-Per-query cost @ 10K queries/mo (typical single-user volume):+Estimated downstream input cost of the retrieved payload @ 10K queries/mo:- Haiku 4.5 Sonnet 4.6 Opus 4.7- ($1/M) ($3/M) ($5/M)- conservative $40/mo $120/mo $200/mo- balanced $100/mo $300/mo $500/mo- tokenmax $200/mo $600/mo $1,000/mo+ Haiku 5.5 Sonnet 5.5 Opus 5.5+ ($0.10/M in) ($2/M in) ($4/M in)+ conservative $4/mo $80/mo $160/mo+ balanced $10/mo $200/mo $400/mo+ tokenmax $20/mo $400/mo $800/mo-(scales linearly: ×10 for 100K/mo, ÷10 for 1K. 25x corner-to-corner spread.- Natural diagonal pairings — cheap/cheap → frontier/frontier — span ~4x.)+ Assumed payload per query: conservative 4K, balanced 10K, tokenmax 20K tokens.+ Scales linearly: x10 for 100K queries/mo, /10 for 1K. 200x corner-to-corner spread.+ Embedding, reranking and query expansion are separate provider charges.```**Ask the operator (paraphrase if needed):**@@ -256,13 +263,13 @@ Per-query cost @ 10K queries/mo (typical single-user volume):> a one-time setup decision that controls retrieval payload size. Which mode> do you want?>-> 1) conservative — tight 4K budget, 10 chunks max.+> 1) conservative — tight 4K budget, 10 chunks max, no reranker.> Best for Haiku subagents, cost-sensitive setups, high-volume loops.>-> 2) balanced — 12K budget, 25 chunks. Sonnet-tier sweet spot.+> 2) balanced — 12K budget, 25 chunks, reranked.>-> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —-> no budget, 50 chunks. Best for Opus/frontier models.+> 3) tokenmax (recommended with a chat key) — no budget, 50 chunks, reranked,+> `gbrain query` expands by default. 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@@ -293,7 +300,7 @@ result cache; budget for fresh retrieval. Read the command-level caveats in[search modes](docs/guides/search-modes.md) rather than treating a mode choice asa guarantee of zero paid calls.-**Why this matters:** the cost spread between corners of the matrix is 25x.+**Why this matters:** the cost spread between corners of the matrix is about 200x.An agent that silently accepts the default and starts running queries againsta user who didn't expect tokenmax-class context loads can rack up surprisespend. Confirm before continuing.diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex c4eb0e7c8d..41544b7a93 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language through `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (`fts-language.ts`; they KEEP the `SET search_path = pg_catalog, public` hardening, which CREATE OR REPLACE resets) — then backfills `pages` and `content_chunks` through `src/core/search-vector-backfill.ts` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. It then replaces `idx_facts_fts` (v237) under the language through `ensureFactsFtsIndex` (`src/core/facts/fts-index.ts`): the new index is built beside the old one (CONCURRENTLY on Postgres) and renamed into place, so writes never wait and search keeps an index (no row rewrite). Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.-- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.+- `src/commands/init-mode-picker.ts` — install-time mode recommendation and mandatory operator choice. `recommendModeFor` recommends `tokenmax` with a chat key, `balanced` with a ready reranker and no chat key, and `conservative` for a Haiku subagent or when neither exists; `resolveModePickerInputs` reads keys through `mergedProviderEnv` (so `~/.gbrain/config.json` keys count) and the reranker through `rerankerReadiness`. `gbrain init --search-mode <mode>` (`searchModeChoiceFromArgs`) records the operator's choice, suppresses the first-run `search_mode` ask and refuses on a brain with another mode unless `--force`; picker choices record `search.mode_source: auto`, explicit ones `operator`. Reasons, the `[AGENT]` banner and the cost matrix come from `src/core/search/mode-advice.ts`. Pinned by `test/init-mode-picker.test.ts`.- `src/core/embedding-migration-cli.ts` — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by `commands/migrate-embeddings.ts`). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.- `test/migrate-embeddings-recovery-cli.serial.test.ts` — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static `EMBEDDING_MIGRATION_RECOVERY` is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by `test/migrate-embeddings-op-contract.serial.test.ts`. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 788d246fef..ea548d2052 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -60,6 +60,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/metadata-boost-gate.ts` — the ONE parse + decision contract for `search.metadata_boost_gate` (`always` | `lexical`; every bundle is `lexical`, `DEFAULT_METADATA_BOOST_GATE` stays `always` so a knobs literal without the field keeps its pre-wave hash identity). `lexicalArmsVoted` answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); `decideMetadataBoosts({gate, lexicalVoted})` returns `{gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}`. Image-modality queries are exempt from the gate: `hybridSearch` never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and `lexical` would silently disable the boosts for the whole modality — the caller passes `modality` (from `effectiveModality`) and an image decision applies the boosts as before (reason `image_modality`). Under `lexical`, `hybridSearch` passes `skipMetadataBoosts` into `runPostFusionStages` so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to `lexical` in all three bundles. The decision is surfaced as `HybridSearchMeta.metadata_boost_gate` (`--explain`); knobs-hash part `mbg=`; override chain per-call `metadataBoostGate` → config → bundle (`normalizeMetadataBoostGate` is the shared parser, garbage falls through). Pinned by `test/search/metadata-boost-gate.test.ts` (pure contract, hash participation, resolution chain) and `test/search/metadata-boost-gate-hybrid.test.ts` (hermetic PGLite hub-vs-gold corpus: `always` reproduces the hub-first regression, the default yields gold-first, config and per-call planes, unparseable falls through).- `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.diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex 8a1148f595..4cc558a3f7 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -180,15 +180,18 @@ reports effective `cache_enabled: false`, and `cache stats` reports### Cost intuitionThe table estimates only the tokens your *downstream agent* pays to read-per query. Embedding, reranking and expansion calls can add separate charges. The-corner-to-corner spread is ~25x once you pair mode with downstream model.-Rough anchors at 10K queries/month, full payload, no cache savings:--| Mode \ Downstream | Haiku-class (\$1/M in) | Sonnet-class (\$3/M in) | Opus-class (\$5/M in) |+per query: an assumed payload per mode times 10K queries a month times the+model's input rate from gbrain's pricing table (`src/core/model-pricing.ts`).+Embedding, reranking and expansion calls are separate charges. The+corner-to-corner spread is about 200x once you pair mode with downstream model.+The install picker and the upgrade banner print the same matrix from+`src/core/search/mode-advice.ts`.++| Mode \ Downstream | Haiku 5.5 (\$0.10/M in) | Sonnet 5.5 (\$2/M in) | Opus 5.5 (\$4/M in) ||---|---|---|---|-| conservative (~4K tok) | **\$40/mo** | \$120/mo | \$200/mo |-| balanced (~10K tok) | \$100/mo | \$300/mo | \$500/mo |-| tokenmax (~20K tok) | \$200/mo | \$600/mo | **\$1,000/mo** |+| conservative (~4K tok) | **\$4/mo** | \$80/mo | \$160/mo |+| balanced (~10K tok) | \$10/mo | \$200/mo | \$400/mo |+| tokenmax (~20K tok) | \$20/mo | \$400/mo | **\$800/mo** |Scales linearly with volume. Budget for fresh retrieval on every query whilesemantic result caching is disabled; repeated searches may take longer and use@@ -232,12 +235,21 @@ the search path, such as an evidence gate that drops results with no evidencefor the question but, by default, never below three results and never an exact match.None of them changes a mode bundle. See [System One](system-one.md).-The mode picker runs inside `gbrain init`. Non-TTY initialization tentatively-applies its recommendation: `conservative` for a Haiku subagent or no detected-expansion-capable key, otherwise `tokenmax`. Existing valid selections are-preserved. This differs from retrieval's `balanced` fallback when no valid-`search.mode` is stored; the picker asks agents to confirm the choice with-their operator before continuing a real setup.+The mode picker runs inside `gbrain init`. Non-TTY and `--json` initialization+tentatively applies its recommendation: `tokenmax` with a chat key (Anthropic,+OpenAI or Google), `balanced` with a ready reranker but no chat key (nothing in+`balanced` needs a chat model), and `conservative` for a Haiku subagent or when+neither exists. Keys count whether they are exported or saved in+`~/.gbrain/config.json`. Existing valid selections are preserved, and the+picker asks agents to confirm the choice with their operator before+continuing a real setup.++An agent that already knows the operator's choice records it at install time+with `gbrain init --search-mode <conservative|balanced|tokenmax>`: no+recommendation, no first-run `search_mode` question, and the brain records+`search.mode_source: operator` (picker choices record `auto`; `gbrain config+set search.mode` records `operator`). On a brain that already has a different+mode, `--search-mode` refuses unless you also pass `--force`.## Query instruction prefixdiff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex cdf405fcd2..cfcc13241e 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -275,7 +275,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -312,7 +312,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/llms-full.txt b/llms-full.txtindex 1f0e48be02..bc738c0bd3 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1729,7 +1729,7 @@ start here.default but printed a 9-cell cost matrix (mode × downstream model)preceded by `[AGENT]` markers. You MUST relay the matrix to the operatorand confirm their choice before continuing. Cost spread between corners- is 25x — silent acceptance is the wrong default. See+ is about 200x — silent acceptance is the wrong default. See[`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) Step 3.5 for theexact ask-the-user protocol. The same banner fires on `gbrain post-upgrade`for a brain created before v0.32.3, when search modes arrived.@@ -2730,26 +2730,33 @@ loop; full reference in `docs/ENGINES.md` ("Engine detection and access repair")## Step 3.5: Confirm search mode with the user (DO NOT SKIP)This is the `search_mode` decision from the first-run bundle.-`gbrain init` auto-applied a default search mode (`tokenmax` unless your subagent-tier is Haiku-class or no expansion-capable API key — Anthropic, OpenAI, or-Google — is configured). The init output included the cost matrix below preceded-by `[AGENT]` markers. You must NOT silently accept the default. Stop and ask the-operator.+`gbrain init` auto-applied a default search mode: `tokenmax` with a chat key+(Anthropic, OpenAI or Google), `balanced` with a ready reranker but no chat key,+and `conservative` when your subagent tier is Haiku-class or neither exists. The init output+included the cost matrix below preceded by `[AGENT]` markers. You must NOT+silently accept the default. Stop and ask the operator.++If you already know the operator's choice, record it at install time instead:+`gbrain init --search-mode <conservative|balanced|tokenmax>` stores it as the+operator's (`search.mode_source: operator`) and init asks no `search_mode`+question. On an existing brain with a different mode it refuses unless you pass+`--force`.**Present this matrix verbatim:**-<!-- Cost matrix: keep this block aligned with src/commands/init-mode-picker.ts; CLAUDE.md links here rather than duplicating it. -->+<!-- Cost matrix: generated by costMatrixLines() in src/core/search/mode-advice.ts (prices from src/core/model-pricing.ts); test/init-mode-picker.test.ts keeps this block in sync. -->```-Per-query cost @ 10K queries/mo (typical single-user volume):+Estimated downstream input cost of the retrieved payload @ 10K queries/mo:- Haiku 4.5 Sonnet 4.6 Opus 4.7- ($1/M) ($3/M) ($5/M)- conservative $40/mo $120/mo $200/mo- balanced $100/mo $300/mo $500/mo- tokenmax $200/mo $600/mo $1,000/mo+ Haiku 5.5 Sonnet 5.5 Opus 5.5+ ($0.10/M in) ($2/M in) ($4/M in)+ conservative $4/mo $80/mo $160/mo+ balanced $10/mo $200/mo $400/mo+ tokenmax $20/mo $400/mo $800/mo-(scales linearly: ×10 for 100K/mo, ÷10 for 1K. 25x corner-to-corner spread.- Natural diagonal pairings — cheap/cheap → frontier/frontier — span ~4x.)+ Assumed payload per query: conservative 4K, balanced 10K, tokenmax 20K tokens.+ Scales linearly: x10 for 100K queries/mo, /10 for 1K. 200x corner-to-corner spread.+ Embedding, reranking and query expansion are separate provider charges.```**Ask the operator (paraphrase if needed):**@@ -2758,13 +2765,13 @@ Per-query cost @ 10K queries/mo (typical single-user volume):> a one-time setup decision that controls retrieval payload size. Which mode> do you want?>-> 1) conservative — tight 4K budget, 10 chunks max.+> 1) conservative — tight 4K budget, 10 chunks max, no reranker.> Best for Haiku subagents, cost-sensitive setups, high-volume loops.>-> 2) balanced — 12K budget, 25 chunks. Sonnet-tier sweet spot.+> 2) balanced — 12K budget, 25 chunks, reranked.>-> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —-> no budget, 50 chunks. Best for Opus/frontier models.+> 3) tokenmax (recommended with a chat key) — no budget, 50 chunks, reranked,+> `gbrain query` expands by default. 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@@ -2795,7 +2802,7 @@ result cache; budget for fresh retrieval. Read the command-level caveats in[search modes](docs/guides/search-modes.md) rather than treating a mode choice asa guarantee of zero paid calls.-**Why this matters:** the cost spread between corners of the matrix is 25x.+**Why this matters:** the cost spread between corners of the matrix is about 200x.An agent that silently accepts the default and starts running queries againsta user who didn't expect tokenmax-class context loads can rack up surprisespend. Confirm before continuing.@@ -3481,7 +3488,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -3518,7 +3525,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..768960b6d3 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -277,7 +277,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -314,7 +314,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..768960b6d3 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -277,7 +277,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -314,7 +314,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..768960b6d3 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -277,7 +277,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -314,7 +314,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/scripts/agent-contract-baselines/marker-literal.tsv b/scripts/agent-contract-baselines/marker-literal.tsvindex c4bd40f8d4..c4d0afff58 100644--- a/scripts/agent-contract-baselines/marker-literal.tsv+++ b/scripts/agent-contract-baselines/marker-literal.tsv@@ -3,7 +3,6 @@ src/commands/config.ts 1src/commands/doctor/upgrade-banner.ts 6src/commands/google-attachments.ts 1src/commands/google.ts 4-src/commands/init-mode-picker.ts 6-src/commands/upgrade.ts 5+src/commands/upgrade.ts 2src/core/advisor/render.ts 2src/core/skillpack/brain-pack-advisory.ts 1diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvnew file mode 100644index 0000000000..e69097fdc8--- /dev/null+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -0,0 +1 @@+# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>countdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e1859121e8..87664f434c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 3030 ratchet +1 System One v1 evals: search arms clasrc/core/search/hybrid.ts 1632 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)src/core/types.ts 2292 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)-src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)+src/commands/init.ts 1882 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1955 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts)+src/core/config.ts 1956 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +1 GBRA-81 item 1: search.mode_source registeredsrc/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)@@ -44,4 +44,4 @@ src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subsetsrc/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)-src/commands/config.ts 1507 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook+src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 GBRA-81 item 1: config set search.mode records search.mode_source operatordiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 359405bb0e..02f21876fc 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -197,6 +197,7 @@ test/harness-onboarding.test.ts harness identity and private handoff 6 readFileStest/hook-command.serial.test.ts user-prompt 16 source-surface-helpertest/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSynctest/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSync+test/init-mode-picker.test.ts cost matrix: newest models, priced from model-pricing 6 readFileSynctest/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSynctest/integrations.test.ts CLI integration 3 source-surface-helpertest/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSync,source-surface-helperdiff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..768960b6d3 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -277,7 +277,7 @@ stdout (`--json`):"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -314,7 +314,7 @@ stdout (`--json`):}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 412e3d7230..0750716043 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -44,7 +44,7 @@"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e","context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",- "conventions/agent-operator-protocol.md": "d22b616c90d84d7035cf2c56ed2c59d361b06a0499f548ae21e81bd23823efce",+ "conventions/agent-operator-protocol.md": "0bc91b8b146436933166839246ce387db6b1af479dcd378f5b4d3a8fcef4c685","conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",diff --git a/src/commands/config.ts b/src/commands/config.tsindex a13db21e91..8f3a65d5ef 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -1445,8 +1445,8 @@ export async function runConfig(engine: BrainEngine, args: string[]) {// set that already persisted.if (key === 'search.mode') {try {- const { runModeSwitchUx } = await import('../core/search/mode-switch-ux.ts');- const { isSearchMode } = await import('../core/search/mode.ts');+ const [{ runModeSwitchUx }, { isSearchMode }] = await Promise.all([import('../core/search/mode-switch-ux.ts'), import('../core/search/mode.ts')]);+ if (isSearchMode(value)) await engine.setConfig('search.mode_source', 'operator');await runModeSwitchUx({oldMode: oldSearchMode && isSearchMode(oldSearchMode) ? oldSearchMode : null,newMode: value,diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.tsindex 6303c12c10..147e0f97e2 100644--- a/src/commands/doctor/checks/search-eval.ts+++ b/src/commands/doctor/checks/search-eval.ts@@ -27,7 +27,7 @@ export async function checkSearchMode(engine: BrainEngine): Promise<Check> {const overrides = await engine.listConfigKeys('search.');// Exclude search.mode itself + the upgrade-notice state key from the// override roster — they aren't knobs.- const overrideKeys = overrides.filter(k => k !== 'search.mode' && k !== 'search.mode_upgrade_notice_shown');+ const overrideKeys = overrides.filter(k => k !== 'search.mode' && k !== 'search.mode_upgrade_notice_shown' && k !== 'search.mode_source');const { loadSearchModeConfig, resolveSearchMode } = await import('../../../core/search/mode.ts');const loaded = await loadSearchModeConfig(engine);diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.tsindex cfcb66166f..7a6082837b 100644--- a/src/commands/init-first-run.ts+++ b/src/commands/init-first-run.ts@@ -20,10 +20,11 @@ import type { BrainEngine } from '../core/engine.ts';import { resolveGbrainBin } from '../core/gbrain-bin.ts';import { configReadiness, embeddingEnablement, harnessWiringEntry } from '../core/readiness.ts';import type { SearchMode } from '../core/search/mode.ts';+import { costMatrixSentence } from '../core/search/mode-advice.ts';import type { McpSurface } from '../mcp/surface.ts';export interface InitFirstRunInputs {- /** The search mode init applied and why (from the install-time picker). */+ /** The search mode the install-time picker applied and why; absent when `--search-mode` recorded the operator's choice. */searchMode?: { mode: SearchMode; reason: string };/** The config init saved; harness wiring is read from its config-plane readiness. */config?: GBrainConfig | null;@@ -35,15 +36,11 @@ export interface InitFirstRunInputs {surface?: McpSurface;}-const SEARCH_MODE_COST =- 'Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): ' +- 'conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.';-function searchModeDecision(applied: { mode: SearchMode; reason: string }): Decision {const modes: SearchMode[] = ['conservative', 'balanced', 'tokenmax'];return {id: 'search_mode',- question: `Which search mode should this brain use? ${SEARCH_MODE_COST}`,+ question: `Which search mode should this brain use? ${costMatrixSentence()}`,options: modes.map(m => ({ id: m, label: m === applied.mode ? `${m} (applied)` : m, argv: ['gbrain', 'config', 'set', 'search.mode', m] })),default: applied.mode,default_reason: applied.reason,diff --git a/src/commands/init-mode-picker.ts b/src/commands/init-mode-picker.tsindex 47f774d33b..6f21f0c0a8 100644--- a/src/commands/init-mode-picker.ts+++ b/src/commands/init-mode-picker.ts@@ -1,21 +1,27 @@/**- * v0.32.3 search-lite install-time mode picker.+ * Install-time search-mode picker.** Runs as a phase inside `gbrain init` AFTER `engine.initSchema()` so DB* config writes work [CDX-7]. Idempotent: if `search.mode` is already set* (re-init / second run), the picker is skipped entirely.** TTY flow shows the menu. Non-TTY (CI, scripted init, --mcp-only) applies- * the auto-recommendation, prints the cost matrix + an [AGENT] directive to+ * the recommendation, prints the cost matrix + an [AGENT] directive to* confirm with the operator, and points at `gbrain config set search.mode`.* The mode picker NEVER blocks an init run — readLineSafe caps at 60s and* falls back to the recommendation on timeout / EOF.*- * Smart auto-suggestion: reads models.tier.subagent / models.default /- * expansion-capable key presence (Anthropic/OpenAI/Google) + brain size hint- * to RECOMMEND a mode. The recommendation is informational only — the user- * picks. This is the "agents perfectly tune for user needs" piece at- * install time.+ * `gbrain init --search-mode <mode>` records an operator's choice instead:+ * no recommendation, no first-run `search_mode` ask, `search.mode_source:+ * operator`. On a brain whose mode is already set to something else it+ * refuses unless `--force`. Picker choices record `search.mode_source: auto`.+ *+ * The recommendation reads the configured model tiers, whether a chat key+ * exists (Anthropic / OpenAI / Google) and whether the reranker the+ * recommended mode would use is ready (rerankerReadiness, not a key name),+ * both through mergedProviderEnv so a key saved in ~/.gbrain/config.json+ * counts. Its copy (reasons, banner, matrix) lives in+ * src/core/search/mode-advice.ts.*/import type { BrainEngine } from '../core/engine.ts';@@ -23,153 +29,123 @@ import { readLineSafe } from './init.ts';import {SEARCH_MODES,SEARCH_MODE_KEY,- DEFAULT_SEARCH_MODE,isSearchMode,+ loadSearchModeConfig,+ resolveSearchMode,type SearchMode,} from '../core/search/mode.ts';+import {+ MODE_REASONS,+ QUERY_EXPANSION_LINE,+ RECOMMENDED_SEARCH_MODE,+ SEARCH_MODE_SOURCE_KEY,+ agentBannerLines,+ costMatrixLines,+ type SearchModeSource,+} from '../core/search/mode-advice.ts';+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';+import { mergedProviderEnv } from '../core/ai/provider-env.ts';+import { rerankerReadiness } from '../core/ai/reranker-readiness.ts';/**- * The full set of inputs that can shape the auto-suggestion. Caller passes- * what it knows (model defaults, API key presence, etc.); function falls- * back to environment / config for anything not provided.+ * The inputs that shape the recommendation. Undefined means unknown; the+ * no-keys branch fires only when both key inputs are known to be false.*/export interface ModePickerInputs {- /** Configured subagent tier model id (e.g. 'anthropic:claude-haiku-4-5'). */+ /** Configured subagent tier model id (e.g. 'anthropic:claude-haiku-5-5'). */subagentModel?: string | null;/** Configured default model id. */defaultModel?: string | null;- /** True iff an expansion-capable API key (Anthropic / OpenAI / Google) is- * configured. LLM query expansion routes through the gateway's chat lane,- * not the embedding lane — an OpenAI-only gate wrongly told Anthropic-keyed- * installs "no LLM expansion possible". */- hasExpansionKey?: boolean;+ /** A chat key (Anthropic / OpenAI / Google) is configured, in the environment or the config file. */+ hasChatKey?: boolean;+ /** The reranker the recommended mode would use is ready (readiness, not a key name). */+ hasRerankKey?: boolean;/** Approximate page count of the brain (after initSchema, before bulk import). */pageCount?: number;}/**- * Derive a smart recommendation from the inputs. Pure function so it's- * trivially testable.- *- * Heuristic (default-tokenmax bias — preserve the v0.31.x power-user- * shape per the v0.32.3 install-picker directive):- * - Opus / Frontier model OR Sonnet / unknown → tokenmax (max-quality default)- * - Haiku subagent → conservative (cost-sensitive setups)- * - No expansion-capable key (Anthropic/OpenAI/Google) → conservative- * (LLM expansion cannot run anyway, so tight budget makes more sense)- *- * Rationale: the previous "default to balanced unless Opus detected" logic- * silently downgraded users who were running Sonnet-tier work and expected- * the v0.31.x default (expand=true, limit=20) to carry forward. Tokenmax- * is the closest mode bundle to that prior default. Operators who want- * something tighter pick conservative or balanced explicitly.+ * The recommendation. Pure.+ * - Haiku subagent → conservative (a small-context model).+ * - No chat key and no ready reranker → conservative.+ * - A ready reranker without a chat key → balanced.+ * - Opus, or anything else → tokenmax (RECOMMENDED_SEARCH_MODE).*/export function recommendModeFor(inputs: ModePickerInputs): { mode: SearchMode; reason: string } {- const haiku = /haiku/i.test(inputs.subagentModel ?? '');- if (haiku) {- return {- mode: 'conservative',- reason: 'Haiku subagent tier detected — tight 4K budget keeps per-call cost down.',- };- }- if (inputs.hasExpansionKey === false) {- return {- mode: 'conservative',- reason: 'No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled.',- };- }+ if (/haiku/i.test(inputs.subagentModel ?? '')) return { mode: 'conservative', reason: MODE_REASONS.haiku };+ if (inputs.hasChatKey === false && inputs.hasRerankKey === false) return { mode: 'conservative', reason: MODE_REASONS.noKeys };+ if (inputs.hasChatKey === false && inputs.hasRerankKey === true) return { mode: 'balanced', reason: MODE_REASONS.rerankOnly };const opus = /opus/i.test(inputs.defaultModel ?? '') || /opus/i.test(inputs.subagentModel ?? '');- if (opus) {- return {- mode: 'tokenmax',- reason: 'Opus-class model detected — quality ceiling worth the token cost.',- };- }- return {- mode: 'tokenmax',- reason: 'Preserves the v0.31.x default retrieval shape (expand=on, generous result set). Pick conservative or balanced if cost-sensitive.',- };+ if (opus) return { mode: RECOMMENDED_SEARCH_MODE, reason: MODE_REASONS.opus };+ return { mode: RECOMMENDED_SEARCH_MODE, reason: MODE_REASONS.default };}+/** Chat keys the recommendation counts, after mergedProviderEnv folds config-file keys and the GEMINI alias. */+const CHAT_KEY_ENV = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY'] as const;+/**- * Resolve inputs from the engine + environment. Best-effort; any read- * failure falls through to defaults. Pure: never throws.+ * Resolve inputs from the engine, the config file and the environment.+ * Best-effort; any read failure falls through to "unknown". Never throws.*/-async function resolveInputs(engine: BrainEngine): Promise<ModePickerInputs> {+export async function resolveModePickerInputs(engine: BrainEngine): Promise<ModePickerInputs> {const safeGet = async (k: string): Promise<string | null> => {try { return await engine.getConfig(k); } catch { return null; }};-- const [subagentModel, defaultModel] = await Promise.all([- safeGet('models.tier.subagent'),- safeGet('models.default'),- ]);+ const [subagentModel, defaultModel] = await Promise.all([safeGet('models.tier.subagent'), safeGet('models.default')]);let pageCount = 0;+ try { pageCount = (await engine.getStats()).page_count ?? 0; } catch { /* swallow */ }++ // One provider plane for both inputs: process env over the config file over+ // DB-plane keys (mergedProviderEnv over loadConfigWithEngine), the plane+ // rerankerReadinessForEngine uses when no gateway is configured. Not the+ // gateway's: init configures it from process env alone, which would miss a+ // key saved in ~/.gbrain/config.json.+ let env: Record<string, string> | null = null;+ let cfg: GBrainConfig | null = null;try {- const stats = await engine.getStats();- pageCount = stats.page_count ?? 0;- } catch { /* swallow */ }-- return {- subagentModel,- defaultModel,- hasExpansionKey: Boolean(- process.env.ANTHROPIC_API_KEY ||- process.env.OPENAI_API_KEY ||- process.env.GOOGLE_GENERATIVE_AI_API_KEY ||- process.env.GEMINI_API_KEY, // gateway accepts GEMINI_API_KEY as a first-class alias- ),- pageCount,- };+ try { cfg = loadConfig(); } catch { cfg = null; }+ try { cfg = await loadConfigWithEngine(engine, cfg); } catch { /* file plane alone */ }+ env = mergedProviderEnv(cfg, process.env);+ } catch { env = null; }+ const hasChatKey = env ? CHAT_KEY_ENV.some(name => !!env![name]) : undefined;++ let hasRerankKey: boolean | undefined;+ try {+ const overrides = (await loadSearchModeConfig(engine)).overrides;+ const model = resolveSearchMode({ mode: RECOMMENDED_SEARCH_MODE, overrides }).reranker_model;+ hasRerankKey = env ? rerankerReadiness(model, env, { baseUrlOverrides: cfg?.provider_base_urls ?? null }).ready : undefined;+ } catch { hasRerankKey = undefined; }++ return { subagentModel, defaultModel, hasChatKey, hasRerankKey, pageCount };}const MENU_TEXT = `Search mode preference──────────────────────-Three named modes. Cost depends on BOTH the mode AND your downstream model-— the corner-to-corner spread is 25x. Pick the pairing intentionally.+Three named modes. Cost depends on BOTH the mode AND your downstream model.+Pick the pairing intentionally.-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 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):-- Haiku 4.5 Sonnet 4.6 Opus 4.7- ($1/M input) ($3/M input) ($5/M input)- conservative $40/mo $120/mo $200/mo- balanced $100/mo $300/mo $500/mo- tokenmax $200/mo $600/mo $1,000/mo--(scales linearly — multiply by 10 for 100K/mo, divide by 10 for 1K/mo)+${costMatrixLines(' ').join('\n')}-Natural pairings span ~4x (cheap/cheap → frontier/frontier). Mismatches-(tokenmax+Haiku, conservative+Opus) waste capacity in different-directions. Downstream provider prompt caching may discount input charges;-it does not skip retrieval or downstream generation.+GBrain's semantic result caching is temporarily disabled; budget for fresh retrieval.+Downstream provider prompt caching may discount input charges; it does not skip+retrieval or downstream generation.- 1) conservative 4K-token cap, 10 results by default.+ 1) conservative 4K-token cap, 10 results by default, no reranker.Best for: Haiku subagents, cost-sensitive agents,high-volume search loops, MCP servers w/ many users.- 2) balanced 12K-token cap, 25 results by default.- Best for: Sonnet-tier work, mixed workloads.- (The middle path most users land on.)+ 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.- Best for: Opus/frontier models, broad retrieval,- low-volume high-stakes work.+ 3) tokenmax no token cap, 50 results by default, reranked,+ query expansion on by default.+ Best for: the widest retrieval, low-volume high-stakes work.-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.+${QUERY_EXPANSION_LINE}+Actual expansion needs configured embedding and expansion providers; cloud+expansion sends the query to the configured provider.You can change this any time with: gbrain config set search.mode <mode>Per-knob tuning + recommendation engine ships at: gbrain search tune@@ -190,101 +166,99 @@ export function parseModeInput(raw: string): SearchMode | null {return null;}+export interface SearchModeChoice {+ /** `gbrain init --search-mode <mode>`: the operator's choice. */+ explicit?: SearchMode;+ /** `gbrain init --force`: lets --search-mode replace an existing brain's mode. */+ force?: boolean;+ /** How init refuses (prints, exits); the picker throws when absent. */+ refuse?: (message: string) => never;+}++/** Parse `--search-mode` from init's argv; an invalid value goes to `fail`. */+export function searchModeChoiceFromArgs(args: string[], fail: (message: string, jsonOutput: boolean) => never): SearchModeChoice {+ const json = args.includes('--json');+ const i = args.indexOf('--search-mode');+ if (i === -1) return {};+ const value = (args[i + 1] ?? '').trim().toLowerCase();+ if (!isSearchMode(value)) fail(`gbrain init: --search-mode must be one of ${SEARCH_MODES.join(', ')} (got: ${args[i + 1] ?? ''})`, json);+ return { explicit: value as SearchMode, force: args.includes('--force'), refuse: message => fail(message, json) };+}++async function persistMode(engine: BrainEngine, mode: SearchMode, source: SearchModeSource): Promise<void> {+ await engine.setConfig(SEARCH_MODE_KEY, mode);+ await engine.setConfig(SEARCH_MODE_SOURCE_KEY, source);+}+/*** Run the picker. Returns the resolved mode.** Idempotent: if `search.mode` is already set, the picker is skipped- * (returns the existing value without prompting). This makes re-init- * safe and lets the upgrade flow set the mode programmatically before- * the picker fires.+ * (returns the existing value without prompting), unless `force`. An+ * explicit choice is recorded as the operator's and never calls onDecision,+ * so init's first-run bundle carries no `search_mode` ask.*/export async function runModePicker(engine: BrainEngine,- opts: { jsonOutput?: boolean; force?: boolean; onDecision?: (d: { mode: SearchMode; reason: string }) => void } = {},+ opts: SearchModeChoice & { jsonOutput?: boolean; onDecision?: (d: { mode: SearchMode; reason: string }) => void } = {},): Promise<SearchMode> {- // Idempotent: don't re-prompt if already chosen, unless --force.- if (!opts.force) {- try {- const existing = await engine.getConfig(SEARCH_MODE_KEY);- if (existing && isSearchMode(existing)) {- return existing as SearchMode;- }- } catch { /* fall through to picker */ }+ let existing: SearchMode | null = null;+ try {+ const raw = await engine.getConfig(SEARCH_MODE_KEY);+ if (raw && isSearchMode(raw)) existing = raw;+ } catch { /* fall through to picker */ }++ if (opts.explicit) {+ if (existing && existing !== opts.explicit && !opts.force) {+ const message = `This brain already has search.mode ${existing}; gbrain init --search-mode does not change an existing brain's mode. ` ++ `Run \`gbrain config set search.mode ${opts.explicit}\`, or re-run gbrain init with --force.`;+ if (opts.refuse) opts.refuse(message);+ throw new Error(message);+ }+ await persistMode(engine, opts.explicit, 'operator');+ if (opts.jsonOutput) {+ console.log(JSON.stringify({ phase: 'search_mode_picker', mode: opts.explicit, reason: 'Chosen with gbrain init --search-mode.', auto: false, source: 'operator' }));+ } else {+ console.log(`Search mode set to: ${opts.explicit} (chosen with --search-mode)`);+ }+ return opts.explicit;}- const inputs = await resolveInputs(engine);- const rec = recommendModeFor(inputs);+ if (existing && !opts.force) return existing;++ const rec = recommendModeFor(await resolveModePickerInputs(engine));opts.onDecision?.({ mode: rec.mode, reason: rec.reason });// JSON mode (used by --json init) — apply the recommendation silently// and emit a structured event. No interactive prompt.if (opts.jsonOutput) {- try { await engine.setConfig(SEARCH_MODE_KEY, rec.mode); } catch { /* swallow */ }- console.log(JSON.stringify({- phase: 'search_mode_picker',- mode: rec.mode,- reason: rec.reason,- auto: true,- }));+ try { await persistMode(engine, rec.mode, 'auto'); } catch { /* swallow */ }+ console.log(JSON.stringify({ phase: 'search_mode_picker', mode: rec.mode, reason: rec.reason, auto: true, source: 'auto' }));return rec.mode;}- // Non-TTY (agent-driven install, CI, scripted init): print the FULL matrix- // and emit an explicit [AGENT] directive. The previous version printed- // 2 stderr lines that agents typically miss / don't relay to the human.- // Now: the agent sees the same matrix the human-TTY picker shows, plus- // a directive saying "show this to your operator and confirm before- // moving on." The applied default is the recommendation above — the- // banner interpolates it (a static "preserves the v0.31.x shape" line- // used to claim tokenmax semantics even when conservative was applied).+ // Non-TTY (agent-driven install, CI, scripted init): the full matrix plus+ // an explicit [AGENT] directive to relay it and confirm with the operator.if (!process.stdin.isTTY) {- try { await engine.setConfig(SEARCH_MODE_KEY, rec.mode); } catch { /* swallow */ }- console.log('');- console.log('═══════════════════════════════════════════════════════════════');- console.log(`[gbrain] search mode tentatively set to: ${rec.mode}`);- console.log(`[gbrain] Reason: ${rec.reason}`);- console.log('═══════════════════════════════════════════════════════════════');- console.log('');- console.log('[AGENT] Before continuing, SHOW this matrix to your operator and');- console.log(`[AGENT] ask which mode they want. The default above (${rec.mode}) was`);- console.log('[AGENT] auto-selected from the Reason line. Run `gbrain config set');- console.log('[AGENT] search.mode <conservative|balanced|tokenmax>` if the operator');- console.log('[AGENT] picks differently. See INSTALL_FOR_AGENTS.md Step 3.5 for the');- console.log('[AGENT] full protocol.');- console.log('');- console.log('Per-query cost @ 10K queries/mo (search payload only, no cache savings):');- console.log('');- console.log(' Haiku 4.5 Sonnet 4.6 Opus 4.7');- console.log(' ($1/M input) ($3/M input) ($5/M input)');- console.log(' conservative $40/mo $120/mo $200/mo');- console.log(' balanced $100/mo $300/mo $500/mo');- console.log(' tokenmax $200/mo $600/mo $1,000/mo');- 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 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>');- console.log('To see what is running: gbrain search modes');- console.log('');+ try { await persistMode(engine, rec.mode, 'auto'); } catch { /* swallow */ }+ for (const line of agentBannerLines(rec.mode, rec.reason)) console.log(line);return rec.mode;}- // Interactive TTY: menu + readLineSafe.+ // Interactive TTY: menu + readLineSafe. A typed choice other than the+ // recommendation is the operator's; Enter or a timeout keeps the recommendation.console.log(MENU_TEXT);console.log(` Recommended: ${rec.mode} (${rec.reason})`);console.log('');- const raw = await readLineSafe(`Mode [${rec.mode}]: `, rec.mode, 60_000);- const picked = parseModeInput(raw) ?? rec.mode;+ const typed = parseModeInput(await readLineSafe(`Mode [${rec.mode}]: `, rec.mode, 60_000));+ const picked = typed ?? rec.mode;try {- await engine.setConfig(SEARCH_MODE_KEY, picked);+ await persistMode(engine, picked, typed && typed !== rec.mode ? 'operator' : 'auto');} catch (err) {// Worst case: config write fails. Mode resolution falls back to balanced- // at search-time anyway, so we don't block init. Emit the failure to- // stderr so the operator sees it.+ // at search-time anyway, so we don't block init.console.error(`[gbrain] WARN: failed to persist search.mode (${(err as Error).message ?? 'unknown'}). Defaulting to ${picked} at search-time.`);}diff --git a/src/commands/init.ts b/src/commands/init.tsindex 35ce79ea73..1850a55a34 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -47,6 +47,7 @@ async function runInitBranches(args: string[]) {validateInitFlags(args);registrationSurface = (await import('../mcp/surface.ts')).parseSurfaceFlag(args) ?? undefined;+ searchModeChoice = (await import('./init-mode-picker.ts')).searchModeChoiceFromArgs(args, failInitFlag);const isSupabase = args.includes('--supabase');const isPGLite = args.includes('--pglite');@@ -260,6 +261,7 @@ const INIT_VALUE_FLAGS = new Set(['--oauth-client-id','--oauth-client-secret','--surface',+ '--search-mode',]);function validateInitFlags(args: string[]) {@@ -1268,7 +1270,7 @@ export async function initPGLite(opts: {// Non-TTY auto-selects; --json emits a structured event.const { runModePicker } = await import('./init-mode-picker.ts');let searchMode: { mode: SearchModeName; reason: string } | undefined;- await runModePicker(engine, { jsonOutput: opts.jsonOutput, onDecision: d => { searchMode = d; } });+ await runModePicker(engine, { jsonOutput: opts.jsonOutput, ...searchModeChoice, onDecision: d => { searchMode = d; } });const stats = await engine.getStats();@@ -1320,6 +1322,7 @@ const INIT_EMBEDDING_HINT = 'Pick an embedding model whose dimensions match (`gb* "More:" footer so they never compete with the primary action.*/let registrationSurface: McpSurface | undefined;+let searchModeChoice: import('./init-mode-picker.ts').SearchModeChoice = {};function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boolean } = {}): void {const register = harnessRegistrationCommand(registrationSurface);console.log('');@@ -1601,7 +1604,7 @@ export async function initPostgresCore(opts: {// PGLite path above — runs AFTER initSchema, idempotent on re-init.const { runModePicker: runPostgresModePicker } = await import('./init-mode-picker.ts');let searchMode: { mode: SearchModeName; reason: string } | undefined;- await runPostgresModePicker(engine, { jsonOutput: opts.jsonOutput, onDecision: d => { searchMode = d; } });+ await runPostgresModePicker(engine, { jsonOutput: opts.jsonOutput, ...searchModeChoice, onDecision: d => { searchMode = d; } });const stats = await engine.getStats();@@ -1856,6 +1859,7 @@ OPTIONSDefault subagent driver (v0.27+)--no-embedding Defer embedding setup (skips the embedding-key check)--surface <verbs|starter|full> Tool surface the printed harness registration pins (default full)+ --search-mode <conservative|balanced|tokenmax> Record the operator's search mode (no first-run ask; an existing brain's mode needs --force)--skip-embed-check Skip the init-time embedding-key validation (config +live test-embed). Also via GBRAIN_INIT_SKIP_EMBED_CHECK=1diff --git a/src/commands/search.ts b/src/commands/search.tsindex e137529d1d..2447fabc32 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -149,7 +149,7 @@ async function runModesSubcommand(engine: BrainEngine, args: string[]): Promise<process.exit(1);}const overrides = await engine.listConfigKeys('search.');- const toRemove = overrides.filter((k) => k !== SEARCH_MODE_KEY && k !== 'search.mode_upgrade_notice_shown');+ const toRemove = overrides.filter((k) => k !== SEARCH_MODE_KEY && k !== 'search.mode_upgrade_notice_shown' && k !== 'search.mode_source');if (toRemove.length === 0) {console.log('No search.* overrides set. Mode bundle is the only voice.');return;diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex a83c740c45..8376b26501 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -541,17 +541,16 @@ function saveUpgradeState(oldVersion: string, newVersion: string) {* installs do.*//**- * v0.32.3 search-lite mode banner, moved out of runPostUpgrade unchanged.+ * The search-mode banner for a brain that never chose a mode (copy: core/search/mode-advice.ts).*/-async function printSearchModeUpgradeBanner(engine: BrainEngine): Promise<void> {+export async function printSearchModeUpgradeBanner(engine: BrainEngine): Promise<void> {// One-shot: fires at most once per install (state persisted via `search.mode_upgrade_notice_shown`).- // Reframes from "behavior is regressing" to "named modes available" per [CDX-1+2+3]: the production- // query op still defaults expand=true and limit=20.+ // A brain with no search.mode resolves to the default (balanced); the banner says so and relays the matrix.try {const shown = await engine.getConfig('search.mode_upgrade_notice_shown');const existingMode = await engine.getConfig('search.mode');if (shown !== 'true' && !existingMode) {- printSearchModeBanner();+ await printSearchModeBanner();await engine.setConfig('search.mode_upgrade_notice_shown', 'true');}} catch {@@ -897,40 +896,10 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {if (json) await writeJsonDocument(JSON.stringify(report));}-/** The v0.32.3 one-shot search-mode banner post-upgrade prints (stdout; stderr under --json). */-function printSearchModeBanner(): void {- console.log('');- console.log('═══════════════════════════════════════════════════════════════');- console.log('[gbrain] v0.32.3 added named search modes (conservative/balanced/tokenmax).');- console.log('[gbrain] Your current behavior is unchanged — the `query` op still defaults');- console.log('[gbrain] expand=true and limit=20, same as v0.31.x.');- console.log('═══════════════════════════════════════════════════════════════');- console.log('');- console.log('[AGENT] Relay this matrix to your operator and ask which mode they want.');- console.log('[AGENT] Recommended default: tokenmax (preserves current retrieval shape).');- console.log('[AGENT] Run `gbrain config set search.mode <mode>` after they decide.');- console.log('');- console.log('Per-query cost @ 10K queries/mo (typical single-user volume):');- console.log('');- console.log(' Haiku 4.5 Sonnet 4.6 Opus 4.7');- console.log(' ($1/M) ($3/M) ($5/M)');- console.log(' conservative $40/mo $120/mo $200/mo');- console.log(' balanced $100/mo $300/mo $500/mo');- console.log(' tokenmax $200/mo $600/mo $1,000/mo');- console.log('');- console.log(' (scales linearly — multiply by 10 for 100K/mo)');- console.log(' 25x corner-to-corner spread. Natural diagonal pairings span ~4x.');- console.log('');- console.log('To pick:');- console.log(' gbrain search modes # see what is running');- console.log(' gbrain config set search.mode <conservative|balanced|tokenmax>');- console.log(' gbrain search tune # data-driven recommendations');- console.log('');- console.log('tokenmax bumps limit to 50 (current default is 20). To preserve');- console.log('your EXACT current shape:');- console.log(' gbrain config set search.mode tokenmax');- console.log(' gbrain config set search.searchLimit 20');- console.log('');+/** The one-shot search-mode banner post-upgrade prints for a brain with no search.mode (stdout; stderr under --json). */+async function printSearchModeBanner(): Promise<void> {+ const { upgradeBannerLines } = await import('../core/search/mode-advice.ts');+ for (const line of upgradeBannerLines()) console.log(line);}interface PostUpgradeReport {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cfd5281b93..fd86b1b220 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -469,6 +469,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ 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.' },+ { since: '0.60.178.0', text: '`gbrain init --search-mode <conservative|balanced|tokenmax>` records the operator\'s choice: no recommendation, no first-run `search_mode` question, and `search.mode_source: operator` (picker choices record `auto`, and `gbrain config set search.mode` records `operator`). On a brain that already has a different mode it refuses unless `--force`. Init now recommends `balanced` instead of `conservative` when a reranker is ready but no chat key exists, and provider keys saved in `~/.gbrain/config.json` count toward the recommendation. The install matrix now prices Haiku 5.5, Sonnet 5.5 and Opus 5.5 from gbrain\'s pricing table (about a 200x corner-to-corner spread), and switching modes no longer promises a cache refill while semantic result caching is off.' },];/** 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.tsindex 535bf49f53..3c180c8c6a 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -44,10 +44,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],- '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'],+ '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', '--search-mode', '--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', '--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'],+ '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', '--search-mode', '--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'],@@ -68,11 +68,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'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', '--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'],+ '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', '--search-mode', '--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'],@@ -90,7 +90,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--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', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -104,7 +104,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],+ 'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],@@ -132,7 +132,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex 32ff08c483..962e4b72a3 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1341,6 +1341,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// (commands/upgrade.ts, ops/image.ts, ops/search.ts, private-visibility.ts,// last-retrieved.ts).'search.mode_upgrade_notice_shown',+ 'search.mode_source','search.image_query.max_bytes','search.image_query.daily_budget_usd_per_client','search.image_query.remote_max_bytes',diff --git a/src/core/search/mode-advice.ts b/src/core/search/mode-advice.tsnew file mode 100644index 0000000000..076efa71d1--- /dev/null+++ b/src/core/search/mode-advice.ts@@ -0,0 +1,151 @@+/**+ * The one source of gbrain's search-mode recommendation and the copy that+ * states it: the install picker's reasons, menu and `[AGENT]` banner, init's+ * first-run `search_mode` decision, the post-upgrade banner, and the cost+ * matrix they all print. Prices come from the canonical chat-pricing table+ * (`src/core/model-pricing.ts`), so a price change there moves every surface.+ *+ * The matrix estimates the downstream model's input cost of reading the+ * retrieved payload: an assumed payload per query for each mode (at or under+ * that mode's token budget) times 10K queries a month times the model's input+ * rate. Embedding, reranking and query expansion are separate provider+ * charges and are not in it.+ */+import { agentBlock } from '../agent-markers.ts';+import { canonicalLookup } from '../model-pricing.ts';+import type { SearchMode } from './mode.ts';++/** Who chose `search.mode`: `auto` (the install picker's recommendation) or `operator` (an explicit choice). */+export const SEARCH_MODE_SOURCE_KEY = 'search.mode_source';+export type SearchModeSource = 'auto' | 'operator';++/** The mode gbrain recommends for a brain with a chat key when nothing argues for another. */+export const RECOMMENDED_SEARCH_MODE: SearchMode = 'tokenmax';++const MODES: readonly SearchMode[] = ['conservative', 'balanced', 'tokenmax'];++/** The newest model of each Anthropic family the matrix prices, cheapest first. */+export const COST_MATRIX_MODELS: ReadonlyArray<{ label: string; id: string }> = [+ { label: 'Haiku 5.5', id: 'anthropic:claude-haiku-5-5' },+ { label: 'Sonnet 5.5', id: 'anthropic:claude-sonnet-5-5' },+ { label: 'Opus 5.5', id: 'anthropic:claude-opus-5-5' },+];++/** Assumed retrieved payload per query, in tokens, for each mode. */+export const COST_MATRIX_PAYLOAD_TOKENS: Readonly<Record<SearchMode, number>> = { conservative: 4_000, balanced: 10_000, tokenmax: 20_000 };+export const COST_MATRIX_QUERIES_PER_MONTH = 10_000;++function inputRate(modelId: string): number {+ const price = canonicalLookup(modelId);+ if (!price) throw new Error(`mode-advice: no canonical price for ${modelId}`);+ return price.input;+}++/** Estimated monthly downstream input cost (USD) of `mode`'s payload read by `modelId`. */+export function monthlyPayloadCost(mode: SearchMode, modelId: string): number {+ return (COST_MATRIX_PAYLOAD_TOKENS[mode] * COST_MATRIX_QUERIES_PER_MONTH / 1_000_000) * inputRate(modelId);+}++function usd(n: number): string {+ if (n < 10) return `$${n.toFixed(2).replace(/\.00$/, '')}`;+ return `$${Math.round(n).toLocaleString('en-US')}`;+}++/** Cheapest cell to dearest cell, rounded. */+export function costMatrixSpread(): number {+ const cells = MODES.flatMap(m => COST_MATRIX_MODELS.map(x => monthlyPayloadCost(m, x.id)));+ return Math.round(Math.max(...cells) / Math.min(...cells));+}++const tokensK = (m: SearchMode) => `${COST_MATRIX_PAYLOAD_TOKENS[m] / 1000}K`;++/** The matrix as aligned text lines (no trailing blank line). */+export function costMatrixLines(indent = ' '): string[] {+ const col = (s: string) => s.padEnd(14);+ const lines = [+ `Estimated downstream input cost of the retrieved payload @ ${COST_MATRIX_QUERIES_PER_MONTH / 1000}K queries/mo:`,+ '',+ `${indent}${''.padEnd(16)}${COST_MATRIX_MODELS.map(x => col(x.label)).join('')}`.trimEnd(),+ `${indent}${''.padEnd(16)}${COST_MATRIX_MODELS.map(x => col(`(${usd(inputRate(x.id))}/M in)`)).join('')}`.trimEnd(),+ ...MODES.map(m => `${indent}${m.padEnd(16)}${COST_MATRIX_MODELS.map(x => col(`${usd(monthlyPayloadCost(m, x.id))}/mo`)).join('')}`.trimEnd()),+ '',+ `${indent}Assumed payload per query: ${MODES.map(m => `${m} ${tokensK(m)}`).join(', ')} tokens.`,+ `${indent}Scales linearly: x10 for 100K queries/mo, /10 for 1K. ${costMatrixSpread()}x corner-to-corner spread.`,+ `${indent}Embedding, reranking and query expansion are separate provider charges.`,+ ];+ return lines;+}++/** The matrix in one sentence (init's first-run decision). */+export function costMatrixSentence(): string {+ const labels = COST_MATRIX_MODELS.map(x => x.label).join(' / ');+ const cells = MODES.map(m => `${m} ${COST_MATRIX_MODELS.map(x => usd(monthlyPayloadCost(m, x.id))).join(' / ')}`).join(', ');+ return `Estimated downstream input cost of the retrieved payload at ${COST_MATRIX_QUERIES_PER_MONTH / 1000}K queries/month (${labels}): ${cells} per month.`;+}++/** 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 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. */+export const MODE_REASONS = {+ haiku: 'Haiku subagent tier detected — conservative keeps the payload at 4K tokens for a small-context model.',+ noKeys: 'No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced\'s reranker could not run.',+ rerankOnly: 'A reranker is ready but there is no chat key — balanced reranks with it; nothing in balanced needs a chat model.',+ opus: 'Opus-class model detected — quality ceiling worth the token cost.',+ default: 'A chat key is configured — tokenmax gives the widest retrieval; pick conservative or balanced if cost-sensitive.',+} as const;++/** The non-TTY banner the picker prints after applying `applied`: an agent block asking the operator, then the matrix. */+export function agentBannerLines(applied: SearchMode, reason: string): string[] {+ return [+ '',+ '═══════════════════════════════════════════════════════════════',+ `[gbrain] search mode tentatively set to: ${applied}`,+ `[gbrain] Reason: ${reason}`,+ '═══════════════════════════════════════════════════════════════',+ '',+ ...agentBlock({+ ask: 'Which search mode should this brain use: conservative, balanced or tokenmax?',+ why: `The default above (${applied}) was auto-selected from the Reason line. Before continuing, show this matrix to your operator and ask which mode they want; INSTALL_FOR_AGENTS.md Step 3.5 has the full protocol.`,+ next: 'ask_user: if the operator picks differently, run `gbrain config set search.mode <conservative|balanced|tokenmax>` (or `gbrain init --search-mode <mode>` at install time).',+ verify: 'gbrain search modes',+ }).trimEnd().split('\n'),+ '',+ ...costMatrixLines(' '),+ ` ${QUERY_EXPANSION_LINE}`,+ '',+ 'To change later: gbrain config set search.mode <mode>',+ 'To see what is running: gbrain search modes',+ '',+ ];+}++/** The post-upgrade banner for a brain that has no `search.mode` (it runs the default, balanced). */+export function upgradeBannerLines(): string[] {+ return [+ '',+ '═══════════════════════════════════════════════════════════════',+ '[gbrain] This brain has no search.mode set, so it runs balanced',+ '[gbrain] (named modes: conservative / balanced / tokenmax).',+ '═══════════════════════════════════════════════════════════════',+ '',+ ...agentBlock({+ ask: 'Which search mode should this brain use: conservative, balanced or tokenmax?',+ why: `Relay this matrix to your operator and ask which mode they want. Recommended for a brain with a chat key: ${RECOMMENDED_SEARCH_MODE}.`,+ next: 'ask_user: run `gbrain config set search.mode <mode>` after they decide.',+ verify: 'gbrain search modes',+ }).trimEnd().split('\n'),+ '',+ ...costMatrixLines(' '),+ ` ${QUERY_EXPANSION_LINE}`,+ '',+ 'To pick:',+ ' gbrain search modes # see what is running',+ ' gbrain config set search.mode <conservative|balanced|tokenmax>',+ ' gbrain search tune # data-driven recommendations',+ '',+ ];+}diff --git a/src/core/search/mode-switch-ux.ts b/src/core/search/mode-switch-ux.tsindex e2ac40a83c..2b0b0f757b 100644--- a/src/core/search/mode-switch-ux.ts+++ b/src/core/search/mode-switch-ux.ts@@ -134,15 +134,19 @@ export function summarizeTransition(};}- // Narrowing: dropping a feature (e.g. balanced → conservative drops- // reranker + expansion). Cache will refill within TTL; no backfill.+ // 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.if (oldMode && narrowness(newMode) < narrowness(oldMode)) {return {kind: 'narrowing',reindex_required: false,callout_lines: [`Switched to ${newMode}. Some features dropped from prior mode.`,- `Cache refills within TTL (default 1h). No backfill required.`,+ ...(oldMode === 'tokenmax'+ ? ['New chunks embed with title context instead of per-chunk synopses; existing vectors keep serving until they are replaced.']+ : []),+ `The next search uses ${newMode} (semantic result caching is disabled). No backfill required.`,],};}@@ -155,7 +159,7 @@ export function summarizeTransition(`Switched to ${newMode}.`,oldMode? `Existing wrapped embeddings (if any) continue serving queries.`- : `First-time mode set. Cache will populate as queries run.`,+ : `First-time mode set; the next search uses it.`,],};}diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex e8a4aa69bd..26d54a52f8 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -19,6 +19,7 @@ import { REMOTE_PRIVATE_PAGES_KEY } from '../src/core/search/private-visibility.const DIRECTLY_READ_SINGLETONS = [SEARCH_MODE_KEY,'search.mode_upgrade_notice_shown', // commands/upgrade.ts+ 'search.mode_source', // search/mode-coaching.ts (who chose search.mode)'search.image_query.max_bytes', // ops/image.ts'search.image_query.daily_budget_usd_per_client', // ops/image.ts'search.image_query.remote_max_bytes', // ops/image.tsdiff --git a/test/fixtures/agent-contract/v1/journey/init-first-run.json b/test/fixtures/agent-contract/v1/journey/init-first-run.jsonindex 6473970075..19b1fe35a3 100644--- a/test/fixtures/agent-contract/v1/journey/init-first-run.json+++ b/test/fixtures/agent-contract/v1/journey/init-first-run.json@@ -33,7 +33,7 @@"decisions": [{"id": "search_mode",- "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "question": "Which search mode should this brain use? Estimated downstream input cost of the retrieved payload at 10K queries/month (Haiku 5.5 / Sonnet 5.5 / Opus 5.5): conservative $4 / $80 / $160, balanced $10 / $200 / $400, tokenmax $20 / $400 / $800 per month.","options": [{"id": "conservative",@@ -70,7 +70,7 @@}],"default": "conservative",- "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ "default_reason": "No chat key (Anthropic/OpenAI/Google) and no ready reranker — conservative keeps a tight 4K budget; balanced's reranker could not run."},{"id": "writeback",diff --git a/test/init-mode-picker.test.ts b/test/init-mode-picker.test.tsindex e18f86ebd8..0a4b5176e7 100644--- a/test/init-mode-picker.test.ts+++ b/test/init-mode-picker.test.ts@@ -1,21 +1,45 @@/**- * v0.32.3 search-lite install-time mode picker tests.+ * Install-time search-mode picker.*- * Pure-function coverage (recommendModeFor + parseModeInput) plus the- * idempotent runModePicker behavior. The interactive TTY branch is- * exercised indirectly via the non-TTY path here; full TTY simulation- * lives in the e2e suite (test/e2e/...).+ * The recommendation over every input combination (chat key yes/no, ready+ * reranker yes/no, Haiku / Opus / unknown model), the inputs resolved from+ * the environment and from a key saved only in ~/.gbrain/config.json, the+ * shared cost matrix and banners, `--search-mode` (operator choice,+ * refuse-or-force), `search.mode_source`, and the `--json` event. The TTY+ * menu branch needs a terminal and is not exercised here.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {- recommendModeFor,+ MODE_PICKER_MENU,parseModeInput,+ recommendModeFor,+ resolveModePickerInputs,runModePicker,+ searchModeChoiceFromArgs,} from '../src/commands/init-mode-picker.ts';+import {+ COST_MATRIX_MODELS,+ MODE_REASONS,+ agentBannerLines,+ costMatrixLines,+ costMatrixSentence,+ monthlyPayloadCost,+ upgradeBannerLines,+} from '../src/core/search/mode-advice.ts';+import { canonicalLookup } from '../src/core/model-pricing.ts';import { withEnv } from './helpers/with-env.ts';+const NO_KEYS = {+ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, GOOGLE_GENERATIVE_AI_API_KEY: undefined,+ GEMINI_API_KEY: undefined, VOYAGE_API_KEY: undefined, OPENROUTER_API_KEY: undefined,+};+let engine: PGLiteEngine;+let home: string;beforeAll(async () => {engine = new PGLiteEngine();@@ -28,239 +52,302 @@ afterAll(async () => {});beforeEach(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-mode-picker-'));await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'search.%' OR key LIKE 'models.%'`);});-describe('recommendModeFor — auto-suggestion heuristic', () => {- test('Opus default → tokenmax', () => {- const r = recommendModeFor({ defaultModel: 'anthropic:claude-opus-4-7' });- expect(r.mode).toBe('tokenmax');- expect(r.reason).toMatch(/Opus/);+/** Runs `fn` with no provider keys and a fresh GBRAIN_HOME, plus `env`. */+function inHome<T>(env: Record<string, string | undefined>, fn: () => Promise<T>): Promise<T> {+ return withEnv({ ...NO_KEYS, GBRAIN_HOME: home, ...env }, fn);+}++function writeConfigFile(fields: Record<string, string>): void {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...fields }));+}++async function captureLog(fn: () => Promise<unknown>): Promise<string[]> {+ const original = console.log;+ const lines: string[] = [];+ console.log = (msg?: unknown) => { lines.push(String(msg ?? '')); };+ try { await fn(); } finally { console.log = original; }+ return lines;+}++describe('recommendModeFor: every input combination', () => {+ const models = [+ { name: 'Haiku', subagentModel: 'anthropic:claude-haiku-5-5' },+ { name: 'Opus', defaultModel: 'anthropic:claude-opus-5-5' },+ { name: 'unknown', subagentModel: undefined },+ ] as const;+ const expected = (model: string, chat: boolean, rerank: boolean): string => {+ if (model === 'Haiku') return 'conservative';+ if (!chat && !rerank) return 'conservative';+ return chat ? 'tokenmax' : 'balanced';+ };+ for (const m of models) {+ for (const chat of [true, false]) {+ for (const rerank of [true, false]) {+ test(`${m.name} model, chat key ${chat ? 'yes' : 'no'}, reranker ${rerank ? 'ready' : 'not ready'} → ${expected(m.name, chat, rerank)}`, () => {+ const { name: _name, ...model } = m;+ const r = recommendModeFor({ ...model, hasChatKey: chat, hasRerankKey: rerank });+ expect(r.mode).toBe(expected(m.name, chat, rerank) as never);+ expect(r.reason.length).toBeGreaterThan(0);+ });+ }+ }+ }++ test('each branch names its reason', () => {+ expect(recommendModeFor({ subagentModel: 'anthropic:claude-haiku-5-5', hasChatKey: true }).reason).toBe(MODE_REASONS.haiku);+ expect(recommendModeFor({ hasChatKey: false, hasRerankKey: false }).reason).toBe(MODE_REASONS.noKeys);+ expect(recommendModeFor({ hasChatKey: false, hasRerankKey: true }).reason).toBe(MODE_REASONS.rerankOnly);+ expect(recommendModeFor({ defaultModel: 'anthropic:claude-opus-5-5', hasChatKey: true }).reason).toBe(MODE_REASONS.opus);+ expect(recommendModeFor({ hasChatKey: true, hasRerankKey: true }).reason).toBe(MODE_REASONS.default);});- test('Opus subagent → tokenmax', () => {- const r = recommendModeFor({ subagentModel: 'anthropic:claude-opus-4-7' });- expect(r.mode).toBe('tokenmax');+ test('unknown key state is not "no keys": empty inputs get the default', () => {+ expect(recommendModeFor({}).mode).toBe('tokenmax');});- test('Haiku subagent → conservative', () => {- const r = recommendModeFor({ subagentModel: 'anthropic:claude-haiku-4-5' });+ test('a Haiku subagent wins over an Opus default model', () => {+ const r = recommendModeFor({ defaultModel: 'anthropic:claude-opus-5-5', subagentModel: 'anthropic:claude-haiku-5-5', hasChatKey: true, hasRerankKey: true });expect(r.mode).toBe('conservative');- expect(r.reason).toMatch(/Haiku/);});+});- test('No expansion-capable key → conservative (LLM expansion cannot run)', () => {- const r = recommendModeFor({ hasExpansionKey: false });- expect(r.mode).toBe('conservative');- // Provider-neutral copy: expansion routes through the chat lane, so an- // Anthropic or Google key counts — the reason must not say "No OpenAI".- expect(r.reason).toMatch(/expansion-capable/i);- expect(r.reason).not.toMatch(/No OpenAI key/);+describe('resolveModePickerInputs: keys through mergedProviderEnv and reranker readiness', () => {+ test('no keys anywhere → no chat key, reranker not ready → conservative', async () => {+ await inHome({}, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs.hasChatKey).toBe(false);+ expect(inputs.hasRerankKey).toBe(false);+ expect(recommendModeFor(inputs).mode).toBe('conservative');+ });});- test('Sonnet / unknown → tokenmax (preserve-v0.31.x default)', () => {- const r = recommendModeFor({ subagentModel: 'anthropic:claude-sonnet-4-6', hasExpansionKey: true });- expect(r.mode).toBe('tokenmax');- expect(r.reason).toMatch(/v0\.31\.x|preserve/i);+ test('a Voyage key in the environment without a chat key → balanced', async () => {+ await inHome({ VOYAGE_API_KEY: 'pa-test-stub' }, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs).toMatchObject({ hasChatKey: false, hasRerankKey: true });+ expect(recommendModeFor(inputs)).toEqual({ mode: 'balanced', reason: MODE_REASONS.rerankOnly });+ });});- test('Empty inputs → tokenmax (preserve-v0.31.x default)', () => {- const r = recommendModeFor({});- expect(r.mode).toBe('tokenmax');+ test('a Voyage key saved only in ~/.gbrain/config.json counts', async () => {+ writeConfigFile({ voyage_api_key: 'pa-test-stub' });+ await inHome({}, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs).toMatchObject({ hasChatKey: false, hasRerankKey: true });+ expect(recommendModeFor(inputs).mode).toBe('balanced');+ });});+ test('a chat key saved only in ~/.gbrain/config.json counts', async () => {+ writeConfigFile({ anthropic_api_key: 'sk-ant-test-stub' });+ await inHome({}, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs.hasChatKey).toBe(true);+ expect(inputs.hasRerankKey).toBe(false);+ expect(recommendModeFor(inputs)).toEqual({ mode: 'tokenmax', reason: MODE_REASONS.default });+ });+ });- test('Haiku subagent wins over Opus default (cost-sensitive takes precedence)', () => {- // Reordered in the install-picker DX pass: Haiku check fires BEFORE Opus- // because a user running a Haiku subagent loop is signalling cost- // sensitivity. Tokenmax over Haiku would silently dump 50-chunk payloads- // into a model that struggles past 5-10 chunks. The Haiku floor wins.- const r = recommendModeFor({- defaultModel: 'anthropic:claude-opus-4-7',- subagentModel: 'anthropic:claude-haiku-4-5',- hasExpansionKey: true,+ test('GEMINI_API_KEY counts as a chat key', async () => {+ await inHome({ GEMINI_API_KEY: 'gm-test-stub' }, async () => {+ expect((await resolveModePickerInputs(engine)).hasChatKey).toBe(true);});- expect(r.mode).toBe('conservative');});-});-describe('MENU_TEXT cost-matrix anchors (must match CLAUDE.md + methodology doc)', () => {- test('25x corner-to-corner spread framing is named', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- // Updating these REQUIRES bumping CLAUDE.md ## Search Mode + the- // methodology doc + README in lockstep.- expect(MODE_PICKER_MENU).toContain('25x');- expect(MODE_PICKER_MENU).toContain('corner-to-corner');+ test('a configured reranker that cannot run is not counted ready because a Voyage key exists', async () => {+ await engine.setConfig('search.reranker.model', 'nonexistent-provider:model');+ await inHome({ VOYAGE_API_KEY: 'pa-test-stub' }, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs.hasRerankKey).toBe(false);+ expect(recommendModeFor(inputs).mode).toBe('conservative');+ });});- test('does not claim the semantic result cache saves money while it is disabled', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- // CLAUDE.md ## Search Mode: "Semantic result caching is temporarily- // disabled; budget for fresh retrieval on every query."- expect(MODE_PICKER_MENU).not.toContain('semantic cache is free');- expect(MODE_PICKER_MENU).toContain('semantic result caching is temporarily disabled');+ test('model tiers are read from the brain config', async () => {+ await engine.setConfig('models.tier.subagent', 'anthropic:claude-haiku-5-5');+ await inHome({ ANTHROPIC_API_KEY: 'sk-ant-test-stub' }, async () => {+ const inputs = await resolveModePickerInputs(engine);+ expect(inputs.subagentModel).toBe('anthropic:claude-haiku-5-5');+ expect(recommendModeFor(inputs).mode).toBe('conservative');+ });});+});- test('cost matrix lists every cell at the natural diagonal and corners', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- // Three anchor cells from the natural diagonal at 10K/mo volume. Scales- // linearly; multiplying by 10 gives the 100K/mo numbers the methodology- // doc + CLAUDE.md cite ("multiply by 10 for 100K/mo" prose anchor).- expect(MODE_PICKER_MENU).toContain('$40/mo'); // conservative + Haiku- expect(MODE_PICKER_MENU).toContain('$300/mo'); // balanced + Sonnet (default natural)- expect(MODE_PICKER_MENU).toContain('$1,000/mo'); // tokenmax + Opus+describe('cost matrix: newest models, priced from model-pricing', () => {+ test('prices every cell from the canonical pricing table', () => {+ for (const { id } of COST_MATRIX_MODELS) {+ const input = canonicalLookup(id)!.input;+ expect(monthlyPayloadCost('conservative', id)).toBeCloseTo(4_000 * 10_000 / 1e6 * input, 6);+ expect(monthlyPayloadCost('balanced', id)).toBeCloseTo(10_000 * 10_000 / 1e6 * input, 6);+ expect(monthlyPayloadCost('tokenmax', id)).toBeCloseTo(20_000 * 10_000 / 1e6 * input, 6);+ }});- test('volume frame is 10K queries/month with linear-scale callout', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- expect(MODE_PICKER_MENU).toContain('10K queries/mo');- expect(MODE_PICKER_MENU).toContain('scales linearly');+ test('names the newest Anthropic models, not retired ones', () => {+ const text = costMatrixLines().join('\n');+ for (const label of ['Haiku 5.5', 'Sonnet 5.5', 'Opus 5.5']) expect(text).toContain(label);+ for (const old of ['Haiku 4.5', 'Sonnet 4.6', 'Opus 4.7', '25x']) expect(text).not.toContain(old);+ expect(text).toContain('10K queries/mo');+ expect(text).toContain('Scales linearly');});- test('all three downstream model rates are explicit', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- expect(MODE_PICKER_MENU).toContain('Haiku 4.5');- expect(MODE_PICKER_MENU).toContain('Sonnet 4.6');- expect(MODE_PICKER_MENU).toContain('Opus 4.7');- expect(MODE_PICKER_MENU).toContain('$1/M');- expect(MODE_PICKER_MENU).toContain('$3/M');- expect(MODE_PICKER_MENU).toContain('$5/M');+ test('the menu, the [AGENT] banner and the upgrade banner print the same matrix', () => {+ const matrix = costMatrixLines(' ').slice(2, 7).map(l => l.trim());+ const surfaces = [MODE_PICKER_MENU, agentBannerLines('balanced', 'r').join('\n'), upgradeBannerLines().join('\n')];+ for (const surface of surfaces) for (const row of matrix) expect(surface).toContain(row);});- test('query-verb Haiku-expansion surcharge is named explicitly, not attributed to tokenmax', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- // Cross-line match — the surcharge phrase can wrap.- const flat = MODE_PICKER_MENU.replace(/\s+/g, ' ');- expect(flat).toContain('gbrain query adds ~$1.50 per 1K queries');- expect(MODE_PICKER_MENU).toContain('Haiku expansion call');- // `gbrain query` expands in every mode (#4601); the surcharge is not a tokenmax line item.- expect(flat).not.toContain('tokenmax adds');- expect(flat).toContain('--no-expand');+ test('INSTALL_FOR_AGENTS.md Step 3.5 carries the generated matrix verbatim', () => {+ const doc = readFileSync(join(import.meta.dir, '..', 'INSTALL_FOR_AGENTS.md'), 'utf8');+ expect(doc).toContain(costMatrixLines(' ').join('\n'));});- test('cache-hit discount framing is named', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');- expect(MODE_PICKER_MENU).toContain('cache');- // The numbers below are full-payload pre-cache; real loops see 50-80% discount.- expect(MODE_PICKER_MENU).toMatch(/50-80%|discount/);+ test('the first-run sentence carries the same cells', () => {+ const sentence = costMatrixSentence();+ expect(sentence).toContain('Haiku 5.5 / Sonnet 5.5 / Opus 5.5');+ expect(sentence).toContain(`balanced $10 / $200 / $400`);});- test('tune command is surfaced as the next step', async () => {- const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');+ 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 search` never expands');+ 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');});});-describe('parseModeInput — menu choice mapper', () => {- test('numeric 1/2/3 → conservative/balanced/tokenmax', () => {+describe('parseModeInput', () => {+ test('numeric 1/2/3 and names (case-insensitive)', () => {expect(parseModeInput('1')).toBe('conservative');expect(parseModeInput('2')).toBe('balanced');expect(parseModeInput('3')).toBe('tokenmax');- });-- test('mode names (case-insensitive)', () => {- expect(parseModeInput('conservative')).toBe('conservative');- expect(parseModeInput('CONSERVATIVE')).toBe('conservative');- expect(parseModeInput('TokenMax')).toBe('tokenmax');- expect(parseModeInput(' balanced ')).toBe('balanced');+ expect(parseModeInput(' TokenMax ')).toBe('tokenmax');});test('empty / unrecognized → null', () => {- expect(parseModeInput('')).toBeNull();- expect(parseModeInput(' ')).toBeNull();- expect(parseModeInput('foo')).toBeNull();- expect(parseModeInput('4')).toBeNull();- expect(parseModeInput('0')).toBeNull();+ for (const raw of ['', ' ', 'foo', '4', '0']) expect(parseModeInput(raw)).toBeNull();});});-describe('runModePicker non-TTY surfaces full matrix + [AGENT] directive', () => {- test('non-TTY output includes the cost matrix and the [AGENT] directive', async () => {- const originalLog = console.log;- const captured: string[] = [];- console.log = (msg: string) => { captured.push(String(msg)); };- try {- await runModePicker(engine);- } finally {- console.log = originalLog;- }- const out = captured.join('\n');- // Matrix corners + diagonal mid- expect(out).toContain('$40/mo');- expect(out).toContain('$300/mo');- expect(out).toContain('$1,000/mo');- // 25x spread framing- expect(out).toContain('25x corner-to-corner');- // Explicit agent directive — load-bearing for agent-platform install paths- expect(out).toContain('[AGENT]');- expect(out.toLowerCase()).toContain('show this matrix');- expect(out).toContain('INSTALL_FOR_AGENTS.md');+describe('runModePicker: non-TTY and --json', () => {+ test('non-TTY applies tokenmax for a keyed brain, records auto, prints the [AGENT] banner', async () => {+ await inHome({ ANTHROPIC_API_KEY: 'sk-ant-test-stub' }, async () => {+ let decision: { mode: string; reason: string } | undefined;+ const out = (await captureLog(() => runModePicker(engine, { onDecision: d => { decision = d; } }))).join('\n');+ expect(await engine.getConfig('search.mode')).toBe('tokenmax');+ expect(await engine.getConfig('search.mode_source')).toBe('auto');+ expect(decision).toEqual({ mode: 'tokenmax', reason: MODE_REASONS.default });+ expect(out).toContain('[gbrain] search mode tentatively set to: tokenmax');+ expect(out.toLowerCase()).toContain('show this matrix');+ expect(out).toContain('INSTALL_FOR_AGENTS.md');+ expect(out).toContain('gbrain init --search-mode <mode>');+ expect(out).toContain('Opus 5.5');+ });});-});-describe('runModePicker — non-TTY auto-select + idempotent', () => {- test('non-TTY auto-selects + writes config + emits operator hint', async () => {- // Bun test runs non-TTY by default.- const picked = await runModePicker(engine);- // Default model unset → balanced. Should write search.mode.- const stored = await engine.getConfig('search.mode');- expect(stored).toBe(picked);- expect(['conservative', 'balanced', 'tokenmax']).toContain(picked);+ test('non-TTY on a keyless brain applies conservative', async () => {+ await inHome({}, async () => {+ await captureLog(() => runModePicker(engine));+ expect(await engine.getConfig('search.mode')).toBe('conservative');+ expect(await engine.getConfig('search.mode_source')).toBe('auto');+ });+ });++ test('--json emits one structured event with auto: true and source auto', async () => {+ await inHome({ VOYAGE_API_KEY: 'pa-test-stub' }, async () => {+ const lines = await captureLog(() => runModePicker(engine, { jsonOutput: true }));+ const event = JSON.parse(lines.find(l => l.startsWith('{'))!);+ expect(event).toEqual({ phase: 'search_mode_picker', mode: 'balanced', reason: MODE_REASONS.rerankOnly, auto: true, source: 'auto' });+ expect(await engine.getConfig('search.mode')).toBe('balanced');+ });+ });++ test('idempotent: an existing mode is kept and nothing is recorded', async () => {+ await engine.setConfig('search.mode', 'tokenmax');+ await inHome({ ANTHROPIC_API_KEY: 'sk-ant-test-stub' }, async () => {+ let decided = false;+ expect(await runModePicker(engine, { onDecision: () => { decided = true; } })).toBe('tokenmax');+ expect(decided).toBe(false);+ expect(await engine.getConfig('search.mode')).toBe('tokenmax');+ expect(await engine.getConfig('search.mode_source')).toBeNull();+ });});- test('idempotent: second call returns existing mode without overwrite', async () => {+ test('--force re-runs the recommendation over an existing mode', async () => {await engine.setConfig('search.mode', 'tokenmax');- const picked = await runModePicker(engine);- expect(picked).toBe('tokenmax');- // No accidental overwrite.- const stored = await engine.getConfig('search.mode');- expect(stored).toBe('tokenmax');+ await inHome({ ANTHROPIC_API_KEY: 'sk-ant-test-stub' }, async () => {+ await engine.setConfig('search.mode', 'conservative');+ await captureLog(() => runModePicker(engine, { force: true }));+ expect(await engine.getConfig('search.mode')).toBe('tokenmax');+ expect(await engine.getConfig('search.mode_source')).toBe('auto');+ });});+});- test('--force re-prompts even if mode is already set', async () => {- await engine.setConfig('search.mode', 'conservative');- // Non-TTY + force → re-runs auto-suggest with current inputs.- const picked = await runModePicker(engine, { force: true });- // With no model hints + no API key state, default is balanced. The picker- // will overwrite the existing mode.- expect(['conservative', 'balanced', 'tokenmax']).toContain(picked);- const stored = await engine.getConfig('search.mode');- expect(stored).toBe(picked);+describe('init --search-mode: the operator\'s choice', () => {+ const fail = (message: string): never => { throw new Error(`refused: ${message}`); };++ test('parses the flag; an invalid value is refused', () => {+ expect(searchModeChoiceFromArgs(['--pglite'], fail)).toEqual({});+ expect(searchModeChoiceFromArgs(['--search-mode', 'Balanced'], fail)).toMatchObject({ explicit: 'balanced', force: false });+ expect(searchModeChoiceFromArgs(['--search-mode', 'tokenmax', '--force'], fail)).toMatchObject({ explicit: 'tokenmax', force: true });+ expect(() => searchModeChoiceFromArgs(['--search-mode', 'max'], fail)).toThrow(/--search-mode must be one of conservative, balanced, tokenmax/);+ expect(() => searchModeChoiceFromArgs(['--search-mode'], fail)).toThrow(/--search-mode must be one of/);});- test('jsonOutput mode emits a structured event and writes config', async () => {- // Capture console.log output.- const originalLog = console.log;- const captured: string[] = [];- console.log = (msg: string) => { captured.push(msg); };- try {- const picked = await runModePicker(engine, { jsonOutput: true });- const stored = await engine.getConfig('search.mode');- expect(stored).toBe(picked);- const jsonLine = captured.find(l => l.startsWith('{'));- expect(jsonLine).toBeDefined();- const obj = JSON.parse(jsonLine!);- expect(obj.phase).toBe('search_mode_picker');- expect(obj.auto).toBe(true);- expect(['conservative', 'balanced', 'tokenmax']).toContain(obj.mode);- } finally {- console.log = originalLog;- }+ test('a fresh brain records the choice as operator and asks nothing', async () => {+ await inHome({}, async () => {+ let decided = false;+ const lines = await captureLog(() => runModePicker(engine, { explicit: 'tokenmax', jsonOutput: true, onDecision: () => { decided = true; } }));+ expect(decided).toBe(false);+ expect(await engine.getConfig('search.mode')).toBe('tokenmax');+ expect(await engine.getConfig('search.mode_source')).toBe('operator');+ expect(JSON.parse(lines.find(l => l.startsWith('{'))!)).toMatchObject({ phase: 'search_mode_picker', mode: 'tokenmax', auto: false, source: 'operator' });+ expect(lines.join('\n')).not.toContain('[AGENT]');+ });});- test('Opus default model + OpenAI key → picker auto-recommends tokenmax', async () => {- // OPENAI_API_KEY must be present — the no-key short-circuit fires before- // the Opus check (gbrain can't do vector search without embeddings).- await withEnv({ OPENAI_API_KEY: 'sk-test-stub' }, async () => {- await engine.setConfig('models.default', 'anthropic:claude-opus-4-7');- const picked = await runModePicker(engine);- expect(picked).toBe('tokenmax');+ test('an existing brain with another mode refuses without --force and changes nothing', async () => {+ await engine.setConfig('search.mode', 'balanced');+ await inHome({}, async () => {+ await expect(runModePicker(engine, { explicit: 'tokenmax', refuse: fail })).rejects.toThrow(+ /refused: This brain already has search.mode balanced.*gbrain config set search.mode tokenmax.*--force/,+ );+ expect(await engine.getConfig('search.mode')).toBe('balanced');+ expect(await engine.getConfig('search.mode_source')).toBeNull();});});- test('Haiku subagent → picker auto-recommends conservative', async () => {- await engine.setConfig('models.tier.subagent', 'anthropic:claude-haiku-4-5');- const picked = await runModePicker(engine);- expect(picked).toBe('conservative');+ test('--force replaces an existing brain\'s mode and records operator', async () => {+ await engine.setConfig('search.mode', 'balanced');+ await inHome({}, async () => {+ await captureLog(() => runModePicker(engine, { explicit: 'tokenmax', force: true }));+ expect(await engine.getConfig('search.mode')).toBe('tokenmax');+ expect(await engine.getConfig('search.mode_source')).toBe('operator');+ });+ });++ test('the same mode on an existing brain is accepted and marks it the operator\'s', async () => {+ await engine.setConfig('search.mode', 'tokenmax');+ await inHome({}, async () => {+ await captureLog(() => runModePicker(engine, { explicit: 'tokenmax', refuse: fail }));+ expect(await engine.getConfig('search.mode_source')).toBe('operator');+ });+ });+});++describe('upgrade banner', () => {+ test('states the default a mode-less brain runs and the recommendation from the shared source', () => {+ const text = upgradeBannerLines().join('\n');+ expect(text).toContain('runs balanced');+ expect(text).toContain('Recommended for a brain with a chat key: tokenmax');+ expect(text).not.toMatch(/expand=true|preserves current retrieval shape|v0\.31/);});});diff --git a/test/init-search-mode.serial.test.ts b/test/init-search-mode.serial.test.tsnew file mode 100644index 0000000000..e3f065776b--- /dev/null+++ b/test/init-search-mode.serial.test.ts@@ -0,0 +1,64 @@+/**+ * `gbrain init --search-mode <mode>` through the real binary: the operator's+ * choice is recorded (`search.mode_source: operator`) and the `--json`+ * document carries no first-run `search_mode` decision; on a brain with+ * another mode it refuses (exit 2, naming both fixes) unless `--force`; a+ * plain keyless `init --json` still asks, with conservative applied.+ *+ * Serial: real subprocesses and PGLite datastores in temp homes.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';++const KEYLESS = { ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, GEMINI_API_KEY: undefined, GOOGLE_GENERATIVE_AI_API_KEY: undefined };+const INIT = ['init', '--pglite', '--no-embedding', '--json'];++function decisionIds(stdout: string): string[] {+ const doc = JSON.parse(stdout) as { notices?: Array<{ decisions?: Array<{ id: string }> }> };+ return (doc.notices ?? []).flatMap(n => (n.decisions ?? []).map(d => d.id));+}++describe('gbrain init --search-mode', () => {+ test('records the operator\'s choice, asks nothing, refuses a different mode later unless --force', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-init-search-mode-'));+ const opts = { home, env: KEYLESS, timeoutMs: 180_000 };++ const chosen = await runCli([...INIT, '--search-mode', 'tokenmax'], opts);+ expect(chosen.exitCode).toBe(0);+ expect(decisionIds(chosen.stdout)).not.toContain('search_mode');+ expect((await runCli(['config', 'get', 'search.mode'], opts)).stdout.trim()).toBe('tokenmax');+ expect((await runCli(['config', 'get', 'search.mode_source'], opts)).stdout.trim()).toBe('operator');++ const refused = await runCli([...INIT, '--search-mode', 'balanced'], opts);+ expect(refused.exitCode).toBe(2);+ const err = JSON.parse(refused.stdout) as { code: string; message: string };+ expect(err.code).toBe('invalid_params');+ expect(err.message).toContain('This brain already has search.mode tokenmax');+ expect(err.message).toContain('gbrain config set search.mode balanced');+ expect(err.message).toContain('--force');+ expect((await runCli(['config', 'get', 'search.mode'], opts)).stdout.trim()).toBe('tokenmax');++ const forced = await runCli([...INIT, '--search-mode', 'balanced', '--force'], opts);+ expect(forced.exitCode).toBe(0);+ expect((await runCli(['config', 'get', 'search.mode'], opts)).stdout.trim()).toBe('balanced');+ }, 300_000);++ test('an invalid mode is refused before anything is written', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-init-search-mode-'));+ const bad = await runCli([...INIT, '--search-mode', 'max'], { home, env: KEYLESS, timeoutMs: 120_000 });+ expect(bad.exitCode).toBe(2);+ expect(bad.stdout).toContain('--search-mode must be one of conservative, balanced, tokenmax');+ }, 180_000);++ test('a plain keyless init --json still carries the search_mode decision, conservative applied', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-init-search-mode-'));+ const opts = { home, env: KEYLESS, timeoutMs: 180_000 };+ const plain = await runCli(INIT, opts);+ expect(plain.exitCode).toBe(0);+ expect(decisionIds(plain.stdout)).toContain('search_mode');+ expect((await runCli(['config', 'get', 'search.mode_source'], opts)).stdout.trim()).toBe('auto');+ }, 300_000);+});diff --git a/test/search/mode-receipt.serial.test.ts b/test/search/mode-receipt.serial.test.tsnew file mode 100644index 0000000000..a2345df768--- /dev/null+++ b/test/search/mode-receipt.serial.test.ts@@ -0,0 +1,146 @@+/**+ * Fresh-init receipt per search mode: the settings a new brain resolves and+ * 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+ * any mode (it queues the page's embedding; per-chunk synopses come only from+ * the separate contextual-retrieval backfill).+ *+ * Serial: configures the process-global gateway and its test transports.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { runModePicker } from '../../src/commands/init-mode-picker.ts';+import { loadSearchModeConfig, resolveSearchMode, type SearchMode } from '../../src/core/search/mode.ts';+import {+ configureGateway, resetGateway,+ __setEmbedTransportForTests, __setGenerateObjectTransportForTests, __setGenerateTextTransportForTests,+ __setRerankTransportForTests, __setChatTransportForTests, __clearQueryEmbedCacheForTests,+} from '../../src/core/ai/gateway.ts';++const DIMS = 1536;+const calls = { embed: 0, rerank: 0, expand: 0, chat: 0 };+const reset = () => { calls.embed = 0; calls.rerank = 0; calls.expand = 0; calls.chat = 0; };++beforeAll(() => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS,+ expansion_model: 'anthropic:claude-haiku-5-5',+ env: { OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test', VOYAGE_API_KEY: 'pa-test' },+ });+ __setEmbedTransportForTests((async (p: { values: string[] }) => {+ calls.embed++;+ return { embeddings: p.values.map(() => Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0.01))), values: p.values, warnings: [], usage: { tokens: p.values.length } };+ }) as never);+ __setGenerateObjectTransportForTests((async () => {+ calls.expand++;+ return { object: { queries: ['zirconium needle fixture notes', 'notes about the needle fixture'] }, usage: { inputTokens: 100, outputTokens: 20 } };+ }) as never);+ __setGenerateTextTransportForTests((async () => { calls.chat++; return { text: '{"queries":[]}', usage: {} }; }) as never);+ __setChatTransportForTests(async () => { calls.chat++; throw new Error('no chat in this receipt'); });+ __setRerankTransportForTests(async (_url, init) => {+ calls.rerank++;+ const docs = (JSON.parse(String(init.body)) as { documents: string[] }).documents;+ return new Response(JSON.stringify({ results: docs.map((_, index) => ({ index, relevance_score: 1 - index / 100 })) }), { status: 200, headers: { 'content-type': 'application/json' } });+ });+});++afterAll(() => {+ __setEmbedTransportForTests(null);+ __setGenerateObjectTransportForTests(null);+ __setGenerateTextTransportForTests(null);+ __setChatTransportForTests(null);+ __setRerankTransportForTests(null);+ resetGateway();+});++function ctx(engine: PGLiteEngine): OperationContext {+ return { engine, remote: false, sourceId: 'default', config: { engine: 'pglite' }, logger: console, dryRun: false };+}++async function waitForEmbedding(engine: PGLiteEngine): Promise<void> {+ for (let i = 0; i < 200; i++) {+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks WHERE embedded_at IS NOT NULL`);+ if (Number(rows[0]?.n) > 0) return;+ await Bun.sleep(25);+ }+ throw new Error('the queued embedding never ran');+}++const QUESTION = 'who wrote the zirconium needle retrieval fixture notes';++/** Expected receipt per mode; `null` token budget means no cap. */+const RECEIPTS: Record<SearchMode, {+ settings: { searchLimit: number; tokenBudget: number | null; reranker_enabled: boolean; reranker_top_n_in: number; expansion: boolean; contextual_retrieval: string };+ put_page: typeof calls; search: typeof calls; query: typeof calls;+}> = {+ conservative: {+ settings: { searchLimit: 10, tokenBudget: 4000, reranker_enabled: false, reranker_top_n_in: 30, expansion: false, contextual_retrieval: 'none' },+ put_page: { embed: 0, rerank: 0, expand: 0, chat: 0 },+ search: { embed: 1, rerank: 0, expand: 0, chat: 0 },+ query: { embed: 1, rerank: 0, expand: 0, chat: 0 },+ },+ balanced: {+ settings: { searchLimit: 25, tokenBudget: 12000, reranker_enabled: true, reranker_top_n_in: 25, expansion: false, contextual_retrieval: 'title' },+ put_page: { embed: 0, rerank: 0, expand: 0, chat: 0 },+ search: { embed: 1, rerank: 1, expand: 0, chat: 0 },+ 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' },+ 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 },+ },+};++describe('fresh-init receipt per search mode', () => {+ for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {+ test(`${mode}: resolved settings and provider calls for one put_page, one search, one query`, async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ try {+ const log = console.log;+ console.log = () => {};+ try { await runModePicker(engine, { explicit: mode }); } finally { console.log = log; }++ const resolved = resolveSearchMode({ mode, overrides: (await loadSearchModeConfig(engine)).overrides });+ const want = RECEIPTS[mode];+ expect({+ searchLimit: resolved.searchLimit, tokenBudget: resolved.tokenBudget ?? null, reranker_enabled: resolved.reranker_enabled,+ reranker_top_n_in: resolved.reranker_top_n_in, expansion: resolved.expansion, contextual_retrieval: resolved.contextual_retrieval as string,+ }).toEqual(want.settings);++ reset();+ const put = await operationsByName.put_page.handler(ctx(engine), {+ slug: 'notes/zirconium-needle',+ content: '---\ntype: note\ntitle: Zirconium Needle\n---\nThe zirconium needle retrieval fixture notes were written by alice-example.\n',+ });+ expect((put as { embedding_state?: string }).embedding_state).toBe('queued');+ expect({ ...calls }).toEqual(want.put_page);+ // The queued embedding drains in this process: one call for the page's chunk.+ await waitForEmbedding(engine);+ expect(calls.embed).toBe(1);++ reset();+ __clearQueryEmbedCacheForTests();+ const found = await operationsByName.search.handler(ctx(engine), { query: QUESTION });+ expect(JSON.stringify(found)).toContain('notes/zirconium-needle');+ expect({ ...calls }).toEqual(want.search);++ reset();+ __clearQueryEmbedCacheForTests();+ const answered = await operationsByName.query.handler(ctx(engine), { query: QUESTION });+ expect(JSON.stringify(answered)).toContain('notes/zirconium-needle');+ expect({ ...calls }).toEqual(want.query);+ } finally {+ await engine.disconnect();+ }+ }, 120_000);+ }+});