Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.3.0 feat(providers): ZeroEntropy deprecation — Voyage new-install default, sunset migration + playbook, September removal staged (#4160)

Garry Tancc3e284316d6
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 890382a6aa..98313d1618 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.2.0 -->
+<!-- gbrain-runbook-stamp: 0.46.3.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26a15dbc59..23ee979235 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,74 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.3.0] - 2026-08-15
+
+**ZeroEntropy is shutting down on 2026-09-04 — gbrain now gets you off it
+before that date costs you retrieval.** The provider that shipped as the
+default embedding + reranking stack from v0.36 through v0.46 is winding down
+its hosted API. This release makes the transition a guided, one-command move
+instead of a surprise outage:
+
+- **New default: Voyage.** Fresh installs land on `voyage:voyage-4` (1024d) —
+ the strongest hosted retrieval embedder on current benchmarks — and the same
+ `VOYAGE_API_KEY` powers the new `voyage:rerank-2.5` reranker (written as
+ explicit config whenever a Voyage key is present at init; keyed installs
+ without one get reranking explicitly disabled instead of inheriting a
+ fallback they can't use) and the multimodal model. One key, all three
+ touchpoints. The v4 family shares one embedding space, so you can later
+ point queries at `voyage-4-large` or `-lite` without re-indexing.
+- **Nothing changes out from under existing brains.** A brain configured for
+ ZeroEntropy (or riding the old default) keeps working exactly as before until
+ the shutdown date — this release only detects, warns, and hands you the
+ playbook. Every surface that used to steer you toward the dying provider
+ (init auto-pick, the interactive picker, `gbrain providers`, setup hints)
+ now steers you to the replacement instead, and using it prints a
+ once-per-process heads-up.
+- **The switch is one command:** `gbrain migrate embeddings --to voyage:voyage-4
+ --dim 1024 --dry-run` (cost preview), then `--yes`. Prefer OpenAI? It can
+ keep your existing column width: `--to openai:text-embedding-3-small
+ --dim 1280`. Reranker: `gbrain config set search.reranker.model
+ voyage:rerank-2.5`. Self-hosting the Apache-2.0 weights remains documented in
+ docs/guides/embedding-migration.md.
+- **Your agent gets told too.** A v0.46.3 migration checks whether your brain
+ still resolves to the sunsetting provider (embedding, reranker, or custom
+ columns), prints an ACTION REQUIRED notice with the blast radius and cost
+ estimate, and files a durable action item pointing at the agent playbook
+ (`skills/migrations/v0.46.3.0.md`). `gbrain doctor`'s provider check now
+ prints width-aware paste-ready commands, and its documented suppression
+ switch (`gbrain config set doctor.suppress_provider_sunset true`) actually
+ works now.
+- `gbrain ze-switch` no longer switches brains onto the sunsetting provider
+ (`--undo` still moves brains off it), and `gbrain migrate embeddings` refuses
+ a re-embed onto a provider with an announced shutdown — self-hosters with a
+ wire-compatible endpoint pass `--force-sunset-target`. Voyage's
+ `voyage-code-4` is available for code-heavy brains.
+- Setup fixes that ride along: init now detects provider keys stored in
+ `~/.gbrain/config.json` (file plane), not just env vars; a keyless brain
+ upgrades in place via `gbrain init --force --embedding-model voyage:voyage-4`
+ (the deferred-setup sentinel is cleared); and keyless fresh installs size the
+ embedding column at the new default width.
+
+### To take advantage of v0.46.3.0
+
+`gbrain upgrade` is enough — no schema migration.
+
+1. **Upgrade and check:**
+ ```bash
+ gbrain upgrade
+ gbrain doctor
+ ```
+2. **If the upgrade printed ACTION REQUIRED** (or doctor flags
+ `provider_sunset`): run the printed migrate command before 2026-09-04, or
+ hand your agent `skills/migrations/v0.46.3.0.md` — it walks the whole
+ switch, including the reranker and edge cases.
+3. **Things to watch:** existing brains see zero behavior change from this
+ release itself; fresh installs default to `voyage:voyage-4` at 1024
+ dimensions; reranking configured on the sunsetting provider dies with it on
+ 2026-09-04 unless you set the voyage reranker (or disable reranking). If
+ anything looks wrong, file an issue with `gbrain doctor` output:
+ https://github.com/garrytan/gbrain/issues
+
## [0.46.2.0] - 2026-08-15
**Dream synthesis now triages before it spends.**
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4df0da311c..976b14c36e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -65,7 +65,7 @@ src/
yaml-lite.ts Lightweight YAML parser
chunkers/ 3-tier chunking (recursive, semantic, llm)
search/ Hybrid search (vector, keyword, hybrid, expansion, dedup)
- embedding.ts Embedding service (provider-routed; ZeroEntropy default)
+ embedding.ts Embedding service (provider-routed; Voyage default)
mcp/
server.ts MCP stdio server (generated from operations)
http-transport.ts HTTP MCP transport (OAuth, body caps)
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 816c1976a3..fe50bee572 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -55,19 +55,22 @@ restart the shell or add the PATH export to the shell profile.
## Step 2: API Keys
-Ask the user for these. gbrain defaults to the ZeroEntropy embedding + reranker stack
-(as of v0.36.2.0); OpenAI/Voyage are still supported as fallbacks via `gbrain config
-set embedding_model <provider:model>`.
+Ask the user for these. gbrain defaults to the Voyage embedding + reranker stack
+(`voyage:voyage-4` @ 1024d + `voyage:rerank-2.5` — one key covers both); OpenAI is the
+main alternative, chosen at init via `--embedding-model <provider:model>`. ZeroEntropy
+is deprecated (its hosted API shuts down 2026-09-04): init auto-pick and the picker
+exclude it, and every ZE embed/rerank prints a deprecation warning.
```bash
-export ZEROENTROPY_API_KEY=ze-... # default embedding + reranker (v0.36.2.0+)
-export OPENAI_API_KEY=sk-... # fallback for vector search; also used for chat models
+export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
+export OPENAI_API_KEY=sk-... # alternative for vector search; also used for chat models
export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search quality via query expansion
```
-Save to shell profile or `.env`. Keys are picked up by `gbrain config set` automatically
-or can be stored in `~/.gbrain/config.json` (file plane). Without any embedding provider,
-keyword search still works. Without Anthropic, search works but skips query expansion.
+Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). Do
+NOT use `gbrain config set` for API keys — it writes the DB plane, which the embedding
+pipeline never reads. Without any embedding provider, keyword search still works.
+Without Anthropic, search works but skips query expansion.
## Step 3: Create the Brain
diff --git a/README.md b/README.md
index 409adb2069..1d44bba24f 100644
--- a/README.md
+++ b/README.md
@@ -307,7 +307,7 @@ The whole loop is described in [`docs/architecture/topologies.md`](docs/architec
## Capabilities
-**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The ZeroEntropy reranker is on in `balanced` and `tokenmax`, off in `conservative`. Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page.
+**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The cross-encoder reranker is on in `balanced` and `tokenmax`, off in `conservative` — new installs get Voyage `rerank-2.5`; brains that never set `search.reranker.model` still fall back to the deprecated ZeroEntropy `zerank-2` (hosted API ends 2026-09-04) until the September cutover. Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page.
**Self-wiring knowledge graph.** Every `put_page` extracts entity refs from markdown/wikilinks/typed-link syntax and writes edges with zero LLM calls. Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. The graph is what produces the +31.4 P@5 lift over vector-only RAG. **Obsidian-style vaults:** bare `[[note-name]]` wikilinks that point across folders — you wrote `[[struktura]]` but the page lives at `projects/struktura.md` — resolve by basename once you opt in with `gbrain config set link_resolution.global_basename true`. Off by default; `gbrain doctor` tells you how many edges you'd gain before you flip it. See [migrating an Obsidian vault](INSTALL_FOR_AGENTS.md#step-45-wire-the-knowledge-graph).
@@ -345,8 +345,8 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).
- **Email + calendar**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
-- **Embedding providers**: a dozen providers covered — OpenAI (default fallback), OpenRouter, Voyage, ZeroEntropy (default), Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: ZeroEntropy `zerank-2` hosted (the default; on in `balanced` and `tokenmax` modes) plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted ZeroEntropy weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the new-install default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; still the fallback for brains that never set `search.reranker.model`), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential gateway**: vault-aware secret distribution. [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
@@ -364,7 +364,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain now repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](docs/ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](docs/INSTALL.md#pglite-crashes-on-macos-26x-tahoe).
-**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys in your environment: set `OPENAI_API_KEY` (or `ZEROENTROPY_API_KEY` / `VOYAGE_API_KEY`) before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker. In non-TTY contexts (CI, Docker) with no keys, init exits 1 with a paste-ready setup hint; pass `--no-embedding` to defer setup until runtime. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
**Hourly cron sync keeps timing out on a federated brain?** Switch your
cron to a per-source loop with shell `timeout(1)` doing the OS-level kill
@@ -510,4 +510,4 @@ MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production
Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that ships as the default. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
+Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that shipped as the default from v0.36 through v0.46. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
diff --git a/TODOS.md b/TODOS.md
index bc48d60f9c..327e03b0d1 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,67 @@
# TODOS
+## v0.47 SEPTEMBER REMOVAL — ZeroEntropy (filed v0.46.3.0; TARGET: ship 2026-09-04..2026-09-08)
+
+ZeroEntropy's hosted API dies 2026-09-04. v0.46.3.0 deprecated it (split-default:
+new installs → voyage; legacy runtime fallbacks stay ZE; detect-and-notify
+migration). The removal wave deletes the provider and performs the hard cutover.
+Staged-deletion discipline (ship replacements → migrate call sites → update tests
+→ THEN delete; see the skills/_brain-filing-rules precedent below):
+
+- [ ] **P1 — HARD CUTOVER: retire the legacy configless runtime fallbacks.**
+ `DEFAULT_EMBEDDING_MODEL`/`DEFAULT_EMBEDDING_DIMENSIONS` (src/core/ai/defaults.ts)
+ stop resolving to `zeroentropyai:*`; unmigrated configless brains get a HARD,
+ actionable error naming `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024`.
+ Also flip `DEFAULT_RERANKER_MODEL` (gateway.ts) + the three mode-bundle
+ `reranker_model` values (mode.ts:298,348,403) to `voyage:rerank-2.5` — one-time
+ knobs-hash query-cache miss for ALL modes incl. conservative (reranker_model is
+ hashed unconditionally; document in that release's CHANGELOG). Verify the schema
+ generators' legacy-constant consumers (pglite-schema, postgres-engine,
+ embedding-column.ts registry fallback) get a deliberate post-ZE story.
+- [ ] **P1 — PREREQ before recipe deletion: move gateway.ts's `'/models/rerank'`
+ default path onto explicit per-recipe `path` fields.** llama-server-reranker and
+ dashscope-rerank may ride the implicit ZE-shaped fallback — audit + pin with tests
+ FIRST or their rerank calls 404 the day the fallback goes.
+- [ ] **P1 — Delete the provider surface.** `src/core/ai/recipes/zeroentropyai.ts` +
+ registry entries (recipes/index.ts); `zeroEntropyCompatFetch`,
+ `MAX_ZEROENTROPY_RESPONSE_BYTES`, `ZeroEntropyResponseTooLargeError` + the
+ fetch-ternary arm (gateway.ts); ZE sets in dims.ts; `ze-switch.ts` +
+ `retrieval-upgrade-planner.ts` + `retrieval-upgrade-prompt.ts` (~1200 lines) +
+ cli.ts dispatch/CLI_ONLY/flag-registry rows; `checkZeEmbeddingHealth` in doctor
+ (`provider_sunset` STAYS and goes generic — read `recipe.sunset` instead of the
+ hardcoded ZE constants); pricing rows LAST (budget-tracker rerank metering reads
+ them for historical audit rows). NOTE: test/ai/zeroentropy-compat-fetch.test.ts
+ greps gateway.ts SOURCE TEXT — delete the test with the code, in the same commit.
+- [ ] **P1 — Self-host continuity decision.** The v0.46.3 playbook's zero-re-embed
+ path keeps the `zeroentropyai:zembed-1` id behind a base-URL override to a
+ ZE-wire-compatible endpoint. Recipe deletion breaks it. Decide: keep a minimal
+ local-only recipe shell (no picker/auto-pick, no hosted default URL), ship a
+ signature-migration tool (rewrite pages.embedding_signature provider ids without
+ re-embedding), or explicitly end the promise with a loud migration note. The
+ playbook (skills/migrations/v0.46.3.0.md) links here — honor it.
+- [ ] **P2 — Tests + CI.** Delete the 8 ZE-dedicated test files
+ (zeroentropy-recipe, zeroentropy-compat-fetch, dims-zeroentropy,
+ e2e/zeroentropy-live, ze-switch-cli, ze-switch-env-override, doctor-ze-checks,
+ provider-sunset-doctor.serial gets REWRITTEN generic not deleted) + update ~40
+ coupled files; drop the zeroentropy-live job + ZEROENTROPY_API_KEY secret from
+ .github/workflows/e2e.yml:168,179 (already date-skip-gated since v0.46.3);
+ scripts/test-weights.json rows.
+- [ ] **P2 — Config + docs.** `zeroentropy_api_key` config key: keep
+ parseable-but-warned (removing it would make old config.json files fail to
+ load); delete docs/ai-providers/zeroentropy.md + its scripts/llms-config.ts
+ entry (+ `bun run build:llms`); v0.46.3 migration stays registered and must
+ degrade gracefully once the recipe is gone (notice-only — verify its copy).
+- [ ] **P2 — Custom-column off-ramp (not removal-gated, but September makes it
+ urgent for affected users).** Write-side custom-column migration
+ (`gbrain embed --column X --model Y`, embedding-column.ts:60-62 v2 deferral) so
+ ZE-backed `embedding_columns` entries get an executable migration instead of
+ drop-and-re-embed guidance.
+- [ ] **P3 — Optional `cohere-rerank` recipe.** Cohere rerank-4.0-pro is the
+ strongest surviving hosted reranker (Agentset ELO 1629, behind only the dying
+ zerank-2) for users who want max rerank quality on a dedicated key. Wire shape
+ differs from the ZE/voyage dialect — needs its own `top_param`/response mapping
+ audit. Filed from the v0.46.3 CEO review (deferred cherry-pick).
+
## Issues #5+#6 follow-ups (pool starvation + process isolation; plan: ~/.claude/plans/system-instruction-you-are-working-witty-moore.md)
- [ ] **P1-companion — nested-checkout audit + dev-mode detection.** **What:**
@@ -743,9 +805,10 @@ The eng-review + Codex outside-voice narrowed the wave to these deferrals:
covers anthropic + openai; Google was deferred because Gemini's native suffix is unproven
(its OpenAI-compat route is `/v1beta/openai`). Verify the correct `@ai-sdk/google` suffix,
then add `google` to the helper. Where: `src/core/ai/gateway.ts:resolveNativeBaseUrl`.
-- [ ] **P3 — Fold Voyage/Google/LiteLLM/OpenRouter API keys into `buildGatewayConfig`.**
- It folds only OPENAI/ANTHROPIC/ZEROENTROPY file-plane keys today, so `config.json`-set keys
- for other providers only work if also in `process.env`. Extend the mapping. Where:
+- [ ] **P3 — Fold Google/LiteLLM/OpenRouter API keys into `buildGatewayConfig`.**
+ Voyage + Dashscope + Google were folded by #2662 (`build-gateway-config.ts:33-60`);
+ remaining gaps are the aggregator keys (litellm, openrouter) whose `config.json`-set
+ keys only work if also in `process.env`. Extend the mapping. Where:
`src/core/ai/build-gateway-config.ts`.
- [ ] **P3 — OpenRouter per-model custom-dim handling.** OpenRouter declares recipe-wide
`dims_options` and mixes fixed-dim + arbitrary models, so it's excluded from `trust_custom_dims`.
diff --git a/VERSION b/VERSION
index a8bca2376f..cb09b6274b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.2.0
+0.46.3.0
\ No newline at end of file
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 3541294dcf..43f67addb0 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -26,7 +26,7 @@ Your agent now reads `skills/RESOLVER.md` once per request, routes intent to the
Scaffolded skills are first-class files in your agent repo — edit freely. To pull upstream gbrain improvements later, `gbrain skillpack reference <name>` diffs your local copy vs the bundle. The legacy `skillpack install` managed-block model was retired in v0.36.0.0; if you're upgrading from an older release, run `gbrain skillpack migrate-fence` once to strip the legacy fence and keep your existing skill rows.
-To upgrade later: `gbrain upgrade` runs schema migrations + post-upgrade prompts (chunker bumps, the v0.36.2.0 ZeroEntropy switch). Always TTY-only; non-TTY upgrades skip prompts with informational stderr lines.
+To upgrade later: `gbrain upgrade` runs schema migrations + post-upgrade prompts (chunker bumps, provider-sunset notices). Always TTY-only; non-TTY upgrades skip prompts with informational stderr lines.
## 2. CLI standalone
@@ -48,14 +48,16 @@ gbrain migrate --to pglite # Postgres → PGLite (rare)
For shared / large / multi-machine deployments (a team or company brain with multiple users hitting one server over HTTP MCP with OAuth scoping per user), follow the dedicated walkthrough: **[Tutorial: set up GBrain as your company brain](tutorials/company-brain.md)**.
-API keys live in `~/.gbrain/config.json` (file plane) or env vars (`OPENAI_API_KEY`, `OPENROUTER_API_KEY`, `ZEROENTROPY_API_KEY`, `VOYAGE_API_KEY`, `ANTHROPIC_API_KEY`). Set via CLI:
+API keys live in `~/.gbrain/config.json` (file plane) or env vars (`VOYAGE_API_KEY`, `OPENAI_API_KEY`, `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`). Set them via env or by editing `~/.gbrain/config.json` directly — do NOT use `gbrain config set` for API keys (that writes the DB plane, which the embedding pipeline never reads):
```bash
-gbrain config set zeroentropy_api_key sk-...
-gbrain config set openrouter_api_key sk-or-...
-gbrain config set anthropic_api_key sk-ant-...
+export VOYAGE_API_KEY=pa-... # default embedding (voyage-4) + reranker (rerank-2.5) — one key
+export OPENAI_API_KEY=sk-... # alternative embeddings; also used for chat models
+export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search via query expansion
```
+`ZEROENTROPY_API_KEY` is still honored but deprecated — the ZeroEntropy hosted API shuts down 2026-09-04 (see [`docs/ai-providers/zeroentropy.md`](ai-providers/zeroentropy.md) for the off-ramp).
+
Common follow-ups:
```bash
diff --git a/docs/ai-providers/llama-server-reranker.md b/docs/ai-providers/llama-server-reranker.md
index 2cf5428a25..b4b88a2899 100644
--- a/docs/ai-providers/llama-server-reranker.md
+++ b/docs/ai-providers/llama-server-reranker.md
@@ -22,9 +22,13 @@ Two flavors of "local" this recipe covers:
This recipe is the path override + recipe shape. Any provider whose
request/response wire matches ZE/llama.cpp can use it by just pointing
-at a different base URL. Providers whose wire shape differs (Voyage uses
-`top_k` not `top_n`, returns `data[]` not `results[]`) need a separate
-recipe with adapter hooks — that lands in a follow-up plan.
+at a different base URL. A provider whose request differs only in the
+top-N key declares it via the recipe's `top_param` — that's how the
+hosted Voyage reranker recipe (`voyage:rerank-2.5`, the new-install
+default, `top_k`) works. On the response side the gateway parser accepts
+both known array keys (`results[]` for ZE/llama.cpp, `data[]` for
+Voyage's REST — the shared item shape is `{index, relevance_score}`);
+a genuinely different item shape needs its own recipe with adapter hooks.
## Setup
diff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.md
index 56b4fa90a0..5677ec7abc 100644
--- a/docs/ai-providers/zeroentropy.md
+++ b/docs/ai-providers/zeroentropy.md
@@ -1,20 +1,44 @@
-# ZeroEntropy — zembed-1 + zerank-2
-
-> **Hosted API shutdown: 2026-09-04.** ZeroEntropy announced (2026-07-24)
-> that its hosted endpoints — `/models/embed` and `/models/rerank` — shut
-> down on that date. A brain still embedding through the hosted API loses
-> semantic retrieval entirely on that date: query embedding uses the same
+# ZeroEntropy — zembed-1 + zerank-2 (DEPRECATED)
+
+> **DEPRECATED — hosted API shutdown: 2026-09-04.** ZeroEntropy announced
+> (2026-07-24) that its hosted endpoints — `/models/embed` and
+> `/models/rerank` — shut down on that date, and gbrain has deprecated the
+> recipe: `gbrain init` auto-pick and the interactive picker exclude it
+> (explicit `--embedding-model zeroentropyai:*` still works, with a loud
+> warning), every ZE embed/rerank call prints a once-per-process
+> deprecation warning, `gbrain providers` annotates it DEPRECATED, and
+> `gbrain ze-switch` refuses to switch a brain ONTO ZeroEntropy (`--undo`
+> and `--dry-run` still work). The September release removes the recipe
+> entirely. A brain still embedding through the hosted API loses semantic
+> retrieval entirely on the shutdown date: query embedding uses the same
> endpoint, so **existing vectors become unqueryable**, not just new
> content. Two fixes, either works:
>
-> 1. **Self-host the same model** — zembed-1 weights are Apache-2.0. Serve
-> them via `llama-server` or Ollama and point the config at the local
-> endpoint. Keeps every existing vector; no re-embed at all.
-> 2. **Migrate to another provider** — `gbrain migrate embeddings --to
-> <provider:model> --dim <N> --dry-run` (resumable; see
-> [the migration guide](../guides/embedding-migration.md)). `gbrain
-> doctor` (check `provider_sunset`) prints this command with your
-> brain's actual `--dim` filled in.
+> 1. **Migrate to Voyage (recommended)** — `gbrain migrate embeddings
+> --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then
+> `--yes`. 1280 is not a valid Voyage width (valid: 256/512/1024/2048),
+> so a 1280d brain gets a one-time schema/HNSW rebuild to 1024 — the
+> command handles it, resumable if killed. The OpenAI alternative keeps
+> the width (flexible dims): `--to openai:text-embedding-3-small --dim
+> 1280`. Reranker: `gbrain config set search.reranker.model
+> voyage:rerank-2.5` (needs `VOYAGE_API_KEY`) or `gbrain config set
+> search.reranker.enabled false`. See
+> [the migration guide](../guides/embedding-migration.md); `gbrain
+> doctor` (check `provider_sunset`) prints both commands target-aware
+> (Voyage at 1024; OpenAI keep-width when your brain's actual width is
+> valid there).
+> 2. **Self-host the same model (zero re-embed, advanced)** — zembed-1
+> weights are Apache-2.0. Keep the `zeroentropyai:zembed-1` model id
+> (the embedding signature must not change) and point its base URL at
+> your own endpoint: `gbrain config set
+> provider_base_urls.zeroentropyai <url>`. The endpoint must speak
+> **ZeroEntropy's wire dialect** (`/models/embed`, `{results: [...]}`
+> responses — the id routes through a ZE-specific compat fetch), so a
+> generic OpenAI-compatible llama-server or Ollama endpoint will NOT
+> work without a compat proxy in front. Switching the provider id
+> instead changes `pages.embedding_signature` and triggers a full
+> re-embed. This path survives only until the September removal release
+> deletes the recipe.
>
> The hosted setup below remains accurate until the shutdown date.
@@ -98,15 +122,20 @@ The reranker is the bigger story: gbrain had no cross-encoder reranker
stage before v0.35.0.0. It slots between RRF dedup and token-budget
enforcement in hybrid search.
-### Default-on with `tokenmax` mode
+### Default-on with `balanced` and `tokenmax` modes
-`tokenmax` mode now defaults `search.reranker.enabled = true` with
-`zerank-2`. If you already use `tokenmax` AND have `ZEROENTROPY_API_KEY`
-set, reranker fires automatically. Without the key, every rerank call
-fails-open (audit-logged) and search returns RRF order — same UX as
-before, just with an observable failure surfaced via `gbrain doctor`.
+The `balanced` and `tokenmax` mode bundles default
+`search.reranker.enabled = true`. Brains that never set
+`search.reranker.model` still fall back to `zerank-2` (the legacy bundle
+default until the September cutover — new installs write explicit reranker
+config instead: `voyage:rerank-2.5` when a Voyage key is present, otherwise
+`search.reranker.enabled false`). With
+`ZEROENTROPY_API_KEY` set, the ZE reranker fires automatically. Without
+the key, every rerank call fails-open (audit-logged) and search returns
+RRF order — same UX as before, just with an observable failure surfaced
+via `gbrain doctor`.
-### Opt-in on `conservative` or `balanced` mode
+### Opt-in on `conservative` mode
```bash
gbrain config set search.reranker.enabled true
@@ -136,8 +165,8 @@ Two probes run for reranker:
| Config key | Default | Notes |
|---|---|---|
-| `search.reranker.enabled` | `true` for tokenmax, `false` for others | One-flip opt-in/out |
-| `search.reranker.model` | `zeroentropyai:zerank-2` | Try `zerank-1` (older SOTA) or `zerank-1-small` (Apache-2.0 open) |
+| `search.reranker.enabled` | `true` for balanced/tokenmax, `false` for conservative | One-flip opt-in/out |
+| `search.reranker.model` | `zeroentropyai:zerank-2` (legacy fallback; new installs write `voyage:rerank-2.5`) | The recommended replacement is `voyage:rerank-2.5` |
| `search.reranker.top_n_in` | `30` | Candidates sent to reranker (caps API spend) |
| `search.reranker.top_n_out` | `null` (no truncate) | Truncate reranked output to this many; `null` preserves full length |
| `search.reranker.timeout_ms` | `5000` | HTTP timeout; long stalls degrade UX worse than RRF fallback |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index d20f6245a2..3d68c1dc8a 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -126,8 +126,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/spend-posture.ts` — spend-control surface (#2139). `resolveSpendPosture(engine): 'gated'|'tokenmax'` (DB-plane `spend.posture`, fail-open `gated`); `tokenmax` makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). `parseUsdLimit(raw, def, {allowZero?})` accepts `off`/`unlimited`/`none` → `Infinity`; `formatUsdLimit(n)` renders `Infinity` as the string `'unlimited'` (never raw — `JSON.stringify(Infinity)` is `null`); `usdLimitToCap(n)` maps `Infinity` → `undefined` at the BudgetTracker boundary so ledger rows never serialize null. `normalizeSpendPosture`/`isValidSpendPosture` back the `config set` validation. Doc: `docs/operations/spend-controls.md`. Pinned by `test/sync-cost-preview.test.ts` + `test/spend-off-switch.test.ts`.
- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, falling back to `DEFAULT_EMBEDDING_DIMENSIONS=1536`, an OpenAI default not a Voyage one).
- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage/zeroentropy) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to `${recipe.base_url}/models/rerank` with bearer auth, returns `RerankResult[]` sorted by relevance. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length at `:595`, Layer 2 per-embedding base64 at `:619`) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:<model>`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport.
-- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by regression in `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned by regression). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge.
+- `src/core/ai/defaults.ts` — leaf module holding the embedding/reranker default constants (no gateway import, so schema + registry helpers can read them without loading provider SDKs). Split-default: `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` (`voyage:voyage-4`) + `NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS` (1024) feed every new-install surface — init auto-pick canonical tiebreak, the interactive picker default, the no-keys hint, keyless fresh-install schema sizing (passed as an explicit init param), and all recommendation copy (playbook, banners, doctor fix-hints, advisor). `NEW_INSTALL_DEFAULT_RERANKER_MODEL` (`voyage:rerank-2.5`) is written as explicit `search.reranker.model` config at init whenever a Voyage key is present on either plane (env or `~/.gbrain/config.json`), regardless of which embedding provider was picked (`init.ts:writeNewInstallRerankerDefault`, shared by the PGLite + Postgres paths); keyed non-Voyage installs get explicit `search.reranker.enabled false` instead (never inherit the doomed legacy bundle fallback they have no key for), keyless installs get NO reranker write (the documented keyless-recovery re-init must find virgin reranker config so its override still lands), deliberate `zeroentropyai:*` installs are left on the legacy bundle, and an existing explicit reranker choice is never clobbered. Quoted by the migration playbook; the runtime reranker defaults (gateway `DEFAULT_RERANKER_MODEL` + the mode-bundle values) stay on `zerank-2` until the September removal. `DEFAULT_EMBEDDING_MODEL` (`zeroentropyai:zembed-1`) + `DEFAULT_EMBEDDING_DIMENSIONS` (1280) serve ONLY as the configless runtime fallback for brains with no `embedding_model` in file config — their stored vectors live in ZE's 1280d space, so flipping the fallback under them would break retrieval before the provider dies; the September removal release deletes the fallback and hard-errors unmigrated configless brains with the migrate command. `ZEROENTROPY_SUNSET_DATE` (`'2026-09-04'`) is the single source of truth for the upgrade banners, the `provider_sunset` doctor check, and the ZE recipe's `sunset` metadata.
+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length at `:595`, Layer 2 per-embedding base64 at `:619`) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:<model>`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport.
+- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by regression in `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned by regression). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and the `gbrain providers` DEPRECATED annotation; the recipe itself is deleted in the September removal release.
- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Same wave adds: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (closes file-plane / DB-plane divergence where doctor said "not configured" while live search was actively reranking — the field-plane `getRerankerModel()` read nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: `openai/text-embedding-3-small` at 1536 dims with Matryoshka `dims_options: [512, 768, 1024, 1536]`; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is INFORMATIONAL — the real gate is `isAnthropicProvider()` in `src/core/model-config.ts` which hard-pins gbrain's subagent infra to Anthropic-direct. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
@@ -135,7 +136,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network.
- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap. A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).
- `src/core/search/autocut.ts` (default ON in reranked modes) — Weaviate-style autocut: score-discontinuity result-sizing on the cross-encoder rerank separatrix. `applyAutocut(results, scoreOf, cfg)` normalizes the reranker scores, finds the largest consecutive gap, and cuts there when it clears `jumpRatio` (default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guards `top<=0`/non-finite, never returns empty, and no-ops when <2 results carry a finite `rerank_score` (covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (see `return-policy.ts`) that the RRF rank1→rank2 gap is ~flat whether rank-1 is right or wrong — not a separatrix; the cross-encoder score IS. So autocut runs ONLY where the reranker ran (the floor reaches `balanced`+`tokenmax`; `conservative` is a documented no-op). Exports `AutocutConfig`, `DEFAULT_AUTOCUT` (frozen: `enabled=true, jumpRatio=0.20, minKeep=1`), `AutocutDecision` (`{applied, signal:'rerank'|'none', cut, kept, total, gapRatio}`), `AutocutInput`, `autocutFromConfig`, `resolveAutocut`, `applyAutocut`. Cache-key integration (clean path, not the adaptive-return cache-skip hack): enable+sensitivity flow through `ModeBundle` → `ResolvedSearchKnobs` → `knobsHash` exactly like `graph_signals`. `mode.ts` adds `autocut`/`autocut_jump` (conservative false, balanced/tokenmax [email protected]) AND sets `reranker_top_n_in = searchLimit` for reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop — closes the load-bearing recall finding). Autocut folds into `knobsHash` as its own parts entry (`mode.ts:KNOBS_HASH_VERSION` is the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired into `hybridSearch` AFTER adaptive-return, BEFORE the limit slice, first page only; emits `HybridSearchMeta.autocut`. BOTH the cache-miss `finalMeta` and cache-HIT `cachedMeta` rebuilds carry `autocut`+`adaptive_return`+`mode`+`embedding_column`. Preserves alias-hop exact matches: `applyAutocut` takes an optional `preserve` predicate; hybrid passes `r => r.alias_hit === true` so a canonical page injected by `applyAliasHop` after reranking (no `rerank_score`) is never cut. Agent surface: `query` op `autocut` boolean (ceiling override — `false` forces full top-K); `SearchOpts.autocut`; `--explain` shows per-result `rerank_score`, `formatAutocutSummary` renders the decision when search meta is threaded; `gbrain search modes` attribution; metric glossary `autocut.signal`/`autocut.gap_ratio`. Config: `search.autocut`, `search.autocut_jump`. Default-ON backed by an in-repo eval gate — `test/search/autocut-eval.test.ts` (also `bun run eval:autocut`) measures precision-lift-without-recall-regression over labeled qrels fixtures with modeled cross-encoder distributions (no API key, no sibling repo; runs in CI): mean precision 0.33→0.94, recall 1.00→0.95, ZERO recall regression on enumeration queries. Env-overridable floors. Pinned by `test/search/autocut.test.ts` (pure-fn), `test/search/query-op-autocut.test.ts` (agent surface), `test/search/autocut-integration.serial.test.ts` (IRON-RULE behavioral via `rerankerFn` DI seam: cliff trims, flat doesn't, no-reranker no-ops, `autocut:false` ceiling, composes with adaptive-return), `test/search/autocut-eval.test.ts` (the precision/recall gate), and the knobsHash assertions in `test/search-mode.test.ts`.
-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), avoiding the backfill loop where tiktoken-grounded budgeting undercounted Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. Recipe docstring at `:7-16` names the seven hosted flexible-dim models that accept `output_dimension` (`voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`) and notes `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative regression assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe-shape regression pinned by `test/ai/voyage-code-3-recipe.test.ts`.
+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the recommended `zerank-2` replacement, same `VOYAGE_API_KEY` as embeddings): `rerank-2.5` flagship ($0.05/M) + `rerank-2.5-lite` ($0.02/M; prices verified 2026-08-15), `path: '/rerank'`, `top_param: 'top_k'` (Voyage's response wire matches ZE's `{results: [{index, relevance_score}]}`; only the request's top-N key differs), 5MB byte-proxy payload cap matching the ZE-era pre-flight. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), avoiding the backfill loop where tiktoken-grounded budgeting undercounted Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative regression assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the newer hosted code model, flexible dims, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe-shape regression pinned by `test/ai/voyage-code-3-recipe.test.ts`.
- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe-shape regression pinned by `test/anthropic-model-ids.test.ts`.
- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor. Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.
- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts`, `minions/batch-projection.ts`, and `cycle/budget-meter.ts`.
@@ -148,7 +149,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. 8-step resolution chain: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves non-Anthropic, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` (the Anthropic Messages API tool-loop can't run on OpenAI/Gemini). `_resetDeprecationWarningsForTest()` also clears `_subagentTierWarningsEmitted`. Pinned by `test/model-config.serial.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape.
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (13 `PER_TASK_KEYS`, now including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
-- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + file-plane `openai/anthropic/zeroentropy_api_key` from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
+- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/zeroentropy/dashscope/google, #2662 — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Single owner of folding file-plane API keys (openai/anthropic/zeroentropy) into the gateway env and threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries, `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.
- `src/core/skill-catalog.ts` — host-repo skill catalog backing the MCP `list_skills` / `get_skill` ops. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `crossReferenceTools(declared, ctx)` splits a skill's declared `tools:` into `usable_tools` vs `unavailable_tools`; `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. Skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). Two ops register in `src/core/operations.ts` (`list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` + `cliHints:{name:'skill', positional:['name']}`) and dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
@@ -200,7 +201,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same unmitigated-until-now window `embedPage`'s single-page chunkless branch already ships with. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` (#3391) lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent (#3037): all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND the pre-migration `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` shapes are gone). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. The other six commands (`extract`, `lint`, `backlinks`, `reindex`, `integrity`, `pages`) adopt the same pattern in a follow-up wave. #1737: `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`.
- `src/core/retrieval-upgrade-planner.ts` — `runSchemaTransition(engine, targetDim)` (exported) is the ONE atomic dimension-transition path, shared by `ze-switch` and `gbrain migrate embeddings`. In a single transaction it rebuilds ALL THREE dim-pinned text-embedding-space columns at `targetDim` — `content_chunks.embedding`, `query_cache.embedding`, `facts.embedding` — preserving each column's declared type (`vector` vs `halfvec`, probed from `information_schema`) and recreating its HNSW index with the matching opclass, gated on `hnswIndexExpected` (above the per-type dim ceiling pgvector refuses the index and exact scans remain the path). query_cache + facts are created at brain-birth width by `migrate.ts` and NO migration ever ALTERs them, so omitting either leaves it silently broken: a narrow `query_cache.embedding` makes every `store()`/`lookup()` fail inside the cache's own error-swallowing (permanent 0% hit rate), and a narrow `facts.embedding` fails every per-fact embed write (the doctor check that would warn is skipped on PGLite, the default engine). `content_chunks.embedding_image` / `embedding_multimodal` are the deliberate exception — separate multimodal models, dimensions independent of the text model. Pinned by `test/embedding-migration.test.ts` (all three widths + a real INSERT at the new width into each) and `test/e2e/migrate-embeddings-postgres.test.ts`.
- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core (#3390): `planEmbeddingMigration` (workload counts via the widened stale predicates with the TARGET signature + `includeNullSignature`, so a mid-migration re-plan counts only what remains; cost via `embedding-pricing.ts`; `null_signature_chunks` split out for #3391 visibility; reranker-on-outgoing-provider warning), `applyEmbeddingMigration` (env-override gate BEFORE any mutation → in-flight state marker `embedding_migration.state` → `runSchemaTransition` when the ACTUAL column width differs from target → DB-plane `embedding_model`/`embedding_dimensions` → `persistConfig` callback for the file plane → `invalidateStaleSignatureEmbeddings({includeNullSignature: true})` → `SemanticQueryCache.clear()`), `completeEmbeddingMigration` (clears the marker + stamps `embedding_migration.completed`; call only at zero backlog), `resolveMigrationTarget` (validates `provider:model` via `resolveRecipe`, dims via `embeddingDimsForModel` or explicit `--dim`), `migrationSignature` (matches `currentEmbeddingSignature()` shape). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Reuses `runSchemaTransition` (now exported from `retrieval-upgrade-planner.ts`) so ze-switch and the migration share ONE dimension-transition path. `reconcilePageSignatures(engine, plan)` runs after the re-embed drain and BEFORE the completion probe: it stamps the target signature on every page that has zero NULL-embedding chunks, covering pages whose chunks straddle a `listStaleChunks` batch boundary (the embed loop only stamps when `stale.length === existing.length`, so a split page is embedded correctly but never stamped — without the reconcile a >1-batch brain reports "incomplete" and the re-run re-invalidates and re-pays for those pages). Sound only because apply() invalidated everything not already in the target space; pages with a remaining NULL chunk stay unstamped so a real embed failure still surfaces. Invalidation is ordered BEFORE the config writes so a crash on a same-dim swap leaves rows merely stale (empty results) rather than new-space queries scored against old-space vectors (silently wrong). Pinned by `test/embedding-migration.test.ts` (PGLite) + `test/e2e/migrate-embeddings-postgres.test.ts` (real pgvector).
-- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`, the command README/doctor promised since v0.36). Flow: plan → render (stderr when `--json` so stdout stays JSON-clean) → consent gate (TTY y/N prompt or `--yes`; non-TTY without `--yes` refuses exit 2, mirroring the reindex-code cost gate) → live probe (one embed against the TARGET model/dims BEFORE any mutation — bad key/model/dim fails with nothing changed) → `applyEmbeddingMigration` with `persistEmbeddingFileConfig` (writes `~/.gbrain/config.json` + reconfigures the in-process gateway — the gateway reads file/env, NOT the DB plane) → `runEmbedCore({stale, catchUp, singleFlight, includeNullSignature, pace})` → drain check → `completeEmbeddingMigration` or exit 1 with the resume hint (re-run the same command). When the re-embed was skipped because another backfill holds the per-source single-flight lock (`EmbedResult.lock_skipped` — the state a hard-killed run leaves behind for up to the 60-min lock TTL), the exit-1 message says so instead of misreporting embed failures, since an immediate re-run cannot resume until the lock expires. Also surfaced as the `migrate_embeddings` op (scope admin, localOnly, hidden cliHints; handler hard-refuses `ctx.remote !== false` and returns `needs_confirmation` + plan without `yes: true`). Pinned by `test/migrate-embeddings-flow.serial.test.ts` (full lifecycle incl. interrupted-run resume on PGLite) + `test/provider-sunset-doctor.serial.test.ts` (lock-skip visibility). Discovery surfaces for brains pinned to a sunsetting provider: the `provider_sunset` doctor check (every run; paste-ready command with the ACTUAL column width via `readContentChunksEmbeddingDim`; warn before the date, fail after it ONLY when embedded vectors actually exist on the dead provider — zero-vector brains stay warn so doctor-as-CI-gate keeps exiting 0; reranker exposure resolved via `resolveSearchMode`, the plane search actually reranks with, not the gateway plane; suppress via `doctor.suppress_provider_sunset`; self-host escape hatch given equal billing) and the one-shot `gbrain upgrade` banner (`ze_sunset_notice_shown`, same reranker resolution); the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `src/core/ai/defaults.ts`, and `checkProviderSunset(engine, now?)` takes an injectable clock so tests pin both date branches.
+- `src/core/ze-exposure.ts` — ZeroEntropy sunset exposure detection: the one shared answer to "is this brain still depending on ZeroEntropy?", consumed by the v0.46.3 version migration (`src/commands/migrations/v0_46_3.ts`) and the stage-2 upgrade banner. Standalone module by design — it must survive the September deletion of the ze-switch/retrieval-upgrade subsystem. `detectZeExposure(engine, fileCfg?, env?)` resolves exposure from the EFFECTIVE embedding model (env `GBRAIN_EMBEDDING_MODEL` → file `embedding_model` → the legacy configless runtime fallback — resolution-based, NOT vector evidence, so a configless brain is exposed even with zero vectors), the resolved reranker (through `resolveSearchMode`, the same plane search actually reranks with), and ZE-backed custom `embedding_columns` (file + DB planes). Tri-state `status`: a failed DB probe downgrades to `'unknown'`, never to `'clear'` — callers nag on `'unknown'` (fail-safe). Blast-radius counts (ZE-stamped pages, embedded chunks, est. re-embed cost at the recommended target) are LIMIT-capped at `BLAST_RADIUS_CAP` (100K) so a million-chunk brain can't stall apply-migrations on a full-table COUNT; blast-radius probe failures are informational and never flip status. `renderZeActionRequired(exposure)` renders the shared ACTION REQUIRED body both consumers wrap (migrate command with `--dim 1024` + the 1280-not-a-valid-Voyage-width note, the `voyage:rerank-2.5` reranker fix, the no-automated-custom-column-off-ramp honesty, and the env-override callout when `GBRAIN_EMBEDDING_MODEL` itself forces ZE).
+- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--pace[=mode]] [--ignore-env-override] [--force-sunset-target]` (alias: `gbrain retrieval-upgrade`, the command README/doctor promised since v0.36). `resolveMigrationTarget` refuses a target whose recipe carries `sunset` metadata — a paid full re-embed onto a provider with an announced shutdown would strand the brain; `--force-sunset-target` is the loud escape hatch for self-hosters running a wire-compatible endpoint behind a `provider_base_urls` override. Flow: plan → render (stderr when `--json` so stdout stays JSON-clean) → consent gate (TTY y/N prompt or `--yes`; non-TTY without `--yes` refuses exit 2, mirroring the reindex-code cost gate) → live probe (one embed against the TARGET model/dims BEFORE any mutation — bad key/model/dim fails with nothing changed) → `applyEmbeddingMigration` with `persistEmbeddingFileConfig` (writes `~/.gbrain/config.json` + reconfigures the in-process gateway — the gateway reads file/env, NOT the DB plane) → `runEmbedCore({stale, catchUp, singleFlight, includeNullSignature, pace})` → drain check → `completeEmbeddingMigration` or exit 1 with the resume hint (re-run the same command). When the re-embed was skipped because another backfill holds the per-source single-flight lock (`EmbedResult.lock_skipped` — the state a hard-killed run leaves behind for up to the 60-min lock TTL), the exit-1 message says so instead of misreporting embed failures, since an immediate re-run cannot resume until the lock expires. Also surfaced as the `migrate_embeddings` op (scope admin, localOnly, hidden cliHints; handler hard-refuses `ctx.remote !== false` and returns `needs_confirmation` + plan without `yes: true`). Pinned by `test/migrate-embeddings-flow.serial.test.ts` (full lifecycle incl. interrupted-run resume on PGLite) + `test/provider-sunset-doctor.serial.test.ts` (lock-skip visibility). Discovery surfaces for brains pinned to a sunsetting provider: the `provider_sunset` doctor check (every run; TARGET-AWARE paste-ready commands — the Voyage target at its valid 1024 width, noting when the brain's actual width via `readContentChunksEmbeddingDim` isn't valid there, plus the OpenAI keep-width alternative when the width is ≤1536; warn before the date, fail after it ONLY when embedded vectors actually exist on the dead provider — zero-vector brains stay warn so doctor-as-CI-gate keeps exiting 0; reranker exposure resolved via `resolveSearchMode`, the plane search actually reranks with, not the gateway plane; ZE-backed custom `embedding_columns` entries flagged via `detectZeCustomColumns` — no automated off-ramp, the message points at the playbook; suppress via `doctor.suppress_provider_sunset`, registered in `KNOWN_CONFIG_KEYS`; self-host escape hatch given equal billing) and the one-shot `gbrain upgrade` banner (`ze_sunset_notice_shown`, same reranker resolution); the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `src/core/ai/defaults.ts`, and `checkProviderSunset(engine, now?)` takes an injectable clock so tests pin both date branches.
+- `src/commands/ze-switch.ts` — the legacy ZeroEntropy switch command, now a refusal surface: the forward path (switching a brain ONTO ZeroEntropy, including resuming a half-applied switch) refuses with exit 1 and `reason: 'provider_sunset'`, printing the off-ramp (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run`); only `--undo` (moves a brain OFF ZE — restores prior model + dim + reranker; `--non-interactive` requires `--confirm-reembed` because undo re-embeds at the prior width) and `--dry-run` (read-only plan) still run. The whole command is deleted in the September removal release.
- `src/core/conversation-parser/` — 17-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (17 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); and **`--background` via `maybeBackground`**. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, closing the "terminal audit row written after partial insertFacts failure" class. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`.
@@ -292,6 +295,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `put_page` not `capture` since `capture` is CLI-only, not an MCP tool) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing an inline `bearer_token` managed block because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name)}` — binary-generic so `claude` and `codex` share the path; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all four agents) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set and that `capture` is NOT advertised) + `test/serve-skills-publish-nudge.test.ts` (the `test/audit/batch-retry-audit.test.ts` ENOENT case was made hermetic — it had read the real `~/.gbrain/audit`).
- `src/commands/upgrade.ts` — self-update CLI. `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally.
- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators no longer call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in the `MIGRATIONS` array in `src/core/migrate.ts`. `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (running in-process removes the spawn that died with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
+- `src/commands/migrations/v0_46_3.ts` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.
- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (pre-subagent-era brains), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Fixes the double-encode bug on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.
- `src/commands/orphans.ts` — `gbrain orphans [--json] [--count] [--include-pseudo] [--source <id>]`: surfaces pages with zero inbound wikilinks, grouped by domain (auto-generated/raw/pseudo filtered by default). Also exposed as `find_orphans` MCP op. `findOrphans`/`getOrphansData` (the canonical pure fn shared with doctor's `orphan_ratio`) takes `{ sourceId?, sourceIds? }`; `BrainEngine.findOrphanPages(opts?)` (both engines) scopes ONLY the candidate side (`p.source_id = $1` scalar, or `= ANY($1::text[])` federated) while still counting inbound links from ANY source — a page in source X linked FROM source Y is reachable, so NOT an orphan of X (deliberate definition; the stricter intra-source-only reading is rejected). `--source` is an explicit raw-flag parse (NOT `resolveSourceWithTier`, which would scope bare invocations to a default). The `total_linkable` denominator enumerates ALL live pages (scoped) and subtracts every excluded-by-slug page (templates/, scratch/, etc.) so excluded NON-orphan pages with inbound links don't inflate it and suppress warnings. The `find_orphans` MCP op threads `sourceScopeOpts(ctx)` so a source-bound OAuth client doesn't see brain-wide orphans. `gbrain doctor --source <id>` scopes `orphan_ratio` and, under explicit `--source` below 100 entity pages, reports the ratio with a low-scale caveat (thin-client `doctor --source` orphan_ratio remains brain-wide — TODO). Pinned by `test/orphans-source-scope.test.ts` (PGLite) + `test/e2e/engine-parity.test.ts` (Postgres↔PGLite scalar + federated parity). Contributed by @knee5.
- `src/commands/salience.ts` — `gbrain salience [--days N] [--limit N] [--kind PREFIX] [--json]`: pages ranked by emotional + activity salience over a recency window. Mirrors orphans.ts shape (pure data fn + JSON formatter + human formatter). Calls `engine.getRecentSalience(opts)`. Score formula: `(emotional_weight × 5) + ln(1 + active_take_count) + 1/(1 + days_since_update)`.
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 2fe2922e53..7a31743b16 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -44,13 +44,13 @@ Three regexes, zero LLM tokens, single SQL `addLinksBatch` call with `INSERT ...
Heuristic link-type inference (`attended`, `works_at`, `invested_in`, `founded`, `advises`) fires from surrounding sentence context — also LLM-free. Power users who want richer types add them via the typed-link blockquote convention.
-## ZeroEntropy as reranker: 60% top-1 reshuffle
+## Cross-encoder reranker: 60% top-1 reshuffle
-ZeroEntropy's `zerank-2` is the default reranker (on for the `balanced` and `tokenmax` mode bundles, off for `conservative`). On a real-corpus benchmark across 20 queries, zerank-2 reshuffles **60% of top-1 results** after the hybrid + RRF + graph stack. That's the headline number.
+The reranker is on for the `balanced` and `tokenmax` mode bundles, off for `conservative`. New installs with a Voyage key get `rerank-2.5` written as explicit `search.reranker.model` config (the recommended reranker; same `VOYAGE_API_KEY` as embeddings — keyed installs without one get reranking explicitly disabled instead); brains that never set the key still fall back to the legacy ZeroEntropy `zerank-2` mode-bundle default, which is deprecated (the hosted API ends 2026-09-04 — switch with `gbrain config set search.reranker.model voyage:rerank-2.5`) and remains the fallback only until the September cutover. On a real-corpus benchmark across 20 queries, zerank-2 reshuffles **60% of top-1 results** after the hybrid + RRF + graph stack. That's the headline number.
The mechanical reason: hybrid ranking is locally optimal per strategy but globally suboptimal. A cross-encoder reranker reads the query + each candidate document jointly, with full attention. It catches the cases where the vector + keyword + graph signals all agreed on a document that's semantically related but topically wrong.
-The cost: +150ms p50 latency, ~$0.025/M tokens. Disabled with `gbrain config set search.reranker.enabled false`. For agent loops that do downstream LLM work after retrieval, the latency is invisible.
+The cost: +150ms p50 latency, ~$0.025–0.05/M tokens depending on the reranker. Disabled with `gbrain config set search.reranker.enabled false`. For agent loops that do downstream LLM work after retrieval, the latency is invisible.
## Source-aware ranking
@@ -150,7 +150,7 @@ graph augment (optional two-pass structural expansion — walkDepth > 0)
deduplication (4-layer: per-page cap, Jaccard, type diversity)
│
▼
-reranker (zerank-2 cross-encoder — balanced/tokenmax; fail-open)
+reranker (cross-encoder — balanced/tokenmax; fail-open)
│
▼
alias hop (exact alias match injects/boosts the canonical page)
diff --git a/docs/designs/2026_05_EVAL_PLAN.md b/docs/designs/2026_05_EVAL_PLAN.md
index 7d96b1b9d3..55324031b1 100644
--- a/docs/designs/2026_05_EVAL_PLAN.md
+++ b/docs/designs/2026_05_EVAL_PLAN.md
@@ -1,5 +1,7 @@
# Embedder Shootout — May 2026 Eval Plan
+> **Historical note:** this plan predates the ZeroEntropy hosted-API sunset (2026-09-04); the ZeroEntropy cells below are historical.
+
**Status:** approved, ready to execute
**Owner:** Garry
**Plan source:** `~/.claude/plans/system-instruction-you-are-working-linear-origami.md` (review log)
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.md
index 49e08765bd..0323b0f720 100644
--- a/docs/embedding-migrations.md
+++ b/docs/embedding-migrations.md
@@ -2,9 +2,9 @@
GBrain stores embeddings in a fixed-dimension `vector(N)` column on
`content_chunks`. If you switch to a model with a different dimension
-(e.g. `openai:text-embedding-3-large` 1536 → `zeroentropyai:zembed-1`
-1280, or `voyage:voyage-4-large` 2048), the on-disk column type doesn't
-change automatically.
+(e.g. `openai:text-embedding-3-large` 1536 → `voyage:voyage-4` 1024, or
+`voyage:voyage-4-large` 2048), the on-disk column type doesn't change
+automatically.
`gbrain init`, `gbrain doctor`, and `gbrain embed --stale` all detect
this mismatch and refuse to silently proceed. This doc is the recipe
@@ -63,8 +63,8 @@ single-command wrapper:
```bash
gbrain reinit-pglite \
- --embedding-model zeroentropyai:zembed-1 \
- --embedding-dimensions 1280
+ --embedding-model voyage:voyage-4 \
+ --embedding-dimensions 1024
```
This backs up the existing brain to `<path>.bak`, runs `gbrain init`
@@ -84,8 +84,8 @@ mv ~/.gbrain/brain.pglite ~/.gbrain/brain.pglite.bak
# every other field in ~/.gbrain/config.json (chat model,
# expansion model, API keys).
gbrain init --pglite \
- --embedding-model zeroentropyai:zembed-1 \
- --embedding-dimensions 1280
+ --embedding-model voyage:voyage-4 \
+ --embedding-dimensions 1024
# 3. Re-import your brain repo. `gbrain sync` reads the brain repo
# from disk and re-creates the page rows.
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index fac2a0ed49..f1456871e1 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -3,9 +3,9 @@
`gbrain migrate embeddings` re-embeds an entire brain onto a different
embedding provider/model, safely and resumably. It is the forward path off a
sunsetting provider (for example ZeroEntropy's hosted API, which shuts down
-2026-09-04 and is the shipped default for brains that never picked a model) —
-but it is provider-agnostic: any configured `provider:model` works as a
-target.
+2026-09-04 and remains the configless runtime fallback for existing brains
+that never picked a model — new installs default to `voyage:voyage-4`) — but
+it is provider-agnostic: any configured `provider:model` works as a target.
Also reachable as `gbrain retrieval-upgrade` — the alias that `gbrain doctor`
repair hints and the README point at.
@@ -14,32 +14,58 @@ repair hints and the README point at.
```bash
# Preview the work + cost. Changes nothing.
-gbrain migrate embeddings --to openai:text-embedding-3-small --dry-run
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run
# Run it (interactive confirm shows chunk count + $ estimate first).
-gbrain migrate embeddings --to openai:text-embedding-3-small
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024
# Non-interactive (cron / scripts): --yes is required, else exit 2.
-gbrain migrate embeddings --to voyage:voyage-3-large --yes
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
```
`--dim <N>` overrides the target width; it defaults to the provider recipe's
declared width and is required for recipes that don't declare one (litellm,
llama-server, and other bring-your-own-model providers).
+Targets on a provider with an announced shutdown are refused (a paid re-embed
+onto a dying API would strand the brain). Self-hosting a wire-compatible
+endpoint behind a `provider_base_urls` override? `--force-sunset-target` is
+the explicit escape hatch.
+
+## Recommended targets
+
+- **`voyage:voyage-4 --dim 1024`** (the new-install default). One
+ `VOYAGE_API_KEY` covers embedding, the `rerank-2.5` reranker, and the
+ multimodal model; the voyage-4 family shares one embedding space, so you
+ can later point the query model at `voyage-4-large` or `voyage-4-lite`
+ without reindexing. Note: **1280 is not a valid Voyage width** (valid:
+ 256/512/1024/2048), so a legacy 1280d brain gets a one-time schema/HNSW
+ index rebuild to 1024 — the command handles it, and it is resumable if
+ killed.
+- **`openai:text-embedding-3-small --dim 1280`** — the keep-your-width
+ alternative: OpenAI's text-embedding-3 models support flexible dims, so a
+ 1280d brain keeps its column (no schema rebuild). No reranker coverage on
+ the OpenAI key.
+
+Set the target's API key via `export VOYAGE_API_KEY=...` (or edit
+`~/.gbrain/config.json` directly) — do NOT use `gbrain config set
+voyage_api_key`: that writes the DB plane, which the embedding pipeline never
+reads.
+
**Pick `--dim` = your brain's current column width when the target supports
it.** A different width triggers the destructive schema transition (column +
index rebuild across all three dim-pinned tables); the same width skips it
entirely. `gbrain doctor` (check `provider_sunset`, for providers with an
-announced shutdown) prints the paste-ready command with your actual width
-already filled in — it reads the real `vector(N)` column, not the config
-value, which can drift.
+announced shutdown) prints target-aware paste-ready commands — the Voyage
+command at its valid 1024 width, plus an OpenAI keep-width alternative with
+your actual width filled in when that width is valid there — reading the real
+`vector(N)` column, not the config value, which can drift.
## How affected brains find out (provider sunsets)
-Two surfaces flag a brain whose embedding model (or reranker) is on a
-provider with an announced hosted-API shutdown, such as ZeroEntropy
-(2026-09-04):
+Three surfaces flag a brain whose embedding model, reranker, or custom
+embedding columns are on a provider with an announced hosted-API shutdown,
+such as ZeroEntropy (2026-09-04):
- **`gbrain doctor`** — the `provider_sunset` check warns on every run until
the brain is off the provider. After the shutdown date it escalates to
@@ -48,15 +74,25 @@ provider with an announced hosted-API shutdown, such as ZeroEntropy
resolves to the dead default stays `warn`, so doctor-as-CI-gate setups
don't start exiting 1 on the date. The reranker side resolves through the
same plane search actually reranks with (the mode bundle +
- `search.reranker.*` overrides). The message carries the paste-ready
- migration command with the brain's actual `--dim`. Accepted the risk?
+ `search.reranker.*` overrides), and ZE-backed custom `embedding_columns`
+ entries are flagged too. The message carries target-aware paste-ready
+ migration commands (Voyage at 1024; OpenAI keep-width when your width is
+ valid there). Accepted the risk?
`gbrain config set doctor.suppress_provider_sunset true` silences it.
- **`gbrain upgrade`** — a one-shot banner (gated by
- `ze_sunset_notice_shown`) with the same two fixes.
-
-Both state the full consequence: after the shutdown, **existing vectors
-become unqueryable** — query embedding uses the same endpoint as ingestion —
-not just new content.
+ `ze_sunset_notice_shown`) with the same two fixes, plus a stage-2 banner
+ per brain.
+- **The v0.46.3 version migration** (runs via `gbrain upgrade` /
+ `gbrain apply-migrations`) — detect-and-notify only: it checks the host
+ brain's exposure (embedding, reranker, custom columns), prints the ACTION
+ REQUIRED block, and files an agent action item pointing at
+ `skills/migrations/v0.46.3.0.md` in
+ `~/.gbrain/migrations/pending-host-work.jsonl`. It never changes config or
+ spends money on your behalf.
+
+All of them state the full consequence: after the shutdown, **existing
+vectors become unqueryable** — query embedding uses the same endpoint as
+ingestion — not just new content.
## What it does, in order
@@ -162,14 +198,32 @@ vector spaces in one index, degrading retrieval with nothing in the logs.
## Reranker
Migrating embeddings does not touch the reranker. If
-`search.reranker.model` points at the outgoing provider, the plan prints a
-warning; disable it (`gbrain config set search.reranker.enabled false`) or
-point it at another provider.
+`search.reranker.model` (or the mode-bundle fallback) resolves to the
+outgoing provider, the plan prints a warning; point it at the recommended
+replacement — `gbrain config set search.reranker.model voyage:rerank-2.5`
+(needs `VOYAGE_API_KEY`) — or disable it
+(`gbrain config set search.reranker.enabled false`).
+
+## Custom embedding columns
+
+There is **no automated off-ramp for custom `embedding_columns` entries**:
+`migrate embeddings` covers the primary column only. Re-declare each custom
+column's config on the new provider and re-embed its content, or drop the
+column config.
## Self-hosting instead of migrating
If the outgoing model's weights are available (zembed-1's are Apache-2.0),
-serving them locally via `llama-server` / `ollama` / a LiteLLM proxy
-preserves your existing vectors — no re-embed at all. Point
-`embedding_model` at the local recipe and keep the same dimensions. The
+self-hosting preserves your existing vectors — no re-embed at all — but only
+when the embedding signature doesn't change: keep the SAME model id
+(`zeroentropyai:zembed-1`) and point its base URL at your endpoint with
+`gbrain config set provider_base_urls.zeroentropyai <url>`. The endpoint
+must speak ZeroEntropy's wire dialect (`/models/embed`,
+`{results: [...]}` responses) — the model id routes through a ZE-specific
+compat fetch, so a generic OpenAI-compatible `llama-server` or Ollama
+endpoint will NOT work without a compat proxy in front. Switching the
+provider id instead (e.g. `llama-server:zembed-1`) changes
+`pages.embedding_signature`, and the next stale-embed pass re-embeds
+everything — a full re-embed, not a zero-cost move. This path survives only
+until the September removal release deletes the `zeroentropyai` recipe. The
migration command is for when you'd rather move to a hosted provider.
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 5aaaac0f86..95d74711d8 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -1,6 +1,6 @@
# Embedding providers
-GBrain ships with 16 embedding-provider recipes covering OpenAI, ZeroEntropy, Voyage, OpenRouter (single key, many hosted models), the major hosted alternatives, three local options, and a universal escape hatch (LiteLLM proxy). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
+GBrain ships with 16 embedding-provider recipes covering Voyage (the default), OpenAI, OpenRouter (single key, many hosted models), the major hosted alternatives, three local options, a universal escape hatch (LiteLLM proxy), and the deprecated ZeroEntropy recipe (hosted API shuts down 2026-09-04). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
This page is the human-readable counterpart: capability per provider, env-var setup, dimensions, cost, and known constraints.
@@ -13,9 +13,9 @@ gbrain providers test --model openai:text-embedding-3-large # smoke-test
gbrain init --pglite --model voyage # use a non-default provider
```
-## Init resolves your provider from env keys
+## Init resolves your provider from your keys
-As of v0.37, `gbrain init --pglite` auto-detects which provider to use from your env vars. With `OPENAI_API_KEY` set, you get OpenAI. With `ZEROENTROPY_API_KEY` set, you get ZeroEntropy. If multiple provider keys are set, init fires an interactive picker. If no provider keys are set in a non-TTY context (CI, Docker build), init exits 1 with a paste-ready setup hint. Explicit flags (`--embedding-model`, `--no-embedding`) always win over env detection.
+`gbrain init --pglite` auto-detects which provider to use from your provider keys — env vars or the file plane (`~/.gbrain/config.json` fields like `voyage_api_key`; env wins when both are set). With `VOYAGE_API_KEY` set, you get Voyage (`voyage:voyage-4` @ 1024d). With `OPENAI_API_KEY` set, you get OpenAI. Whenever a Voyage key is present — even if a different embedding provider is picked — init also writes `search.reranker.model voyage:rerank-2.5` as explicit config (one key covers both); keyed installs without a Voyage key get `search.reranker.enabled false` written instead. If multiple provider keys are set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). ZeroEntropy is deprecated and excluded from both auto-pick and the picker — explicit `--embedding-model zeroentropyai:*` still works, with a loud warning. With no provider keys at all, init continues keyless (keyword-only search) with a loud notice; recover later with `gbrain init --force --embedding-model voyage:voyage-4`. Explicit flags (`--embedding-model`, `--no-embedding`) always win over key detection.
The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atomically, so subsequent runs are deterministic across releases.
@@ -23,10 +23,10 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
| Provider | env vars | default dims | cost ($/1M tokens) | local? | multimodal? |
|---|---|---|---|---|---|
-| `zeroentropyai` (hosted API **shuts down 2026-09-04** — see note below) | `ZEROENTROPY_API_KEY` | 2560 (Matryoshka to 1280/640/320/...) | 0.05 | no | no |
+| `voyage` (**default** — `voyage-4` @ 1024d; `rerank-2.5` reranker on the same key) | `VOYAGE_API_KEY` | 1024 | 0.06 (`voyage-4`) | no | yes (`voyage-multimodal-3`) |
| `openai` | `OPENAI_API_KEY` | 1536 | 0.13 | no | no |
| `openrouter` | `OPENROUTER_API_KEY` | 1536 | 0.02 | no | model-dependent |
-| `voyage` | `VOYAGE_API_KEY` | 1024 | 0.18 | no | yes (`voyage-multimodal-3`) |
+| `zeroentropyai` — **DEPRECATED** (hosted API **shuts down 2026-09-04**; replacement `voyage:voyage-4` — see note below) | `ZEROENTROPY_API_KEY` | 2560 (Matryoshka to 1280/640/320/...) | 0.05 | no | no |
| `google` | `GOOGLE_GENERATIVE_AI_API_KEY` | 768 | 0.025 | no | no |
| `azure-openai` | `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENT` | 1536 | 0.13 | no | no |
| `minimax` | `MINIMAX_API_KEY` | 1536 | 0.07 | no | no |
@@ -42,7 +42,7 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
**Note on local providers.** Ollama and llama-server have no required API key, so they don't show up in env-detection auto-pick. Pick them explicitly with `--embedding-model ollama:<model>` to avoid silently routing to a daemon that may not be running.
-**Note on the ZeroEntropy hosted API.** ZeroEntropy announced (2026-07-24) that its hosted endpoints shut down on **2026-09-04**. A brain still embedding through the hosted API loses semantic retrieval entirely on that date — query embedding uses the same endpoint, so existing vectors become unqueryable, not just new content. Either self-host the Apache-2.0 zembed-1 weights via llama-server/Ollama (keeps every existing vector, no re-embed), or migrate with `gbrain migrate embeddings` — see [the migration guide](../guides/embedding-migration.md). `gbrain doctor` (check `provider_sunset`) flags affected brains and prints the paste-ready command with the brain's actual `--dim` filled in.
+**Note on the ZeroEntropy hosted API.** ZeroEntropy announced (2026-07-24) that its hosted endpoints shut down on **2026-09-04**, and the recipe is deprecated: init auto-pick and the interactive picker exclude it (explicit `--embedding-model zeroentropyai:*` still works, with a loud warning), every ZE embed/rerank call prints a once-per-process deprecation warning, and `gbrain providers` annotates it DEPRECATED. A brain still embedding through the hosted API loses semantic retrieval entirely on that date — query embedding uses the same endpoint, so existing vectors become unqueryable, not just new content. The off-ramp: `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then `--yes`. 1280 is not a valid Voyage width (valid: 256/512/1024/2048), so a 1280d brain gets a one-time schema/HNSW rebuild to 1024; the OpenAI alternative keeps the width (flexible dims): `--to openai:text-embedding-3-small --dim 1280`. See [the migration guide](../guides/embedding-migration.md). Self-hosting the Apache-2.0 zembed-1 weights keeps every existing vector with zero re-embed, but the endpoint must speak ZeroEntropy's wire dialect — a generic OpenAI-compatible llama-server/Ollama will NOT work without a compat proxy (details in [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)). `gbrain doctor` (check `provider_sunset`) flags affected brains — including ZE-backed custom embedding columns — and prints target-aware paste-ready commands (Voyage at 1024; OpenAI keep-width when the brain's actual width is valid there); accepted the risk? `gbrain config set doctor.suppress_provider_sunset true` silences it.
## If first import fails
@@ -64,8 +64,8 @@ The doctor distinguishes two repair paths:
- **Cost-sensitive, English-only**: Ollama (free, local) or Voyage (paid, best quality per dollar).
- **Quality-first**: Voyage `voyage-4-large` (1024-2048 dims, ~3-4× more dense tokens than OpenAI tiktoken).
-- **Code-heavy brain (gstack per-worktree, source repos)**: Voyage `voyage-code-3` (1024 default; supports 256/512/1024/2048). Tuned on programming languages. Voyage publishes head-to-head numbers showing it outperforms their general flagships on code retrieval ([voyageai.com/blog](https://voyageai.com/blog)). For gstack's per-worktree pglite-backed code brain, this is the right default — see Topology 3 in `docs/architecture/topologies.md`.
-- **Reranking pair**: ZeroEntropy `zerank-2` is the hosted default in `tokenmax` mode (see [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)). Voyage `rerank-2.5` pairs cleanly with Voyage embeddings.
+- **Code-heavy brain (gstack per-worktree, source repos)**: Voyage `voyage-code-3` (1024 default; supports 256/512/1024/2048), or the newer `voyage-code-4` (hosted, flexible dims, $0.12/M). Tuned on programming languages. Voyage publishes head-to-head numbers showing it outperforms their general flagships on code retrieval ([voyageai.com/blog](https://voyageai.com/blog)). For gstack's per-worktree pglite-backed code brain, this is the right default — see Topology 3 in `docs/architecture/topologies.md`.
+- **Reranking pair**: Voyage `rerank-2.5` ($0.05/M; `rerank-2.5-lite` at $0.02/M for cost-sensitive setups) is the new-install default and rides the same `VOYAGE_API_KEY` as embeddings. ZeroEntropy `zerank-2` remains the fallback only for brains that never set `search.reranker.model` — deprecated, hosted API ends 2026-09-04 (see [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)).
- **Local reranking (no API spend)**: `llama-server-reranker` recipe (v0.40.6.1) — point gbrain at your own `llama-server --reranking` instance running Qwen3-Reranker or self-hosted ZeroEntropy weights. Same `gateway.rerank()` seam, $0 per call. Walkthrough in [`docs/ai-providers/llama-server-reranker.md`](../ai-providers/llama-server-reranker.md).
- **One key for many hosted models**: OpenRouter. Set `OPENROUTER_API_KEY` and use `openrouter:<provider>/<model>` for chat against GPT-5.2, Claude 4.x, Gemini 3, DeepSeek, and dozens more without juggling per-provider keys. Embedding catalog includes OpenAI, Google, Qwen, BGE-M3.
- **Enterprise compliance**: Azure OpenAI (data residency + private endpoints) or self-hosted via llama-server / Ollama.
@@ -77,15 +77,17 @@ The doctor distinguishes two repair paths:
### OpenAI
-Default. Set `OPENAI_API_KEY`. Models: `text-embedding-3-large` (3072 max, 1536 default), `text-embedding-3-small` (1536). Matryoshka via the `dimensions` field — gbrain pins it from `embedding_dimensions` config so existing 1536-dim brains stay aligned across SDK upgrades.
+The main alternative to the Voyage default (its flexible-dim `text-embedding-3` models can keep an existing column width during a provider migration). Set `OPENAI_API_KEY`. Models: `text-embedding-3-large` (3072 max, 1536 default), `text-embedding-3-small` (1536). Matryoshka via the `dimensions` field — gbrain pins it from `embedding_dimensions` config so existing 1536-dim brains stay aligned across SDK upgrades.
Optional `OPENAI_BASE_URL` — point the native OpenAI provider at an OpenAI-compatible gateway. A bare host is normalized to carry the `/v1` suffix automatically (so `https://gw.example.com` and `https://gw.example.com/v1` both work); when unset, the SDK's default endpoint is untouched. `ANTHROPIC_BASE_URL` gets the same normalization for Anthropic chat/expansion calls.
### Voyage AI
-Best-in-class quality on the Voyage 4 family (Jan 2026 release). Set `VOYAGE_API_KEY`. Models: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-4-nano`, `voyage-3.5`, `voyage-code-3` (code-tuned), `voyage-finance-2`, `voyage-law-2`, `voyage-multimodal-3` (text + image).
+**The default provider** — new installs get `voyage-4` @ 1024d ($0.06/M) plus the `rerank-2.5` reranker on the same key. Best-in-class quality on the Voyage 4 family (Jan 2026 release). Set `VOYAGE_API_KEY`. Models: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-4-nano`, `voyage-code-4` (code-tuned, hosted, flexible dims, $0.12/M), `voyage-3.5`, `voyage-code-3`, `voyage-finance-2`, `voyage-law-2`, `voyage-multimodal-3` (text + image).
-Voyage 4 family shares an embedding space across all variants, so you can index with `voyage-4-large` and query with `voyage-4-lite` without reindexing. Dims: 256, 512, 1024, 2048. **2048 exceeds pgvector's HNSW cap of 2000** — those brains fall back to exact vector scans (still correct, just slower).
+Voyage 4 family shares an embedding space across all variants, so you can index with `voyage-4` and later point the query model at `voyage-4-large` or `voyage-4-lite` without reindexing. Dims: 256, 512, 1024, 2048. **2048 exceeds pgvector's HNSW cap of 2000** — those brains fall back to exact vector scans (still correct, just slower).
+
+Voyage also serves the hosted rerankers `rerank-2.5` ($0.05/M) and `rerank-2.5-lite` ($0.02/M) at `POST /v1/rerank` (prices verified 2026-08-15) — the new-install reranker default, configured via `gbrain config set search.reranker.model voyage:rerank-2.5`.
**For brains that index source code** (gstack's per-worktree pglite-backed code brain — see Topology 3 in `docs/architecture/topologies.md`), prefer `voyage-code-3` over `voyage-4-large`. Voyage tunes it on programming languages and publishes head-to-head numbers vs their general flagships on code retrieval. Configure at install time:
diff --git a/docs/operations/headless-install.md b/docs/operations/headless-install.md
index 9df1df5ec4..eaa6091050 100644
--- a/docs/operations/headless-install.md
+++ b/docs/operations/headless-install.md
@@ -1,6 +1,6 @@
# Headless install: Docker, CI, postinstall
-`gbrain init --pglite` in a non-TTY context (Docker `RUN`, CI step, postinstall hook) exits 1 when no embedding-provider API key is present in the environment. This is a deliberate fail-loud — the alternative is a silent-broken state where init succeeds with a default that doesn't match any real key.
+`gbrain init --pglite` in a non-TTY context (Docker `RUN`, CI step, postinstall hook) with no embedding-provider API key continues **keyless** (keyword-only search) with a loud notice — a first-class supported end state, not an error (Pattern 3 below). Init reads keys from the environment or from `~/.gbrain/config.json` (env wins). Two fail-louds remain: a near-miss env var name (e.g. `OPENAPI_API_KEY`) exits 1 with the corrected spelling instead of being silently ignored, and multiple keys with no canonical candidate exit 1 asking for an explicit `--embedding-model`.
Three patterns work for headless installs. Pick whichever fits your image lifecycle.
@@ -13,23 +13,25 @@ If your CI / Docker pipeline can inject the API key as a build-time env var, set
FROM oven/bun:1 AS builder
# Inject key at build via --build-arg or `--env` from CI.
-ARG OPENAI_API_KEY
-ENV OPENAI_API_KEY=$OPENAI_API_KEY
+ARG VOYAGE_API_KEY
+ENV VOYAGE_API_KEY=$VOYAGE_API_KEY
RUN bun install -g github:garrytan/gbrain#latest-stable
-RUN gbrain init --pglite # auto-picks OpenAI, persists config
+RUN gbrain init --pglite # auto-picks the Voyage default (voyage-4 @ 1024d), persists config
```
```yaml
# GitHub Actions equivalent
- name: Initialize gbrain
env:
- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
run: |
bun install -g github:garrytan/gbrain#latest-stable
gbrain init --pglite
```
+Any provider key works the same way (`OPENAI_API_KEY` → OpenAI, etc.); see [the provider matrix](../integrations/embedding-providers.md).
+
Init writes `~/.gbrain/config.json` with the resolved `embedding_model` + `embedding_dimensions`. Subsequent runs (in the same image / runner) read from that config and don't re-resolve.
## Pattern 2: Provider key only at runtime (deferred-setup)
@@ -44,19 +46,20 @@ RUN bun install -g github:garrytan/gbrain#latest-stable
# width, but no embed callsite will actually run until runtime config.
RUN gbrain init --pglite --no-embedding
-# At container start (entrypoint), provide the real provider:
+# At container start (entrypoint), the runtime env now carries the key —
+# re-init resolves the provider from it (or pin one explicitly with
+# --embedding-model <provider>:<model>):
ENTRYPOINT ["/bin/sh", "-c", "\
- gbrain config set embedding_model openai:text-embedding-3-large \
- && gbrain init --force --pglite \
+ gbrain init --force --pglite \
&& exec gbrain serve"]
```
-The `gbrain init --no-embedding` opt-in writes `embedding_disabled: true` to config. Every embed callsite (`gbrain import`, `gbrain embed`, the `runEmbedCore` library entry point) checks this and refuses cleanly with a `gbrain config set embedding_model <id>` hint rather than proceeding with a silent default.
+The `gbrain init --no-embedding` opt-in writes `embedding_disabled: true` to config. Every embed callsite (`gbrain import`, `gbrain embed`, the `runEmbedCore` library entry point) checks this and refuses cleanly with a re-init hint (`gbrain init --force --embedding-model voyage:voyage-4`) rather than proceeding with a silent default. (`gbrain config set embedding_model` is refused by design — it's a file-plane schema-sizing field the DB-plane command can't affect.)
The runtime `gbrain init --force` re-runs the init flow against the now-populated env, which:
-- Removes `embedding_disabled` from config.
-- Resolves the provider via env detection.
+- Removes `embedding_disabled` from config (an explicit `--embedding-model` flag also clears it).
+- Resolves the provider via key detection (env vars or `~/.gbrain/config.json`).
- Re-templates the PGLite schema if dim differs from the build-time default.
## Pattern 3: No key, ever (keyless mode)
@@ -73,15 +76,16 @@ RUN gbrain init --pglite --no-embedding # keyless install — done; no runtime
Since every embedding cost gate is structurally moot with no key, none of `docs/operations/spend-controls.md` applies until you add one.
-## What WON'T work
+## What changed from older releases
```dockerfile
-# Don't do this — silent default leaves you with vector(1280) ZE column
-# and 1536d OpenAI provider at runtime, mismatched.
-RUN gbrain init --pglite
+# On older gbrain releases this persisted a silent provider default that
+# mismatched the runtime key (a legacy-width column with a different-width
+# provider at runtime).
+RUN gbrain init --pglite # no keys in the build env
```
-If an older image used this pattern, `gbrain doctor` will surface the mismatch on first run after upgrade and print a paste-ready repair command — `gbrain init --force --pglite --embedding-model <model> --embedding-dimensions <dims>` for brains with no embeddings yet, `gbrain migrate embeddings --to <model> --dim <dims>` for non-empty brains.
+It now continues keyless — the same end state as Pattern 3 — and recovery is Pattern 2's runtime `gbrain init --force`. If an older image shipped the mismatched shape, `gbrain doctor` will surface the mismatch on first run after upgrade and print a paste-ready repair command — `gbrain init --force --pglite --embedding-model <model> --embedding-dimensions <dims>` for brains with no embeddings yet, `gbrain migrate embeddings --to <model> --dim <dims>` for non-empty brains.
## Verifying a headless install
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index dd7a1a7da3..fb9a47d01d 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -493,9 +493,9 @@ OAuth source scoping only guards the HTTP MCP path. If the brain's Postgres and
## Part 13: Cost and speed expectations
-Real numbers from the published benchmark, running the default stack (GBrain with ZeroEntropy for embedding + reranker):
+Real numbers from the published benchmark. The benchmark ran the then-default ZeroEntropy stack (now deprecated — its hosted API ends 2026-09-04); the current default is Voyage `voyage-4` + `rerank-2.5`, in the same price and latency class:
-- **Embedding cost:** $0.05 per million tokens. For comparison, GBrain configured with OpenAI is $0.13 (2.6× more expensive), Voyage is $0.18 (3.6× more).
+- **Embedding cost:** the current default (`voyage:voyage-4`) is $0.06 per million tokens; the benchmark's ZeroEntropy stack was $0.05. For comparison, GBrain configured with OpenAI is $0.13.
- **Ingest speed:** about 22 seconds for a small test corpus of 164 pages on the host machine. For a 10K-page corpus, expect about 20 minutes the first time, then most syncs are incremental and finish in seconds.
- **Query latency:** about 122 ms median for a `gbrain search`. For comparison, the same query through GBrain with OpenAI takes about 282 ms.
- **Synthesized-answer latency:** a few seconds, dominated by the Anthropic API.
@@ -503,7 +503,7 @@ Real numbers from the published benchmark, running the default stack (GBrain wit
Full methodology and per-run receipt JSONs live in [the gbrain-evals repo](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-05-23-v0.40.6.0-snapshot.md).
-For a 25-person company at sustained use, expect about $35 a month in embeddings (ZeroEntropy at $0.05/million tokens), $50 a month in Anthropic calls for the synthesized-answer queries, plus your hosting bill. Under $100 a month for the AI side at most companies your size.
+For a 25-person company at sustained use, expect about $40 a month in embeddings (the default `voyage-4` at $0.06/million tokens), $50 a month in Anthropic calls for the synthesized-answer queries, plus your hosting bill. Under $100 a month for the AI side at most companies your size.
---
@@ -515,7 +515,7 @@ Check `gbrain auth list` on the host and confirm their client has `--source` set
### "Sync is slow and feels stuck"
-The first sync embeds every page, which takes time. Check `gbrain sources status` for the live page count. If it's climbing you're not stuck, you're just embedding. If you've got a 10K-page corpus and ZeroEntropy is being throttled, the per-source parallel sync looks like progress on three sources at once rather than one source moving fast.
+The first sync embeds every page, which takes time. Check `gbrain sources status` for the live page count. If it's climbing you're not stuck, you're just embedding. If you've got a 10K-page corpus and your embedding provider is throttling you, the per-source parallel sync looks like progress on three sources at once rather than one source moving fast.
### "I see a page I shouldn't see"
diff --git a/docs/tutorials/personal-brain.md b/docs/tutorials/personal-brain.md
index a88e16ff22..3445f7325c 100644
--- a/docs/tutorials/personal-brain.md
+++ b/docs/tutorials/personal-brain.md
@@ -106,8 +106,7 @@ In the AlphaClaw UI (Providers tab):
- **OpenAI API Key.** Required for embeddings if you use the OpenAI provider.
- **Anthropic API Key.** Required for Claude (the main model the agent talks through).
- **Perplexity API Key.** Optional, for web search.
-- **Voyage API Key.** Optional, alternative to OpenAI for embeddings.
-- **ZeroEntropy API Key.** Recommended. GBrain ships with ZeroEntropy as the default embedder + reranker because it's about 2× faster than OpenAI and about 2.6× cheaper.
+- **Voyage API Key.** Recommended. GBrain ships with Voyage as the default embedder + reranker (`voyage-4` + `rerank-2.5`) — one key covers both, at about half OpenAI's embedding price.
You can use the same keys across multiple agents.
@@ -236,7 +235,7 @@ Brains share through git. My main agent can populate another agent's brain by pu
|-----------|-------------|
| Render Pro (minimum viable) | about $85 |
| Supabase (small) | free to $25 |
-| OpenAI API (embeddings) | $5 to $20 (much less if you use ZeroEntropy as the default) |
+| OpenAI API (embeddings) | $5 to $20 (about half that on the default Voyage stack) |
| Anthropic API (Claude) | $50 to $500 (usage dependent) |
| **Total minimum** | **about $100 to $150 a month** |
diff --git a/llms-full.txt b/llms-full.txt
index 48ef09b2be..715c4e0435 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1075,19 +1075,22 @@ restart the shell or add the PATH export to the shell profile.
## Step 2: API Keys
-Ask the user for these. gbrain defaults to the ZeroEntropy embedding + reranker stack
-(as of v0.36.2.0); OpenAI/Voyage are still supported as fallbacks via `gbrain config
-set embedding_model <provider:model>`.
+Ask the user for these. gbrain defaults to the Voyage embedding + reranker stack
+(`voyage:voyage-4` @ 1024d + `voyage:rerank-2.5` — one key covers both); OpenAI is the
+main alternative, chosen at init via `--embedding-model <provider:model>`. ZeroEntropy
+is deprecated (its hosted API shuts down 2026-09-04): init auto-pick and the picker
+exclude it, and every ZE embed/rerank prints a deprecation warning.
```bash
-export ZEROENTROPY_API_KEY=ze-... # default embedding + reranker (v0.36.2.0+)
-export OPENAI_API_KEY=sk-... # fallback for vector search; also used for chat models
+export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
+export OPENAI_API_KEY=sk-... # alternative for vector search; also used for chat models
export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search quality via query expansion
```
-Save to shell profile or `.env`. Keys are picked up by `gbrain config set` automatically
-or can be stored in `~/.gbrain/config.json` (file plane). Without any embedding provider,
-keyword search still works. Without Anthropic, search works but skips query expansion.
+Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). Do
+NOT use `gbrain config set` for API keys — it writes the DB plane, which the embedding
+pipeline never reads. Without any embedding provider, keyword search still works.
+Without Anthropic, search works but skips query expansion.
## Step 3: Create the Brain
@@ -1917,7 +1920,7 @@ The whole loop is described in [`docs/architecture/topologies.md`](docs/architec
## Capabilities
-**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The ZeroEntropy reranker is on in `balanced` and `tokenmax`, off in `conservative`. Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page.
+**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The cross-encoder reranker is on in `balanced` and `tokenmax`, off in `conservative` — new installs get Voyage `rerank-2.5`; brains that never set `search.reranker.model` still fall back to the deprecated ZeroEntropy `zerank-2` (hosted API ends 2026-09-04) until the September cutover. Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page.
**Self-wiring knowledge graph.** Every `put_page` extracts entity refs from markdown/wikilinks/typed-link syntax and writes edges with zero LLM calls. Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. The graph is what produces the +31.4 P@5 lift over vector-only RAG. **Obsidian-style vaults:** bare `[[note-name]]` wikilinks that point across folders — you wrote `[[struktura]]` but the page lives at `projects/struktura.md` — resolve by basename once you opt in with `gbrain config set link_resolution.global_basename true`. Off by default; `gbrain doctor` tells you how many edges you'd gain before you flip it. See [migrating an Obsidian vault](INSTALL_FOR_AGENTS.md#step-45-wire-the-knowledge-graph).
@@ -1955,8 +1958,8 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).
- **Email + calendar**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
-- **Embedding providers**: a dozen providers covered — OpenAI (default fallback), OpenRouter, Voyage, ZeroEntropy (default), Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: ZeroEntropy `zerank-2` hosted (the default; on in `balanced` and `tokenmax` modes) plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted ZeroEntropy weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the new-install default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; still the fallback for brains that never set `search.reranker.model`), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential gateway**: vault-aware secret distribution. [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
@@ -1974,7 +1977,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain now repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](docs/ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](docs/INSTALL.md#pglite-crashes-on-macos-26x-tahoe).
-**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys in your environment: set `OPENAI_API_KEY` (or `ZEROENTROPY_API_KEY` / `VOYAGE_API_KEY`) before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker. In non-TTY contexts (CI, Docker) with no keys, init exits 1 with a paste-ready setup hint; pass `--no-embedding` to defer setup until runtime. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
**Hourly cron sync keeps timing out on a federated brain?** Switch your
cron to a per-source loop with shell `timeout(1)` doing the OS-level kill
@@ -2120,7 +2123,7 @@ MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production
Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that ships as the default. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
+Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that shipped as the default from v0.36 through v0.46. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
---
diff --git a/llms.txt b/llms.txt
index 442f7b676f..112ed74cb6 100644
--- a/llms.txt
+++ b/llms.txt
@@ -31,7 +31,7 @@ Repo: https://github.com/garrytan/gbrain
## AI providers
-- [docs/ai-providers/zeroentropy.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/zeroentropy.md): ZeroEntropy zembed-1 embedding + zerank-2 reranker (hosted): API key, embedding switch, reranker config.
+- [docs/ai-providers/zeroentropy.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/zeroentropy.md): ZeroEntropy zembed-1 embedding + zerank-2 reranker (hosted): API key, embedding switch, reranker config. (deprecated; hosted sunset 2026-09-04)
- [docs/ai-providers/llama-server-reranker.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/llama-server-reranker.md): Local reranker via llama.cpp --reranking: Qwen3-Reranker or self-hosted ZE weights, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.
## Debugging
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index f886badb82..b05dfd7ee6 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.2.0",
+ "version": "0.46.3.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 4b199e8bb8..b2517ca65d 100644
--- a/package.json
+++ b/package.json
@@ -157,7 +157,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.2.0",
+ "version": "0.46.3.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index 84fb078a66..87f2c87d23 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -157,7 +157,11 @@ done
# Step 3: smoke-test run-e2e.sh argv + shard handling.
echo "[ci-local] Smoke: run-e2e.sh argv + shard..."
SMOKE_NO_ARGS=$(bash scripts/run-e2e.sh --dry-run-list | wc -l | tr -d ' ')
-EXPECTED_ALL=$(ls test/e2e/*.test.ts | wc -l | tr -d ' ')
+# run-e2e.sh's no-arg list is the test/e2e glob PLUS phantom-redirect-engine-
+# parity (lives in test/; its Postgres arm is only reachable through this
+# DATABASE_URL-bearing lane — see the comment in run-e2e.sh). Mirror that +1
+# here or the smoke check fails on every tree where the counts drift.
+EXPECTED_ALL=$(( $(ls test/e2e/*.test.ts | wc -l | tr -d ' ') + 1 ))
if [ "$SMOKE_NO_ARGS" != "$EXPECTED_ALL" ]; then
echo "[ci-local] ERROR: --dry-run-list (no args) printed $SMOKE_NO_ARGS, expected $EXPECTED_ALL" >&2
exit 1
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index b1c4fa9f46..15cb3b2a88 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -176,7 +176,7 @@ export const SECTIONS: DocSection[] = [
{
title: "docs/ai-providers/zeroentropy.md",
description:
- "ZeroEntropy zembed-1 embedding + zerank-2 reranker (hosted): API key, embedding switch, reranker config.",
+ "ZeroEntropy zembed-1 embedding + zerank-2 reranker (hosted): API key, embedding switch, reranker config. (deprecated; hosted sunset 2026-09-04)",
path: "docs/ai-providers/zeroentropy.md",
// Setup walkthrough — discoverable in the index, not inlined in the
// single-fetch bundle (keeps llms-full.txt under FULL_SIZE_BUDGET).
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index dfbdca1a66..6221126374 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -26,7 +26,9 @@
"test/ai/rerank.test.ts": 16,
"test/ai/schema-templating.test.ts": 4,
"test/ai/silent-drop-regression.test.ts": 9,
+ "test/ai/sunset-warn.test.ts": 10,
"test/ai/voyage-code-3-recipe.test.ts": 3,
+ "test/ai/voyage-reranker-recipe.test.ts": 3,
"test/ai/zeroentropy-compat-fetch.test.ts": 16,
"test/ai/zeroentropy-recipe.test.ts": 1,
"test/anomalies.test.ts": 1,
@@ -189,6 +191,7 @@
"test/dream.test.ts": 26718,
"test/drift-watch.test.ts": 255,
"test/dry-fix.test.ts": 442,
+ "test/e2e/voyage-rerank-live.test.ts": 1,
"test/edge-extractor.test.ts": 252,
"test/effective-date.test.ts": 6,
"test/embed-backfill-submit.test.ts": 3099,
@@ -397,6 +400,7 @@
"test/migrate.test.ts": 102260,
"test/migration-orchestrator-v0_21_0.test.ts": 7,
"test/migration-orchestrator-v0_31_0.test.ts": 12960,
+ "test/migration-orchestrator-v0_46_3.serial.test.ts": 8000,
"test/migration-resume.test.ts": 9,
"test/migration-v0-29-1.serial.test.ts": 3273,
"test/migrations-cjk-wave.test.ts": 3280,
@@ -708,6 +712,7 @@
"test/worker-shutdown-disconnect.test.ts": 3260,
"test/writer.test.ts": 37365,
"test/yaml-lite.test.ts": 9,
+ "test/ze-exposure.test.ts": 9000,
"test/ze-switch-cli.test.ts": 4227,
"test/zombie-reap.test.ts": 3
}
diff --git a/skills/migrations/v0.46.3.0.md b/skills/migrations/v0.46.3.0.md
new file mode 100644
index 0000000000..7848e25bbe
--- /dev/null
+++ b/skills/migrations/v0.46.3.0.md
@@ -0,0 +1,140 @@
+---
+version: 0.46.3
+feature_pitch:
+ headline: "ZeroEntropy shuts down 2026-09-04 — switch embedding + reranker before then. New default: Voyage."
+ one_liner: "One command migrates the brain: gbrain migrate embeddings --to voyage:voyage-4 --dim 1024"
+ user_action_required: true
+---
+
+# v0.46.3 migration — ZeroEntropy shutdown (ACTION REQUIRED before 2026-09-04)
+
+ZeroEntropy's hosted API — the former default for BOTH embedding (`zembed-1`)
+and reranking (`zerank-2`) — stops working on **2026-09-04**. A brain still
+resolving to `zeroentropyai:*` loses semantic retrieval ENTIRELY on that date
+(existing vectors become unqueryable, not just new content).
+
+**Nothing was changed automatically.** v0.46.3 only detects exposure and files
+this action item. The brain keeps working until the date. The switch itself
+costs money (a one-time re-embed) and needs a target API key, so it is the
+user's/agent's explicit call.
+
+## Agent action — when to run this migration
+
+Run the steps below when the user says anything like:
+
+- "ZeroEntropy" / "zembed" / "zerank" anything
+- "migrate my embeddings" / "switch embedding provider"
+- "search stopped working" / "embedding provider error" (after 2026-09-04)
+- "doctor says provider_sunset" / "gbrain is warning about a provider"
+- after any `gbrain upgrade` that printed the ACTION REQUIRED sunset block
+
+Also proactively surface it when `~/.gbrain/migrations/pending-host-work.jsonl`
+contains a `"migration": "0.46.3"` entry.
+
+## Step 1 — confirm exposure
+
+```bash
+gbrain doctor --json | jq '.checks[] | select(.name=="provider_sunset")'
+```
+
+`warn`/`fail` mentioning zeroentropyai = exposed. `ok` = already migrated
+(nothing to do; remove the pending-host-work entry).
+
+## Step 2 — pick the target by which key exists
+
+**Preferred — Voyage** (`VOYAGE_API_KEY` in env, or `voyage_api_key` in
+`~/.gbrain/config.json`). One key covers embedding + reranking + the
+multimodal model, and voyage-4 is the current hosted retrieval-quality
+leader. To set the key: `export VOYAGE_API_KEY=...` or edit
+`~/.gbrain/config.json` directly — do NOT use `gbrain config set
+voyage_api_key` (that writes the DB plane, which the embedding pipeline never
+reads).
+
+```bash
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run # cost preview — show the user
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
+```
+
+Note: **1280 is not a valid Voyage width** (valid: 256/512/1024/2048), so this
+includes a one-time schema/HNSW index rebuild to 1024. The command handles it;
+it is resumable if killed.
+
+**Alternative — OpenAI** (`OPENAI_API_KEY`). No reranker coverage, but OpenAI
+text-embedding-3 supports flexible widths, so a 1280d brain can keep its
+column (no schema rebuild):
+
+```bash
+gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --dry-run
+gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --yes
+# (or --dim 1536 for the model's native width — costs a schema rebuild)
+```
+
+**Neither key** — get one of the two (Voyage: https://dash.voyageai.com/api-keys),
+or self-host (below).
+
+## Step 3 — reranker
+
+If the doctor/notice flagged the reranker (balanced/tokenmax modes rerank with
+ZE zerank-2 by default until the removal release):
+
+```bash
+gbrain config set search.reranker.model voyage:rerank-2.5 # needs VOYAGE_API_KEY
+# or turn reranking off:
+gbrain config set search.reranker.enabled false
+```
+
+Without either, reranking silently fails open (no rerank, autocut off) after
+the shutdown date — search still works, ordering quality drops.
+
+## Step 4 — custom embedding columns (rare)
+
+If the notice listed ZE-backed `embedding_columns` entries: there is **no
+automated off-ramp** for custom columns yet (`migrate embeddings` covers the
+primary column only). Re-declare the column config on the new provider and
+re-embed its content, or drop the column config. A write-side custom-column
+migration is a filed follow-up (TODOS.md).
+
+## Step 5 — verify
+
+```bash
+gbrain doctor --json | jq '.checks[] | select(.name=="provider_sunset") | .status' # → "ok"
+gbrain search "anything you know is in the brain" # sanity check
+```
+
+Then remove/mark the `0.46.3` entry in
+`~/.gbrain/migrations/pending-host-work.jsonl` as done.
+
+## Self-hosting (zero re-embed, advanced)
+
+zembed-1's weights are Apache-2.0. Keeping vectors WITHOUT re-embedding
+requires keeping the `zeroentropyai:zembed-1` model id (the embedding
+signature must not change) and pointing its base URL at your own endpoint:
+
+```bash
+gbrain config set provider_base_urls.zeroentropyai http://your-host:PORT/v1
+```
+
+Two honest caveats:
+
+1. The endpoint must speak **ZeroEntropy's wire dialect** (`/models/embed`,
+ `{results: [...]}` responses) — a generic OpenAI-compatible llama-server or
+ Ollama endpoint will NOT work; you need a ZE-wire-compatible proxy in front.
+2. This works only until the September removal release deletes the
+ `zeroentropyai` recipe. A self-host continuity decision (possibly a compat
+ mode) is tracked in TODOS.md — if you rely on this path, follow that item.
+
+Switching the provider id instead (e.g. `llama-server:zembed-1`) changes
+`pages.embedding_signature`, and the next stale-embed pass re-embeds
+everything — that path is a full re-embed, not a zero-cost move.
+
+Note: `gbrain migrate embeddings` refuses `--to zeroentropyai:*` by default
+(it protects everyone else from re-embedding onto the dying hosted API). With
+your base-URL override in place, pass `--force-sunset-target` to proceed.
+
+## When NOT to run this migration
+
+- The brain is keyless (`embedding_disabled: true`) with no ZE reranker or
+ custom columns — nothing to migrate.
+- `provider_sunset` already reports `ok` — done; just clear the pending entry.
+- You only mounted someone else's brain: the migration is host-scoped; the
+ brain's owner migrates it (their upgrade banner + doctor nag them).
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 1aaa3da2d7..42fd8f973f 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -127,6 +127,7 @@
"migrations/v0.40.3.0.md": "5f500f8c543c2b6f41778b0bd3beedada68f7284f7933ad8b769322b433a8fe9",
"migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5",
"migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b",
+ "migrations/v0.46.3.0.md": "7762212509ea3f954b31ae4ebb9ee8fc1e497ac021c633fa95631f03a2eaaecc",
"migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 0d10f3258a..0da015e64d 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -1909,7 +1909,7 @@ export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {
return {
name: 'reranker_health',
status: 'warn',
- message: `${authFails.length} reranker auth failure(s) in last 7 days. Fix: verify ZEROENTROPY_API_KEY and run \`gbrain models doctor\`.`,
+ message: `${authFails.length} reranker auth failure(s) in last 7 days. Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run \`gbrain models doctor\`.`,
};
}
@@ -1949,9 +1949,13 @@ export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {
if (unknownFails.length >= 3) {
const setupHint = unknownFails.some((f) => {
const summary = String(f.error_summary ?? '');
- return summary.includes('ZEROENTROPY_API_KEY') || summary.toLowerCase().includes('api key');
+ return (
+ summary.includes('ZEROENTROPY_API_KEY') ||
+ summary.includes('VOYAGE_API_KEY') ||
+ summary.toLowerCase().includes('api key')
+ );
})
- ? ' Fix: verify ZEROENTROPY_API_KEY and run `gbrain models doctor`.'
+ ? " Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run `gbrain models doctor`."
: '';
return {
name: 'reranker_health',
@@ -2748,7 +2752,18 @@ export async function checkProviderSunset(engine: BrainEngine, now: number = Dat
}
const onSunsetEmbedding = model.startsWith('zeroentropyai:');
const onSunsetReranker = !!reranker?.startsWith('zeroentropyai:');
- if (!onSunsetEmbedding && !onSunsetReranker) {
+ // Custom embedding columns can route queries through a ZE-backed model
+ // even when the primary embedding + reranker are clear — without this arm
+ // the check reports ok while those columns die on the date.
+ let zeColumns: string[] = [];
+ try {
+ const { detectZeCustomColumns } = await import('../core/ze-exposure.ts');
+ zeColumns = (await detectZeCustomColumns(engine)).columns;
+ } catch {
+ // Probe failed — make no custom-column claim.
+ }
+ const onSunsetColumns = zeColumns.length > 0;
+ if (!onSunsetEmbedding && !onSunsetReranker && !onSunsetColumns) {
return {
name,
status: 'ok',
@@ -2774,7 +2789,6 @@ export async function checkProviderSunset(engine: BrainEngine, now: number = Dat
} catch {
// Probe failed (fresh/odd brain) — no exposure claim, warn-only.
}
- const dimFlag = dims ? ` --dim ${dims}` : '';
parts.push(
past
? hasVectors
@@ -2782,21 +2796,37 @@ export async function checkProviderSunset(engine: BrainEngine, now: number = Dat
: `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE}. No embedded vectors exist yet, so retrieval is not impacted — but embedding will fail until the config points elsewhere.`
: `embedding_model="${model}": the hosted API shuts down on ${ZEROENTROPY_SUNSET_DATE}. On that date semantic retrieval stops entirely — existing vectors become unqueryable (query embedding uses the same endpoint), not just new content.`,
);
+ // v0.46.3: the paste-ready fix is TARGET-AWARE on dimensions. Voyage's
+ // valid widths are {256, 512, 1024, 2048} — blindly preserving this
+ // brain's actual width (usually 1280) would emit a command Voyage
+ // rejects. OpenAI text-3 supports flexible widths up to its native
+ // size, so the keep-width form is offered only when valid there.
+ const openaiDimFlag = dims && dims <= 1536 ? ` --dim ${dims}` : ' --dim 1536';
+ const openaiKeepsWidth = !!(dims && dims <= 1536);
parts.push(
`Two fixes, either works: ` +
- `[1] self-host the same model — zembed-1 weights are Apache-2.0; serve them via llama-server or Ollama and point the config at the local endpoint. Keeps every existing vector, no re-embed (docs/guides/embedding-migration.md, "Self-hosting instead of migrating"). ` +
- `[2] migrate to another provider (resumable; preview cost first): ` +
- `gbrain migrate embeddings --to <provider:model>${dimFlag} --dry-run` +
- (dims ? ` — keep --dim ${dims} (this brain's actual index width) to avoid a needless schema rebuild when the target supports it.` : ''),
+ `[1] self-host the same model — zembed-1 weights are Apache-2.0; keep the zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible server — the id speaks ZE's /models/embed dialect). Keeps every existing vector, no re-embed (docs/guides/embedding-migration.md). ` +
+ `[2] migrate (resumable; preview cost first): ` +
+ `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` +
+ (dims && dims !== 1024 ? ` (${dims} is not a valid Voyage width — the migration rebuilds the index at 1024)` : '') +
+ `; OpenAI alternative${openaiKeepsWidth ? ` keeps this brain's ${dims}d width` : ''}: ` +
+ `gbrain migrate embeddings --to openai:text-embedding-3-small${openaiDimFlag} --dry-run.`,
);
}
if (onSunsetReranker) {
parts.push(
`The reranker (${reranker}) is on the same provider; after the shutdown search falls back to unreranked ordering. ` +
- `Fix: gbrain config set search.reranker.enabled false, or point search.reranker.model at another provider.`,
+ `Fix: gbrain config set search.reranker.model voyage:rerank-2.5 (needs VOYAGE_API_KEY), or disable: gbrain config set search.reranker.enabled false.`,
+ );
+ }
+ if (onSunsetColumns) {
+ parts.push(
+ `Custom embedding column(s) backed by the shutting-down provider: ${zeColumns.join(', ')}. ` +
+ `No automated off-ramp exists for custom columns yet (migrate embeddings covers the primary column only) — ` +
+ `re-declare them on a new provider and re-embed (skills/migrations/v0.46.3.0.md).`,
);
}
- if (onSunsetEmbedding || onSunsetReranker) {
+ if (onSunsetEmbedding || onSunsetReranker || onSunsetColumns) {
parts.push('Accepted the risk? Silence this check: gbrain config set doctor.suppress_provider_sunset true');
}
// fail = retrieval is ACTUALLY down (past the date AND embedded vectors
@@ -2814,10 +2844,10 @@ export async function checkProviderSunset(engine: BrainEngine, now: number = Dat
* v0.36.0.0 (A5): embedding_width_consistency doctor check.
*
* Cross-checks that `config.embedding_dimensions` matches the actual
- * `vector(N)` width on `content_chunks.embedding`. Drift here means the
- * ze-switch was interrupted mid-flight (schema changed but config write
- * crashed, or vice versa). Surfaces a paste-ready `gbrain ze-switch
- * --resume` hint.
+ * `vector(N)` width on `content_chunks.embedding`. Drift here means an
+ * embedding migration was interrupted mid-flight (schema changed but the
+ * config write crashed, or vice versa). Recovery path: `gbrain migrate
+ * embeddings` (resumable).
*/
export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
try {
diff --git a/src/commands/init-provider-picker.ts b/src/commands/init-provider-picker.ts
index f1a163749c..ad3bdf799e 100644
--- a/src/commands/init-provider-picker.ts
+++ b/src/commands/init-provider-picker.ts
@@ -123,6 +123,12 @@ export async function pickProvider(opts: PickProviderOpts): Promise<PickedProvid
const all = listRecipes();
let ready = readyRecipesForTouchpoint(all, opts.touchpoint, env);
+ // v0.46.3: never OFFER a provider whose hosted API has an announced shutdown
+ // (recipe.sunset) — a fresh install must not be steered onto a dying
+ // provider. Explicit --embedding-model still works (with a loud warning)
+ // until the removal release.
+ ready = ready.filter((r) => !r.sunset);
+
// Probe-gate the ollama daemon: `envReady` treats no-key-required as
// ready, but daemon-up ≠ model-pulled — the exact trap that let a keyless
// Enter "choose" a broken ollama config and continue silently degraded.
@@ -179,7 +185,9 @@ export async function pickProvider(opts: PickProviderOpts): Promise<PickedProvid
label += ` (${tp.default_dims}d)`;
}
if (tp && 'models' in tp && Array.isArray(tp.models) && tp.models.length > 0) {
- label += ` ${tp.models[0]}`;
+ // v0.46.3: show the canonical model (default_model), not array position —
+ // the displayed row must match what a pick actually selects.
+ label += ` ${('default_model' in tp && tp.default_model) || tp.models[0]}`;
}
const hint = localHints.get(r.id);
if (hint) label += ` [${hint}]`;
@@ -215,9 +223,10 @@ export async function pickProvider(opts: PickProviderOpts): Promise<PickedProvid
const tp = picked.touchpoints[opts.touchpoint];
if (!tp) return null;
- // Pick first model in the recipe's list (callers can override via flag).
+ // v0.46.3: pick the recipe's canonical model (default_model), falling back to
+ // array position (callers can override via flag).
const modelId = ('models' in tp && Array.isArray(tp.models) && tp.models.length > 0)
- ? tp.models[0]
+ ? (('default_model' in tp && tp.default_model) || tp.models[0])
: '';
if (!modelId) {
writeStderr(`\nRecipe "${picked.id}" declares no models for ${opts.touchpoint}. Aborting.\n`);
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 78a55f7296..478a4e1e48 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -312,6 +312,13 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
if (verbose) {
out.embedding_model = verbose;
+ // v0.46.3: an EXPLICIT --embedding-model wins over a seeded deferred-setup
+ // sentinel — without this, `gbrain init --force --embedding-model
+ // voyage:voyage-4` on a keyless brain (embedding_disabled persisted) would
+ // silently re-persist embedding_disabled and the documented recovery
+ // command would be a no-op. (--no-embedding is parsed later and still
+ // wins when both flags are passed.)
+ delete out.noEmbedding;
} else if (shorthand) {
const { getRecipe } = await import('../core/ai/recipes/index.ts');
const recipe = getRecipe(shorthand);
@@ -331,15 +338,22 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
);
process.exit(1);
}
- const firstModel = recipe.touchpoints.embedding?.models[0];
- if (!firstModel) {
+ // v0.46.3: the shorthand resolves the recipe's canonical model, not array
+ // position — Voyage lists voyage-4-large first but its canonical default
+ // is voyage-4 (see EmbeddingTouchpoint.default_model).
+ const canonicalModel =
+ recipe.touchpoints.embedding?.default_model ?? recipe.touchpoints.embedding?.models[0];
+ if (!canonicalModel) {
console.error(`Provider ${shorthand} has no embedding models listed. Use --embedding-model provider:model.`);
process.exit(1);
}
- out.embedding_model = `${shorthand}:${firstModel}`;
+ out.embedding_model = `${shorthand}:${canonicalModel}`;
+ // v0.46.3: explicit flag wins over a seeded deferred-setup sentinel (see the
+ // verbose branch above).
+ delete out.noEmbedding;
// #2051: width follows the model actually chosen, not the recipe default.
const { embeddingDimsForModel } = await import('../core/ai/model-resolver.ts');
- out.embedding_dimensions = embeddingDimsForModel(recipe, firstModel);
+ out.embedding_dimensions = embeddingDimsForModel(recipe, canonicalModel);
}
if (dimsArg !== null && !Number.isNaN(dimsArg) && dimsArg > 0) {
@@ -373,6 +387,22 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
}
}
+ // v0.46.3: an explicitly-requested sunset provider (verbose or shorthand form)
+ // is allowed until the removal release, but never silently — warn loudly and
+ // proceed (D3: hide + warn, allow explicit).
+ if (out.embedding_model) {
+ const { getRecipe } = await import('../core/ai/recipes/index.ts');
+ const sunsetRecipe = getRecipe(out.embedding_model.split(':')[0]);
+ if (sunsetRecipe?.sunset) {
+ const rep = sunsetRecipe.sunset.replacement?.embedding;
+ console.error(
+ `WARNING: ${sunsetRecipe.name} stops working on ${sunsetRecipe.sunset.date}. ` +
+ `Proceeding because you asked explicitly${rep ? `, but the recommended provider is ${rep}` : ''}. ` +
+ `Migrate before that date: gbrain migrate embeddings --to ${rep ?? '<provider:model>'} --dry-run`,
+ );
+ }
+ }
+
if (expansion) out.expansion_model = expansion;
if (chat) out.chat_model = chat;
@@ -453,6 +483,10 @@ export async function groupReadyByProvider(
// still picker-selectable explicitly, but silent auto-pick is wrong UX.
const required = r.auth_env?.required ?? [];
if (required.length === 0) continue;
+ // v0.46.3: never auto-pick a provider whose hosted API has an announced
+ // shutdown (recipe.sunset). Explicit --embedding-model still works
+ // (with a loud warning) until the removal release.
+ if (r.sunset) continue;
if (envReady(r, env)) {
ready.push({ recipeId: r.id, recipe: r });
seen.add(r.id);
@@ -501,13 +535,12 @@ function printNoEmbeddingProviderHint(typos: Array<{ userSet: string; suggested:
console.error(' gbrain init --force --pglite --embedding-model <id>)');
console.error('');
console.error('Or set a key for semantic search:');
+ console.error(' export VOYAGE_API_KEY=pa-… # voyage:voyage-4 (1024d) — default');
console.error(' export OPENAI_API_KEY=sk-… # openai:text-embedding-3-large (1536d)');
- console.error(' export ZEROENTROPY_API_KEY=ze-… # zeroentropyai:zembed-1 (2560d, Matryoshka)');
- console.error(' export VOYAGE_API_KEY=pa-… # voyage:voyage-3-large (1024d)');
console.error('Then re-run: gbrain init --pglite');
console.error('');
console.error('Or pick explicitly:');
- console.error(' gbrain init --pglite --embedding-model openai:text-embedding-3-large');
+ console.error(' gbrain init --pglite --embedding-model voyage:voyage-4');
// D13: surface near-miss env vars (e.g. OPENAPI_API_KEY → OPENAI_API_KEY).
if (typos.length > 0) {
console.error('');
@@ -517,6 +550,62 @@ function printNoEmbeddingProviderHint(typos: Array<{ userSet: string; suggested:
}
}
+/**
+ * v0.46.3: voyage-keyed installs (any picked embedding provider) get the
+ * recommended reranker written as EXPLICIT per-brain config — the mode-bundle
+ * reranker default stays on the sunsetting legacy provider until the
+ * September removal (split-default), so without this write a fresh voyage
+ * brain would resolve a reranker whose key it doesn't have; keyed non-voyage
+ * installs get explicit `search.reranker.enabled false` instead, and keyless
+ * installs get no write. Never clobbers an existing explicit choice (re-init
+ * preserves user config). Best-effort: reranking is fail-open, a missed
+ * override degrades to no-rerank, never breaks init. Shared by the PGLite and
+ * Postgres init paths (one edit site for the September bundle flip).
+ */
+async function writeNewInstallRerankerDefault(
+ engine: { getConfig(key: string): Promise<string | null>; setConfig(key: string, value: string): Promise<void> },
+ resolvedModel: string | undefined,
+): Promise<void> {
+ // Deliberate legacy setups keep the legacy bundle reranker (works until the
+ // provider's shutdown; warn-on-use covers it).
+ if (resolvedModel?.startsWith('zeroentropyai:')) return;
+ try {
+ // Never-clobber: an existing explicit reranker model OR enabled override
+ // means the user already decided — leave both keys alone.
+ const [existingModel, existingEnabled] = await Promise.all([
+ engine.getConfig('search.reranker.model'),
+ engine.getConfig('search.reranker.enabled'),
+ ]);
+ if (existingModel || existingEnabled != null) return;
+ // Voyage key on either plane (env or ~/.gbrain/config.json) → point the
+ // reranker at it. Otherwise the bundle default still resolves the legacy
+ // sunset reranker, which this install has no key for and which dies on
+ // 2026-09-04 — disable it explicitly so fresh installs don't inherit a
+ // doomed fail-open (per-search timeout penalty after the shutdown).
+ const hasVoyageKey =
+ !!process.env.VOYAGE_API_KEY || !!loadConfigFileOnly()?.voyage_api_key;
+ if (resolvedModel?.startsWith('voyage:') || hasVoyageKey) {
+ const { NEW_INSTALL_DEFAULT_RERANKER_MODEL } = await import('../core/ai/defaults.ts');
+ await engine.setConfig('search.reranker.model', NEW_INSTALL_DEFAULT_RERANKER_MODEL);
+ console.log(` Reranker: ${NEW_INSTALL_DEFAULT_RERANKER_MODEL} (same VOYAGE_API_KEY)`);
+ } else if (resolvedModel) {
+ // Keyed non-voyage install (e.g. openai): make the no-reranker state
+ // explicit instead of inheriting the legacy sunset bundle default this
+ // brain has no key for. KEYLESS installs deliberately get NO write —
+ // the documented recovery re-init must find virgin reranker config so
+ // its voyage override still lands (never-clobber would block it).
+ await engine.setConfig('search.reranker.enabled', 'false');
+ console.log(
+ ' Reranker: disabled (no VOYAGE_API_KEY — enable later: ' +
+ 'gbrain config set search.reranker.enabled true && ' +
+ 'gbrain config set search.reranker.model voyage:rerank-2.5)',
+ );
+ }
+ } catch {
+ // Cosmetic; never block init.
+ }
+}
+
/** Loud keyless-continue notice for the no-keys default path. The upgrade
* command is `init --force` re-init, NOT `config set embedding_model` — that
* key is a schema-sizing file-plane field that `gbrain config set` refuses
@@ -531,28 +620,43 @@ function printKeylessContinueNotice(): void {
}
async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boolean): Promise<void> {
- const ready = await groupReadyByProvider('embedding');
+ // v0.46.3: provider readiness folds FILE-PLANE keys too (docs explicitly
+ // permit `voyage_api_key` etc. in ~/.gbrain/config.json) — env still wins
+ // via buildGatewayConfig's spread order. Without this, a non-interactive
+ // fresh install keyed only via config.json reported zero providers and
+ // silently persisted keyless mode.
+ const fileCfgForKeys = loadConfigFileOnly();
+ let effectiveEnv: NodeJS.ProcessEnv = process.env;
+ if (fileCfgForKeys) {
+ try {
+ const { buildGatewayConfig } = await import('../core/ai/build-gateway-config.ts');
+ effectiveEnv = buildGatewayConfig(fileCfgForKeys).env as NodeJS.ProcessEnv;
+ } catch {
+ // Fold failure → env-only readiness (pre-v0.46.3 behavior).
+ }
+ }
+ const ready = await groupReadyByProvider('embedding', effectiveEnv);
const isTTY = !nonInteractive && !!process.stdin.isTTY;
if (ready.length === 1) {
const r = ready[0].recipe;
const tp = r.touchpoints.embedding!;
if (Array.isArray(tp.models) && tp.models.length > 0) {
- const model = tp.models[0];
+ // v0.46.3: recipes carry a canonical default_model — array order is
+ // quality-sorted, not recommendation-sorted (Voyage lists voyage-4-large
+ // first; the canonical pick is voyage-4).
+ const model = tp.default_model ?? tp.models[0];
const fullModel = `${r.id}:${model}`;
- // When the resolved provider matches the canonical default model
- // (DEFAULT_EMBEDDING_MODEL), use the gateway's
- // DEFAULT_EMBEDDING_DIMENSIONS instead of the recipe's `default_dims`
- // (which is the recipe's "largest sensible" tier). This keeps
- // fresh-install schema width aligned with the v0.37.11.0 system
- // default — for ZE that means 1280 (the Matryoshka step closest to
- // legacy OpenAI 1536), not the recipe's 2560.
- const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } =
+ // When the resolved provider matches the NEW-INSTALL canonical default
+ // model, use NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS instead of the
+ // recipe's `default_dims` so fresh-install schema width stays aligned
+ // with the system default (1024 for voyage-4).
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_MODEL, NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS } =
await import('../core/ai/defaults.ts');
const { embeddingDimsForModel } = await import('../core/ai/model-resolver.ts');
// #2051: non-canonical models resolve per-model, not recipe-wide.
- const dims = fullModel === DEFAULT_EMBEDDING_MODEL
- ? DEFAULT_EMBEDDING_DIMENSIONS
+ const dims = fullModel === NEW_INSTALL_DEFAULT_EMBEDDING_MODEL
+ ? NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS
: embeddingDimsForModel(r, model);
out.embedding_model = fullModel;
out.embedding_dimensions = dims;
@@ -572,6 +676,66 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
// MEANT to configure a key — completing keyless there would silently bury
// their typo.
if (ready.length === 0) {
+ // v0.46.3: the sunset exclusion must NOT convert a working legacy brain to
+ // keyless. A configless EXISTING brain (config.json has a database but no
+ // embedding_model — it rides the legacy runtime fallback) being re-inited
+ // with only a sunset-provider key would otherwise land in the zero-ready
+ // path and get `embedding_disabled: true` written — disabling semantic
+ // search BEFORE the provider's shutdown. When the brain already depends
+ // on the sunsetting provider and its key is present, keep it (with the
+ // loud warning); FRESH installs still never get steered onto it.
+ const { listRecipes } = await import('../core/ai/recipes/index.ts');
+ const { envReady } = await import('./providers.ts');
+ const sunsetReady = listRecipes().filter(
+ (r) =>
+ r.sunset &&
+ (r.auth_env?.required ?? []).length > 0 &&
+ envReady(r, effectiveEnv) &&
+ (r.touchpoints.embedding?.models?.length ?? 0) > 0,
+ );
+ if (sunsetReady.length > 0) {
+ const fileCfg = fileCfgForKeys;
+ const existingConfiglessBrain =
+ !!fileCfg &&
+ !!(fileCfg.database_path || fileCfg.database_url) &&
+ !fileCfg.embedding_model &&
+ fileCfg.embedding_disabled !== true;
+ if (!existingConfiglessBrain) {
+ // FRESH install with only a sunset-provider key: keyless-continue is
+ // right, but "no keys detected" would be false — name the key we
+ // deliberately ignored and the way out (D3: hide + WARN, not hide
+ // silently).
+ const r = sunsetReady[0];
+ console.error(
+ `NOTE: ${r.auth_env?.required?.[0] ?? r.id} is set, but ${r.name} shuts down on ` +
+ `${r.sunset!.date} — not auto-selecting it for a new brain. ` +
+ `Set VOYAGE_API_KEY (recommended) or force it explicitly: ` +
+ `gbrain init --pglite --embedding-model ${r.id}:${r.touchpoints.embedding!.default_model ?? r.touchpoints.embedding!.models[0]} (not recommended).`,
+ );
+ }
+ if (existingConfiglessBrain) {
+ const r = sunsetReady[0];
+ const tp = r.touchpoints.embedding!;
+ const model = tp.default_model ?? tp.models[0];
+ const fullModel = `${r.id}:${model}`;
+ const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } =
+ await import('../core/ai/defaults.ts');
+ const { embeddingDimsForModel } = await import('../core/ai/model-resolver.ts');
+ // Legacy brains ride the legacy width (their stored vectors live there).
+ const dims = fullModel === DEFAULT_EMBEDDING_MODEL
+ ? DEFAULT_EMBEDDING_DIMENSIONS
+ : embeddingDimsForModel(r, model);
+ out.embedding_model = fullModel;
+ out.embedding_dimensions = dims;
+ console.error(
+ `WARNING: this brain currently embeds via ${r.name}, which stops working on ` +
+ `${r.sunset!.date}. Keeping ${fullModel} (${dims}d) so nothing breaks today — ` +
+ `migrate before that date: gbrain migrate embeddings --to ` +
+ `${r.sunset!.replacement?.embedding ?? '<provider:model>'} --dry-run`,
+ );
+ return;
+ }
+ }
const typos = await findEnvKeyTypos();
if (typos.length > 0) {
printNoEmbeddingProviderHint(typos);
@@ -585,7 +749,7 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
// TTY → picker (local providers like ollama may be selectable); a null
// pick (nothing offered, user skipped, or EOF) continues keyless.
const { pickProvider } = await import('./init-provider-picker.ts');
- const picked = await pickProvider({ touchpoint: 'embedding', env: process.env, isTTY: true });
+ const picked = await pickProvider({ touchpoint: 'embedding', env: effectiveEnv, isTTY: true });
if (!picked) {
printKeylessContinueNotice();
out.noEmbedding = true;
@@ -601,16 +765,16 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
// keys — failing there blocked scripted installs), else fail-loud per D2/D3
// (a genuinely ambiguous set with no canonical candidate stays explicit).
if (!isTTY) {
- const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } =
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_MODEL, NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS } =
await import('../core/ai/defaults.ts');
- const canonicalProvider = DEFAULT_EMBEDDING_MODEL.split(':')[0];
+ const canonicalProvider = NEW_INSTALL_DEFAULT_EMBEDDING_MODEL.split(':')[0];
const canonical = ready.find((p) => p.recipeId === canonicalProvider);
if (canonical) {
- out.embedding_model = DEFAULT_EMBEDDING_MODEL;
- out.embedding_dimensions = DEFAULT_EMBEDDING_DIMENSIONS;
+ out.embedding_model = NEW_INSTALL_DEFAULT_EMBEDDING_MODEL;
+ out.embedding_dimensions = NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS;
console.error(
`Multiple embedding providers env-ready (${ready.map(p => p.recipeId).join(', ')}). ` +
- `Using the default ${DEFAULT_EMBEDDING_MODEL} (${DEFAULT_EMBEDDING_DIMENSIONS}d). ` +
+ `Using the default ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} (${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS}d). ` +
`Override with --embedding-model.`,
);
return;
@@ -620,7 +784,7 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
process.exit(1);
}
const { pickProvider } = await import('./init-provider-picker.ts');
- const picked = await pickProvider({ touchpoint: 'embedding', env: process.env, isTTY: true });
+ const picked = await pickProvider({ touchpoint: 'embedding', env: effectiveEnv, isTTY: true });
if (!picked) {
// The embedding picker offers an explicit "0) none — continue keyless"
// option (and returns null on it). Honor that instead of aborting: a user
@@ -924,8 +1088,8 @@ function printResolvedAIChoice(
console.warn(' export ZEROENTROPY_API_KEY=...');
console.warn(' Or add to ~/.gbrain/config.json:');
console.warn(' "zeroentropy_api_key": "..."');
- console.warn(' Or pick a different provider:');
- console.warn(' gbrain init --pglite --embedding-model openai:text-embedding-3-large --embedding-dimensions 1536');
+ console.warn(' NOTE: ZeroEntropy shuts down 2026-09-04 — prefer the default instead:');
+ console.warn(' gbrain init --pglite --embedding-model voyage:voyage-4');
}
}
}
@@ -953,7 +1117,7 @@ async function initPGLite(opts: {
let resolvedModel: string | undefined;
if (opts.aiOpts?.noEmbedding) {
// D9 deferred-setup mode: skip preflight, no model/dim resolved.
- console.log(` --no-embedding: deferred setup — configure with \`gbrain config set embedding_model <id>\` before import`);
+ console.log(` --no-embedding: deferred setup — enable later with \`gbrain init --force --embedding-model voyage:voyage-4\` (\`config set embedding_model\` is refused by design)`);
} else if (opts.aiOpts?.embedding_model) {
const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
const pre = resolveSchemaEmbeddingDim({
@@ -981,9 +1145,20 @@ async function initPGLite(opts: {
// resolveAIOptions above: CLI flags > env vars > existing file > gateway
// defaults.
const { configureGateway } = await import('../core/ai/gateway.ts');
+ // v0.46.3: keyless fresh installs size the embedding column at the NEW-INSTALL
+ // width (1024), not the legacy configless fallback (1280) — the sizing is an
+ // explicit param here, NOT a rewire of the schema generators' legacy import
+ // (those also run on existing-brain reconnects, where legacy must stay
+ // legacy). Existing keyless brains are unaffected: initSchema never resizes
+ // an existing column, and the Lane B.5 mismatch guard stays off for keyless
+ // (resolvedDim is undefined).
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS: newInstallDims } =
+ await import('../core/ai/defaults.ts');
configureGateway({
embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
- embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
+ embedding_dimensions:
+ resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
+ (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
expansion_model: opts.aiOpts?.expansion_model,
chat_model: opts.aiOpts?.chat_model,
env: { ...process.env },
@@ -1066,6 +1241,8 @@ async function initPGLite(opts: {
}
}
+ await writeNewInstallRerankerDefault(engine, resolvedModel);
+
// v0.37.10.0 T7 (D9) + v0.37.11.0 Lane B.4: atomic embedding-config
// persistence on top of the existing file-plane config (preserves
// user-set fields like zeroentropy_api_key, chat_model, expansion_model).
@@ -1092,6 +1269,14 @@ async function initPGLite(opts: {
// unless explicitly overridden by --schema-pack on re-init.
...(opts.schemaPack ? { schema_pack: opts.schemaPack } : {}),
};
+ // v0.46.3: leaving deferred-setup mode — a resolved (model, dims) tuple must
+ // also CLEAR a stale embedding_disabled sentinel inherited via the
+ // ...existingFile spread, or the documented recovery command
+ // (`init --force --embedding-model ...`) persists a config that still
+ // disables embedding at runtime.
+ if (!opts.aiOpts?.noEmbedding && resolvedModel && resolvedDim) {
+ delete config.embedding_disabled;
+ }
// PR1: new installs publish their skill catalog over MCP by default
// (existing config wins on re-init, so a prior opt-out is preserved).
config.mcp = { publish_skills: true, ...(config.mcp ?? {}) };
@@ -1211,7 +1396,7 @@ async function initPostgres(opts: {
let resolvedDim: number | undefined;
let resolvedModel: string | undefined;
if (opts.aiOpts?.noEmbedding) {
- console.log(` --no-embedding: deferred setup — configure with \`gbrain config set embedding_model <id>\` before import`);
+ console.log(` --no-embedding: deferred setup — enable later with \`gbrain init --force --embedding-model voyage:voyage-4\` (\`config set embedding_model\` is refused by design)`);
} else if (opts.aiOpts?.embedding_model) {
const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
const pre = resolveSchemaEmbeddingDim({
@@ -1231,9 +1416,15 @@ async function initPostgres(opts: {
// T6: unconditional configureGateway BEFORE initSchema.
const { configureGateway } = await import('../core/ai/gateway.ts');
+ // v0.46.3: keyless fresh installs size at the NEW-INSTALL width (see the
+ // PGLite path's comment — same explicit-param rationale).
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS: newInstallDims } =
+ await import('../core/ai/defaults.ts');
configureGateway({
embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
- embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
+ embedding_dimensions:
+ resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
+ (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
expansion_model: opts.aiOpts?.expansion_model,
chat_model: opts.aiOpts?.chat_model,
env: { ...process.env },
@@ -1355,6 +1546,8 @@ async function initPostgres(opts: {
}
}
+ await writeNewInstallRerankerDefault(engine, resolvedModel);
+
// v0.37.10.0 T7 (D9) + v0.37.11.0 Lane B.4 (Postgres mirror): atomic
// embedding-config persistence on top of the existing file-plane config.
// Same precedence + same merge contract as the PGLite path above.
@@ -1375,6 +1568,14 @@ async function initPostgres(opts: {
// v0.42 (T17): same schema_pack default as PGLite path.
...(opts.schemaPack ? { schema_pack: opts.schemaPack } : {}),
};
+ // v0.46.3: leaving deferred-setup mode — a resolved (model, dims) tuple must
+ // also CLEAR a stale embedding_disabled sentinel inherited via the
+ // ...existingFile spread, or the documented recovery command
+ // (`init --force --embedding-model ...`) persists a config that still
+ // disables embedding at runtime.
+ if (!opts.aiOpts?.noEmbedding && resolvedModel && resolvedDim) {
+ delete config.embedding_disabled;
+ }
// PR1: new installs publish their skill catalog over MCP by default
// (existing config wins on re-init, so a prior opt-out is preserved).
config.mcp = { publish_skills: true, ...(config.mcp ?? {}) };
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 46e565bfa2..c1d49de515 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -43,6 +43,7 @@ export interface MigrateEmbeddingsFlags {
json: boolean;
noEmbed: boolean;
ignoreEnvOverride: boolean;
+ forceSunsetTarget: boolean;
batchSize?: number;
pace?: ReturnType<typeof parsePaceArgs>;
}
@@ -62,6 +63,7 @@ export function parseMigrateEmbeddingsFlags(args: string[]): MigrateEmbeddingsFl
json: args.includes('--json'),
noEmbed: args.includes('--no-embed'),
ignoreEnvOverride: args.includes('--ignore-env-override'),
+ forceSunsetTarget: args.includes('--force-sunset-target'),
...(batchSize !== undefined && { batchSize }),
pace: parsePaceArgs(args),
};
@@ -89,6 +91,9 @@ Flags:
--pace[=mode] DB-contention pacing for the re-embed (off|gentle|balanced|aggressive).
--ignore-env-override Proceed even when GBRAIN_EMBEDDING_* env vars would
override the target at runtime (you know why).
+ --force-sunset-target Allow migrating ONTO a provider with an announced
+ shutdown (e.g. a self-hosted wire-compatible endpoint
+ behind a provider_base_urls override).
--help Show this help.
A killed run is resumable: re-run the same command. Already-migrated chunks
@@ -253,6 +258,7 @@ export async function runMigrateEmbeddings(
...(flags.dim !== undefined && { dim: flags.dim }),
...(fromModel !== undefined && { fromModel }),
...(fromDims !== undefined && { fromDims }),
+ ...(flags.forceSunsetTarget && { allowSunsetTarget: true }),
});
} catch (e) {
serr(e instanceof Error ? e.message : String(e));
diff --git a/src/commands/migrations/index.ts b/src/commands/migrations/index.ts
index 2ee5280265..22597ed17b 100644
--- a/src/commands/migrations/index.ts
+++ b/src/commands/migrations/index.ts
@@ -27,6 +27,7 @@ import { v0_29_1 } from './v0_29_1.ts';
import { v0_31_0 } from './v0_31_0.ts';
import { v0_32_2 } from './v0_32_2.ts';
import { v0_43_0 } from './v0_43_0.ts';
+import { v0_46_3 } from './v0_46_3.ts';
export const migrations: Migration[] = [
v0_11_0,
@@ -45,6 +46,7 @@ export const migrations: Migration[] = [
v0_31_0,
v0_32_2,
v0_43_0,
+ v0_46_3,
];
/** Look up a migration by exact version string. */
diff --git a/src/commands/migrations/v0_46_3.ts b/src/commands/migrations/v0_46_3.ts
new file mode 100644
index 0000000000..cef9fbeffe
--- /dev/null
+++ b/src/commands/migrations/v0_46_3.ts
@@ -0,0 +1,260 @@
+/**
+ * v0.46.3 migration — ZeroEntropy sunset notice (detect-and-notify ONLY).
+ *
+ * ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE (see
+ * src/core/ai/defaults.ts). This orchestrator:
+ *
+ * A. Detects the HOST brain's exposure via src/core/ze-exposure.ts
+ * (effective-model resolution — env → file → legacy fallback; plus the
+ * resolved reranker and ZE-backed custom columns). Read-only.
+ * B. When exposed (or exposure is UNKNOWN — fail-safe): prints the ACTION
+ * REQUIRED block and appends one idempotent pending-host-work entry
+ * pointing the host agent at skills/migrations/v0.46.3.0.md.
+ *
+ * It performs NO config writes, NO pinning, and NEVER invokes
+ * `migrate embeddings` (the migration costs money and needs a target key the
+ * user may not have — that decision belongs to the user/agent via the
+ * playbook). The v0.46.3 split-default keeps existing brains fully working
+ * until the date; this migration is purely the loud, durable notification.
+ *
+ * UNKNOWN handling: returns `complete` with detail `exposure_unknown` — NOT
+ * `partial`. Three consecutive partials would wedge the whole migration chain
+ * behind `--force-retry` (apply-migrations.ts); the stage-2 upgrade banner and
+ * `gbrain doctor` carry the ongoing nag instead.
+ *
+ * Host-scoped: apply-migrations runs once per host (global completed.jsonl).
+ * Mounted/team brains are covered by the per-brain stage-2 banner + doctor.
+ *
+ * NOTE: `apply-migrations --dry-run` exits before invoking orchestrators —
+ * the `opts.dryRun` path here is exercised by tests, not by that CLI flag.
+ */
+
+import { existsSync, readFileSync, mkdirSync, appendFileSync } from 'fs';
+import { join } from 'path';
+
+import type {
+ Migration,
+ OrchestratorOpts,
+ OrchestratorResult,
+ OrchestratorPhaseResult,
+} from './types.ts';
+import { loadConfig, loadConfigFileOnly, toEngineConfig, gbrainPath } from '../../core/config.ts';
+import { ZEROENTROPY_SUNSET_DATE } from '../../core/ai/defaults.ts';
+import { createEngine } from '../../core/engine-factory.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+
+const MIGRATION_VERSION = '0.46.3';
+const PLAYBOOK_SKILL = 'skills/migrations/v0.46.3.0.md';
+
+function pendingHostWorkDir(): string { return gbrainPath('migrations'); }
+function pendingHostWorkPath(): string { return join(pendingHostWorkDir(), 'pending-host-work.jsonl'); }
+
+interface PendingHostWorkEntry {
+ migration: string;
+ ts: string;
+ skill: string;
+ reason: string;
+}
+
+function existingEntryForVersion(version: string): boolean {
+ const p = pendingHostWorkPath();
+ if (!existsSync(p)) return false;
+ try {
+ const raw = readFileSync(p, 'utf-8');
+ for (const line of raw.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const obj = JSON.parse(trimmed) as PendingHostWorkEntry;
+ if (obj.migration === version) return true;
+ } catch { /* skip malformed */ }
+ }
+ } catch { /* read error */ }
+ return false;
+}
+
+function emitHostWork(reason: string): OrchestratorPhaseResult {
+ try {
+ if (existingEntryForVersion(MIGRATION_VERSION)) {
+ return { name: 'host-work', status: 'skipped', detail: 'already recorded' };
+ }
+ mkdirSync(pendingHostWorkDir(), { recursive: true });
+ const entry: PendingHostWorkEntry = {
+ migration: MIGRATION_VERSION,
+ ts: new Date().toISOString(),
+ skill: PLAYBOOK_SKILL,
+ reason,
+ };
+ // Torn-write guard: a prior crashed writer can leave the file without a
+ // trailing newline; appending directly would concatenate onto the torn
+ // line, producing one unparseable line that existingEntryForVersion skips
+ // forever — losing THE deliverable of this migration. Ensure separation.
+ let prefix = '';
+ if (existsSync(pendingHostWorkPath())) {
+ const raw = readFileSync(pendingHostWorkPath(), 'utf-8');
+ if (raw.length > 0 && !raw.endsWith('\n')) prefix = '\n';
+ }
+ appendFileSync(pendingHostWorkPath(), prefix + JSON.stringify(entry) + '\n');
+ return { name: 'host-work', status: 'complete', detail: pendingHostWorkPath() };
+ } catch (e) {
+ return {
+ name: 'host-work',
+ status: 'failed',
+ detail: e instanceof Error ? e.message : String(e),
+ };
+ }
+}
+
+async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult> {
+ const phases: OrchestratorPhaseResult[] = [];
+
+ const config = loadConfig();
+ const fileCfg = loadConfigFileOnly();
+ if (!config && !fileCfg) {
+ // No gbrain install on this host — nothing to notify about.
+ phases.push({ name: 'detect', status: 'skipped', detail: 'no brain configured' });
+ return { version: MIGRATION_VERSION, status: 'complete', phases };
+ }
+
+ let engine: BrainEngine | null = null;
+ let exposure: import('../../core/ze-exposure.ts').ZeExposure | null = null;
+ try {
+ const { detectZeExposure } = await import('../../core/ze-exposure.ts');
+ if (config) {
+ try {
+ engine = await createEngine(toEngineConfig(config));
+ await engine.connect(toEngineConfig(config));
+ } catch {
+ engine = null; // DB probes will fail → tri-state handles it below.
+ }
+ }
+ if (engine) {
+ exposure = await detectZeExposure(engine, fileCfg);
+ phases.push({
+ name: 'detect',
+ status: 'complete',
+ detail:
+ exposure.status === 'unknown'
+ ? `exposure_unknown (failed probes: ${exposure.unknownProbes.join(', ')})`
+ : exposure.status,
+ });
+ } else {
+ // Config exists but the brain is unreachable: resolution-based exposure
+ // still works from the file plane alone; DB-backed probes are unknown.
+ // getConfig THROWS (not null): returning null would fabricate verified
+ // claims from a DB we never reached — "no ZE custom columns" and "no
+ // reranker override" would read as checked when they weren't. Throwing
+ // routes those probes into unknownProbes (honest tri-state).
+ const fakeEngine = {
+ getConfig: async () => {
+ throw new Error('brain unreachable');
+ },
+ executeRaw: async () => {
+ throw new Error('brain unreachable');
+ },
+ } as unknown as BrainEngine;
+ exposure = await detectZeExposure(fakeEngine, fileCfg);
+ // Force fail-safe posture: probes could not run.
+ if (exposure.status === 'clear') {
+ exposure = { ...exposure, status: 'unknown', unknownProbes: ['engine_connect'] };
+ }
+ phases.push({
+ name: 'detect',
+ status: 'complete',
+ detail: `brain unreachable — ${exposure.status}`,
+ });
+ }
+ } catch (e) {
+ phases.push({
+ name: 'detect',
+ status: 'complete',
+ detail: `exposure_unknown (${e instanceof Error ? e.message : String(e)})`,
+ });
+ exposure = null;
+ } finally {
+ try { await engine?.disconnect(); } catch { /* best-effort */ }
+ }
+
+ const status = exposure?.status ?? 'unknown';
+ if (status === 'clear') {
+ // Unexposed brains complete as a no-op — no nag, no host work.
+ return { version: MIGRATION_VERSION, status: 'complete', phases };
+ }
+
+ // Exposed OR unknown → print the notice + emit host work (fail-safe: when
+ // we can't prove the brain is clear, nag rather than stay silent).
+ if (exposure) {
+ const { renderZeActionRequired } = await import('../../core/ze-exposure.ts');
+ const banner = [
+ '',
+ '='.repeat(74),
+ 'ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 migration notice)',
+ '='.repeat(74),
+ renderZeActionRequired(exposure),
+ '='.repeat(74),
+ '',
+ ].join('\n');
+ // eslint-disable-next-line no-console
+ console.error(banner);
+ } else {
+ // Detection itself crashed (exposure === null): still print a loud,
+ // self-contained advisory — the host-work entry alone is silent until an
+ // agent reads it, and the whole point of this migration is the notice.
+ // eslint-disable-next-line no-console
+ console.error(
+ [
+ '',
+ '='.repeat(74),
+ 'ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 migration notice)',
+ '='.repeat(74),
+ 'Exposure detection failed on this host, so this brain is treated as',
+ `affected until proven otherwise. ZeroEntropy stops working on ${ZEROENTROPY_SUNSET_DATE}.`,
+ 'Run `gbrain doctor` (provider_sunset) and see the agent playbook:',
+ ` ${PLAYBOOK_SKILL}`,
+ '='.repeat(74),
+ '',
+ ].join('\n'),
+ );
+ }
+
+ if (opts.dryRun) {
+ phases.push({ name: 'host-work', status: 'skipped', detail: 'dry-run' });
+ return { version: MIGRATION_VERSION, status: 'complete', phases };
+ }
+
+ const hostWork = emitHostWork(
+ `ZeroEntropy hosted API sunset — embedding/reranker migration required (status: ${status})`,
+ );
+ phases.push(hostWork);
+
+ // A FAILED host-work write (unwritable ~/.gbrain, full disk) is a different
+ // class from `exposure_unknown`: the durable action item — this migration's
+ // entire deliverable — was not recorded. Return `partial` so apply-migrations
+ // retries on the next run and converges once writable; a persistently
+ // unwritable dir earns the loud three-partial WEDGED warning. (`skipped` =
+ // already recorded = fine.)
+ const failedWrite = hostWork.status === 'failed';
+
+ return {
+ version: MIGRATION_VERSION,
+ status: failedWrite ? 'partial' : 'complete',
+ phases,
+ pending_host_work: hostWork.status === 'complete' ? 1 : 0,
+ };
+}
+
+export const v0_46_3: Migration = {
+ version: MIGRATION_VERSION,
+ featurePitch: {
+ headline:
+ 'ZeroEntropy is shutting down 2026-09-04 — brains embedding or reranking with it must switch. New default: Voyage (voyage-4 + rerank-2.5, one key).',
+ description:
+ 'Nothing changes automatically: existing brains keep working until the shutdown date. ' +
+ 'This migration detects whether your brain still resolves to ZeroEntropy (embedding, reranker, or custom columns) ' +
+ 'and, if so, records an action item for your agent at skills/migrations/v0.46.3.0.md. ' +
+ 'The one-command fix: `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then `--yes`. ' +
+ 'OpenAI alternative can keep column widths up to 1536 (e.g. a 1280d brain: `--to openai:text-embedding-3-small --dim 1280`); `gbrain doctor` prints this brain\'s exact width-aware command. ' +
+ 'Reranker: `gbrain config set search.reranker.model voyage:rerank-2.5`.',
+ },
+ orchestrator,
+};
diff --git a/src/commands/models.ts b/src/commands/models.ts
index d999e1a7c7..9b54a82c2f 100644
--- a/src/commands/models.ts
+++ b/src/commands/models.ts
@@ -451,7 +451,7 @@ async function probeRerankerConfig(engine: BrainEngine): Promise<ProbeResult> {
touchpoint: 'reranker_config',
status: 'config',
message: `Provider "${recipe.id}" does not declare a reranker touchpoint.`,
- fix: 'Switch to a provider that does (e.g. zeroentropyai:zerank-2).',
+ fix: 'Switch to a provider that does (e.g. voyage:rerank-2.5).',
elapsed_ms: Date.now() - start,
};
}
diff --git a/src/commands/providers.ts b/src/commands/providers.ts
index 9b13d8da2c..4331fc9810 100644
--- a/src/commands/providers.ts
+++ b/src/commands/providers.ts
@@ -11,6 +11,7 @@ import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
import { probeOllama, probeLMStudio } from '../core/ai/probes.ts';
import { loadConfig } from '../core/config.ts';
import { AIConfigError, AITransientError } from '../core/ai/errors.ts';
+import { lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
import type { Recipe } from '../core/ai/types.ts';
const SCHEMA_VERSION = 1;
@@ -30,6 +31,9 @@ interface ProviderOption {
tier: 'native' | 'openai-compat';
pros: string[];
cons: string[];
+ /** v0.46.3: set when the provider's hosted API has an announced shutdown
+ * (recipe.sunset) — agent-facing consumers must not steer users here. */
+ deprecated?: { date: string; replacement?: string };
}
function configureFromEnv(): void {
@@ -80,7 +84,14 @@ export function formatRecipeTable(recipes: Recipe[], env: NodeJS.ProcessEnv = pr
const hasExpand = !!r.touchpoints.expansion;
const hasChat = !!r.touchpoints.chat && r.touchpoints.chat.models.length > 0;
const ready = envReady(r, env);
- const status = ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`;
+ // v0.46.3: a sunsetting provider is flagged in the listing regardless of
+ // key readiness — "ready" on a dying API is not a state to advertise.
+ const status = r.sunset
+ ? `⚠ DEPRECATED — hosted API ends ${r.sunset.date}` +
+ (r.sunset.replacement?.embedding ? `; use ${r.sunset.replacement.embedding}` : '')
+ : ready
+ ? '✓ ready'
+ : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`;
rows.push(
r.id.padEnd(idCol) +
r.tier.padEnd(18) +
@@ -325,17 +336,35 @@ async function runExplain(args: string[]): Promise<void> {
for (const r of recipes) {
if (r.touchpoints.embedding && r.touchpoints.embedding.models.length > 0) {
const m = r.touchpoints.embedding;
+ // v0.46.3: canonical model, not array position (Voyage lists voyage-4-large
+ // first; its canonical default is voyage-4).
+ const canonicalModel = m.default_model ?? m.models[0];
+ // Price the CANONICAL model, not the recipe-wide touchpoint hint — the
+ // touchpoint cost tracks models[0], which can differ from the canonical
+ // pick (voyage-4 is $0.06/M; the recipe-wide hint reflects the flagship).
+ const modelPrice = lookupEmbeddingPrice(`${r.id}:${canonicalModel}`);
options.push({
- id: `${r.id}:${m.models[0]}`,
+ id: `${r.id}:${canonicalModel}`,
touchpoint: 'embedding',
- model: m.models[0],
+ model: canonicalModel,
dims: m.default_dims,
- cost_per_1m_tokens_usd: m.cost_per_1m_tokens_usd,
+ cost_per_1m_tokens_usd:
+ modelPrice.kind === 'known' ? modelPrice.pricePerMTok : m.cost_per_1m_tokens_usd,
price_last_verified: m.price_last_verified,
env_ready: envReady(r) || (r.id === 'ollama' && ollama.models_endpoint_valid === true),
tier: r.tier,
pros: prosFor(r, 'embedding'),
- cons: consFor(r),
+ cons: r.sunset
+ ? [...consFor(r), `DEPRECATED — hosted API ends ${r.sunset.date}`]
+ : consFor(r),
+ ...(r.sunset
+ ? {
+ deprecated: {
+ date: r.sunset.date,
+ replacement: r.sunset.replacement?.embedding,
+ },
+ }
+ : {}),
});
}
if (r.touchpoints.expansion) {
@@ -452,11 +481,17 @@ function consFor(r: Recipe): string[] {
}
function pickRecommended(options: ProviderOption[], env: Record<string, boolean>, ollamaReady: boolean): { id: string; reason: string } {
- // Embedding recommendation: prefer env-ready native providers in this order.
- const embOpts = options.filter(o => o.touchpoint === 'embedding');
+ // Embedding recommendation: prefer env-ready providers in canonical order —
+ // Voyage first (the v0.46.3 new-install default: one key covers embedding +
+ // rerank-2.5 + multimodal). Never recommend a sunsetting provider.
+ const embOpts = options.filter(o => o.touchpoint === 'embedding' && !o.deprecated);
+ if (env.VOYAGE_API_KEY) {
+ const voyage = embOpts.find(o => o.id.startsWith('voyage:'));
+ if (voyage) return { id: voyage.id, reason: 'VOYAGE_API_KEY set — the default: voyage-4 at 1024 dims; the same key powers the rerank-2.5 reranker and the multimodal model.' };
+ }
if (env.OPENAI_API_KEY) {
const openai = embOpts.find(o => o.id.startsWith('openai:'));
- if (openai) return { id: openai.id, reason: 'OPENAI_API_KEY set — OpenAI default is high-quality and preserves existing 1536-dim schema.' };
+ if (openai) return { id: openai.id, reason: 'OPENAI_API_KEY set — high-quality and preserves an existing 1536-dim schema.' };
}
if (ollamaReady) {
const ollama = embOpts.find(o => o.id.startsWith('ollama:'));
@@ -466,13 +501,9 @@ function pickRecommended(options: ProviderOption[], env: Record<string, boolean>
const google = embOpts.find(o => o.id.startsWith('google:'));
if (google) return { id: google.id, reason: 'GOOGLE_GENERATIVE_AI_API_KEY set — Gemini embedding at 768 dims.' };
}
- if (env.VOYAGE_API_KEY) {
- const voyage = embOpts.find(o => o.id.startsWith('voyage:'));
- if (voyage) return { id: voyage.id, reason: 'VOYAGE_API_KEY set — Voyage at 1024 dims.' };
- }
- // Nothing ready. Recommend OpenAI as the lowest-friction path.
+ // Nothing ready. Recommend the canonical default as the setup path.
return {
- id: 'openai:text-embedding-3-large',
- reason: 'No provider env detected. OpenAI is the fastest setup — get a key at https://platform.openai.com/api-keys.',
+ id: 'voyage:voyage-4',
+ reason: 'No provider env detected. Voyage is the default — get a key at https://dash.voyageai.com/api-keys (one key also powers reranking + multimodal).',
};
}
diff --git a/src/commands/reinit-pglite.ts b/src/commands/reinit-pglite.ts
index 0b2a5a76f7..4b7f03533d 100644
--- a/src/commands/reinit-pglite.ts
+++ b/src/commands/reinit-pglite.ts
@@ -303,8 +303,8 @@ Optional:
--json Emit structured JSON output on stdout.
Examples:
- # Switch from OpenAI/1536 to ZeroEntropy/1280:
- gbrain reinit-pglite --embedding-model zeroentropyai:zembed-1 --embedding-dimensions 1280
+ # Switch from OpenAI/1536 to Voyage/1024:
+ gbrain reinit-pglite --embedding-model voyage:voyage-4 --embedding-dimensions 1024
# Skip the sync step (do it later):
gbrain reinit-pglite --embedding-model openai:text-embedding-3-large \\
diff --git a/src/commands/search.ts b/src/commands/search.ts
index 04ccb66ad1..c37eef37f3 100644
--- a/src/commands/search.ts
+++ b/src/commands/search.ts
@@ -48,7 +48,7 @@ const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {
tokenBudget: 'Per-call token-budget cap (undefined = no cap)',
expansion: 'LLM multi-query expansion (Haiku call per search)',
searchLimit: 'Default `limit` for the operation layer',
- reranker_enabled: 'Cross-encoder reranker (ZE zerank-2) on/off',
+ reranker_enabled: 'Cross-encoder reranker on/off',
reranker_model: 'Provider:model for the reranker',
reranker_top_n_in: 'Candidates sent to reranker per call',
reranker_top_n_out: 'Cap on reranked output (null = no truncate)',
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 14df51a339..06227d8f33 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -515,10 +515,11 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
console.log('');
console.log('Two fixes, either works:');
console.log('');
- console.log('[1] Self-host the same model — zembed-1 weights are Apache-2.0. Serve');
- console.log(' them via llama-server or Ollama and point the config at the local');
- console.log(' endpoint. Keeps every existing vector; NO re-embed at all. See');
- console.log(' docs/guides/embedding-migration.md ("Self-hosting instead of migrating").');
+ console.log('[1] Self-host the same model — zembed-1 weights are Apache-2.0. Keep the');
+ console.log(' zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai');
+ console.log(' at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible');
+ console.log(' server — the id speaks ZE\'s /models/embed dialect). Keeps every');
+ console.log(' vector; NO re-embed. See docs/guides/embedding-migration.md.');
console.log('');
console.log('[2] Migrate to another provider (resumable; preview cost first):');
console.log(` gbrain migrate embeddings --to <provider:model>${dimFlag} --dry-run`);
@@ -541,6 +542,43 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// Banner is cosmetic; never block the upgrade.
}
+ // v0.46.3: stage-2 sunset notice, gated by `ze_sunset_notice_v2_shown`.
+ // Fires even for brains that saw stage 1 — this release ships the
+ // migration playbook + the Voyage default, and the exposure story
+ // widened (custom columns, env overrides, reranker-without-key).
+ // The gate opens on `exposed` and on `unknown` (fail-safe: nag rather
+ // than stay silent). Reranker-only exposure is COVERED by `exposed`:
+ // detectZeExposure sets status='exposed' whenever the resolved
+ // reranker is ZE (including the legacy bundle default), so an
+ // OpenAI/Voyage-embedding brain whose reranking rides the ZE bundle
+ // still opens the gate, and renderZeActionRequired includes the
+ // reranker paragraph.
+ try {
+ const shownV2 = await engine.getConfig('ze_sunset_notice_v2_shown');
+ if (shownV2 !== 'true') {
+ const { detectZeExposure, renderZeActionRequired } =
+ await import('../core/ze-exposure.ts');
+ const exposure = await detectZeExposure(engine);
+ if (exposure.status === 'exposed' || exposure.status === 'unknown') {
+ console.log('');
+ console.log('═══════════════════════════════════════════════════════════════');
+ console.log('[gbrain] ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 notice)');
+ console.log('═══════════════════════════════════════════════════════════════');
+ for (const line of renderZeActionRequired(exposure).split('\n')) {
+ console.log(`[gbrain] ${line}`);
+ }
+ console.log('[AGENT] Relay this to your operator: this brain needs an embedding/');
+ console.log('[AGENT] reranker migration before the shutdown date. Playbook:');
+ console.log('[AGENT] skills/migrations/v0.46.3.0.md');
+ console.log('═══════════════════════════════════════════════════════════════');
+ console.log('');
+ await engine.setConfig('ze_sunset_notice_v2_shown', 'true');
+ }
+ }
+ } catch {
+ // Banner is cosmetic; never block the upgrade.
+ }
+
// PR1: skill-catalog publish consent. New installs default ON at
// `gbrain init`; EXISTING installs stay OFF (default-OFF runtime = no
// silent capability grant on upgrade) until the owner opts in HERE.
diff --git a/src/commands/ze-switch.ts b/src/commands/ze-switch.ts
index e60846d181..a201a1f40a 100644
--- a/src/commands/ze-switch.ts
+++ b/src/commands/ze-switch.ts
@@ -110,6 +110,29 @@ export async function runZeSwitch(args: string[], engine: BrainEngine): Promise<
const flags = parseFlags(args);
+ // v0.46.3: ZeroEntropy is shutting down. Switching a brain ONTO it — including
+ // resuming a half-applied forward switch — is disabled; only --undo (which
+ // moves a brain OFF it) and --dry-run (read-only plan) still run. The whole
+ // command is deleted in the September removal release.
+ if (!flags.undo && !flags.dryRun) {
+ const {
+ ZEROENTROPY_SUNSET_DATE,
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
+ } = await import('../core/ai/defaults.ts');
+ const msg =
+ `ze-switch is disabled: ZeroEntropy shuts down its hosted API on ${ZEROENTROPY_SUNSET_DATE}.\n` +
+ 'Switching onto it (or resuming a half-applied switch) would strand this brain.\n' +
+ `To LEAVE ZeroEntropy: gbrain migrate embeddings --to ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} --dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS} --dry-run\n` +
+ 'To undo a prior switch: gbrain ze-switch --undo';
+ if (flags.json) {
+ console.log(JSON.stringify({ status: 'refused', reason: 'provider_sunset', message: msg }));
+ } else {
+ console.error(msg);
+ }
+ process.exit(1);
+ }
+
try {
// --dry-run: just plan, never apply.
if (flags.dryRun) {
diff --git a/src/core/advisor/collect-setup-smells.ts b/src/core/advisor/collect-setup-smells.ts
index de7884e248..5100f5fb96 100644
--- a/src/core/advisor/collect-setup-smells.ts
+++ b/src/core/advisor/collect-setup-smells.ts
@@ -25,28 +25,58 @@ export const collectSetupSmells: AdvisorCollector = {
const findings: AdvisorFinding[] = [];
const cfg = ctx.config ?? ({} as typeof ctx.config);
- // Embeddings disabled — deferred setup never completed.
+ // Embeddings disabled — deferred setup never completed. No command_argv:
+ // `config set embedding_model` is hard-refused (schema-sizing file-plane
+ // key); the sanctioned path is a re-init.
if (cfg.embedding_disabled === true) {
findings.push({
id: 'embeddings_disabled',
severity: 'warn',
title: 'Embeddings are disabled — semantic search and dedup are off.',
- detail: 'Set an embedding model to turn on vector search.',
- fix: { command_argv: ['gbrain', 'config', 'set', 'embedding_model', '<model-id>'] },
- collector: 'setup-smells',
- ask_user: true,
- });
- } else if (!cfg.embedding_model && !cfg.zeroentropy_api_key && !process.env.ZEROENTROPY_API_KEY) {
- // Default provider needs a key; none present anywhere → embeds will fail.
- findings.push({
- id: 'embedding_key_missing',
- severity: 'warn',
- title: 'No embedding provider key is set — embedding will fail at write time.',
- detail: 'Set zeroentropy_api_key (or choose another provider via embedding_model).',
- fix: { command_argv: ['gbrain', 'config', 'set', 'zeroentropy_api_key', '<key>'] },
+ detail:
+ 'Enable with `gbrain init --force --embedding-model voyage:voyage-4` ' +
+ '(set VOYAGE_API_KEY first).',
+ fix: { command_argv: null },
collector: 'setup-smells',
ask_user: true,
});
+ } else {
+ // v0.46.3: key the "will embeds work" claim on the EFFECTIVE model —
+ // configless brains resolve the legacy runtime fallback until the
+ // September cutover, so the credential that matters is that provider's,
+ // not the recommended default's. Both key planes are checked (env +
+ // file config; the DB plane is never read by the embed pipeline).
+ const { DEFAULT_EMBEDDING_MODEL } = await import('../ai/defaults.ts');
+ const { getRecipe } = await import('../ai/recipes/index.ts');
+ const effectiveModel = cfg.embedding_model ?? DEFAULT_EMBEDDING_MODEL;
+ const provider = effectiveModel.split(':')[0];
+ const recipe = getRecipe(provider);
+ const keyName = recipe?.auth_env?.required?.[0];
+ const fileKeys: Record<string, string | undefined> = {
+ OPENAI_API_KEY: cfg.openai_api_key,
+ VOYAGE_API_KEY: cfg.voyage_api_key,
+ ZEROENTROPY_API_KEY: cfg.zeroentropy_api_key,
+ };
+ const keyMissing = !!keyName && !process.env[keyName] && !fileKeys[keyName];
+ if (keyMissing) {
+ const sunsetNote = recipe?.sunset
+ ? ` NOTE: ${recipe.name} shuts down ${recipe.sunset.date} — migrate instead of ` +
+ `setting its key: \`gbrain migrate embeddings --to ` +
+ `${recipe.sunset.replacement?.embedding ?? 'voyage:voyage-4'} --dry-run\`.`
+ : '';
+ findings.push({
+ id: 'embedding_key_missing',
+ severity: 'warn',
+ title: `Embedding resolves to ${effectiveModel} but ${keyName} is not set — embedding will fail at write time.`,
+ detail:
+ `Set ${keyName} in the environment (or add it to ~/.gbrain/config.json).` +
+ sunsetNote +
+ ' To switch providers: `gbrain init --force --embedding-model voyage:voyage-4` with VOYAGE_API_KEY set.',
+ fix: { command_argv: null },
+ collector: 'setup-smells',
+ ask_user: true,
+ });
+ }
}
// Remote-MCP brain serving agents but skill publishing is off → agents hit
diff --git a/src/core/ai/defaults.ts b/src/core/ai/defaults.ts
index a860bbf449..78a69d5312 100644
--- a/src/core/ai/defaults.ts
+++ b/src/core/ai/defaults.ts
@@ -12,14 +12,53 @@
* install AND every doctor consistency check.
*/
-// v0.36.0 chose ZeroEntropy as the system default after evals showed
-// 11/20 wins vs OpenAI (6) and Voyage (4) on real-corpus benchmarks.
-// 1280 is the closest analog to legacy OpenAI 1536d while staying on
-// the high-recall section of ZE's Matryoshka curve. Valid ZE Matryoshka
-// steps: {2560, 1280, 640, 320, 160, 80, 40} — see ai/dims.ts.
+// LEGACY CONFIGLESS RUNTIME FALLBACK — not the new-install default anymore.
+//
+// v0.36.0 chose ZeroEntropy as the system default (11/20 eval wins vs OpenAI
+// and Voyage). ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE,
+// so v0.46.3 split the default: these two constants now serve ONLY brains with
+// no `embedding_model` in file config (old/hand-rolled installs whose stored
+// vectors live in ZE's 1280d space — flipping this under them would break
+// retrieval BEFORE the provider itself dies). Every new-install surface reads
+// NEW_INSTALL_DEFAULT_* below. The September removal release deletes this
+// fallback and hard-errors unmigrated configless brains with the migrate
+// command. Do NOT point anything new at these.
export const DEFAULT_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
export const DEFAULT_EMBEDDING_DIMENSIONS = 1280;
+// NEW-INSTALL DEFAULT (v0.46.3): voyage-4 @ 1024d.
+//
+// Why Voyage: ZeroEntropy covered BOTH gbrain touchpoints (embedding +
+// reranking); Voyage is the only replacement that covers both on one key
+// (rerank-2.5 rides VOYAGE_API_KEY; OpenAI has no reranker API), the
+// multimodal model is already voyage:voyage-multimodal-3, and the voyage-4
+// family is the current hosted retrieval SOTA. Why voyage-4 (not -large/-lite):
+// $0.06/M ≈ zembed-1's $0.05/M, and the v4 trio SHARES ONE EMBEDDING SPACE —
+// a brain indexed with voyage-4 can later point its query model at
+// voyage-4-large or -lite with no reindex, so the within-family choice is
+// reversible. 1024 is a valid Voyage Matryoshka step {256, 512, 1024, 2048}
+// and matches the embedding_image/embedding_multimodal widths.
+//
+// Consumers (new-install surfaces ONLY): init auto-pick canonical tiebreak,
+// the interactive picker default, the no-keys hint, keyless fresh-install
+// schema sizing (passed as an explicit init param — the schema generators keep
+// importing the legacy constants for existing-brain reconnects), and all
+// recommendation copy (playbook, banners, doctor fix-hints, advisor).
+export const NEW_INSTALL_DEFAULT_EMBEDDING_MODEL = 'voyage:voyage-4';
+export const NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS = 1024;
+
+/**
+ * Recommended reranker replacement (v0.46.3). The runtime reranker defaults
+ * (gateway DEFAULT_RERANKER_MODEL + the mode-bundle reranker_model values)
+ * stay on zerank-2 until the September removal so existing ZE-keyed brains
+ * keep their working reranker until the API actually dies; init writes this
+ * as an explicit `search.reranker.model` config for voyage-keyed installs
+ * (any picked embedding provider; keyed non-voyage installs get explicit
+ * `search.reranker.enabled false` instead), and the migration playbook sets
+ * it for migrating users.
+ */
+export const NEW_INSTALL_DEFAULT_RERANKER_MODEL = 'voyage:rerank-2.5';
+
/**
* ZeroEntropy announced (2026-07-24) that its hosted API — including
* /models/embed and /models/rerank — shuts down on this date. Query
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index b71529d194..c5e815d5e6 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -24,6 +24,9 @@ const VOYAGE_OUTPUT_DIMENSION_MODELS = new Set([
'voyage-4-large',
'voyage-4',
'voyage-4-lite',
+ // voyage-code-4: hosted, flexible dims 256/512/1024/2048 per Voyage's
+ // embeddings docs (verified 2026-08-15).
+ 'voyage-code-4',
'voyage-3-large',
'voyage-3.5',
'voyage-3.5-lite',
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index bd77f8642d..3fbd0bc543 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -98,18 +98,12 @@ function withDefaultTimeout(caller: AbortSignal | undefined, timeoutMs: number):
}
const MAX_CHARS = 8000;
-// v0.36.0.0 (D3 + D4): ZeroEntropy zembed-1 at 1280d via Matryoshka is the
-// new default for embedding. Real-corpus benchmark across 20 queries:
-// - ZE wins 11/20 (OpenAI 6, Voyage 4)
-// - 442ms avg vs OpenAI 973ms (2.2x faster)
-// - $0.05/M tokens vs OpenAI $0.13/M (2.6x cheaper at regular pricing)
-// ZE valid Matryoshka steps are {2560, 1280, 640, 320, 160, 80, 40}; 1280 is
-// the closest analog to current OpenAI 1536d (smaller -> smaller HNSW index
-// -> faster queries) while staying in the high-recall zone of the Matryoshka
-// curve. 1024 (Voyage's step) is NOT a valid ZE dim — see
-// src/core/ai/dims.ts:ZEROENTROPY_VALID_DIMS.
-// New installs without ZEROENTROPY_API_KEY size for 1280d anyway — the
-// AIConfigError surfaces at first embed with a paste-ready setup hint.
+// v0.46.3 SPLIT-DEFAULT: DEFAULT_EMBEDDING_MODEL / DEFAULT_EMBEDDING_DIMENSIONS
+// are now the LEGACY CONFIGLESS RUNTIME FALLBACK only (brains with no
+// `embedding_model` in file config, whose stored vectors live in ZE's 1280d
+// space). ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE; the
+// September removal release deletes this fallback. Every NEW-INSTALL surface
+// reads NEW_INSTALL_DEFAULT_* instead — full rationale in ./defaults.ts.
// Re-exported from the leaf `defaults.ts` so heavy schema/registry modules
// don't transitively load every provider SDK just to read the defaults.
export { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './defaults.ts';
@@ -119,6 +113,11 @@ const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';
// v0.35.0.0+: reranker default. Used only when search.reranker.enabled is set
// AND no explicit reranker_model is configured. Mode bundles' per-mode
// `reranker_model` default to this same value but can be overridden.
+// v0.46.3: stays on the LEGACY zerank-2 until the September removal (reranker
+// split-default: existing ZE-keyed brains keep their working reranker until
+// the API dies; voyage-keyed NEW installs get an explicit
+// `search.reranker.model voyage:rerank-2.5` override written at init, and
+// keyed non-voyage installs get explicit `search.reranker.enabled false`).
const DEFAULT_RERANKER_MODEL = 'zeroentropyai:zerank-2';
let _config: AIGatewayConfig | null = null;
@@ -1417,9 +1416,54 @@ export const perplexityCompatFetch = (async (input: RequestInfo | URL, init?: Re
}
}) as unknown as typeof fetch;
+/**
+ * v0.46.3 once-per-(recipe,touchpoint) sunset warning. Fires when a recipe with
+ * `sunset` metadata is actually USED (embedding resolution / rerank call), so
+ * brains still riding a dying provider hear about it on every process, not
+ * only at upgrade time. Module-level memoization (same pattern as
+ * storage-config.ts's deprecation warn); `_resetSunsetWarningsForTest()` is
+ * the test seam. Never throws — a warning must not take down an embed.
+ */
+const _sunsetWarned = new Set<string>();
+export function _resetSunsetWarningsForTest(): void {
+ _sunsetWarned.clear();
+}
+function warnSunsetOnce(recipe: Recipe, touchpoint: 'embedding' | 'reranker'): void {
+ try {
+ const sunset = recipe.sunset;
+ if (!sunset) return;
+ // A base-URL override routes this provider id to a user-supplied endpoint
+ // (typically a self-hosted wire-compatible server) — the HOSTED shutdown
+ // doesn't apply, so a per-call deprecation warning would be a false
+ // positive. The removal-release continuity story is carried by the
+ // migration notice/banner instead.
+ if (_config?.base_urls?.[recipe.id]) return;
+ const key = `${recipe.id}:${touchpoint}`;
+ if (_sunsetWarned.has(key)) return;
+ _sunsetWarned.add(key);
+ const replacement =
+ touchpoint === 'embedding' ? sunset.replacement?.embedding : sunset.replacement?.reranker;
+ const fix =
+ touchpoint === 'embedding'
+ ? replacement
+ ? ` Migrate: \`gbrain migrate embeddings --to ${replacement} --dry-run\``
+ : ''
+ : replacement
+ ? ` Switch: \`gbrain config set search.reranker.model ${replacement}\``
+ : '';
+ process.stderr.write(
+ `[gbrain] DEPRECATED: ${recipe.name} ${touchpoint} stops working on ` +
+ `${sunset.date}.${sunset.message ? ` ${sunset.message}` : ''}${fix}\n`,
+ );
+ } catch {
+ // Cosmetic; never block the call path.
+ }
+}
+
async function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {
const { parsed, recipe } = resolveRecipe(modelStr);
assertTouchpoint(recipe, 'embedding', parsed.modelId);
+ warnSunsetOnce(recipe, 'embedding');
const cfg = requireConfig();
const cacheKey = `emb:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;
@@ -3907,15 +3951,17 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
'unknown',
);
}
+ warnSunsetOnce(recipe, 'reranker');
// Resolve base URL + auth from the recipe (same path Voyage/ZE embeddings use).
const cfg = requireConfig();
const compat = applyOpenAICompatConfig(recipe, cfg);
// v0.40.6.1: rerank URL path is recipe-pluggable. Defaults to ZeroEntropy's
// legacy `/models/rerank`; openai-style providers like llama.cpp's
- // llama-server set `/v1/rerank`. Wire shape is unchanged — any provider
- // whose request/response shape differs from ZE/llama.cpp (e.g. Voyage with
- // `top_k` / `data[]`) needs separate adapter hooks in a follow-up plan.
+ // llama-server set `/v1/rerank`; Voyage sets `/rerank`. Response shape is
+ // shared across all current dialects ({results: [{index, relevance_score}]});
+ // the only request-side difference is the top-N key, declared per recipe via
+ // `top_param` (v0.46.3).
const url = `${compat.baseURL.replace(/\/$/, '')}${tp.path ?? '/models/rerank'}`;
let auth: { apiKey?: string; headers?: Record<string, string> };
try {
@@ -3937,7 +3983,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
model: parsed.modelId,
query: input.query,
documents: input.documents,
- ...(input.topN !== undefined ? { top_n: input.topN } : {}),
+ ...(input.topN !== undefined ? { [tp.top_param ?? 'top_n']: input.topN } : {}),
});
// Pre-flight payload size guard (CDX1-F17 / plan Phase 3 cost guard). The
@@ -4009,10 +4055,20 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
throw new RerankError(msg, reason, resp.status);
}
const json: any = await resp.json();
- if (!json || !Array.isArray(json.results)) {
- throw new RerankError('rerank: malformed response (no results array)', 'unknown');
+ // v0.46.3: two response dialects share the item shape {index,
+ // relevance_score} but differ in the array key — ZE/llama-server return
+ // `results[]`, Voyage's REST returns `data[]` ({object: "list", data:
+ // [...]}, live-wire verified 2026-08-15; Voyage's Python SDK renames it
+ // `results`, which is why docs-level checks get this wrong). Accept both.
+ const items: any[] | null = Array.isArray(json?.results)
+ ? json.results
+ : Array.isArray(json?.data)
+ ? json.data
+ : null;
+ if (!items) {
+ throw new RerankError('rerank: malformed response (no results/data array)', 'unknown');
}
- const mapped = json.results.map((r: any) => ({
+ const mapped = items.map((r: any) => ({
index: typeof r.index === 'number' ? r.index : 0,
relevanceScore: typeof r.relevance_score === 'number' ? r.relevance_score : 0,
}));
diff --git a/src/core/ai/recipes/voyage.ts b/src/core/ai/recipes/voyage.ts
index 6562cb6d40..70e440e4ba 100644
--- a/src/core/ai/recipes/voyage.ts
+++ b/src/core/ai/recipes/voyage.ts
@@ -32,10 +32,16 @@ export const voyage: Recipe = {
embedding: {
models: [
'voyage-4-large', 'voyage-4', 'voyage-4-lite', 'voyage-4-nano',
+ 'voyage-code-4',
'voyage-3.5', 'voyage-3-large', 'voyage-3', 'voyage-3-lite',
'voyage-code-3', 'voyage-finance-2', 'voyage-law-2',
'voyage-multimodal-3',
],
+ // v0.46.3: canonical pick for every "choose a model for the user" surface.
+ // models[0] is voyage-4-large (quality order); the new-install default is
+ // voyage-4 (price/quality balance, shared v4 embedding space) — see
+ // NEW_INSTALL_DEFAULT_EMBEDDING_MODEL in ai/defaults.ts.
+ default_model: 'voyage-4',
default_dims: 1024,
// Display hint for `gbrain providers` only (billing math goes through
// src/core/embedding-pricing.ts). Rate for the default voyage-4-large.
@@ -59,6 +65,27 @@ export const voyage: Recipe = {
// 4xx).
multimodal_models: ['voyage-multimodal-3'],
},
+ // v0.46.3: Voyage reranking (the recommended zerank-2 replacement — same
+ // VOYAGE_API_KEY as embeddings). gateway.rerank() posts to
+ // `${base_url_default}/rerank` (base already ends in /v1). Wire dialect:
+ // request takes `top_k` (declared via top_param); response is
+ // {object: "list", data: [{index, relevance_score}]} — live-wire verified
+ // 2026-08-15; the gateway's parser accepts both data[] and results[].
+ reranker: {
+ models: ['rerank-2.5', 'rerank-2.5-lite'],
+ default_model: 'rerank-2.5',
+ path: '/rerank',
+ top_param: 'top_k',
+ // https://docs.voyageai.com/docs/pricing (verified 2026-08-15):
+ // rerank-2.5 $0.05/M, rerank-2.5-lite $0.02/M.
+ cost_per_1m_tokens_usd: 0.05,
+ price_last_verified: '2026-08-15',
+ // Voyage enforces token-based caps (32K per query+document pair,
+ // ≤1000 documents/request) rather than a byte cap; 5MB is a
+ // conservative byte-level proxy matching the ZE-era pre-flight so
+ // oversized bodies still fail open before the wire.
+ max_payload_bytes: 5_000_000,
+ },
},
setup_hint: 'Get an API key at https://dash.voyageai.com/api-keys, then `export VOYAGE_API_KEY=...`',
};
diff --git a/src/core/ai/recipes/zeroentropyai.ts b/src/core/ai/recipes/zeroentropyai.ts
index a5367df487..f20b52435a 100644
--- a/src/core/ai/recipes/zeroentropyai.ts
+++ b/src/core/ai/recipes/zeroentropyai.ts
@@ -1,4 +1,9 @@
import type { Recipe } from '../types.ts';
+import {
+ ZEROENTROPY_SUNSET_DATE,
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ NEW_INSTALL_DEFAULT_RERANKER_MODEL,
+} from '../defaults.ts';
/**
* ZeroEntropy ships two specialized small models that target the two weakest
@@ -64,4 +69,16 @@ export const zeroentropyai: Recipe = {
},
setup_hint:
'Get an API key at https://dashboard.zeroentropy.dev, then `export ZEROENTROPY_API_KEY=...`',
+ // ZeroEntropy is winding down; the hosted API dies on the sunset date.
+ // This drives picker/auto-pick exclusion, warn-on-use, and the
+ // `gbrain providers` DEPRECATED annotation. The recipe itself is deleted
+ // in the September removal release (see TODOS.md).
+ sunset: {
+ date: ZEROENTROPY_SUNSET_DATE,
+ message: 'ZeroEntropy is shutting down its hosted API.',
+ replacement: {
+ embedding: NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ reranker: NEW_INSTALL_DEFAULT_RERANKER_MODEL,
+ },
+ },
};
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 2627a1d8c4..7d825fa010 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -28,6 +28,16 @@ export type Implementation =
export interface EmbeddingTouchpoint {
models: string[];
default_dims: number;
+ /**
+ * v0.46.3: canonical model for this recipe's embedding touchpoint. Every
+ * "pick a model for the user" surface resolves `default_model ?? models[0]`:
+ * init auto-pick (single-key and multi-key canonical tiebreak), the
+ * `--embedding-model <provider>` shorthand expansion, and the interactive
+ * picker's selection + displayed row. Exists because array order is a bad
+ * carrier for "recommended": Voyage lists voyage-4-large first (quality
+ * order) but the canonical default is voyage-4 (price/quality balance).
+ */
+ default_model?: string;
/**
* Per-model native dimensions, keyed by bare model id (no `provider:`
* prefix). Consulted before `default_dims` when resolving schema width
@@ -229,6 +239,15 @@ export interface RerankerTouchpoint {
* '/v1/rerank').
*/
path?: string;
+ /**
+ * v0.46.3: request-body key for the "return top N" parameter. Named by wire
+ * shape, not provider. Defaults to 'top_n' (ZeroEntropy/llama-server/jina
+ * dialect); Voyage's /v1/rerank takes 'top_k'. Response parsing accepts
+ * both array keys (`results[]` for ZE/llama-server, `data[]` for Voyage's
+ * REST — live-wire verified) since the item shape
+ * `{index, relevance_score}` is shared.
+ */
+ top_param?: 'top_n' | 'top_k';
/**
* Recipe-level timeout fallback for `gateway.rerank()` and search-mode
* resolution. Caller's `input.timeoutMs` and `search.reranker.timeout_ms`
@@ -307,6 +326,27 @@ export interface Recipe {
aliases?: Record<string, string>;
/** One-line description of setup (shown in wizard + env subcommand). */
setup_hint?: string;
+ /**
+ * v0.46.3: the provider announced a hosted-API shutdown. Drives, from one
+ * source: init picker/auto-pick exclusion, the once-per-process warn-on-use
+ * in the gateway, and the `gbrain providers` DEPRECATED annotation.
+ * (`provider_sunset` in doctor stays provider-specific until the removal
+ * release — this field does not make the doctor generic yet.)
+ * `replacement` is per-touchpoint: one provider can be replaced by different
+ * targets for embedding vs reranking.
+ */
+ sunset?: {
+ /** ISO date the hosted API stops working. */
+ date: string;
+ /** Optional extra context appended to warnings. */
+ message?: string;
+ replacement?: {
+ /** Recommended `provider:model` replacement for the embedding touchpoint. */
+ embedding?: string;
+ /** Recommended `provider:model` replacement for the reranker touchpoint. */
+ reranker?: string;
+ };
+ };
/**
* v0.32 (D12=A): unified auth resolver across embed / expansion / chat
* touchpoints. Returns the header name (`Authorization`, `api-key`, etc.)
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 31840e718c..5390897fbc 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -43,12 +43,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--aliases', '--all', '--allow-shell-jobs', '--allow-unverified-remote', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude-standard', '--exclusive', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--include-pseudo', '--index-audit', '--init', '--input', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--resolve', '--restore-only', '--resume', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
'dream': ['--against', '--aliases', '--all', '--allow-regression', '--anchor', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--ctx-size', '--cycles', '--date', '--detail', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rounds', '--rubric-version', '--save', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--take', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--undo', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],
'edges-backfill': ['--aliases', '--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--include-null-signature', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-extract', '--no-federated', '--older-than', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--workers'],
- 'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--version'],
- 'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],
+ 'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--version'],
+ 'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],
+ 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],
'export': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--explain', '--federated', '--fix', '--follow', '--help', '--include-null-signature', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--slug-prefix', '--source', '--stale', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type'],
'extract': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--multimodal', '--name-status', '--near-symbol', '--ner', '--no-extract', '--no-federated', '--older-than', '--pack', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--run-id', '--since', '--slug', '--source', '--source-id', '--stale', '--strategy', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type', '--verbose', '--workers', '--yes'],
- 'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--to', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],
'features': ['--aliases', '--all', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--no-extract', '--pace', '--pace-max-concurrency', '--pack', '--path', '--pattern', '--pending', '--priority', '--progress-json', '--quiet', '--repo', '--reset', '--resolve', '--run-id', '--since', '--slugs', '--source', '--source-id', '--stale', '--supersessions', '--thin', '--type', '--verbose', '--workers'],
'files': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--no-pointer', '--page', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--retry-failed', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--yes'],
'forget': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
@@ -58,30 +58,30 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--aliases', '--all', '--brain', '--depth', '--direction', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--include-null-signature', '--json', '--lang', '--markdown', '--mcp-only', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--type'],
'hook': ['--aliases', '--all', '--allow-unverified-remote', '--batch-limit', '--brain', '--budget-ms', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--include-null-signature', '--jq', '--json', '--name-only', '--no-embedding', '--no-extract', '--once', '--others', '--path', '--pattern', '--pending', '--porcelain', '--project', '--quiet', '--remove', '--reset', '--resolve', '--show-current', '--show-toplevel', '--source', '--stale', '--stats', '--status', '--supersessions', '--surface', '--thin', '--timeout', '--token', '--token-ttl'],
'import': ['--aliases', '--all', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--code', '--compile', '--concurrency', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--older-than', '--others', '--path', '--pattern', '--pending', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-id', '--stale', '--strategy', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--url', '--workers'],
- 'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version'],
+ 'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version'],
'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],
'integrity': ['--aliases', '--all', '--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--limit', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--url'],
'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--supersessions', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],
'lint': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--aliases', '--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--column', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--help', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--json', '--kind', '--lang', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--near-symbol', '--ner', '--nice', '--no-extract', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resolve', '--restore-only', '--resume', '--run-id', '--safe', '--scope', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--supersessions', '--symbol-kind', '--target', '--target-score', '--thin', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--yes'],
- 'migrate': ['--ab', '--aliases', '--all', '--auto-update', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--build-index', '--by-mention', '--catch-up', '--compile', '--days', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclusive', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--lang', '--locks', '--markdown', '--max-age', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--phase', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--refresh-unqualified', '--remediate', '--reranking', '--reset', '--resolve', '--restore-only', '--resume', '--rollback', '--skip-verify', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
- 'models': ['--aliases', '--all', '--brain', '--ctx-size', '--detail', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--include-null-signature', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--pattern', '--pending', '--reranking', '--reset', '--resolve', '--skip', '--source', '--stale', '--supersessions', '--thin', '--undo', '--version'],
+ 'migrate': ['--ab', '--aliases', '--all', '--auto-update', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--build-index', '--by-mention', '--catch-up', '--compile', '--days', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclusive', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--lang', '--locks', '--markdown', '--max-age', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--phase', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--refresh-unqualified', '--remediate', '--reranking', '--reset', '--resolve', '--restore-only', '--resume', '--rollback', '--skip-verify', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
+ 'models': ['--aliases', '--all', '--brain', '--ctx-size', '--detail', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--include-null-signature', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--pattern', '--pending', '--reranking', '--reset', '--resolve', '--skip', '--source', '--stale', '--supersessions', '--thin', '--to', '--undo', '--version'],
'mounts': ['--alias', '--brain', '--cache', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--explain', '--help', '--id', '--json', '--lang', '--lock', '--markdown', '--mcp-url', '--multimodal', '--near-symbol', '--path', '--restore-only', '--skills-dir', '--source', '--stale', '--symbol-kind', '--thin', '--verbose'],
- 'notability-eval': ['--aliases', '--all', '--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--include-null-signature', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--out', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--skip-llm', '--source', '--stale', '--supersessions', '--target-high', '--target-low', '--target-medium', '--thin', '--version'],
+ 'notability-eval': ['--aliases', '--all', '--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--include-null-signature', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--out', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--skip-llm', '--source', '--stale', '--supersessions', '--target-high', '--target-low', '--target-medium', '--thin', '--to', '--version'],
'onboard': ['--aliases', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--from-pages', '--help', '--history', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-extract', '--offset', '--params', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--reset', '--resolve', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--target-score', '--thin', '--trusted-extraction', '--url', '--with-db', '--yes'],
'orphans': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--count', '--explain', '--follow', '--help', '--include-null-signature', '--include-pseudo', '--json', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout'],
'pages': ['--aliases', '--all', '--brain', '--dry-run', '--help', '--include-null-signature', '--json', '--no-extract', '--older-than', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin'],
'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'],
'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--path', '--pglite', '--quiet', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
'protocol': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-embedding', '--offset', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
- 'providers': ['--brain', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--source', '--surface', '--token-ttl', '--touchpoint', '--version'],
+ 'providers': ['--brain', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--aliases', '--all', '--apply', '--brain', '--code', '--compile', '--explain', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--no-embed', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl'],
'recall': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
'reconcile-links': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--include-null-signature', '--json', '--name-status', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--strategy', '--supersessions', '--thin', '--timeout', '--type'],
- 'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--code', '--compile', '--concurrency', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--version', '--workers', '--yes'],
- 'reindex-code': ['--abi', '--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--older-than', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--serial', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--version', '--workers', '--yes'],
+ 'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--code', '--compile', '--concurrency', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--version', '--workers', '--yes'],
+ 'reindex-code': ['--abi', '--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--older-than', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--serial', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--version', '--workers', '--yes'],
'reindex-frontmatter': ['--aliases', '--all', '--brain', '--concurrency', '--dry-run', '--force', '--help', '--include-null-signature', '--json', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--slug-prefix', '--source', '--stale', '--supersessions', '--thin', '--workers', '--yes'],
'reindex-search-vector': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-null-signature', '--json', '--migrate-only', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--yes'],
@@ -90,7 +90,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abbrev-ref', '--abort', '--aliases', '--all', '--all-sources', '--allow-unverified-remote', '--brain', '--branch', '--break-lock', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--detect', '--diff-filter', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--help', '--http', '--include-null-signature', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--lang', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--pattern', '--pending', '--porcelain', '--push-only', '--quiet', '--rebase', '--repo', '--reset', '--resolve', '--restore-only', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-id', '--stale', '--status', '--strategy', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--unset-all', '--url', '--url-managed', '--yes'],
'resolvers': ['--auto', '--backend', '--brain', '--cost', '--help', '--json', '--source'],
- 'retrieval-upgrade': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranking', '--reset', '--resolve', '--resume', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--version', '--yes'],
+ 'retrieval-upgrade': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--follow', '--force', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranking', '--reset', '--resolve', '--resume', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--version', '--yes'],
'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],
'salience': ['--aliases', '--all', '--brain', '--days', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--slug-prefix', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'schema': ['--alias', '--aliases', '--all', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--inverse', '--json', '--kind', '--no-embedding', '--no-extract', '--pack', '--page-type', '--pattern', '--pending', '--prefix', '--primitive', '--reset', '--resolve', '--schema-pack', '--since', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--target-type', '--thin', '--to', '--token-ttl', '--with-db'],
@@ -111,5 +111,5 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'transcripts': ['--aliases', '--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--code', '--compile', '--days', '--dry-run', '--embed', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-null-signature', '--json', '--limit', '--markdown', '--max-cost-usd', '--no-embedding', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--since', '--slug', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--path', '--pglite', '--quiet', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
'watch': ['--aliases', '--all', '--brain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--token-ttl', '--window-turns'],
- 'ze-switch': ['--aliases', '--all', '--brain', '--confirm-reembed', '--dry-run', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--no-extract', '--non-interactive', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin', '--undo', '--yes'],
+ 'ze-switch': ['--aliases', '--all', '--brain', '--confirm-reembed', '--dim', '--dry-run', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--no-extract', '--non-interactive', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin', '--to', '--undo', '--yes'],
};
diff --git a/src/core/config.ts b/src/core/config.ts
index 79d3d2099f..fee4daae30 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1156,6 +1156,13 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// reconcile-links, and sweep. The documented off-switch is `gbrain config
// set auto_link false` — same unregistered-key class as auto_chronicle.
'auto_link',
+ // v0.46.3: the provider_sunset doctor check's own suppression escape hatch
+ // (doctor.ts) and docs/guides/embedding-migration.md both document
+ // `gbrain config set doctor.suppress_provider_sunset true`, but the key was
+ // never registered — the documented command exited 1 with "Unknown config
+ // key". Same class as auto_chronicle above. Deliberately an exact key, not
+ // a blanket 'doctor.' prefix (unbounded namespaces defeat the typo gate).
+ 'doctor.suppress_provider_sunset',
// #2606: chronicle judge output-token cap (default 4000). Event-dense
// pages overflowed the old hardcoded 1500 and were misrecorded as
// no_events; the cap is now configurable and truncation is surfaced.
diff --git a/src/core/cycle/nightly-quality-probe.ts b/src/core/cycle/nightly-quality-probe.ts
index ef3de08d7a..7621a56f10 100644
--- a/src/core/cycle/nightly-quality-probe.ts
+++ b/src/core/cycle/nightly-quality-probe.ts
@@ -156,7 +156,7 @@ export async function runNightlyQualityProbe(deps: NightlyProbeDeps): Promise<Ni
if (!hasEmbed) {
process.stderr.write(
`[nightly-quality-probe] no embedding provider configured; skipping. ` +
- `Configure OPENAI_API_KEY / VOYAGE_API_KEY / ZEROENTROPY_API_KEY and re-enable.\n`,
+ `Configure VOYAGE_API_KEY / OPENAI_API_KEY and re-enable.\n`,
);
logQualityProbeEvent({
outcome: 'no_embedding_key',
diff --git a/src/core/embed-preflight.ts b/src/core/embed-preflight.ts
index bf7db47d0e..5102d18ad7 100644
--- a/src/core/embed-preflight.ts
+++ b/src/core/embed-preflight.ts
@@ -70,7 +70,10 @@ export function formatEmbeddingCredsError(d: EmbeddingDiagnosis): string {
return [
'No embedding model is configured for this brain.',
'',
- ' Set one: gbrain config set embedding_model openai:text-embedding-3-small',
+ // NOT `gbrain config set embedding_model` — that key is file-plane
+ // schema-sizing config the command refuses; init --force is the
+ // sanctioned re-configuration path.
+ ' Set one: gbrain init --force --embedding-model voyage:voyage-4',
' Or skip embedding now: re-run with --no-embed',
].join('\n');
@@ -80,14 +83,14 @@ export function formatEmbeddingCredsError(d: EmbeddingDiagnosis): string {
'',
` ${d.message}`,
'',
- ' Pick a known provider: gbrain config set embedding_model openai:text-embedding-3-small',
+ ' Pick a known provider: gbrain init --force --embedding-model voyage:voyage-4',
].join('\n');
case 'no_touchpoint':
return [
`Provider "${d.provider}" does not offer an embedding touchpoint.`,
'',
- ' Switch providers: gbrain config set embedding_model openai:text-embedding-3-small',
+ ' Switch providers: gbrain init --force --embedding-model voyage:voyage-4',
' Or run with --no-embed to import-only and embed later.',
].join('\n');
@@ -112,9 +115,9 @@ export function formatEmbeddingCredsError(d: EmbeddingDiagnosis): string {
// Only offer a provider-switch hint when the current provider isn't openai
// (otherwise we'd be suggesting they switch to the thing they already have).
if (d.provider !== 'openai') {
- lines.push(` • Switch providers: gbrain config set embedding_model openai:text-embedding-3-small`);
+ lines.push(` • Switch providers: gbrain init --force --embedding-model openai:text-embedding-3-small`);
} else {
- lines.push(` • Switch providers: gbrain config set embedding_model voyage:voyage-3-large`);
+ lines.push(` • Switch providers: gbrain init --force --embedding-model voyage:voyage-4`);
}
lines.push('');
lines.push(`Example shell setup:`);
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 18b9095de4..4fb5eca291 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -93,7 +93,11 @@ export function migrationSignature(toModel: string, toDims: number): string {
* Throws with a paste-ready message on an unknown provider or when the
* recipe declares no default dims and the caller passed none.
*/
-export function resolveMigrationTarget(to: string, dimFlag?: number): { toModel: string; toDims: number } {
+export function resolveMigrationTarget(
+ to: string,
+ dimFlag?: number,
+ opts?: { allowSunsetTarget?: boolean },
+): { toModel: string; toDims: number } {
if (!to.includes(':')) {
throw new Error(
`--to must be provider:model (e.g. openai:text-embedding-3-small). Got: ${to}`,
@@ -104,6 +108,20 @@ export function resolveMigrationTarget(to: string, dimFlag?: number): { toModel:
if (!recipe.touchpoints.embedding) {
throw new Error(`Provider ${recipe.id} has no embedding support. Pick an embedding-capable provider:model.`);
}
+ // v0.46.3: refuse a PAID full re-embed onto a provider with an announced
+ // shutdown — the live probe passes while the hosted API is still up, so
+ // without this gate an agent replaying an old runbook could strand the
+ // brain days before the shutdown. Same posture as ze-switch's forward
+ // refusal; `--force-sunset-target` (self-hosters with a compatible
+ // endpoint) is the loud escape hatch.
+ if (recipe.sunset && !opts?.allowSunsetTarget) {
+ throw new Error(
+ `Refusing to migrate ONTO ${recipe.name}: its hosted API stops working on ` +
+ `${recipe.sunset.date}, so this paid re-embed would strand the brain. ` +
+ `Recommended target: ${recipe.sunset.replacement?.embedding ?? 'voyage:voyage-4'}. ` +
+ `Self-hosting a compatible endpoint? Re-run with --force-sunset-target.`,
+ );
+ }
const toDims = dimFlag ?? embeddingDimsForModel(recipe, to);
if (!toDims || toDims <= 0) {
throw new Error(
@@ -120,9 +138,11 @@ export function resolveMigrationTarget(to: string, dimFlag?: number): { toModel:
*/
export async function planEmbeddingMigration(
engine: BrainEngine,
- opts: { to: string; dim?: number; fromModel?: string; fromDims?: number },
+ opts: { to: string; dim?: number; fromModel?: string; fromDims?: number; allowSunsetTarget?: boolean },
): Promise<EmbeddingMigrationPlan> {
- const { toModel, toDims } = resolveMigrationTarget(opts.to, opts.dim);
+ const { toModel, toDims } = resolveMigrationTarget(opts.to, opts.dim, {
+ allowSunsetTarget: opts.allowSunsetTarget,
+ });
// From-state: caller (CLI) passes the gateway-resolved values; fall back
// to the shipped defaults for gateway-less contexts (unit tests, op probe).
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index 49e6b35281..5675ff41ef 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -34,10 +34,15 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
'openai:text-embedding-3-small': { pricePerMTok: 0.02 },
// Legacy OpenAI ada (still common in older brains)
'openai:text-embedding-ada-002': { pricePerMTok: 0.10 },
- // Voyage (https://docs.voyageai.com/docs/pricing, verified 2026-07-28)
+ // Voyage (https://docs.voyageai.com/docs/pricing, verified 2026-08-15)
'voyage:voyage-4-large': { pricePerMTok: 0.12 },
'voyage:voyage-4': { pricePerMTok: 0.06 },
'voyage:voyage-4-lite': { pricePerMTok: 0.02 },
+ 'voyage:voyage-code-4': { pricePerMTok: 0.12 },
+ // Voyage rerankers (same pricing page, verified 2026-08-15). Same
+ // budget-tracker rerank-kind fallback rationale as the zerank-2 row below.
+ 'voyage:rerank-2.5': { pricePerMTok: 0.05 },
+ 'voyage:rerank-2.5-lite': { pricePerMTok: 0.02 },
// voyage-4-nano is deliberately absent: it's the open-weight variant (see
// src/core/ai/recipes/voyage.ts) and Voyage's pricing page lists no hosted
// rate for it. A 0 entry would under-estimate anyone paying for it via the
diff --git a/src/core/init-embed-check.ts b/src/core/init-embed-check.ts
index 5a5d5b2170..fba626598f 100644
--- a/src/core/init-embed-check.ts
+++ b/src/core/init-embed-check.ts
@@ -15,9 +15,10 @@
* warn only, never blocks.
*
* Both run against the EFFECTIVE gateway config — process.env overlaid with
- * file-plane keys (openai/anthropic/zeroentropy from config.json) and
- * `opts.apiKey`, plus provider base URLs — built via the same
- * `buildGatewayConfig` runtime uses. Without that, the config-only check would
+ * every file-plane provider key config.json carries (openai / anthropic /
+ * voyage / zeroentropy / dashscope / google — whatever buildGatewayConfig
+ * folds, #2662) and `opts.apiKey`, plus provider base URLs — built via the
+ * same `buildGatewayConfig` runtime uses. Without that, the config-only check would
* false-warn on config.json-keyed users, and the live probe could hit the
* wrong endpoint (custom OpenAI base URL, llama-server, etc.).
*
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 2c72135d59..221e0867fd 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -138,11 +138,15 @@ export class MinionQueue {
);
}
if (verdict === 'unknown') {
+ // v0.46.3: derive the provider list from the recipe registry instead
+ // of a hardcoded string (which drifted silently as recipes came and
+ // went — and would have needed editing again at the ZE removal).
+ const { listRecipes } = await import('../ai/recipes/index.ts');
+ const known = listRecipes().map((r) => r.id).join(', ');
throw new Error(
`subagent job rejected: data.model "${submittedModel}" references an unknown provider. ` +
`Use format provider:model where provider matches a recipe in src/core/ai/recipes/. ` +
- `Known providers: anthropic, openai, google, openrouter, litellm-proxy, ollama, llama-server, ` +
- `together, azure-openai, deepseek, groq, dashscope, minimax, zhipu, voyage, zeroentropyai.`,
+ `Known providers: ${known}.`,
);
}
// 'degraded:no_caching' and 'degraded:no_parallel' pass through — the
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 8711dc4e8c..edcea1f2a8 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -2228,7 +2228,7 @@ const query: Operation = {
embedding_column: {
type: 'string',
description:
- "v0.36: route vector search through a non-default embedding column. Defaults to 'embedding' (OpenAI 1536d) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_zeroentropy'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns.",
+ "v0.36: route vector search through a non-default embedding column. Defaults to 'embedding' (the brain's primary column) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_openai'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns.",
},
adaptive_return: {
type: 'boolean',
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index c74307479c..6dfd0fc909 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -104,10 +104,15 @@ export interface ModeBundle {
*/
reranker_enabled: boolean;
/**
- * Provider:model for the reranker. Default `'zeroentropyai:zerank-2'`.
- * Other ZE rerankers (`zerank-1`, `zerank-1-small`) work via the same
- * recipe; future Cohere/Voyage rerankers drop in as new recipes
- * declaring `touchpoints.reranker`.
+ * Provider:model for the reranker. Bundle default `'zeroentropyai:zerank-2'`
+ * — LEGACY until the September removal (v0.46.3 split-default: existing
+ * ZE-keyed brains keep a working reranker until the hosted API dies on
+ * 2026-09-04; voyage-keyed new installs get an explicit
+ * `search.reranker.model voyage:rerank-2.5` override written at init
+ * (keyed non-voyage installs get explicit `search.reranker.enabled false`),
+ * and the September release flips this bundle value to voyage). Voyage
+ * rerankers (`rerank-2.5`, `rerank-2.5-lite`) are live recipes today via
+ * `touchpoints.reranker`.
*/
reranker_model: string;
/** Candidates to send upstream (default 30). The full result list always
diff --git a/src/core/ze-exposure.ts b/src/core/ze-exposure.ts
new file mode 100644
index 0000000000..144533370c
--- /dev/null
+++ b/src/core/ze-exposure.ts
@@ -0,0 +1,342 @@
+/**
+ * ZeroEntropy sunset exposure detection (v0.46.3).
+ *
+ * One shared answer to "is this brain still depending on ZeroEntropy?" —
+ * consumed by the v0.46.3 version migration (detect-and-notify) and the
+ * stage-2 upgrade banner. Standalone module by design: the ze-switch /
+ * retrieval-upgrade subsystem is deleted in the September removal release and
+ * this file must survive it.
+ *
+ * SCOPE: the brain the given engine is connected to + the HOST file plane
+ * (~/.gbrain/config.json). apply-migrations is host-scoped (one global
+ * completed.jsonl, no --brain flag), so the version migration covers the HOST
+ * brain only; mounted/team brains are covered by the per-brain stage-2 banner
+ * + doctor gates (their `ze_sunset_notice_v2_shown` lives in each brain's own
+ * DB config).
+ *
+ * EXPOSURE = EFFECTIVE-MODEL RESOLUTION, NOT VECTOR EVIDENCE. Precedence:
+ * env (GBRAIN_EMBEDDING_MODEL) → file `embedding_model` → the legacy
+ * configless runtime fallback (DEFAULT_EMBEDDING_MODEL, still ZE until the
+ * September cutover). A configless brain resolves to the ZE fallback
+ * DETERMINISTICALLY — it is exposed even with zero vectors. Signatures and
+ * column width feed only the blast radius: 1280d is NOT ZE-proof (OpenAI
+ * text-3 supports arbitrary Matryoshka widths including 1280).
+ *
+ * TRI-STATE: a failed DB probe downgrades `status` to 'unknown', never to
+ * 'clear'. Callers must nag on 'unknown' (fail-safe), and the migration
+ * returns `complete` with an `exposure_unknown` detail rather than `partial`
+ * — three consecutive partials would wedge the whole migration chain behind
+ * `--force-retry` (apply-migrations.ts).
+ */
+
+import type { BrainEngine } from './engine.ts';
+import type { GBrainConfig } from './config.ts';
+import { loadConfigFileOnly } from './config.ts';
+import { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE } from './ai/defaults.ts';
+import {
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
+ NEW_INSTALL_DEFAULT_RERANKER_MODEL,
+} from './ai/defaults.ts';
+import { lookupEmbeddingPrice } from './embedding-pricing.ts';
+
+const ZE_PREFIX = 'zeroentropyai:';
+
+/** Strict column-name shape (mirrors the registry's validateColumnKey
+ * contract). Registry keys read here come from BOTH config planes — the DB
+ * plane can be written by another party on mounted/team brains, and these
+ * names are rendered verbatim into the agent-directed ACTION REQUIRED banner,
+ * so nonconforming names are dropped rather than echoed (text-injection
+ * hardening; sanctioned write paths already enforce this shape). */
+const SAFE_COLUMN_KEY = /^[a-z_][a-z0-9_]{0,62}$/;
+
+/** Blast-radius counts are LIMIT-capped so a million-chunk brain can't stall
+ * apply-migrations on a full-table COUNT. */
+export const BLAST_RADIUS_CAP = 100_000;
+
+export type ZeExposureStatus = 'exposed' | 'clear' | 'unknown';
+
+export interface ZeBlastRadius {
+ /** Pages whose embedding_signature is ZE-stamped (capped; null = probe failed). */
+ zeSignedPages: number | null;
+ zeSignedPagesCapped: boolean;
+ /** Non-NULL embedded chunks (capped; null = probe failed / not ZE-exposed). */
+ embeddedChunks: number | null;
+ embeddedChunksCapped: boolean;
+ /** Rough re-embed cost at the recommended target (~400 tokens/chunk). */
+ estReembedUsd: number | null;
+}
+
+export interface ZeExposure {
+ status: ZeExposureStatus;
+ /** Effective embedding model resolves to zeroentropyai:* (and not disabled). */
+ zeEmbedding: boolean;
+ /** ...because file config names it explicitly. */
+ zeExplicit: boolean;
+ /** ...because nothing is configured and the legacy runtime fallback applies. */
+ bareDefaultZe: boolean;
+ /** Env override (GBRAIN_EMBEDDING_MODEL) names ZE — env wins over file, so
+ * the notice must tell the operator the env var itself has to change. */
+ envOverride: boolean;
+ /** The RESOLVED reranker (explicit config or still-legacy bundle default,
+ * when reranking is enabled for the active mode) is zeroentropyai:*. */
+ zeReranker: boolean;
+ /** Custom embedding_columns registry entries backed by a ZE model. */
+ zeCustomColumns: string[];
+ /** VOYAGE_API_KEY in env OR voyage_api_key in file config. */
+ hasVoyageKey: boolean;
+ /** provider_base_urls.zeroentropyai is overridden (file or DB plane) — the
+ * operator may be self-hosting a ZE-wire endpoint, so the HOSTED shutdown
+ * may not break them. Exposure stays exposed (fail-safe: we can't verify
+ * the endpoint), but the notice says so instead of claiming certain death. */
+ selfHostBaseUrl: boolean;
+ /** Names of probes that failed (drove status to 'unknown'). */
+ unknownProbes: string[];
+ blastRadius: ZeBlastRadius;
+}
+
+/** PRIVATE — both call sites pass hardcoded literal SQL; never pass dynamic
+ * or config-derived strings into `innerSql` (it is string-composed). If a
+ * future probe needs a parameter, add a fixed named query instead. */
+async function cappedCount(engine: BrainEngine, innerSql: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM (${innerSql} LIMIT ${BLAST_RADIUS_CAP + 1}) t`,
+ );
+ return Number(rows?.[0]?.n ?? 0);
+}
+
+function zeColumnsFromRegistry(registry: unknown, out: Set<string>): void {
+ if (!registry || typeof registry !== 'object') return;
+ for (const [name, entry] of Object.entries(registry as Record<string, unknown>)) {
+ if (!SAFE_COLUMN_KEY.test(name)) continue; // never echo nonconforming names
+ const provider = (entry as { provider?: unknown } | null)?.provider;
+ if (typeof provider === 'string' && provider.startsWith(ZE_PREFIX)) out.add(name);
+ }
+}
+
+/**
+ * ZE-backed custom-column names for this brain (file + DB registry planes).
+ * Shared by detectZeExposure and doctor's provider_sunset check — the doctor
+ * must not report ok while a ZE-backed custom column is still live.
+ */
+export async function detectZeCustomColumns(
+ engine: BrainEngine,
+ fileCfgArg?: GBrainConfig | null,
+): Promise<{ columns: string[]; probeFailed: boolean }> {
+ const fileCfg = fileCfgArg !== undefined ? fileCfgArg : loadConfigFileOnly();
+ const zeCols = new Set<string>();
+ zeColumnsFromRegistry(fileCfg?.embedding_columns, zeCols);
+ let probeFailed = false;
+ try {
+ const raw = await engine.getConfig('embedding_columns');
+ if (raw) zeColumnsFromRegistry(JSON.parse(raw), zeCols);
+ } catch {
+ probeFailed = true;
+ }
+ return { columns: [...zeCols].sort(), probeFailed };
+}
+
+/**
+ * Detect this brain's ZeroEntropy exposure. Every DB probe is individually
+ * try/caught; a failure marks the probe unknown instead of throwing (a broken
+ * schema must not turn detection into a crash — or into a false 'clear').
+ */
+export async function detectZeExposure(
+ engine: BrainEngine,
+ fileCfgArg?: GBrainConfig | null,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<ZeExposure> {
+ const fileCfg = fileCfgArg !== undefined ? fileCfgArg : loadConfigFileOnly();
+ const unknownProbes: string[] = [];
+
+ // --- Embedding axis: pure config resolution, cannot fail -----------------
+ const disabled = fileCfg?.embedding_disabled === true;
+ const envModel = env.GBRAIN_EMBEDDING_MODEL?.trim() || undefined;
+ const fileModel = fileCfg?.embedding_model;
+ const effective = envModel ?? fileModel ?? DEFAULT_EMBEDDING_MODEL;
+ const zeEmbedding = !disabled && effective.startsWith(ZE_PREFIX);
+ const envOverride = !disabled && !!envModel?.startsWith(ZE_PREFIX);
+ const zeExplicit = !disabled && !envModel && !!fileModel?.startsWith(ZE_PREFIX);
+ const bareDefaultZe = !disabled && !envModel && !fileModel;
+
+ // --- Reranker axis: resolve through the SAME plane search reranks with ---
+ // (mode bundle + search.reranker.* config; env excluded). Detectable
+ // precisely because the bundle default stays legacy-ZE until September.
+ let zeReranker = false;
+ try {
+ const { loadSearchModeConfig, resolveSearchMode } = await import('./search/mode.ts');
+ const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
+ zeReranker = knobs.reranker_enabled && knobs.reranker_model.startsWith(ZE_PREFIX);
+ } catch {
+ unknownProbes.push('reranker_resolution');
+ }
+
+ // --- Custom-column axis: both planes (file + DB registry) ----------------
+ const colProbe = await detectZeCustomColumns(engine, fileCfg);
+ if (colProbe.probeFailed) unknownProbes.push('embedding_columns_db');
+ const zeCustomColumns = colProbe.columns;
+
+ const hasVoyageKey = !!(env.VOYAGE_API_KEY || fileCfg?.voyage_api_key);
+
+ // --- Self-host signal (informational): base-URL override on either plane --
+ let selfHostBaseUrl = !!fileCfg?.provider_base_urls?.zeroentropyai;
+ if (!selfHostBaseUrl) {
+ try {
+ selfHostBaseUrl = !!(await engine.getConfig('provider_base_urls.zeroentropyai'));
+ } catch {
+ // Informational only — a failed probe never flips status here.
+ }
+ }
+
+ // --- Blast radius (informational; failures do NOT flip status) -----------
+ const blastRadius: ZeBlastRadius = {
+ zeSignedPages: null,
+ zeSignedPagesCapped: false,
+ embeddedChunks: null,
+ embeddedChunksCapped: false,
+ estReembedUsd: null,
+ };
+ if (zeEmbedding) {
+ try {
+ const n = await cappedCount(
+ engine,
+ `SELECT 1 FROM pages WHERE embedding_signature LIKE '${ZE_PREFIX}%'`,
+ );
+ blastRadius.zeSignedPages = Math.min(n, BLAST_RADIUS_CAP);
+ blastRadius.zeSignedPagesCapped = n > BLAST_RADIUS_CAP;
+ } catch {
+ // Pre-v108 schemas have no embedding_signature column — informational.
+ }
+ try {
+ const n = await cappedCount(
+ engine,
+ `SELECT 1 FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ blastRadius.embeddedChunks = Math.min(n, BLAST_RADIUS_CAP);
+ blastRadius.embeddedChunksCapped = n > BLAST_RADIUS_CAP;
+ const price = lookupEmbeddingPrice(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);
+ if (price.kind === 'known' && blastRadius.embeddedChunks !== null) {
+ // ~400 tokens/chunk repo-wide average (CLAUDE.md cost anchors).
+ const tokens = blastRadius.embeddedChunks * 400;
+ blastRadius.estReembedUsd = (tokens / 1_000_000) * price.pricePerMTok;
+ }
+ } catch {
+ // Fresh/odd brains: no chunk count, no cost estimate. Informational.
+ }
+ }
+
+ const exposed = zeEmbedding || zeReranker || zeCustomColumns.length > 0;
+ const status: ZeExposureStatus = exposed
+ ? 'exposed'
+ : unknownProbes.length > 0
+ ? 'unknown'
+ : 'clear';
+
+ return {
+ status,
+ zeEmbedding,
+ zeExplicit,
+ bareDefaultZe,
+ envOverride,
+ zeReranker,
+ zeCustomColumns,
+ hasVoyageKey,
+ selfHostBaseUrl,
+ unknownProbes,
+ blastRadius,
+ };
+}
+
+function fmtCount(n: number | null, capped: boolean): string {
+ if (n === null) return 'unknown';
+ return capped ? `${n.toLocaleString()}+` : n.toLocaleString();
+}
+
+/**
+ * Render the shared ACTION REQUIRED body. Both the v0.46.3 migration notice
+ * and the stage-2 upgrade banner wrap this text (DRY: the exposure story is
+ * written once). Plain ASCII, <= 78 cols per repo convention.
+ */
+export function renderZeActionRequired(exposure: ZeExposure): string {
+ const lines: string[] = [];
+ lines.push(`ZeroEntropy stops working on ${ZEROENTROPY_SUNSET_DATE}.`);
+ if (exposure.status === 'unknown' && !exposure.zeEmbedding && !exposure.zeReranker) {
+ lines.push(
+ `This brain's exposure could not be fully determined ` +
+ `(failed probes: ${exposure.unknownProbes.join(', ')}). Treat it as affected ` +
+ `until \`gbrain doctor\` reports provider_sunset ok.`,
+ );
+ }
+ if (exposure.zeEmbedding) {
+ const via = exposure.envOverride
+ ? 'via the GBRAIN_EMBEDDING_MODEL env var'
+ : exposure.zeExplicit
+ ? 'via embedding_model in ~/.gbrain/config.json'
+ : 'via the configless runtime fallback (nothing is configured)';
+ lines.push(`This brain EMBEDS with ZeroEntropy (${via}).`);
+ lines.push(
+ `Blast radius: ${fmtCount(exposure.blastRadius.zeSignedPages, exposure.blastRadius.zeSignedPagesCapped)} ` +
+ `ZE-stamped pages / ${fmtCount(exposure.blastRadius.embeddedChunks, exposure.blastRadius.embeddedChunksCapped)} ` +
+ `embedded chunks` +
+ (exposure.blastRadius.estReembedUsd !== null
+ ? ` (${exposure.blastRadius.embeddedChunksCapped ? 'at least ' : ''}~$${exposure.blastRadius.estReembedUsd.toFixed(2)} to re-embed with ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL})`
+ : ''),
+ );
+ lines.push(
+ `Fix: gbrain migrate embeddings --to ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} ` +
+ `--dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS} --dry-run`,
+ );
+ lines.push(
+ ` (Voyage's valid widths are 256/512/1024/2048 — legacy default brains are ` +
+ `1280d and get a one-time rebuild to ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS}.`,
+ );
+ lines.push(
+ ` OpenAI can keep widths up to 1536: --to openai:text-embedding-3-small --dim <width>.`,
+ );
+ lines.push(
+ ` \`gbrain doctor\` prints this brain's exact width-aware command.)`,
+ );
+ if (exposure.envOverride) {
+ lines.push(
+ `NOTE: GBRAIN_EMBEDDING_MODEL currently forces the ZE model — the env var itself`,
+ );
+ lines.push(`must change; config edits alone cannot fix this brain.`);
+ }
+ }
+ if (exposure.zeReranker) {
+ lines.push(
+ `Reranking currently resolves to ZE zerank-2 and dies the same day. Fix:`,
+ );
+ lines.push(
+ ` gbrain config set search.reranker.model ${NEW_INSTALL_DEFAULT_RERANKER_MODEL}` +
+ (exposure.hasVoyageKey ? '' : ' (needs VOYAGE_API_KEY)'),
+ );
+ lines.push(` (or disable: gbrain config set search.reranker.enabled false)`);
+ }
+ if (exposure.zeCustomColumns.length > 0) {
+ lines.push(
+ `Custom embedding column(s) backed by ZeroEntropy: ${exposure.zeCustomColumns.join(', ')}.`,
+ );
+ lines.push(
+ `No automated off-ramp exists for custom columns yet (migrate embeddings covers`,
+ );
+ lines.push(
+ `the primary column only) — re-declare them on the new provider and re-embed.`,
+ );
+ }
+ if (exposure.selfHostBaseUrl) {
+ lines.push(
+ `NOTE: provider_base_urls.zeroentropyai is overridden. If that endpoint is a`,
+ );
+ lines.push(
+ `self-hosted ZE-wire-compatible server, the hosted shutdown does not break it —`,
+ );
+ lines.push(
+ `but the zeroentropyai provider id is still slated for removal (see the`,
+ );
+ lines.push(`self-host continuity TODO in the playbook) — plan a migration anyway.`);
+ }
+ lines.push(`Nothing has been changed automatically; this brain keeps working until the date.`);
+ lines.push(`Agent playbook: skills/migrations/v0.46.3.0.md`);
+ return lines.join('\n');
+}
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 6c6b58a89b..f856c87c9e 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.46.2.0 -->
+<!-- gbrain-template-stamp: 0.46.3.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/rerank.test.ts b/test/ai/rerank.test.ts
index 196520525c..728e42df79 100644
--- a/test/ai/rerank.test.ts
+++ b/test/ai/rerank.test.ts
@@ -431,3 +431,106 @@ describe('gateway.rerank() — v0.40.6.1 path regression: zerank-1-small unaffec
expect(capturedUrl.endsWith('/models/rerank')).toBe(true);
});
});
+
+describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
+ function configureVoyage(model: string = 'voyage:rerank-2.5'): void {
+ configureGateway({
+ reranker_model: model,
+ env: { VOYAGE_API_KEY: 'pa-test-voyagekey' },
+ });
+ }
+
+ test('posts to https://api.voyageai.com/v1/rerank (path override, no /v1/v1)', async () => {
+ configureVoyage();
+ let capturedUrl = '';
+ __setRerankTransportForTests(async (url) => {
+ capturedUrl = url;
+ return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
+ });
+ await rerank({ query: 'q', documents: ['d'] });
+ expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
+ });
+
+ test('request carries top_k (NOT top_n) — the only wire difference', async () => {
+ configureVoyage();
+ let body: any = null;
+ __setRerankTransportForTests(async (_url, init) => {
+ body = JSON.parse(String(init?.body ?? '{}'));
+ return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
+ });
+ await rerank({ query: 'q', documents: ['a', 'b'], topN: 1 });
+ expect(body.top_k).toBe(1);
+ expect(body.top_n).toBeUndefined();
+ expect(body.model).toBe('rerank-2.5');
+ });
+
+ test('ZE dialect still sends top_n (regression: top_param defaults)', async () => {
+ configureZE();
+ let body: any = null;
+ __setRerankTransportForTests(async (_url, init) => {
+ body = JSON.parse(String(init?.body ?? '{}'));
+ return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
+ });
+ await rerank({ query: 'q', documents: ['a', 'b'], topN: 1 });
+ expect(body.top_n).toBe(1);
+ expect(body.top_k).toBeUndefined();
+ });
+
+ test("voyage's REST data[] response parses (live-wire shape, 2026-08-15)", async () => {
+ configureVoyage();
+ __setRerankTransportForTests(async () =>
+ mockResp({
+ object: 'list',
+ data: [{ index: 1, relevance_score: 0.8 }, { index: 0, relevance_score: 0.3 }],
+ model: 'rerank-2.5',
+ usage: { total_tokens: 12 },
+ }),
+ );
+ const out = await rerank({ query: 'q', documents: ['a', 'b'] });
+ expect(out).toEqual([
+ { index: 1, relevanceScore: 0.8 },
+ { index: 0, relevanceScore: 0.3 },
+ ]);
+ });
+
+ test('the legacy results[] shape still parses too (ZE/llama-server dialect)', async () => {
+ configureVoyage();
+ __setRerankTransportForTests(async () =>
+ mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
+ );
+ const out = await rerank({ query: 'q', documents: ['a'] });
+ expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
+ });
+
+ test('malformed response (neither results[] nor data[]) → RerankError', async () => {
+ configureVoyage();
+ __setRerankTransportForTests(async () => mockResp({ items: [{ index: 0 }] }));
+ await expect(rerank({ query: 'q', documents: ['a'] })).rejects.toThrow(RerankError);
+ });
+
+ test('missing VOYAGE_API_KEY → RerankError auth (fail-open class)', async () => {
+ resetGateway();
+ configureGateway({ reranker_model: 'voyage:rerank-2.5', env: {} });
+ __setRerankTransportForTests(async () =>
+ mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
+ );
+ try {
+ await rerank({ query: 'q', documents: ['a'] });
+ expect.unreachable('should have thrown');
+ } catch (e) {
+ expect(e).toBeInstanceOf(RerankError);
+ expect((e as RerankError).reason).toBe('auth');
+ }
+ });
+
+ test('rerank-2.5-lite passes the allowlist', async () => {
+ configureVoyage('voyage:rerank-2.5-lite');
+ let body: any = null;
+ __setRerankTransportForTests(async (_url, init) => {
+ body = JSON.parse(String(init?.body ?? '{}'));
+ return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
+ });
+ await rerank({ query: 'q', documents: ['a'] });
+ expect(body.model).toBe('rerank-2.5-lite');
+ });
+});
diff --git a/test/ai/sunset-warn.test.ts b/test/ai/sunset-warn.test.ts
new file mode 100644
index 0000000000..d524ab61b7
--- /dev/null
+++ b/test/ai/sunset-warn.test.ts
@@ -0,0 +1,112 @@
+/**
+ * v0.46.3 — once-per-process sunset warn-on-use.
+ *
+ * A recipe with `sunset` metadata warns on stderr the first time each
+ * touchpoint is actually used, exactly once per (recipe, touchpoint), with a
+ * paste-ready replacement command. Driven through the rerank path (the
+ * embedding path shares the same warnSunsetOnce helper) with the stubbed
+ * rerank transport. `_resetSunsetWarningsForTest` is the seam.
+ */
+
+import { describe, test, expect, afterEach, beforeEach } from 'bun:test';
+import {
+ configureGateway,
+ resetGateway,
+ rerank,
+ __setRerankTransportForTests,
+ _resetSunsetWarningsForTest,
+} from '../../src/core/ai/gateway.ts';
+
+function mockResp(json: unknown, status = 200): Response {
+ return new Response(JSON.stringify(json), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+let stderrChunks: string[] = [];
+let origWrite: typeof process.stderr.write;
+
+beforeEach(() => {
+ _resetSunsetWarningsForTest();
+ stderrChunks = [];
+ origWrite = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: any) => {
+ stderrChunks.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write;
+ configureGateway({
+ reranker_model: 'zeroentropyai:zerank-2',
+ env: { ZEROENTROPY_API_KEY: 'sk-test-zerokey' },
+ });
+ __setRerankTransportForTests(async () =>
+ mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
+ );
+});
+
+afterEach(() => {
+ process.stderr.write = origWrite;
+ __setRerankTransportForTests(null);
+ _resetSunsetWarningsForTest();
+ resetGateway();
+});
+
+describe('sunset warn-on-use (v0.46.3)', () => {
+ test('first ZE rerank prints the deprecation warning with the replacement command', async () => {
+ await rerank({ query: 'q', documents: ['a'] });
+ const all = stderrChunks.join('');
+ expect(all).toContain('DEPRECATED');
+ expect(all).toContain('2026-09-04');
+ expect(all).toContain('search.reranker.model voyage:rerank-2.5');
+ });
+
+ test('fires once per process, not once per call', async () => {
+ await rerank({ query: 'q', documents: ['a'] });
+ await rerank({ query: 'q2', documents: ['b'] });
+ const hits = stderrChunks.join('').split('DEPRECATED').length - 1;
+ expect(hits).toBe(1);
+ });
+
+ test('reset seam re-arms the warning', async () => {
+ await rerank({ query: 'q', documents: ['a'] });
+ _resetSunsetWarningsForTest();
+ await rerank({ query: 'q2', documents: ['b'] });
+ const hits = stderrChunks.join('').split('DEPRECATED').length - 1;
+ expect(hits).toBe(2);
+ });
+
+ test('a non-sunset provider warns nothing', async () => {
+ resetGateway();
+ configureGateway({
+ reranker_model: 'voyage:rerank-2.5',
+ env: { VOYAGE_API_KEY: 'pa-test' },
+ });
+ await rerank({ query: 'q', documents: ['a'] });
+ expect(stderrChunks.join('')).not.toContain('DEPRECATED');
+ });
+});
+
+describe('sunset warn-on-use — embedding touchpoint (v0.46.3)', () => {
+ test('first ZE embed resolution warns with the migrate command', async () => {
+ _resetSunsetWarningsForTest();
+ stderrChunks = [];
+ resetGateway();
+ configureGateway({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: 1280,
+ env: { ZEROENTROPY_API_KEY: 'sk-test-zerokey' },
+ });
+ const { __setEmbedTransportForTests, embedQuery } = await import('../../src/core/ai/gateway.ts');
+ __setEmbedTransportForTests(async (args: any) => ({
+ embeddings: args.values.map(() => Array.from({ length: 1280 }, () => 0.01)),
+ }) as any);
+ try {
+ await embedQuery('hello');
+ } finally {
+ __setEmbedTransportForTests(null);
+ }
+ const all = stderrChunks.join('');
+ expect(all).toContain('DEPRECATED');
+ expect(all).toContain('migrate embeddings --to voyage:voyage-4');
+ });
+});
diff --git a/test/ai/voyage-reranker-recipe.test.ts b/test/ai/voyage-reranker-recipe.test.ts
new file mode 100644
index 0000000000..752ef027fe
--- /dev/null
+++ b/test/ai/voyage-reranker-recipe.test.ts
@@ -0,0 +1,89 @@
+/**
+ * v0.46.3 — Voyage reranker touchpoint + canonical-model recipe contract.
+ *
+ * Pins:
+ * - The voyage recipe declares a reranker touchpoint: rerank-2.5 (default) +
+ * rerank-2.5-lite, POST path '/rerank' (base_url_default already ends in
+ * /v1 — no /v1/v1 doubling), request top-N key `top_k` via `top_param`.
+ * - `default_model: 'voyage-4'` on the embedding touchpoint — array order is
+ * quality-sorted (voyage-4-large first) and must NOT drive selection.
+ * - voyage-code-4 is in the embedding models AND in the flexible-dims set.
+ * - The zeroentropyai recipe carries `sunset` metadata with per-touchpoint
+ * replacements pointing at the voyage models.
+ * - Pricing rows exist for the voyage rerankers (budget-tracker's rerank
+ * metering falls back to the embedding pricing table).
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { voyage } from '../../src/core/ai/recipes/voyage.ts';
+import { zeroentropyai } from '../../src/core/ai/recipes/zeroentropyai.ts';
+import { getRecipe } from '../../src/core/ai/recipes/index.ts';
+import { EMBEDDING_PRICING } from '../../src/core/embedding-pricing.ts';
+import { supportsVoyageOutputDimension } from '../../src/core/ai/dims.ts';
+import {
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ NEW_INSTALL_DEFAULT_RERANKER_MODEL,
+} from '../../src/core/ai/defaults.ts';
+
+describe('voyage reranker touchpoint (v0.46.3)', () => {
+ test('declares rerank-2.5 as the default reranker at /rerank with top_k', () => {
+ const tp = voyage.touchpoints.reranker;
+ expect(tp).toBeDefined();
+ expect(tp!.models).toEqual(['rerank-2.5', 'rerank-2.5-lite']);
+ expect(tp!.default_model).toBe('rerank-2.5');
+ expect(tp!.path).toBe('/rerank');
+ expect(tp!.top_param).toBe('top_k');
+ expect(tp!.max_payload_bytes).toBeGreaterThan(0);
+ });
+
+ test('base URL + path compose without /v1/v1 doubling', () => {
+ const url = `${voyage.base_url_default!.replace(/\/$/, '')}${voyage.touchpoints.reranker!.path}`;
+ expect(url).toBe('https://api.voyageai.com/v1/rerank');
+ });
+
+ test('registry resolves the same recipe object', () => {
+ expect(getRecipe('voyage')?.touchpoints.reranker?.default_model).toBe('rerank-2.5');
+ });
+});
+
+describe('voyage canonical embedding model (v0.46.3)', () => {
+ test('default_model is voyage-4, NOT models[0] (voyage-4-large)', () => {
+ const tp = voyage.touchpoints.embedding!;
+ expect(tp.default_model).toBe('voyage-4');
+ expect(tp.models[0]).toBe('voyage-4-large');
+ expect(tp.models).toContain('voyage-4');
+ });
+
+ test('voyage-code-4 is listed and in the flexible-dims set', () => {
+ expect(voyage.touchpoints.embedding!.models).toContain('voyage-code-4');
+ expect(supportsVoyageOutputDimension('voyage-code-4')).toBe(true);
+ // The open-weight nano stays excluded (existing contract).
+ expect(supportsVoyageOutputDimension('voyage-4-nano')).toBe(false);
+ });
+
+ test('new-install default constants point at voyage', () => {
+ expect(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL).toBe('voyage:voyage-4');
+ expect(NEW_INSTALL_DEFAULT_RERANKER_MODEL).toBe('voyage:rerank-2.5');
+ });
+});
+
+describe('zeroentropyai sunset metadata (v0.46.3)', () => {
+ test('recipe carries sunset date + per-touchpoint replacements', () => {
+ expect(zeroentropyai.sunset).toBeDefined();
+ expect(zeroentropyai.sunset!.date).toBe('2026-09-04');
+ expect(zeroentropyai.sunset!.replacement?.embedding).toBe('voyage:voyage-4');
+ expect(zeroentropyai.sunset!.replacement?.reranker).toBe('voyage:rerank-2.5');
+ });
+
+ test('voyage carries NO sunset (it is the replacement, not the deprecated)', () => {
+ expect(voyage.sunset).toBeUndefined();
+ });
+});
+
+describe('voyage reranker pricing rows (v0.46.3)', () => {
+ test('rerank-2.5 + rerank-2.5-lite are priced (budget-tracker fallback)', () => {
+ expect(EMBEDDING_PRICING['voyage:rerank-2.5']?.pricePerMTok).toBe(0.05);
+ expect(EMBEDDING_PRICING['voyage:rerank-2.5-lite']?.pricePerMTok).toBe(0.02);
+ expect(EMBEDDING_PRICING['voyage:voyage-code-4']?.pricePerMTok).toBe(0.12);
+ });
+});
diff --git a/test/ai/zeroentropy-compat-fetch.test.ts b/test/ai/zeroentropy-compat-fetch.test.ts
index e12824b6d5..ea18d575c3 100644
--- a/test/ai/zeroentropy-compat-fetch.test.ts
+++ b/test/ai/zeroentropy-compat-fetch.test.ts
@@ -36,9 +36,11 @@ describe('zeroEntropyCompatFetch — shim structural shape', () => {
// fetch` the function-arrow type loses Bun's `preconnect` method
// signature. Pinning here prevents a future refactor from removing
// the cast and re-introducing the tsc TS2741 failure documented in
- // gateway.ts:556 comments.
+ // gateway.ts:556 comments. (Window is 3000 chars because v0.46.3's
+ // `warnSunsetOnce` block sits between the last shim cast and
+ // `resolveEmbeddingProvider`.)
const src = await Bun.file(GATEWAY_PATH).text();
- expect(src).toMatch(/\}\)\s*as unknown as typeof fetch;[\s\S]{0,200}async function resolveEmbeddingProvider/);
+ expect(src).toMatch(/\}\)\s*as unknown as typeof fetch;[\s\S]{0,3000}async function resolveEmbeddingProvider/);
});
test('URL rewrite: /embeddings → /models/embed (CDX1-F2)', async () => {
diff --git a/test/apply-migrations.test.ts b/test/apply-migrations.test.ts
index e79bbdfa7c..f5f229f305 100644
--- a/test/apply-migrations.test.ts
+++ b/test/apply-migrations.test.ts
@@ -108,7 +108,7 @@ describe('buildPlan — diff against completed + installed VERSION', () => {
// autopilot cooperative, v0.16.0 = subagent runtime, v0.18.0 = multi-
// source brains, v0.18.1 = RLS hardening, v0.21.0 = Cathedral II
// (renumbered from v0.20.0 after master shipped v0.20.x in parallel).
- expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0']);
+ expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3']);
});
test('already applied → v0.11.0 lands in `applied` bucket, not pending', () => {
@@ -148,7 +148,7 @@ describe('buildPlan — diff against completed + installed VERSION', () => {
// v0.22.4, v0.28.0, v0.29.1, v0.31.0 were added later; installed=0.12.0
// means they belong in skippedFuture, not pending. v0.11.0 and v0.12.0
// stay pending despite being ≤ installed — that is the H9 invariant.
- expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0']);
+ expect(plan.skippedFuture.map(m => m.version)).toEqual(['0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0', '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0', '0.32.2', '0.43.0', '0.46.3']);
});
test('--migration filter narrows to one version', () => {
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
index e914d38a16..ad8222f88c 100644
--- a/test/config-set.test.ts
+++ b/test/config-set.test.ts
@@ -82,6 +82,14 @@ describe('KNOWN_CONFIG_KEYS', () => {
expect(KNOWN_CONFIG_KEYS).toContain('zeroentropy_api_key');
});
+ test('registers the provider_sunset suppression key (v0.46.3 documented command)', () => {
+ // doctor.ts + docs/guides/embedding-migration.md both document
+ // `gbrain config set doctor.suppress_provider_sunset true`; the key must
+ // be registered or the documented command exits 1 with "Unknown config
+ // key". Exact key, deliberately not a 'doctor.' prefix.
+ expect(KNOWN_CONFIG_KEYS).toContain('doctor.suppress_provider_sunset');
+ });
+
test('registers only the live conversation-parser fallback key', () => {
expect(KNOWN_CONFIG_KEYS).toContain('conversation_parser.llm_fallback_enabled');
expect(KNOWN_CONFIG_KEY_PREFIXES).not.toContain('conversation_parser.');
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 6cef46c379..4df47eda45 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -120,7 +120,9 @@ describe('doctor command', () => {
} as any);
expect(check.status).toBe('warn');
expect(check.message).toContain('unknown');
- expect(check.message).toContain('ZEROENTROPY_API_KEY');
+ // v0.46.3: the hint names the reranker provider's key generically
+ // (VOYAGE_API_KEY example) — ZE is sunsetting.
+ expect(check.message).toContain('VOYAGE_API_KEY');
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
diff --git a/test/e2e/fresh-install-pglite.test.ts b/test/e2e/fresh-install-pglite.test.ts
index 1b3f3f3bce..1c24fad2b6 100644
--- a/test/e2e/fresh-install-pglite.test.ts
+++ b/test/e2e/fresh-install-pglite.test.ts
@@ -19,43 +19,57 @@ import {
configureGateway,
resetGateway,
__setEmbedTransportForTests,
- DEFAULT_EMBEDDING_MODEL,
- DEFAULT_EMBEDDING_DIMENSIONS,
} from '../../src/core/ai/gateway.ts';
+import {
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
+} from '../../src/core/ai/defaults.ts';
describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end', () => {
let tmpHome: string;
let origHome: string | undefined;
- let origZeKey: string | undefined;
- let origOpenaiKey: string | undefined;
- let origVoyageKey: string | undefined;
+ // v0.46.3: the single-ready provider for a fresh install is VOYAGE (ZE is
+ // sunset-excluded from auto-pick). Scrub EVERY embedding-capable key a dev
+ // machine might carry so init sees exactly one ready provider — otherwise
+ // ambient multi-provider env (Garry's setup) fails the disambiguation gate
+ // before the test body runs.
+ const SCRUB_KEYS = [
+ 'ZEROENTROPY_API_KEY',
+ 'OPENAI_API_KEY',
+ 'VOYAGE_API_KEY',
+ 'OPENROUTER_API_KEY',
+ 'PERPLEXITY_API_KEY',
+ 'GOOGLE_GENERATIVE_AI_API_KEY',
+ 'GEMINI_API_KEY',
+ 'DASHSCOPE_API_KEY',
+ 'MISTRAL_API_KEY',
+ 'NVIDIA_API_KEY',
+ 'ZHIPU_API_KEY',
+ 'MINIMAX_API_KEY',
+ 'AZURE_OPENAI_API_KEY',
+ ] as const;
+ const savedKeys: Record<string, string | undefined> = {};
beforeEach(() => {
tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-e2e-fresh-'));
origHome = process.env.GBRAIN_HOME;
- origZeKey = process.env.ZEROENTROPY_API_KEY;
- // Save + clear OPENAI_API_KEY + VOYAGE_API_KEY so init only sees
- // one provider as env-ready (ZE). Without this, dev machines with
- // multi-provider env (Garry's setup) fail init's disambiguation gate
- // ("Multiple embedding providers env-ready: openai, voyage,
- // zeroentropyai") before the test body runs.
- origOpenaiKey = process.env.OPENAI_API_KEY;
- origVoyageKey = process.env.VOYAGE_API_KEY;
- delete process.env.OPENAI_API_KEY;
- delete process.env.VOYAGE_API_KEY;
+ for (const k of SCRUB_KEYS) {
+ savedKeys[k] = process.env[k];
+ delete process.env[k];
+ }
process.env.GBRAIN_HOME = tmpHome;
- // Stub key so init's setup-hint check passes.
- process.env.ZEROENTROPY_API_KEY = 'sk-test-ze';
+ // Stub key so init auto-picks the canonical voyage default.
+ process.env.VOYAGE_API_KEY = 'pa-test-voyage';
});
afterEach(() => {
rmSync(tmpHome, { recursive: true, force: true });
if (origHome === undefined) delete process.env.GBRAIN_HOME;
else process.env.GBRAIN_HOME = origHome;
- if (origZeKey === undefined) delete process.env.ZEROENTROPY_API_KEY;
- else process.env.ZEROENTROPY_API_KEY = origZeKey;
- if (origOpenaiKey !== undefined) process.env.OPENAI_API_KEY = origOpenaiKey;
- if (origVoyageKey !== undefined) process.env.VOYAGE_API_KEY = origVoyageKey;
+ for (const k of SCRUB_KEYS) {
+ if (savedKeys[k] === undefined) delete process.env[k];
+ else process.env[k] = savedKeys[k];
+ }
__setEmbedTransportForTests(null);
// Restore legacy-preload gateway state.
configureGateway({
@@ -65,17 +79,16 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
});
});
- test('bare `init --pglite`: schema sized to gateway defaults (ZE/1280)', async () => {
- // Reset gateway so init.ts has to resolve defaults from
+ test('bare `init --pglite`: schema sized to the new-install default (voyage-4/1024)', async () => {
+ // Reset gateway so init.ts has to resolve the new-install default from
// ai/defaults.ts. This is the actual production code path for a
- // fresh install: bare `gbrain init --pglite` with no env or file
- // config.
+ // fresh install: bare `gbrain init --pglite` with a single ready key.
resetGateway();
- // Stub embed transport to return synthetic 1280-dim vectors. The
+ // Stub embed transport to return synthetic target-width vectors. The
// bug fix is dimension alignment — actual provider correctness is
// tested elsewhere.
- const synthVec = Array.from({ length: DEFAULT_EMBEDDING_DIMENSIONS }, () => 0.01);
+ const synthVec = Array.from({ length: NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS }, () => 0.01);
__setEmbedTransportForTests(async (args: any) => ({
embeddings: args.values.map(() => synthVec),
}) as any);
@@ -106,18 +119,21 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
const allOut = stdoutBuf.join('\n');
// Init prints the resolved embedding choice (B.1).
- expect(allOut).toContain(DEFAULT_EMBEDDING_MODEL);
- expect(allOut).toContain(`(${DEFAULT_EMBEDDING_DIMENSIONS}d)`);
+ expect(allOut).toContain(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);
+ expect(allOut).toContain(`(${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS}d)`);
// config.json contains the saved resolved defaults (B.4 + CDX-3).
const cfgPath = join(tmpHome, '.gbrain', 'config.json');
expect(existsSync(cfgPath)).toBe(true);
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
expect(cfg.engine).toBe('pglite');
- expect(cfg.embedding_model).toBe(DEFAULT_EMBEDDING_MODEL);
- expect(cfg.embedding_dimensions).toBe(DEFAULT_EMBEDDING_DIMENSIONS);
+ expect(cfg.embedding_model).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);
+ expect(cfg.embedding_dimensions).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);
- // The actual schema column dim matches.
+ // The actual schema column dim matches, and the voyage-picked install
+ // wrote the explicit reranker override (v0.46.3 split-default: the bundle
+ // default stays legacy-ZE, so a fresh voyage brain needs this config or
+ // it resolves a reranker whose key it doesn't have).
const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
const engine = new PGLiteEngine();
await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
@@ -125,15 +141,196 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
const { readContentChunksEmbeddingDim } = await import('../../src/core/embedding-dim-check.ts');
const colDim = await readContentChunksEmbeddingDim(engine);
expect(colDim.exists).toBe(true);
- expect(colDim.dims).toBe(DEFAULT_EMBEDDING_DIMENSIONS);
+ expect(colDim.dims).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);
+ expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
} finally {
await engine.disconnect();
}
}, 30000);
+ test('re-init never clobbers an existing explicit reranker choice', async () => {
+ resetGateway();
+ const synthVec = Array.from({ length: NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS }, () => 0.01);
+ __setEmbedTransportForTests(async (args: any) => ({
+ embeddings: args.values.map(() => synthVec),
+ }) as any);
+ const origLog = console.log;
+ const origWarn = console.warn;
+ console.log = () => {};
+ console.warn = () => {};
+ try {
+ const { runInit } = await import('../../src/commands/init.ts');
+ await runInit(['--pglite', '--non-interactive']);
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
+ try {
+ await engine.setConfig('search.reranker.model', 'openrouter:cohere/rerank-custom');
+ } finally {
+ await engine.disconnect();
+ }
+ // Re-init the same brain: the override write must respect the user's
+ // explicit choice (never-clobber contract).
+ await runInit(['--pglite', '--non-interactive', '--force']);
+ const engine2 = new PGLiteEngine();
+ await engine2.connect({ database_path: cfg.database_path, engine: 'pglite' });
+ try {
+ expect(await engine2.getConfig('search.reranker.model')).toBe('openrouter:cohere/rerank-custom');
+ } finally {
+ await engine2.disconnect();
+ }
+ } finally {
+ console.log = origLog;
+ console.warn = origWarn;
+ }
+ }, 60000);
+
+ test('explicit --embedding-model on a sunset provider proceeds WITH a loud warning (D3 allow-explicit)', async () => {
+ resetGateway();
+ process.env.ZEROENTROPY_API_KEY = 'ze-test-explicit';
+ const synthVec = Array.from({ length: 1280 }, () => 0.01);
+ __setEmbedTransportForTests(async (args: any) => ({
+ embeddings: args.values.map(() => synthVec),
+ }) as any);
+ const origLog = console.log;
+ const origWarn = console.warn;
+ const origError = console.error;
+ let errBuf = '';
+ console.log = () => {};
+ console.warn = () => {};
+ console.error = (...args: unknown[]) => { errBuf += args.join(' ') + '\n'; };
+ try {
+ const { runInit } = await import('../../src/commands/init.ts');
+ await runInit([
+ '--pglite', '--non-interactive',
+ '--embedding-model', 'zeroentropyai:zembed-1',
+ '--embedding-dimensions', '1280',
+ ]);
+ const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
+ // Allowed until the September removal — explicit choice is honored...
+ expect(cfg.embedding_model).toBe('zeroentropyai:zembed-1');
+ // ...but never silently: the sunset warning names the date + escape route.
+ expect(errBuf).toContain('2026-09-04');
+ expect(errBuf).toContain('migrate embeddings');
+ } finally {
+ console.log = origLog;
+ console.warn = origWarn;
+ console.error = origError;
+ }
+ }, 30000);
+
+ test('v0.46.3: keyed NON-voyage install disables the reranker explicitly (no doomed legacy default)', async () => {
+ resetGateway();
+ delete process.env.VOYAGE_API_KEY;
+ process.env.OPENAI_API_KEY = 'sk-test-openai';
+ const origLog = console.log;
+ const origError = console.error;
+ console.log = () => {};
+ console.error = () => {};
+ try {
+ const { runInit } = await import('../../src/commands/init.ts');
+ await runInit(['--pglite', '--non-interactive']);
+ const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
+ expect(cfg.embedding_model).toBe('openai:text-embedding-3-large');
+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
+ try {
+ // No voyage key on either plane → the fresh brain must not silently
+ // inherit the legacy sunset bundle reranker it has no key for.
+ expect(await engine.getConfig('search.reranker.model')).toBeNull();
+ expect(await engine.getConfig('search.reranker.enabled')).toBe('false');
+ } finally {
+ await engine.disconnect();
+ }
+ } finally {
+ console.log = origLog;
+ console.error = origError;
+ }
+ }, 30000);
+
+ test('keyless fresh install sizes the column at the NEW-INSTALL width (1024), not the legacy 1280', async () => {
+ resetGateway();
+ delete process.env.VOYAGE_API_KEY; // zero keys → keyless continue
+ const origLog = console.log;
+ const origWarn = console.warn;
+ const origError = console.error;
+ console.log = () => {};
+ console.warn = () => {};
+ console.error = () => {};
+ try {
+ const { runInit } = await import('../../src/commands/init.ts');
+ await runInit(['--pglite', '--non-interactive']);
+ const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
+ expect(cfg.embedding_disabled).toBe(true);
+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
+ try {
+ const { readContentChunksEmbeddingDim } = await import('../../src/core/embedding-dim-check.ts');
+ const colDim = await readContentChunksEmbeddingDim(engine);
+ expect(colDim.exists).toBe(true);
+ expect(colDim.dims).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);
+ } finally {
+ await engine.disconnect();
+ }
+ } finally {
+ console.log = origLog;
+ console.warn = origWarn;
+ console.error = origError;
+ }
+ }, 30000);
+
+ test('v0.46.3: keyless recovery — `init --force --embedding-model` clears embedding_disabled', async () => {
+ // The documented recovery command for a deferred-setup brain is
+ // `gbrain init --force --embedding-model voyage:voyage-4`. Two traps made
+ // it a silent no-op: the seeded embedding_disabled sentinel set
+ // out.noEmbedding (which an explicit flag must clear), and the persist
+ // block's ...existingFile spread re-wrote the stale sentinel alongside
+ // the new model. This pins the full keyless → keyed round trip.
+ resetGateway();
+ const origLog = console.log;
+ const origWarn = console.warn;
+ const origError = console.error;
+ console.log = () => {};
+ console.warn = () => {};
+ console.error = () => {};
+ try {
+ const { runInit } = await import('../../src/commands/init.ts');
+ // Step 1: keyless install → deferred-setup sentinel persisted.
+ delete process.env.VOYAGE_API_KEY;
+ await runInit(['--pglite', '--non-interactive']);
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ expect(JSON.parse(readFileSync(cfgPath, 'utf-8')).embedding_disabled).toBe(true);
+ // Step 2: the key arrives; run the documented recovery command.
+ process.env.VOYAGE_API_KEY = 'pa-test-voyage';
+ await runInit(['--pglite', '--non-interactive', '--force', '--embedding-model', 'voyage:voyage-4']);
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
+ expect(cfg.embedding_model).toBe('voyage:voyage-4');
+ expect(cfg.embedding_dimensions).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);
+ expect(cfg.embedding_disabled).toBeUndefined();
+ // Keyless init wrote NO reranker config (deliberate), so the recovery
+ // re-init's voyage override lands instead of being never-clobbered.
+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
+ try {
+ expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
+ } finally {
+ await engine.disconnect();
+ }
+ } finally {
+ console.log = origLog;
+ console.warn = origWarn;
+ console.error = origError;
+ }
+ }, 30000);
+
test('init → seed page → embed: chunks have non-null embeddings, no dim mismatch', async () => {
resetGateway();
- const synthVec = Array.from({ length: DEFAULT_EMBEDDING_DIMENSIONS }, (_, i) => i === 0 ? 1 : 0.01);
+ const synthVec = Array.from({ length: NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS }, (_, i) => i === 0 ? 1 : 0.01);
__setEmbedTransportForTests(async (args: any) => ({
embeddings: args.values.map(() => synthVec),
}) as any);
diff --git a/test/e2e/init-fresh-pglite.test.ts b/test/e2e/init-fresh-pglite.test.ts
index d6ffe22276..4b85151778 100644
--- a/test/e2e/init-fresh-pglite.test.ts
+++ b/test/e2e/init-fresh-pglite.test.ts
@@ -135,23 +135,47 @@ describe('v0.45 DX wave — non-TTY no-key defaults to keyless (typo still fail-
test('--non-interactive with multiple provider keys auto-picks the canonical default', async () => {
const multiHome = makeTempHome();
try {
+ // v0.46.3: the canonical new-install default is voyage:voyage-4
+ // (NEW_INSTALL_DEFAULT_EMBEDDING_MODEL); a ZE key no longer counts —
+ // sunset recipes are excluded from auto-pick entirely.
const r = await runCli(['init', '--pglite', '--non-interactive'], {
gbrainHome: multiHome,
env: {
OPENAI_API_KEY: 'sk-test-only-for-init-resolution-NOT-CALLED',
- ZEROENTROPY_API_KEY: 'ze-test-only-for-init-resolution-NOT-CALLED',
+ VOYAGE_API_KEY: 'pa-test-only-for-init-resolution-NOT-CALLED',
},
});
expect(r.exitCode).toBe(0);
expect(r.stderr).toContain('Multiple embedding providers env-ready');
expect(r.stderr).toContain('Override with --embedding-model');
const cfg = JSON.parse(readFileSync(join(multiHome, '.gbrain', 'config.json'), 'utf-8'));
- // Canonical default (DEFAULT_EMBEDDING_MODEL) wins when its key is present.
- expect(cfg.embedding_model).toBe('zeroentropyai:zembed-1');
+ // Canonical default wins when its key is present — voyage-4, NOT the
+ // quality-sorted models[0] (voyage-4-large).
+ expect(cfg.embedding_model).toBe('voyage:voyage-4');
+ expect(cfg.embedding_dimensions).toBe(1024);
} finally {
rmSync(multiHome, { recursive: true, force: true });
}
}, 240000);
+
+ test('--non-interactive with ONLY a sunset-provider key continues keyless (ZE excluded)', async () => {
+ const zeHome = makeTempHome();
+ try {
+ const r = await runCli(['init', '--pglite', '--non-interactive'], {
+ gbrainHome: zeHome,
+ env: { ZEROENTROPY_API_KEY: 'ze-test-only-for-init-resolution-NOT-CALLED' },
+ });
+ // Sunset exclusion means zero READY providers → keyless continue, not
+ // an auto-pick onto a provider that dies 2026-09-04.
+ expect(r.exitCode).toBe(0);
+ expect(r.stderr).toContain('keyless');
+ const cfg = JSON.parse(readFileSync(join(zeHome, '.gbrain', 'config.json'), 'utf-8'));
+ expect(cfg.embedding_disabled).toBe(true);
+ expect(cfg.embedding_model).toBeUndefined();
+ } finally {
+ rmSync(zeHome, { recursive: true, force: true });
+ }
+ }, 240000);
});
// ============================================================================
@@ -173,16 +197,16 @@ describe('v0.45 DX wave — --supabase non-TTY guard + multi-key no-canonical fa
}, 120000);
test('multiple provider keys with NO canonical candidate stays fail-loud with disambiguation hint', async () => {
- // The canonical default provider (zeroentropyai) has no key here, so the
+ // The canonical default provider (voyage, v0.46.3) has no key here, so the
// non-TTY auto-pick cannot resolve the ambiguity — it must fail loud
- // (D2/D3), not guess between openai and voyage.
+ // (D2/D3), not guess between openai and mistral.
const home = makeTempHome();
try {
const r = await runCli(['init', '--pglite', '--non-interactive'], {
gbrainHome: home,
env: {
OPENAI_API_KEY: 'sk-test-only-for-init-resolution-NOT-CALLED',
- VOYAGE_API_KEY: 'pa-test-only-for-init-resolution-NOT-CALLED',
+ MISTRAL_API_KEY: 'mi-test-only-for-init-resolution-NOT-CALLED',
},
});
expect(r.exitCode).toBe(1);
diff --git a/test/e2e/voyage-rerank-live.test.ts b/test/e2e/voyage-rerank-live.test.ts
new file mode 100644
index 0000000000..8a0f345582
--- /dev/null
+++ b/test/e2e/voyage-rerank-live.test.ts
@@ -0,0 +1,98 @@
+/**
+ * LIVE e2e — Voyage rerank + embed wire confirmation (v0.46.3).
+ *
+ * Skip-gated on VOYAGE_API_KEY. This is the REQUIRED pre-ship confirmation of
+ * the rerank wire contract the unit tests pin with stubs: POST
+ * https://api.voyageai.com/v1/rerank with `top_k`, response
+ * `{object: "list", data: [{index, relevance_score}]}` (the gateway parser
+ * accepts both data[] and the legacy results[] dialect). Also round-trips one
+ * voyage-4 embed at the new-install width (1024).
+ *
+ * Run: VOYAGE_API_KEY=... bun test test/e2e/voyage-rerank-live.test.ts
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import {
+ configureGateway,
+ resetGateway,
+ embedQuery,
+ rerank,
+} from '../../src/core/ai/gateway.ts';
+
+const API_KEY = process.env.VOYAGE_API_KEY;
+const skipAll = !API_KEY;
+
+beforeAll(() => {
+ if (skipAll) return;
+ configureGateway({
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ reranker_model: 'voyage:rerank-2.5',
+ env: { VOYAGE_API_KEY: API_KEY! },
+ });
+});
+
+afterAll(() => {
+ if (!skipAll) resetGateway();
+});
+
+describe('Voyage live — rerank wire contract', () => {
+ test('rerank-2.5 returns relevance-ordered data[] and honors top_k', async () => {
+ if (skipAll) {
+ console.warn('[skip] VOYAGE_API_KEY not set');
+ return;
+ }
+ const out = await rerank({
+ query: 'What is the capital of France?',
+ documents: [
+ 'The Eiffel Tower is in Paris, the capital of France.',
+ 'Bananas are a good source of potassium.',
+ 'Paris is the capital and largest city of France.',
+ ],
+ topN: 2,
+ });
+ // top_k honored on the wire: exactly 2 results back.
+ expect(out.length).toBe(2);
+ for (const r of out) {
+ expect(typeof r.index).toBe('number');
+ expect(typeof r.relevanceScore).toBe('number');
+ }
+ // Both returned docs must be the France-relevant ones (index 0 and 2) —
+ // the potassium doc (index 1) is the one top_k=2 drops.
+ const indices = out.map((r) => r.index).sort();
+ expect(indices).toEqual([0, 2]);
+ // Ordered by descending relevance.
+ expect(out[0].relevanceScore).toBeGreaterThanOrEqual(out[1].relevanceScore);
+ }, 30_000);
+
+ test('rerank-2.5-lite also passes the wire', async () => {
+ if (skipAll) {
+ console.warn('[skip] VOYAGE_API_KEY not set');
+ return;
+ }
+ resetGateway();
+ configureGateway({
+ reranker_model: 'voyage:rerank-2.5-lite',
+ env: { VOYAGE_API_KEY: API_KEY! },
+ });
+ const out = await rerank({ query: 'hello', documents: ['hello world', 'goodbye'] });
+ expect(out.length).toBe(2);
+ }, 30_000);
+});
+
+describe('Voyage live — voyage-4 embed at the new-install width', () => {
+ test('embedQuery returns a 1024-dim vector', async () => {
+ if (skipAll) {
+ console.warn('[skip] VOYAGE_API_KEY not set');
+ return;
+ }
+ resetGateway();
+ configureGateway({
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: API_KEY! },
+ });
+ const vec = await embedQuery('fresh install smoke');
+ expect(vec.length).toBe(1024);
+ }, 30_000);
+});
diff --git a/test/e2e/zeroentropy-live.test.ts b/test/e2e/zeroentropy-live.test.ts
index 772c7b1c1c..ede7f88b37 100644
--- a/test/e2e/zeroentropy-live.test.ts
+++ b/test/e2e/zeroentropy-live.test.ts
@@ -35,9 +35,15 @@ import {
const API_KEY = process.env.ZEROENTROPY_API_KEY;
+// v0.46.3 date guard: ZeroEntropy's hosted API shuts down on the sunset date.
+// After it, this live suite can only go permanently red against a dead
+// endpoint — auto-skip regardless of key presence so a slipped removal wave
+// can't wedge CI. The September removal release deletes this file entirely.
+const SUNSET_PASSED = Date.now() >= Date.parse('2026-09-04T00:00:00Z');
+
// Skip the entire file when env is absent. `describe.skipIf` exists in
// modern bun:test; fall back to in-test guards for older runners.
-const skipAll = !API_KEY;
+const skipAll = !API_KEY || SUNSET_PASSED;
beforeAll(() => {
if (skipAll) return;
diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.ts
index 90e7ddd842..86ff3accb8 100644
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@ -117,6 +117,17 @@ describe('resolveMigrationTarget', () => {
expect(() => resolveMigrationTarget('litellm:my-custom-model')).toThrow(/--dim/);
expect(resolveMigrationTarget('litellm:my-custom-model', 1024).toDims).toBe(1024);
});
+ test('v0.46.3: refuses a sunset target (paid re-embed onto a dying provider)', () => {
+ expect(() => resolveMigrationTarget('zeroentropyai:zembed-1')).toThrow(/Refusing to migrate ONTO/);
+ expect(() => resolveMigrationTarget('zeroentropyai:zembed-1')).toThrow(/--force-sunset-target/);
+ });
+ test('v0.46.3: allowSunsetTarget is the loud escape hatch (self-hosted endpoint)', () => {
+ // Self-hosters keep the brain's existing width explicitly (--dim 1280).
+ expect(resolveMigrationTarget('zeroentropyai:zembed-1', 1280, { allowSunsetTarget: true })).toEqual({
+ toModel: 'zeroentropyai:zembed-1',
+ toDims: 1280,
+ });
+ });
});
describe('#3391 includeNullSignature widening', () => {
diff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.ts
index 41d5ac54f4..86773ed051 100644
--- a/test/init-env-detection.test.ts
+++ b/test/init-env-detection.test.ts
@@ -15,6 +15,7 @@
import { describe, test, expect } from 'bun:test';
import { groupReadyByProvider, findEnvKeyTypos, seedAIOptionsFromConfig } from '../src/commands/init.ts';
+import { withEnv } from './helpers/with-env.ts';
describe('groupReadyByProvider — embedding touchpoint', () => {
test('OPENAI_API_KEY alone → openai is ready', async () => {
@@ -27,9 +28,28 @@ describe('groupReadyByProvider — embedding touchpoint', () => {
expect(got.map(p => p.recipeId)).toContain('voyage');
});
- test('ZEROENTROPY_API_KEY alone → zeroentropyai is ready', async () => {
+ test('v0.46.3: file-plane voyage_api_key folds into readiness (buildGatewayConfig env)', async () => {
+ // init's resolveEmbeddingByEnv builds its effective env via
+ // buildGatewayConfig(fileCfg).env so keys placed in ~/.gbrain/config.json
+ // (the documented alternative to shell env) select a provider too. This
+ // pins the mechanism end-to-end: file key → gateway env fold → ready.
+ // buildEnv reads the REAL process.env (env wins over file), so scrub the
+ // ambient key for the duration — dev machines may have a live one set.
+ await withEnv({ VOYAGE_API_KEY: undefined }, async () => {
+ const { buildGatewayConfig } = await import('../src/core/ai/build-gateway-config.ts');
+ const folded = buildGatewayConfig({ voyage_api_key: 'pa-file-plane' } as never).env;
+ expect(folded.VOYAGE_API_KEY).toBe('pa-file-plane');
+ const got = await groupReadyByProvider('embedding', folded as NodeJS.ProcessEnv);
+ expect(got.map(p => p.recipeId)).toContain('voyage');
+ });
+ });
+
+ test('ZEROENTROPY_API_KEY alone → zeroentropyai is NOT auto-pickable (sunset exclusion)', async () => {
+ // v0.46.3: recipes with `sunset` metadata are excluded from auto-pick —
+ // a fresh install must not be steered onto a provider that dies on
+ // 2026-09-04. Explicit --embedding-model still works (with a warning).
const got = await groupReadyByProvider('embedding', { ZEROENTROPY_API_KEY: 'ze-test' });
- expect(got.map(p => p.recipeId)).toContain('zeroentropyai');
+ expect(got.map(p => p.recipeId)).not.toContain('zeroentropyai');
});
test('OPENAI_API_KEY + VOYAGE_API_KEY → both providers in ready list', async () => {
diff --git a/test/init-provider-picker.test.ts b/test/init-provider-picker.test.ts
index 6fbbc7483d..4149996768 100644
--- a/test/init-provider-picker.test.ts
+++ b/test/init-provider-picker.test.ts
@@ -163,3 +163,43 @@ describe('pickProvider — defensive paths', () => {
expect(stderr).toContain('embedding provider');
});
});
+
+describe('pickProvider — v0.46.3 sunset filter + canonical default_model', () => {
+ test('a sunset-only key offers NO provider rows (ZE filtered out)', async () => {
+ // Only ZEROENTROPY_API_KEY set: the sunset filter drops ZE from the
+ // offered list, keyless becomes the default choice, and readLineSafe's
+ // non-TTY-stdin default ('0' when no keyed provider is ready) returns
+ // null → the caller continues keyless.
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'embedding',
+ env: { ZEROENTROPY_API_KEY: 'ze-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ probeLocal: async () => ({ reachable: false }),
+ });
+ expect(got).toBeNull();
+ // The dying provider must not be offered as a numbered choice.
+ expect(stderr).not.toMatch(/\d\) zeroentropyai/);
+ });
+
+ test('voyage pick resolves the canonical default_model (voyage-4, not models[0])', async () => {
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'embedding',
+ env: { VOYAGE_API_KEY: 'pa-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ probeLocal: async () => ({ reachable: false }),
+ });
+ expect(got).not.toBeNull();
+ if (got) {
+ expect(got.fullModel).toBe('voyage:voyage-4');
+ expect(got.modelId).toBe('voyage-4');
+ }
+ // The displayed row must match what a pick selects — canonical, not the
+ // quality-sorted array head.
+ expect(stderr).toContain('voyage-4');
+ expect(stderr).not.toContain('voyage-4-large');
+ });
+});
diff --git a/test/migration-orchestrator-v0_46_3.serial.test.ts b/test/migration-orchestrator-v0_46_3.serial.test.ts
new file mode 100644
index 0000000000..a82926ccd4
--- /dev/null
+++ b/test/migration-orchestrator-v0_46_3.serial.test.ts
@@ -0,0 +1,161 @@
+/**
+ * v0.46.3 orchestrator — ZeroEntropy sunset notice (detect-and-notify only).
+ *
+ * Contract pins (registry shape mirrors migration-orchestrator-v0_21_0):
+ * - registered in the TS registry, correctly ordered after 0.43.0;
+ * - the orchestrator NEVER writes config (no pinning — the split-default
+ * made pinning unnecessary) and NEVER invokes migrate embeddings;
+ * - exposed brain → notice + ONE idempotent pending-host-work entry
+ * (re-run appends nothing);
+ * - dry-run takes no side effects (no pending-host-work write);
+ * - no config at all → complete, no nag;
+ * - unknown/unreachable-brain exposure → still `complete` (NOT partial —
+ * three partials would wedge the migration chain behind --force-retry).
+ *
+ * Serial: sandboxes GBRAIN_HOME + clears GBRAIN_EMBEDDING_* env.
+ */
+
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+let home: string;
+const savedEnv: Record<string, string | undefined> = {};
+const ENV_KEYS = [
+ 'GBRAIN_HOME',
+ 'GBRAIN_EMBEDDING_MODEL',
+ 'GBRAIN_EMBEDDING_DIMENSIONS',
+ 'VOYAGE_API_KEY',
+ 'DATABASE_URL',
+ 'GBRAIN_DATABASE_URL',
+];
+
+beforeEach(() => {
+ for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
+ home = mkdtempSync(join(tmpdir(), 'v047-mig-'));
+ process.env.GBRAIN_HOME = home;
+ delete process.env.GBRAIN_EMBEDDING_MODEL;
+ delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
+ delete process.env.VOYAGE_API_KEY;
+ delete process.env.DATABASE_URL;
+ delete process.env.GBRAIN_DATABASE_URL;
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (savedEnv[k] === undefined) delete process.env[k];
+ else process.env[k] = savedEnv[k];
+ }
+});
+
+// GBRAIN_HOME is a HOME-like root: gbrain resolves its dir as
+// `$GBRAIN_HOME/.gbrain/` (see configDir() in src/core/config.ts).
+function gbrainDir(): string {
+ return join(home, '.gbrain');
+}
+
+function writeZeConfig(): string {
+ mkdirSync(gbrainDir(), { recursive: true });
+ const cfgPath = join(gbrainDir(), 'config.json');
+ writeFileSync(
+ cfgPath,
+ JSON.stringify(
+ {
+ engine: 'pglite',
+ database_path: join(gbrainDir(), 'brain'),
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: 1280,
+ },
+ null,
+ 2,
+ ),
+ );
+ return cfgPath;
+}
+
+function pendingPath(): string {
+ return join(gbrainDir(), 'migrations', 'pending-host-work.jsonl');
+}
+
+function pendingEntries(): Array<{ migration: string }> {
+ if (!existsSync(pendingPath())) return [];
+ return readFileSync(pendingPath(), 'utf-8')
+ .split('\n')
+ .filter((l) => l.trim())
+ .map((l) => JSON.parse(l));
+}
+
+describe('v0.46.3 registry contract', () => {
+ test('registered, ordered after 0.43.0, pitch names the sunset', async () => {
+ const { migrations, getMigration } = await import('../src/commands/migrations/index.ts');
+ const versions = migrations.map((m) => m.version);
+ expect(versions).toContain('0.46.3');
+ expect(versions.indexOf('0.46.3')).toBeGreaterThan(versions.indexOf('0.43.0'));
+ const m = getMigration('0.46.3');
+ expect(m).not.toBeNull();
+ expect(m!.featurePitch.headline).toContain('2026-09-04');
+ expect(m!.featurePitch.headline).toContain('Voyage');
+ expect(m!.featurePitch.description ?? '').toContain('migrate embeddings --to voyage:voyage-4');
+ expect(typeof m!.orchestrator).toBe('function');
+ });
+});
+
+describe('v0.46.3 orchestrator behavior', () => {
+ test('no config at all → complete, no nag, no host-work file', async () => {
+ const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
+ const result = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
+ expect(result.status).toBe('complete');
+ expect(result.phases.some((p) => p.detail?.includes('no brain configured'))).toBe(true);
+ expect(existsSync(pendingPath())).toBe(false);
+ });
+
+ test('exposed ZE brain → notice + one host-work entry; NO config writes; idempotent re-run', async () => {
+ const cfgPath = writeZeConfig();
+ const before = readFileSync(cfgPath, 'utf-8');
+ const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
+
+ const first = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
+ expect(first.status).toBe('complete');
+ expect(first.pending_host_work).toBe(1);
+ expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
+
+ // Detect-and-notify ONLY: the config file is byte-identical afterwards.
+ expect(readFileSync(cfgPath, 'utf-8')).toBe(before);
+
+ const second = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
+ expect(second.status).toBe('complete');
+ expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
+ expect(second.phases.some((p) => p.detail === 'already recorded')).toBe(true);
+ }, 120_000);
+
+ test('dry-run on an exposed brain takes no side effects', async () => {
+ writeZeConfig();
+ const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
+ const result = await v0_46_3.orchestrator({ yes: true, dryRun: true, noAutopilotInstall: true });
+ expect(result.status).toBe('complete');
+ expect(existsSync(pendingPath())).toBe(false);
+ expect(result.phases.some((p) => p.name === 'host-work' && p.status === 'skipped')).toBe(true);
+ }, 120_000);
+
+ test('unreachable brain (bad database_url) → complete with fail-safe nag, never partial', async () => {
+ mkdirSync(gbrainDir(), { recursive: true });
+ writeFileSync(
+ join(gbrainDir(), 'config.json'),
+ JSON.stringify({
+ engine: 'postgres',
+ // Credential-free on purpose: port 1 refuses connections, which is
+ // all this fixture needs (a user:pass URL trips the push-time
+ // secret-scan guardrail even when synthetic).
+ database_url: 'postgres://127.0.0.1:1/void',
+ embedding_model: 'voyage:voyage-4',
+ }),
+ );
+ const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
+ const result = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
+ // A clear-by-config brain whose probes can't run is UNKNOWN → complete
+ // (no chain wedge) + host-work nag (fail-safe).
+ expect(result.status).toBe('complete');
+ expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
+ }, 120_000);
+});
diff --git a/test/provider-sunset-doctor.serial.test.ts b/test/provider-sunset-doctor.serial.test.ts
index 1ae4ccd9bd..865a82c151 100644
--- a/test/provider-sunset-doctor.serial.test.ts
+++ b/test/provider-sunset-doctor.serial.test.ts
@@ -80,8 +80,11 @@ describe('provider_sunset — doctor flags brains pinned to a sunsetting provide
// date-branch in the frozen-clock describe below — this test runs on the
// real clock, so it only asserts date-independent structure.)
expect(sunset!.message).toContain(ZEROENTROPY_SUNSET_DATE);
- // Paste-ready migration command with the brain's ACTUAL column width.
- expect(sunset!.message).toContain('gbrain migrate embeddings --to <provider:model> --dim 1280');
+ // v0.46.3: paste-ready TARGET-AWARE migration commands — voyage at its valid
+ // 1024 width (1280 is not a Voyage step) + the OpenAI keep-width
+ // alternative carrying the brain's ACTUAL column width.
+ expect(sunset!.message).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
+ expect(sunset!.message).toContain('openai:text-embedding-3-small --dim 1280');
// The self-host escape hatch gets equal billing (no migration at all).
expect(sunset!.message).toContain('Apache-2.0');
});
@@ -99,6 +102,9 @@ describe('provider_sunset — doctor flags brains pinned to a sunsetting provide
});
const check = await checkProviderSunset(engine);
expect(FLAGGED).toContain(check.status);
+ // v0.46.3 target-aware hint: the OpenAI keep-width alternative carries the
+ // ACTUAL width (640), never the drifted config value (1280); the voyage
+ // headline is always at its valid 1024 step.
expect(check.message).toContain('--dim 640');
expect(check.message).not.toContain('--dim 1280');
} finally {
diff --git a/test/providers.test.ts b/test/providers.test.ts
index f52969aa62..1b41fa8c30 100644
--- a/test/providers.test.ts
+++ b/test/providers.test.ts
@@ -91,6 +91,10 @@ describe('formatRecipeTable', () => {
expect(lines[2]).toContain('openai');
expect(lines[2]).toContain('✓ ready');
expect(lines[3]).toContain('zeroentropyai');
- expect(lines[3]).toContain('✗ missing ZEROENTROPY_API_KEY');
+ // v0.46.3: sunsetting providers show the DEPRECATED annotation instead of
+ // key-readiness — "ready" on a dying API is not a state to advertise.
+ expect(lines[3]).toContain('DEPRECATED');
+ expect(lines[3]).toContain('2026-09-04');
+ expect(lines[3]).toContain('voyage:voyage-4');
});
});
diff --git a/test/ze-exposure.test.ts b/test/ze-exposure.test.ts
new file mode 100644
index 0000000000..6d5de6740e
--- /dev/null
+++ b/test/ze-exposure.test.ts
@@ -0,0 +1,254 @@
+/**
+ * v0.46.3 — detectZeExposure truth table + engine-parity smoke.
+ *
+ * Exposure is EFFECTIVE-MODEL RESOLUTION (env → file → legacy fallback), not
+ * vector evidence: a configless brain is deterministically ZE-exposed; 1280d
+ * vectors alone prove nothing (OpenAI text-3 supports 1280). Probe failures
+ * downgrade to 'unknown', never to 'clear'. The truth table runs against stub
+ * engines (fast, no DB); the parity smoke runs the real SQL against a fresh
+ * PGLite brain so the pages.embedding_signature / content_chunks probes are
+ * pinned to a real schema.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { detectZeExposure, renderZeActionRequired } from '../src/core/ze-exposure.ts';
+
+/** Stub engine: healthy brain with no rows. getConfig(null) → search-mode
+ * resolution falls through to the balanced bundle (reranker enabled on the
+ * legacy ZE default — deliberate: that IS the implicit-bundle exposure). */
+function stubEngine(overrides?: Partial<Pick<BrainEngine, 'getConfig' | 'executeRaw'>>): BrainEngine {
+ return {
+ getConfig: overrides?.getConfig ?? (async () => null),
+ executeRaw: overrides?.executeRaw ?? (async () => [{ n: 0 }] as any),
+ } as unknown as BrainEngine;
+}
+
+/** A brain whose reranker is already off ZE (explicit voyage override). */
+function voyageRerankerEngine(): BrainEngine {
+ return stubEngine({
+ getConfig: async (key: string) =>
+ key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
+ });
+}
+
+const CLEAN_ENV = {} as NodeJS.ProcessEnv;
+
+describe('detectZeExposure — embedding axis (resolution, not evidence)', () => {
+ test('configless brain (no file config at all) → bareDefaultZe, exposed', async () => {
+ const e = await detectZeExposure(voyageRerankerEngine(), null, CLEAN_ENV);
+ expect(e.zeEmbedding).toBe(true);
+ expect(e.bareDefaultZe).toBe(true);
+ expect(e.zeExplicit).toBe(false);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('file config with no embedding_model → bareDefaultZe, exposed', async () => {
+ const cfg = { engine: 'pglite' } as GBrainConfig;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(e.bareDefaultZe).toBe(true);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('explicit ZE file config → zeExplicit, exposed', async () => {
+ const cfg = { embedding_model: 'zeroentropyai:zembed-1' } as GBrainConfig;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(e.zeExplicit).toBe(true);
+ expect(e.bareDefaultZe).toBe(false);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('voyage-configured brain with voyage reranker → clear', async () => {
+ const cfg = {
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ } as GBrainConfig;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(e.zeEmbedding).toBe(false);
+ expect(e.zeReranker).toBe(false);
+ expect(e.status).toBe('clear');
+ });
+
+ test('embedding_disabled (keyless) suppresses the embedding axis', async () => {
+ const cfg = { embedding_disabled: true } as GBrainConfig;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(e.zeEmbedding).toBe(false);
+ expect(e.bareDefaultZe).toBe(false);
+ });
+
+ test('env override naming ZE wins over a clean file config → envOverride, exposed', async () => {
+ const cfg = { embedding_model: 'openai:text-embedding-3-small' } as GBrainConfig;
+ const env = { GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1' } as NodeJS.ProcessEnv;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, env);
+ expect(e.envOverride).toBe(true);
+ expect(e.zeEmbedding).toBe(true);
+ expect(e.zeExplicit).toBe(false);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('env override naming a SAFE provider clears a ZE file config', async () => {
+ const cfg = { embedding_model: 'zeroentropyai:zembed-1' } as GBrainConfig;
+ const env = { GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-4' } as NodeJS.ProcessEnv;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, env);
+ expect(e.zeEmbedding).toBe(false);
+ expect(e.zeExplicit).toBe(false);
+ });
+});
+
+describe('detectZeExposure — reranker + custom-column axes', () => {
+ test('implicit bundle reranker (nothing configured) counts as exposure', async () => {
+ // The bundle default stays legacy zerank-2 until September — a brain that
+ // reranks with it today loses reranking on the sunset date.
+ const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
+ const e = await detectZeExposure(stubEngine(), cfg, CLEAN_ENV);
+ expect(e.zeReranker).toBe(true);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('ZE-backed custom column is flagged by name', async () => {
+ const cfg = {
+ embedding_model: 'voyage:voyage-4',
+ embedding_columns: {
+ embedding_ze_bench: { provider: 'zeroentropyai:zembed-1', dimensions: 1280, type: 'vector' },
+ embedding_openai: { provider: 'openai:text-embedding-3-small', dimensions: 1536, type: 'vector' },
+ },
+ } as unknown as GBrainConfig;
+ const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(e.zeCustomColumns).toEqual(['embedding_ze_bench']);
+ expect(e.status).toBe('exposed');
+ });
+
+ test('hasVoyageKey reads BOTH env and file plane', async () => {
+ const cfg = { voyage_api_key: 'pa-file' } as GBrainConfig;
+ const viaFile = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
+ expect(viaFile.hasVoyageKey).toBe(true);
+ const viaEnv = await detectZeExposure(voyageRerankerEngine(), null, {
+ VOYAGE_API_KEY: 'pa-env',
+ } as NodeJS.ProcessEnv);
+ expect(viaEnv.hasVoyageKey).toBe(true);
+ });
+});
+
+describe('detectZeExposure — tri-state (unknown never silently clears)', () => {
+ test('probe failure on an otherwise-clear brain → unknown, not clear', async () => {
+ // Search-mode resolution fails OPEN internally (a broken config read
+ // falls through to the bundle → ZE → exposed, which is itself fail-safe).
+ // The truly-unknown shape: reranker override readable and safe, but the
+ // custom-column registry probe fails.
+ const partiallyBroken = stubEngine({
+ getConfig: async (key: string) => {
+ if (key === 'search.reranker.model') return 'voyage:rerank-2.5';
+ if (key === 'embedding_columns') throw new Error('relation "config" corrupt');
+ return null;
+ },
+ });
+ const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
+ const e = await detectZeExposure(partiallyBroken, cfg, CLEAN_ENV);
+ expect(e.status).toBe('unknown');
+ expect(e.unknownProbes).toContain('embedding_columns_db');
+ });
+
+ test('fully-broken engine on a clear-config brain fails SAFE (exposed via bundle), never clear', async () => {
+ const broken = stubEngine({
+ getConfig: async () => {
+ throw new Error('boom');
+ },
+ executeRaw: async () => {
+ throw new Error('boom');
+ },
+ });
+ const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
+ const e = await detectZeExposure(broken, cfg, CLEAN_ENV);
+ // Mode resolution falls open to the balanced bundle (legacy ZE reranker)
+ // → exposed. The invariant under ANY probe failure: status !== 'clear'.
+ expect(e.status).not.toBe('clear');
+ });
+
+ test('probe failure on an exposed brain stays exposed (exposure is config-derived)', async () => {
+ const broken = stubEngine({
+ getConfig: async () => {
+ throw new Error('boom');
+ },
+ executeRaw: async () => {
+ throw new Error('boom');
+ },
+ });
+ const e = await detectZeExposure(broken, null, CLEAN_ENV);
+ expect(e.status).toBe('exposed'); // configless → ZE fallback, deterministic
+ });
+});
+
+describe('detectZeExposure — blast radius (capped, informational)', () => {
+ test('caps counts at 100k and marks them capped', async () => {
+ const big = stubEngine({
+ getConfig: async (key: string) =>
+ key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
+ executeRaw: async () => [{ n: 100_001 }] as any,
+ });
+ const e = await detectZeExposure(big, null, CLEAN_ENV);
+ expect(e.blastRadius.embeddedChunks).toBe(100_000);
+ expect(e.blastRadius.embeddedChunksCapped).toBe(true);
+ expect(renderZeActionRequired(e)).toContain('100,000+');
+ });
+
+ test('cost estimate uses the recommended target price', async () => {
+ const some = stubEngine({
+ getConfig: async (key: string) =>
+ key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
+ executeRaw: async () => [{ n: 1000 }] as any,
+ });
+ const e = await detectZeExposure(some, null, CLEAN_ENV);
+ // 1000 chunks × ~400 tokens × $0.06/M (voyage-4) = $0.024
+ expect(e.blastRadius.estReembedUsd).toBeCloseTo(0.024, 3);
+ });
+});
+
+describe('renderZeActionRequired — notice copy', () => {
+ test('names the axis, the date, and the paste-ready commands', async () => {
+ const e = await detectZeExposure(stubEngine(), null, CLEAN_ENV);
+ const text = renderZeActionRequired(e);
+ expect(text).toContain('2026-09-04');
+ expect(text).toContain('migrate embeddings --to voyage:voyage-4 --dim 1024');
+ // Width-honest copy: the OpenAI alternative names the width slot generically
+ // (the doctor prints the brain's exact width-aware command) — a static 1280
+ // here would be wrong for 640d/2560d ZE brains.
+ expect(text).toContain('openai:text-embedding-3-small --dim <width>');
+ expect(text).toContain('gbrain doctor');
+ expect(text).toContain('search.reranker.model voyage:rerank-2.5');
+ expect(text).toContain('skills/migrations/v0.46.3.0.md');
+ expect(text).toContain('Nothing has been changed automatically');
+ });
+
+ test('env-override notice says the env var itself must change', async () => {
+ const e = await detectZeExposure(voyageRerankerEngine(), null, {
+ GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1',
+ } as NodeJS.ProcessEnv);
+ expect(renderZeActionRequired(e)).toContain('GBRAIN_EMBEDDING_MODEL');
+ });
+});
+
+describe('detectZeExposure — PGLite engine parity smoke', () => {
+ test('the blast-radius SQL runs against a real fresh brain (no unknown probes)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ze-exposure-'));
+ const { createEngine } = await import('../src/core/engine-factory.ts');
+ const engine = await createEngine({ engine: 'pglite' });
+ await engine.connect({ engine: 'pglite', database_path: join(dir, 'brain') });
+ try {
+ await engine.initSchema();
+ const e = await detectZeExposure(engine, null, CLEAN_ENV);
+ // Configless → exposed via the legacy fallback; every probe must have
+ // RUN cleanly on the real schema (pages.embedding_signature exists,
+ // content_chunks counts work).
+ expect(e.status).toBe('exposed');
+ expect(e.unknownProbes).toEqual([]);
+ expect(e.blastRadius.zeSignedPages).toBe(0);
+ expect(e.blastRadius.embeddedChunks).toBe(0);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 120_000);
+});
diff --git a/test/ze-switch-cli.test.ts b/test/ze-switch-cli.test.ts
index 0178f1534a..03c2d39bdd 100644
--- a/test/ze-switch-cli.test.ts
+++ b/test/ze-switch-cli.test.ts
@@ -1,18 +1,20 @@
/**
- * v0.36.0.0 (T3) — `gbrain ze-switch` CLI tests.
+ * v0.46.3 — `gbrain ze-switch` CLI tests (post-sunset-refusal contract).
*
- * Pins:
- * - --dry-run prints a plan, applies nothing
- * - --non-interactive without key exits 1 (unless --ignore-missing-key)
- * - --non-interactive --ignore-missing-key applies + exits 0
- * - --json envelope shape: {status: ..., plan: {...}}
- * - --resume completes a half-applied switch
- * - --undo without snapshot exits 1
+ * ZeroEntropy shuts down 2026-09-04, so switching a brain ONTO it is
+ * disabled. Pins:
+ * - forward switch (bare / --non-interactive / --force) REFUSES, exit 1,
+ * with the migrate-embeddings escape route in the message
+ * - --resume ALSO refuses (resuming a half-applied forward switch would
+ * strand the brain on the dying provider)
+ * - --json refusal envelope: {status: 'refused', reason: 'provider_sunset'}
+ * - --dry-run still prints a read-only plan, changes nothing
+ * - --undo still works (it moves brains OFF the provider) — snapshot seeded
+ * directly since the forward path can no longer create one
* - --help exits 0 without touching the engine
*
- * Engine lifecycle: each test creates + disconnects its own PGLite engine
- * to keep process.exit() semantics clean. The CLI calls process.exit at
- * the end of every path; we intercept via a stub.
+ * Engine lifecycle: one PGLite engine, state reset per test; process.exit is
+ * intercepted via a stub.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
@@ -102,6 +104,26 @@ async function setLegacyConfig() {
await engine.setConfig('embedding_dimensions', '1536');
}
+/** Seed the state a pre-v0.46.3 forward switch would have left behind, so the
+ * --undo path (which must survive until the September removal) is testable
+ * without the now-refused forward path. Mirrors applyRetrievalUpgrade's
+ * snapshot + config writes (retrieval-upgrade-planner.ts). */
+async function seedAppliedSwitch() {
+ await engine.setConfig(
+ KEY_PREVIOUS_SNAPSHOT,
+ JSON.stringify({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ search_reranker_enabled: false,
+ search_reranker_model: null,
+ }),
+ );
+ await engine.setConfig(KEY_REQUESTED, 'true');
+ await engine.setConfig(KEY_APPLIED, 'true');
+ await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ await engine.setConfig('embedding_dimensions', String(ZE_TARGET_EMBEDDING_DIM));
+}
+
describe('--help', () => {
test('exits 0 with usage text', async () => {
const r = await captureExit(() => runZeSwitch(['--help'], engine));
@@ -112,7 +134,7 @@ describe('--help', () => {
});
});
-describe('--dry-run', () => {
+describe('--dry-run (read-only, still allowed)', () => {
test('human output prints plan, changes nothing', async () => {
await setLegacyConfig();
await seedPages(150);
@@ -125,85 +147,68 @@ describe('--dry-run', () => {
expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
});
-
- test('--json output emits a planned envelope', async () => {
- await setLegacyConfig();
- await seedPages(150);
-
- const r = await captureExit(() => runZeSwitch(['--dry-run', '--json'], engine));
- expect(r.exitCode).toBe(0);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('planned');
- expect(env.plan).toBeDefined();
- expect(env.plan.target_embedding_model).toBe('zeroentropyai:zembed-1');
- expect(env.plan.target_dim).toBe(ZE_TARGET_EMBEDDING_DIM);
- });
});
-describe('--non-interactive', () => {
- test('without ZE key + without --ignore-missing-key: exits 1', async () => {
+describe('forward switch — REFUSED (provider sunset)', () => {
+ test('--non-interactive refuses with exit 1 and the escape route', async () => {
await setLegacyConfig();
await seedPages(150);
-
- // Clear the env var so the test runs the no-key path even when the
- // contributor has ZEROENTROPY_API_KEY set in their shell.
- await withEnv({ ZEROENTROPY_API_KEY: undefined }, async () => {
+ await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake' }, async () => {
const r = await captureExit(() => runZeSwitch(['--non-interactive'], engine));
expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('ZEROENTROPY_API_KEY');
+ expect(r.stderr).toContain('2026-09-04');
+ expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4');
+ // Nothing was applied:
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
+ expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
});
});
- test('without ZE key + with --ignore-missing-key: applies, exits 0', async () => {
+ test('--ignore-missing-key does not bypass the refusal', async () => {
await setLegacyConfig();
await seedPages(150);
-
const r = await captureExit(() =>
runZeSwitch(['--non-interactive', '--ignore-missing-key'], engine),
);
- expect(r.exitCode).toBe(0);
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
- expect(await engine.getConfig('embedding_dimensions')).toBe(String(ZE_TARGET_EMBEDDING_DIM));
+ expect(r.exitCode).toBe(1);
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
});
- test('with env ZE key set: applies', async () => {
+ test('--force does not bypass the refusal either', async () => {
await setLegacyConfig();
- await seedPages(150);
- await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake' }, async () => {
- const r = await captureExit(() => runZeSwitch(['--non-interactive'], engine));
- expect(r.exitCode).toBe(0);
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- });
+ const r = await captureExit(() => runZeSwitch(['--force'], engine));
+ expect(r.exitCode).toBe(1);
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
});
- test('--json + --non-interactive: emits {status: "applied"}', async () => {
+ test('--json refusal envelope carries reason provider_sunset', async () => {
await setLegacyConfig();
- await seedPages(150);
const r = await captureExit(() =>
runZeSwitch(['--non-interactive', '--ignore-missing-key', '--json'], engine),
);
- expect(r.exitCode).toBe(0);
+ expect(r.exitCode).toBe(1);
const env = JSON.parse(r.stdout);
- expect(env.status).toBe('applied');
+ expect(env.status).toBe('refused');
+ expect(env.reason).toBe('provider_sunset');
});
-});
-describe('--resume', () => {
- test('completes a half-applied switch', async () => {
+ test('--resume of a half-applied forward switch ALSO refuses', async () => {
await setLegacyConfig();
await seedPages(150);
// Simulate crash partway: requested but not applied.
await engine.setConfig(KEY_REQUESTED, 'true');
const r = await captureExit(() => runZeSwitch(['--resume'], engine));
- expect(r.exitCode).toBe(0);
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr + r.stdout).toContain('migrate embeddings');
+ // Still not applied — resuming onto a dying provider is the harm the
+ // refusal exists to prevent.
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
+ expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
});
});
-describe('--undo', () => {
+describe('--undo (moves brains OFF the provider — still works)', () => {
test('without snapshot exits 1', async () => {
const r = await captureExit(() =>
runZeSwitch(['--undo', '--non-interactive', '--confirm-reembed'], engine),
@@ -218,12 +223,8 @@ describe('--undo', () => {
});
test('with snapshot + --confirm-reembed: reverses the switch', async () => {
- // Set up: apply switch, then undo.
- await setLegacyConfig();
await seedPages(150);
- await captureExit(() =>
- runZeSwitch(['--non-interactive', '--ignore-missing-key'], engine),
- );
+ await seedAppliedSwitch();
expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
const r = await captureExit(() =>
@@ -236,3 +237,16 @@ describe('--undo', () => {
expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
});
});
+
+describe('--dry-run --json (read-only plan still allowed until removal)', () => {
+ test('emits the planned envelope with the ZE target', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+ const r = await captureExit(() => runZeSwitch(['--dry-run', '--json'], engine));
+ expect(r.exitCode).toBe(0);
+ const env = JSON.parse(r.stdout);
+ expect(env.status).toBe('planned');
+ expect(env.plan).toBeDefined();
+ expect(env.plan.target_dim).toBe(ZE_TARGET_EMBEDDING_DIM);
+ });
+});