Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.12.0 chore(ze): interim ZeroEntropy cleanup — retire the encouragement surfaces (#4231)
Garry Tan5ee88a6c23a7
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 7580a3007e..ed8259288c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.11.0",+ "version": "0.46.12.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 57732ab0fe..9a6b499fd1 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.11.0",+ "version": "0.46.12.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex b629e9803d..2b2b032a8a 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.11.0 -->+<!-- gbrain-runbook-stamp: 0.46.12.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b878996695..ea9bfe4d02 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,93 @@All notable changes to GBrain will be documented in this file.+## [0.46.12.0] - 2026-08-16++**Every surface that could still steer you toward the retiring embedding+provider now tells the truth.** The provider's hosted API ends 2026-09-04;+v0.46.3.0 stopped the CLI from *acting* on a switch, but the discovery+surfaces — help text, provider setup output, doctor hints, historical agent+playbooks — still read like a recommendation. A downstream agent reading that+copy recommended switching a brain ONTO the dying provider; this release makes+that impossible.++### Changed++- **`gbrain ze-switch` is now a pure refusal/redirect shim.** `--help` leads+ with RETIRED, the sunset date, and the one maintained off-ramp+ (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024`), and it now+ actually reaches you through the compiled binary (the generic help+ short-circuit used to hide the command's own help entirely). Every+ invocation refuses or redirects with exit 1; retired flags (`--resume`,+ `--non-interactive`, `--force`, …) are still accepted so old scripts get+ the refusal message instead of an unknown-flag error — even on a machine+ with no brain configured.+- **Two scripted contracts changed deliberately:** `ze-switch --undo` no+ longer acts — it prints the exact `gbrain migrate embeddings` command that+ returns the brain to its pre-switch provider (the retired action wrote+ config the runtime never read and emptied vectors with no verified+ re-embed); and `ze-switch --dry-run --json` now returns+ `{status:'refused', reason:'provider_sunset'}` with exit 1 instead of a+ machine-readable plan targeting the dying provider (`status:'planned'`,+ exit 0). JSON envelopes carry both `…_preview` (cost preview) and live+ command fields, and every command those envelopes render preserves an+ explicit `--brain` selector so multi-brain setups are never pointed at the+ wrong database (the engine-free `--help` text shows the generic command).+- **`gbrain providers env <sunsetting-provider>` replaces the signup funnel**+ (dashboard URL + get-a-key hint) with the deprecation notice, replacement+ models, and the migration command — key STATUS still renders for existing+ users. `providers explain` marks sunsetting rows with ⚠ instead of a green+ ready-check. Both render through one shared marker so the surfaces can't+ drift, and the behavior is generic: any future provider sunset inherits it.+- **`gbrain doctor`'s missing-key hint is migration-first** on a sunsetting+ provider: the fix is the off-ramp; the key path survives as a secondary+ note for the remaining hosted window.+- **Historical migration playbooks can no longer be followed past their+ banners.** The two switch-era skill files now open with "Do not execute+ any command in this file", their imperative recommendations are rewritten+ as past-tense record, and their frontmatter pitches are marked HISTORICAL.+ Provider docs drop the price-comparison sell copy and retitle setup as+ "existing brains and self-hosters only — do not onboard".++### Fixed++- The undo guidance is exact: a snapshot with reranking disabled but a model+ id still set now yields `--reranker off` (the old precedence would have+ re-enabled a reranker the pre-switch brain had off); nested model ids+ (`ollama:model:tag`, `openrouter:org/model`) validate correctly; snapshot+ fields are shape-checked before they land in a command you're told to run;+ a failed `--undo` never points back at `--undo`; and the three undo+ failure states (missing / invalid / unreadable snapshot) each report+ truthfully instead of claiming no switch was recorded.++### Removed++- The retired interactive switch banner and its benchmark pitch ("switch to+ the new provider — RECOMMENDED") no longer ship in the binary; the module+ that carried them is deleted ahead of the September removal.++### To take advantage of v0.46.12.0++`gbrain upgrade` is enough — no schema migration.++1. **Upgrade:**+ ```bash+ gbrain upgrade+ ```+2. **If your brain still embeds or reranks through the retiring provider**,+ run the off-ramp before 2026-09-04 (cost preview first):+ ```bash+ gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run+ gbrain migrate embeddings --to voyage:voyage-4 --dim 1024+ ```+ Your agent can follow `skills/migrations/v0.46.3.0.md` end to end.+3. **Things to watch:** scripts that parsed `ze-switch --dry-run --json`'s+ old `planned` envelope or relied on `ze-switch --undo` acting in place+ must switch to `gbrain migrate embeddings` (the printed guidance names+ the exact command, including your `--brain` selector). If anything looks+ wrong, file an issue with `gbrain doctor` output:+ https://github.com/garrytan/gbrain/issues+## [0.46.11.0] - 2026-08-16**Five operational failures from live production brains, fixed at the root.**diff --git a/TODOS.md b/TODOS.mdindex 7f9e623916..e47b9a7040 100644--- a/TODOS.md+++ b/TODOS.md@@ -220,12 +220,19 @@ Staged-deletion discipline (ship replacements → migrate call sites → updateregistry entries (recipes/index.ts); `zeroEntropyCompatFetch`,`MAX_ZEROENTROPY_RESPONSE_BYTES`, `ZeroEntropyResponseTooLargeError` + thefetch-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+ `retrieval-upgrade-planner.ts` + cli.ts dispatch/CLI_ONLY/CLI_ONLY_SELF_HELP/+ SELF_HELP_WITHOUT_ENGINE/flag-registry rows; `checkZeEmbeddingHealth` in doctor(`provider_sunset` STAYS and goes generic — read `recipe.sunset` instead of thehardcoded ZE constants); pricing rows LAST (budget-tracker rerank metering readsthem for historical audit rows). NOTE: test/ai/zeroentropy-compat-fetch.test.tsgreps gateway.ts SOURCE TEXT — delete the test with the code, in the same commit.+ ALREADY DONE by the interim ZE cleanup wave (pre-Sept): `retrieval-upgrade-prompt.ts`+ deleted (banner/marketing copy gone); `ze-switch.ts` is now a ~170-line pure+ refusal/redirect shim (undo/dry-run ACTIONS retired — apply/undo wrote DB-plane+ config the file-plane-canonical runtime never read); `providers env`/`explain` are+ sunset-aware via the shared `sunsetMarker` in providers.ts (generic on+ `recipe.sunset` — the removal wave inherits it); `ze_embedding_health`'s missing-key+ copy is migration-first (the check itself still gets deleted here).- [ ] **P1 — Self-host continuity decision.** The v0.46.3 playbook's zero-re-embedpath keeps the `zeroentropyai:zembed-1` id behind a base-URL override to aZE-wire-compatible endpoint. Recipe deletion breaks it. Decide: keep a minimal@@ -235,11 +242,14 @@ Staged-deletion discipline (ship replacements → migrate call sites → updateplaybook (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.+ e2e/zeroentropy-live, ze-switch-cli [now pins the shim contract — dies with the+ shim], ze-switch-env-override [pins the planner's test-only functions],+ 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:239,250,377 (line refs+ refreshed by the interim cleanup wave; already date-skip-gated since v0.46.3);+ scripts/test-weights.json rows. Also remove 'ze-switch' from the+ cli-help-without-brain HELP_WITHOUT_BRAIN list when the shim dies.- [ ] **P2 — Config + docs.** `zeroentropy_api_key` config key: keepparseable-but-warned (removing it would make old config.json files fail toload); delete docs/ai-providers/zeroentropy.md + its scripts/llms-config.tsdiff --git a/VERSION b/VERSIONindex 3880eeaeba..d7cf5c11b1 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.11.0+0.46.12.0diff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.mdindex 577a47e6e4..7f6bcbe920 100644--- a/docs/ai-providers/zeroentropy.md+++ b/docs/ai-providers/zeroentropy.md@@ -6,10 +6,13 @@> 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+> deprecation warning, `gbrain providers` annotates it DEPRECATED+> (`gbrain providers env zeroentropyai` prints this off-ramp instead of a+> signup link), and+> `gbrain ze-switch` is a pure refusal/redirect shim (every invocation+> refuses or redirects; `--undo` prints the exact migrate command that+> returns a switched brain to its prior provider — it no longer acts).+> 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:@@ -42,28 +45,29 @@>> The hosted setup below remains accurate until the shutdown date.-[ZeroEntropy](https://zeroentropy.dev) ships two specialized small models-for retrieval pipelines:+[ZeroEntropy](https://zeroentropy.dev) shipped two specialized small+models for retrieval pipelines (factual specs kept for existing users and+self-hosters — this is not a recommendation):- **`zembed-1`** — multilingual embedding distilled from zerank-2.Flexible Matryoshka dims (2560/1280/640/320/160/80/40), 32K context,- asymmetric `input_type: query|document` encoding. $0.025/1M tokens- (sale) / $0.05 regular.-- **`zerank-2`** — SOTA multilingual cross-encoder reranker.- $0.025/1M tokens (~50% cheaper than Cohere/Voyage rerankers).- Plus `zerank-1` and `zerank-1-small` for legacy / open-source needs.+ asymmetric `input_type: query|document` encoding.+- **`zerank-2`** — multilingual cross-encoder reranker. Plus `zerank-1`+ and `zerank-1-small` (open-source weights).-Both land in gbrain v0.35.0.0 behind the openai-compatible recipe path,+Both landed in gbrain v0.35.0.0 behind the openai-compatible recipe path,alongside OpenAI and Voyage.-## Setup+## Setup (existing brains and self-hosters only — do not onboard)-1. Get an API key at- [dashboard.zeroentropy.dev](https://dashboard.zeroentropy.dev).-2. Export it:- ```bash- export ZEROENTROPY_API_KEY=<your-key>- ```+New installs use Voyage (`gbrain init` handles it); do not create a new+ZeroEntropy account for a provider that shuts down on 2026-09-04. A brain+that already has a key exports it as before for the remaining hosted+window:++```bash+export ZEROENTROPY_API_KEY=<your-existing-key>+```## Leaving ZeroEntropy (the off-ramp)@@ -124,19 +128,12 @@ the key, every rerank call fails-open (audit-logged) and search returnsRRF order — same UX as before, just with an observable failure surfacedvia `gbrain doctor`.-### Opt-in on `conservative` mode--```bash-gbrain config set search.reranker.enabled true-```--The override sits above the mode-bundle default; opt-out is one flip.--### Cost anchor+### Enabling reranking today-At 30 candidates × ~400 tokens/chunk × $0.025/1M = **~$0.0003/query**.-Rounding error against the `tokenmax + Opus` pairing's ~$700/mo at-single-user volume per the CLAUDE.md cost matrix.+Set the surviving reranker FIRST, then enable — enabling on a brain that+never set `search.reranker.model` falls back to the dying `zerank-2`:+`gbrain config set search.reranker.model voyage:rerank-2.5`, then+`gbrain config set search.reranker.enabled true`.### Verifydiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 090247c703..058bd733b0 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -132,7 +132,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `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/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/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 every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); 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()`.@@ -206,11 +206,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` (strict per-source; multi-source iteration is the caller's job) drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → `getPage` → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, auto-link + write-through) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping.- `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` — legacy ze-switch planner, scheduled for wholesale deletion in the v0.47 ZE-removal wave. The shared primitives it used to own (`runSchemaTransition`, `transitionDimPinnedColumn`, `TEXT_EMBEDDING_DIM_PINNED_TABLES`, `detectEnvOverride`, `EnvOverrideWarning`, `formatEnvOverrideWarning`) now LIVE in `embedding-migration.ts` (the survivor module); this file re-imports/re-exports them for back-compat so existing importers (ze-switch, tests) keep working until the deletion. Its resume/undo paths probe `readContentChunksEmbeddingDim` first and skip the schema transition when the column is already at the target width — a same-width DROP+ADD still deletes every stored vector. Forward `applyRetrievalUpgrade` remains refused at the CLI (`ze-switch` prints the canonical migration command instead).+- `src/core/retrieval-upgrade-planner.ts` — legacy ze-switch planner, scheduled for wholesale deletion in the v0.47 ZE-removal wave; CLI-unreachable (the ze-switch shim refuses every operation) and kept ONLY as a test vehicle: `applyRetrievalUpgrade`/`resumeRetrievalUpgrade` carry the multimodal-column preservation pins and env-override gate cases in `test/retrieval-upgrade-planner.test.ts` + `test/ze-switch-env-override.test.ts`. The shared primitives it used to own (`runSchemaTransition`, `transitionDimPinnedColumn`, `TEXT_EMBEDDING_DIM_PINNED_TABLES`, `detectEnvOverride`, `EnvOverrideWarning`, `formatEnvOverrideWarning`) LIVE in `embedding-migration.ts` (the survivor module); this file re-imports/re-exports them for back-compat until the deletion. Its resume/undo paths probe `readContentChunksEmbeddingDim` first and skip the schema transition when the column is already at the target width — a same-width DROP+ADD still deletes every stored vector. Note the plane caveat: apply/undo write DB-plane config (`engine.setConfig`) that the post-v0.37 file-plane-canonical embed pipeline does not read — one reason the CLI actions were retired.- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core (#3390) and the v0.47 survivor module; owns the schema-transition + env-gate primitives (moved from the planner). `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history + `force_sunset_target`) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → NULL-signature-inclusive invalidation BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, `missing_embeddings` residue, chunkless-pages census, marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.- `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] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override] [--force-sunset-target]` (alias: `gbrain retrieval-upgrade`, dies v0.47). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Discovery surfaces all render the canonical command from `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`): gateway deprecation line, init warnings, upgrade ACTION REQUIRED banner, doctor `provider_sunset`, ze-switch refusal, advisor — drift-guarded by `test/canonical-migration-command.test.ts`; the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `defaults.ts`.-- `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/commands/ze-switch.ts` — pure refusal/redirect shim for the retired ZeroEntropy switch. Every invocation refuses or redirects with exit 1 and `reason: 'provider_sunset'`, printing the off-ramp (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run`); the `--json` refusal envelope is `{status:'refused', reason:'provider_sunset', migrate, migrate_preview, message}` (live command + cost preview, each carrying an explicit `--brain` suffix); `--undo` REDIRECTS (reads the `ze_switch_previous_snapshot` config row and prints the exact migrate command that returns the brain to its pre-switch provider — `{status:'redirected', reason:'provider_sunset', undo_command, undo_preview, message}` in `--json`; missing/corrupt snapshot degrades to the refusal); `--help` answers engine-free via `CLI_ONLY_SELF_HELP` + the `SELF_HELP_WITHOUT_ENGINE` wrapper in cli.ts (exit 0, truthful sunset copy). Retired flags stay REGISTERED (quoted literals feed the generated registry row) so old scripts reach the refusal instead of a pre-dispatch unknown-flag error — the shim never consults them. Nothing here mutates the brain; the retired undo ACTION wrote DB-plane config the file-plane-canonical runtime never read. The whole command is deleted in the September removal release. Pinned by `test/ze-switch-cli.test.ts` + `test/cli-help-without-brain.serial.test.ts`.+- `src/commands/providers.ts` — `gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]`: provider-recipe discovery + smoke-testing over the recipe registry. `list` renders `formatRecipeTable` against the SAME env the gateway actually sees (`buildGatewayConfig(cfg).env`, file-plane keys folded in) so the STATUS column matches what `providers test` and init would report. Home of the ONE shared sunset-marker primitive (`sunsetMarkerText`/`sunsetMarker`, generic on `recipe.sunset` — any future provider sunset inherits it; the v0.47 ZE-removal wave keeps it) consumed by all three human-facing renderings so they can't drift: the `list` status cell, `explain` rows (lead marker is ⚠ regardless of key readiness — never a green ready-check on a sunsetting provider), and the `env` block, where the pure `formatEnvOutput(recipe, env)` (testable without spawning the CLI) replaces the signup funnel (`setup_url`/`setup_hint`) with the deprecation notice, replacement models, and the canonical migration command from `renderCanonicalMigrationCommands` — key STATUS still renders for existing users. Pinned by `test/providers.test.ts`.- `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`.diff --git a/docs/designs/2026_05_EVAL_PLAN.md b/docs/designs/2026_05_EVAL_PLAN.mdindex 55324031b1..19672622ed 100644--- a/docs/designs/2026_05_EVAL_PLAN.md+++ b/docs/designs/2026_05_EVAL_PLAN.md@@ -221,15 +221,19 @@ Wire the harness to drive 3 embedding providers via the newly-exposed gbrain gat```### Smoke verification (run manually before opening PR)++> (Historical: the two `zeroentropyai:` commands below stop passing after+> 2026-09-04 — do not run them. Only the non-ZE smokes remain runnable.)+```bashbun run eval:smoke -- --embedder openai:text-embedding-3-large --dim 1536bun run eval:smoke -- --embedder voyage:voyage-4-large --dim 2048-bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560-bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560 --reranker zeroentropyai:zerank-2+bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560 # historical+bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560 --reranker zeroentropyai:zerank-2 # historical```-All four MUST exit 0. Reports should print the observed vector dim, matching the-configured dim.+The two non-ZE smokes MUST exit 0 (the ZE pair did at the time). Reports+should print the observed vector dim, matching the configured dim.### Open PR β```bashdiff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.mdindex 8f67976951..e637ab9d75 100644--- a/docs/guides/embedding-migration.md+++ b/docs/guides/embedding-migration.md@@ -123,8 +123,8 @@ ingestion — not just new content.census, the un-merged file plane), so a pre-set env var cannot fake acompleted migration.5. **Apply.** When the target width differs from the actual column width,- runs the same atomic schema transition `ze-switch` uses, in one- transaction. It rebuilds **all three dim-pinned text-embedding-space+ runs the atomic schema transition owned by `embedding-migration.ts`+ (the survivor module), in one transaction. It rebuilds **all three dim-pinned text-embedding-spacecolumns** — `content_chunks.embedding`, `query_cache.embedding`, and`facts.embedding` — at the new width, preserving each column's type(`vector` vs `halfvec`) and recreating its HNSW index. Missing any of thediff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.mdindex dd7260d46f..553d09c911 100644--- a/docs/integrations/embedding-providers.md+++ b/docs/integrations/embedding-providers.md@@ -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**, 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.+**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 (`providers env zeroentropyai` prints the deprecation notice + migration command instead of the signup funnel, `providers explain` leads the row with ⚠ regardless of key readiness, and `gbrain doctor`'s ZE missing-key hint is migration-first). 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 failsdiff --git a/llms.txt b/llms.txtindex 8bf1fc0384..649c057309 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. (deprecated; hosted sunset 2026-09-04)+- [docs/ai-providers/zeroentropy.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/zeroentropy.md): ZeroEntropy (deprecated; hosted sunset 2026-09-04): the off-ramp for existing brains — migrate embeddings + reranker, self-host continuity, troubleshooting. Do not onboard.- [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.## Debuggingdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 088f42ea9c..ce6c07a276 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.11.0",+ "version": "0.46.12.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 210aaca1c1..902b6815cb 100644--- a/package.json+++ b/package.json@@ -168,7 +168,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.11.0",+ "version": "0.46.12.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin/README.md b/plugin/README.mdindex b4bc28e7d6..983c571f13 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.11.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.12.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex d3ddf18355..e8e0e00dc0 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. (deprecated; hosted sunset 2026-09-04)",+ "ZeroEntropy (deprecated; hosted sunset 2026-09-04): the off-ramp for existing brains — migrate embeddings + reranker, self-host continuity, troubleshooting. Do not onboard.",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/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bb7b6cce1d..f7cad646ce 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -10,7 +10,7 @@ src/core/pglite-engine.ts 5660 ratchet peel target: containment sprint C15; growsrc/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratchetedsrc/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wavesrc/core/ai/gateway.ts 4117 ratchet watchlist-src/cli.ts 3337 ratchet watchlist+src/cli.ts 3364 ratchet watchlistsrc/core/cycle.ts 2933 ratchetsrc/commands/serve-http.ts 2836 ratchetsrc/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wavediff --git a/skills/migrations/v0.35.0.0.md b/skills/migrations/v0.35.0.0.mdindex 1df3da4e54..1297412f40 100644--- a/skills/migrations/v0.35.0.0.md+++ b/skills/migrations/v0.35.0.0.md@@ -1,17 +1,19 @@----feature_pitch: ZeroEntropy zembed-1 embeddings + zerank-2 cross-encoder reranking+feature_pitch: "HISTORICAL: ZeroEntropy zembed-1 embeddings + zerank-2 reranking (provider retired 2026-09-04)"required_action: no # purely opt-in---# v0.35.0.0 migration notes-> **HISTORICAL — DO NOT FOLLOW.** ZeroEntropy's hosted API shuts down-> **2026-09-04**; the opt-in instructions below would strand a brain on a dead-> provider. To LEAVE ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.+> **HISTORICAL — DO NOT FOLLOW. Do not execute any command in this file.**+> ZeroEntropy's hosted API shuts down **2026-09-04**; the opt-in config+> edits and commands below would strand a brain on a dead provider. To+> LEAVE ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.-ZeroEntropy support landed. **No required user action.** Reranker is on by-default for `tokenmax` mode only; embedding model is unchanged for everyone-unless the user explicitly opts in via config file or env var.+ZeroEntropy support landed (historical record). **No required user action.**+Reranker was on by default for `tokenmax` mode only; the embedding model was+unchanged for everyone unless the user explicitly opted in via config file+or env var.## What changed automatically@@ -28,43 +30,23 @@ unless the user explicitly opts in via config file or env var.- `conservative` and `balanced` modes default reranker = false. Nothingchanges for those users without an explicit opt-in.-## What the user can do (optional)+## What the user could do at the time (historical — do not run any of this)-### Try zembed-1 embeddings+### The zembed-1 opt-in (era recipe, now a strand-your-brain trap)-Switching embedding models invalidates the vector index — you'll need to-re-embed. Edit `~/.gbrain/config.json`:+The era's opt-in was a config-file edit pointing `embedding_model` at+`zeroentropyai:zembed-1` (valid Matryoshka dims: 2560, 1280, 640, 320,+160, 80, 40), followed by a key export and a staged re-embed+(`gbrain models doctor`, a small `--stale` smoke, then the full pass).+Running that today points a brain at an API that dies 2026-09-04 — the+maintained path is the off-ramp in `skills/migrations/v0.46.3.0.md`.-```json-{- "embedding_model": "zeroentropyai:zembed-1",- "embedding_dimensions": 2560-}-```--Valid dims: 2560, 1280, 640, 320, 160, 80, 40 (Matryoshka-style; smaller-trades quality for storage). Then:--```bash-export ZEROENTROPY_API_KEY=...-gbrain models doctor # verify config-gbrain embed --stale --limit 50 # smoke a small re-embed-gbrain embed --stale # full re-embed-```--### Try zerank-2 on conservative/balanced+### The zerank-2 opt-in on conservative/balanced (era recipe)-```bash-export ZEROENTROPY_API_KEY=...-gbrain config set search.reranker.enabled true-gbrain models doctor # verify reranker_config + reachability-gbrain query "some query that previously misranked"-```--To opt out:-```bash-gbrain config set search.reranker.enabled false-```+The era's opt-in was `search.reranker.enabled true` with a ZE key set,+verified via `gbrain models doctor`. Enabling reranking TODAY should set+the surviving model first: `gbrain config set search.reranker.model+voyage:rerank-2.5`, then enable.### Opt out of reranker on tokenmaxdiff --git a/skills/migrations/v0.36.2.0.md b/skills/migrations/v0.36.2.0.mdindex 812852173d..c4cfc347c4 100644--- a/skills/migrations/v0.36.2.0.md+++ b/skills/migrations/v0.36.2.0.md@@ -1,45 +1,40 @@---name: v0.36.2.0version: 0.36.2.0-headline: ZeroEntropy is the new default for embedding + reranker+headline: "HISTORICAL: ZeroEntropy was briefly the default for embedding + reranker"---# v0.36.2.0 Migration: ZeroEntropy as default-> **HISTORICAL — DO NOT FOLLOW.** ZeroEntropy's hosted API shuts down-> **2026-09-04** and `gbrain ze-switch` now refuses forward use. To LEAVE-> ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.+> **HISTORICAL — DO NOT FOLLOW. Do not execute any command in this file.**+> ZeroEntropy's hosted API shuts down **2026-09-04**; every ze-switch+> command below exits 1 with `reason: provider_sunset` today (the command+> is a pure refusal/redirect shim), and the benchmark pitch below is+> obsolete. To LEAVE ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.-**TL;DR:** v0.36.2.0 makes ZeroEntropy (`zembed-1` at 1280d via Matryoshka, `zerank-2` cross-encoder reranker) the default retrieval stack. Real-corpus benchmark says: 2.2× faster than OpenAI, 2.6× cheaper at regular pricing, wins 11/20 head-to-head queries, reranker reshuffles 60% of top-1 results. New installs land on it automatically. Existing brains see a one-shot upgrade prompt with a cost estimate; default-on-Enter is "stay on current provider" so the safe path is the no-action path.+**TL;DR (historical record):** v0.36.2.0 made ZeroEntropy (`zembed-1` at 1280d via Matryoshka, `zerank-2` cross-encoder reranker) the default retrieval stack, on the strength of a real-corpus benchmark that has since been overtaken by events — the provider announced its shutdown. New installs landed on it automatically. Existing brains saw a one-shot upgrade prompt with a cost estimate; default-on-Enter was "stay on current provider".-This migration is **opt-in for existing brains**. Running `gbrain upgrade` does not silently re-embed your data. The prompt is TTY-only; non-TTY upgrades (CI, cron, docker) print an informational stderr line and skip the switch.+This migration was **opt-in for existing brains**. Running `gbrain upgrade` did not silently re-embed data. The prompt was TTY-only; non-TTY upgrades (CI, cron, docker) printed an informational stderr line and skipped the switch.-## What the agent should do post-upgrade+## What the agent did post-upgrade (v0.36.2 era — every command here exits 1 today)-When the user invokes any gbrain command immediately after `gbrain upgrade` to v0.36.2.0:+When a user invoked any gbrain command immediately after `gbrain upgrade` to v0.36.2.0, the playbook was:-1. **Check whether the prompt has been surfaced yet.** `gbrain ze-switch --dry-run --json` shows the planner state including `ze_switch_offered`, `ze_switch_prompt_shown`, and the comparison numbers. If `ze_switch_offered` is true and `ze_switch_prompt_shown` is false, the user hasn't seen the prompt yet.+1. The agent checked planner state via `ze-switch --dry-run --json` (`ze_switch_offered`, `ze_switch_prompt_shown`, the comparison numbers).-2. **Surface the comparison numbers.** Quote the benchmark from the prompt:- - Wins 11/20 queries head-to-head (OpenAI 6, Voyage 4)- - 442ms avg vs OpenAI 973ms (2.2× faster)- - $0.05/M tokens vs OpenAI $0.13 (2.6× cheaper at regular pricing)- - zerank-2 reshuffles 60% of top-1 results- - Only 10-18% overlap between providers — pairing primary + reranker compounds+2. It surfaced the era's benchmark numbers (head-to-head query wins, latency, price, reranker reshuffle rate, provider overlap).-3. **Recommend switching** unless the user has stated a constraint that makes ZE unsuitable (no internet, regulatory concern with a specific provider, contractual commitment to another stack). When recommending, point them at:- ```bash- gbrain ze-switch # interactive prompt- gbrain ze-switch --dry-run # see the plan without applying- ```+3. It recommended switching unless the user had a constraint making ZE unsuitable, pointing at the interactive prompt and the dry-run plan.-4. **If the user already declined** (`ze_switch_already_declined` true) and they ask about it later, mention `gbrain ze-switch --force` re-opens the prompt. The 90-day decline window auto-resets after that, so a year-later contributor "we have better benchmarks now" data gets surfaced naturally.+4. For a prior decline, `--force` re-opened the prompt (90-day re-ask window).-5. **If the user switched and now regrets it**, mention `gbrain ze-switch --undo`. Restores their prior model + dim + reranker state with a symmetric cost-warning prompt (re-embedding back is also a real cost).+5. For regret after switching, `--undo` restored the prior model + dim + reranker state behind a cost-warning prompt.-## The CLI surface in full+None of that flow exists anymore: the recommendation aged into a liability when the shutdown was announced, and today the entire surface refuses.-| Command | Effect |+## The CLI surface in full (historical — every row exits 1 with `provider_sunset` today)++| Command | Effect (v0.36.2 era) ||---|---|| `gbrain ze-switch` | Interactive prompt (TTY only). Default-on-Enter = stay. || `gbrain ze-switch --dry-run` | Print plan as text. Change nothing. |@@ -48,8 +43,8 @@ When the user invokes any gbrain command immediately after `gbrain upgrade` to v| `gbrain ze-switch --non-interactive --ignore-missing-key` | Same, but stage the schema change before the key is ready. Embeddings fail loud until key arrives. || `gbrain ze-switch --resume` | Complete a half-applied switch (crash recovery). || `gbrain ze-switch --force` | Bypass the prompt-shown gate (re-show after `n`). |-| `gbrain ze-switch --undo` | Reverse with cost-warning prompt. |-| `gbrain ze-switch --undo --non-interactive --confirm-reembed` | Scripted undo. The `--confirm-reembed` flag is required (un-doing also pays for re-embed). |+| `gbrain ze-switch --undo` | Reverse with cost-warning prompt. (Today: prints the return-path `gbrain migrate embeddings` command instead of acting.) |+| `gbrain ze-switch --undo --non-interactive --confirm-reembed` | Scripted undo. (Today: prints guidance, exit 1.) |## Consolidation with the v0.32.7 chunker prompt@@ -59,8 +54,8 @@ If a brain has BOTH a stale chunker version AND the ZE-switch offered, the `Retr`gbrain doctor` now runs two new ZE-aware checks:-- **`ze_embedding_health`** — warns if `embedding_model` starts with `zeroentropyai:` but no key is configured (neither env nor `gbrain config set zeroentropy_api_key`). Fix hint points at the setup URL.-- **`embedding_width_consistency`** — asserts the configured `embedding_dimensions` matches the actual `vector(N)` width on `content_chunks.embedding`. Warns on drift. Fix hint suggests `gbrain ze-switch --resume` if drift came from a half-applied switch, or `gbrain config set embedding_dimensions <schema-dim>` to match the existing schema.+- **`ze_embedding_health`** — warns if `embedding_model` starts with `zeroentropyai:` but no key is configured. (At the time the fix hint pointed at the setup URL; today it points at the migration off-ramp.)+- **`embedding_width_consistency`** — asserts the configured `embedding_dimensions` matches the actual `vector(N)` width on `content_chunks.embedding`. Warns on drift. (At the time the fix hint suggested `--resume`; today the check prints an engine-branched recovery recipe — there is no resume.)## What changed under the hood@@ -70,21 +65,21 @@ If a brain has BOTH a stale chunker version AND the ZE-switch offered, the `Retr- Schema transition (when user accepts the switch): DROP indexes → ALTER `content_chunks.embedding` to `vector(1280)` → CREATE INDEX. Atomic inside one `engine.transaction()`. HNSW indexes recreated in the same transaction; no silent slow-search window.- Three new config keys: `ze_switch_prompt_shown`, `ze_switch_requested`, `ze_switch_applied`. Plus `ze_switch_previous_snapshot` (JSON, captures prior config for `--undo`) and `ze_switch_declined_at` (ISO timestamp for the 90-day re-ask gate).-## What NOT to do+## What NOT to do (historical guardrails for the era's flow)-- Don't run `gbrain ze-switch --non-interactive --ignore-missing-key` for a user without explaining the consequence — every embed call will fail until they set `ZEROENTROPY_API_KEY`. Surface that loudly.-- Don't tell the user the sale price ($0.025/M) is the cost they'll pay long-term. It's a promotional rate. The CHANGELOG and prompt cite the regular $0.05/M as the cost anchor.-- Don't assume the user wants the switch because the comparison numbers favor it. The user owns the decision. The prompt's default-on-Enter is "stay" for exactly this reason.+- The `--ignore-missing-key` staging spelling required explaining that every embed call would fail until the key arrived.+- The sale price was promotional; the regular price was the cost anchor.+- The user owned the switch decision; the prompt's default-on-Enter was "stay" for exactly this reason.## Why 1280d, not 1024dThe valid ZE Matryoshka dim steps are `2560, 1280, 640, 320, 160, 80, 40`. 1024 (Voyage's step) is NOT on ZE's list — see `src/core/ai/dims.ts:ZEROENTROPY_VALID_DIMS`. 1280 is the step closest to the prior OpenAI 1536d default and stays in the high-recall zone of the Matryoshka curve.-## Verifying the switch+## Verifying the switch (historical — the ze-switch line exits 1 today)-```bash+```textgbrain doctor # both new checks should be green-gbrain ze-switch --dry-run # status should be skipped_already_applied+gbrain ze-switch --dry-run # (era) status skipped_already_applied; (today) refusesgbrain models # confirm embedding + reranker defaultsgbrain search "test query" --limit 5 # confirm the reranker is firing```diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex a9354010b1..f34105fada 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -119,9 +119,9 @@"migrations/v0.33.0.md": "11710cb11d6eb7dc3ea54b764e3c4a25f8679cf76590acd330f97bfa1c684945","migrations/v0.33.3.0.md": "188a03ca86a97a9aa697cbbc83cc8ca37843fab24db2bd82f1383c400173d5bd","migrations/v0.34.0.0.md": "d421c5ecff0765ac1de3592d3175734db7df52e8658ec101567779c7c56c2db2",- "migrations/v0.35.0.0.md": "1f4083b6447ae694776f35b70ec6c259b03987cb35a8ee4376c8f51db6bb06ce",+ "migrations/v0.35.0.0.md": "a87d0f04f5d1d275c2f283c3736f0208bb9e24a540b0ffb79ec9d4c0de90e01f","migrations/v0.35.7.0.md": "c6d4454bd39e2aa243b3b3d9bc72fe5a4fd25d097be7be2bb14b25604b5c2cc5",- "migrations/v0.36.2.0.md": "becedef44dc377cf95c83ddc479c9ab19f15a984f716fc0b041ba7cde6886f14",+ "migrations/v0.36.2.0.md": "2b3b4cc0dc2e9611b0df9aea0a9cd4281433011c2d88433f768e762b28d56320","migrations/v0.36.5.0.md": "a01a722202dfc3c799693596750c8bee611fe4dafe3cb662f6b4cd0b635cb429","migrations/v0.40.3.0.md": "5f500f8c543c2b6f41778b0bd3beedada68f7284f7933ad8b769322b433a8fe9","migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5",diff --git a/src/cli.ts b/src/cli.tsindex 69aeac9a8a..7470d1ec46 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -162,6 +162,9 @@ const CLI_ONLY_SELF_HELP = new Set([// would hide both — `gbrain dream retriage --help` printed the one-line// dream stub instead of the retriage contract (outside-voice CX9).'dream',+ // ZE interim cleanup: the retired ze-switch shim ships truthful help+ // (sunset refusal + canonical migration command); the generic stub hid it.+ 'ze-switch',]);/**@@ -187,6 +190,9 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, arg// runDream accepts BrainEngine | null; --help (and `retriage --help`) is// answered before any engine-bearing work per the dream.ts IRON RULE.dream: async () => (await import('./commands/dream.ts')).runDream as never,+ // The retired ze-switch shim answers --help engine-free (arg-order adapter+ // lives in ze-switch.ts because runZeSwitch takes (args, engine)).+ 'ze-switch': async () => (await import('./commands/ze-switch.ts')).runZeSwitchSelfHelp as never,};/** Returns true when the command's own help was printed. */@@ -2009,10 +2015,31 @@ async function handleCliOnly(command: string, args: string[]) {}if (command === 'ze-switch') {- // v0.36.0.0 — manual ZE-default switch lever. Owns its own engine lifecycle- // to mirror the doctor pattern.+ // Retired refusal/redirect shim. Only --undo reads the brain (one config+ // row); every other invocation must refuse EVEN ON an unconfigured+ // machine — connecting unconditionally turned the refusal into+ // "No brain configured" and starved --json callers of the envelope.const { runZeSwitch } = await import('./commands/ze-switch.ts');- const eng = await connectEngine();+ if (!args.includes('--undo')) {+ await runZeSwitch(args, null);+ return;+ }+ // --undo reads one config row. An unconfigured machine (or a failed+ // connect) must still get the shim's truthful --json refusal envelope —+ // connectEngine would print plain "No brain configured" and exit before+ // the shim ran, so pre-check the config and degrade to a null engine+ // (the shim words that as a read failure).+ if (!loadConfig()) {+ await runZeSwitch(args, null);+ return;+ }+ let eng: BrainEngine | null = null;+ try {+ eng = await connectEngine();+ } catch {+ await runZeSwitch(args, null);+ return;+ }try {await runZeSwitch(args, eng);} finally {diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.tsindex 7f2ef79f1a..8832500455 100644--- a/src/commands/doctor/checks/graph-embedding.ts+++ b/src/commands/doctor/checks/graph-embedding.ts@@ -249,13 +249,33 @@ export async function checkZeEmbeddingHealth(engine: BrainEngine): Promise<Check// File plane: zeroentropy_api_key on GBrainConfig (added by C.3).const fileKey = loadConfigFileOnly()?.zeroentropy_api_key;if (!envKey && !fileKey) {+ // Migration-first: when the provider has an announced shutdown, the fix+ // for a missing key is to migrate OFF, not to sign up. The key path+ // survives as the secondary note for someone who needs the remaining+ // hosted window. (Generic on recipe.sunset so the copy self-corrects if+ // the recipe ever changes; the whole check is deleted in v0.47.)+ const { getRecipe } = await import('../../../core/ai/recipes/index.ts');+ const sunset = getRecipe('zeroentropyai')?.sunset;+ if (sunset) {+ const { renderCanonicalMigrationCommands } = await import('../../../core/ai/defaults.ts');+ return {+ name: 'ze_embedding_health',+ status: 'warn',+ message:+ `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set — and the ` ++ `hosted API shuts down on ${sunset.date}. Fix: migrate off it: ` ++ `${renderCanonicalMigrationCommands().recommendedDryRun}. If you need hosted ` ++ `ZeroEntropy for the remaining weeks, set the key via ` ++ `\`export ZEROENTROPY_API_KEY=...\` or "zeroentropy_api_key" in ` ++ `~/.gbrain/config.json (gbrain config set writes the DB plane, which the embed pipeline ignores).`,+ };+ }return {name: 'ze_embedding_health',status: 'warn',message:`embedding_model="${model}" but ZEROENTROPY_API_KEY is not set. ` +- `Fix: get a key at https://dashboard.zeroentropy.dev and either ` +- `\`export ZEROENTROPY_API_KEY=...\` or edit ~/.gbrain/config.json ` ++ `Fix: \`export ZEROENTROPY_API_KEY=...\` or edit ~/.gbrain/config.json ` +`to add "zeroentropy_api_key": "...". (gbrain config set writes the DB plane, which the embed pipeline ignores.)`,};}@@ -426,10 +446,11 @@ 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 means a width+ * transition was interrupted mid-flight (schema changed but config write+ * crashed, or vice versa). Surfaces the engine-kind-branched recovery recipe+ * from embeddingMismatchMessage — NOT a ze-switch hint; that command is a+ * refusal shim now.*/export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {try {diff --git a/src/commands/providers.ts b/src/commands/providers.tsindex 4331fc9810..cca1e8d2dc 100644--- a/src/commands/providers.ts+++ b/src/commands/providers.ts@@ -12,6 +12,7 @@ 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 { renderCanonicalMigrationCommands } from '../core/ai/defaults.ts';import type { Recipe } from '../core/ai/types.ts';const SCHEMA_VERSION = 1;@@ -59,6 +60,78 @@ export function envReady(recipe: Recipe, env: NodeJS.ProcessEnv = process.env):return required.every(k => !!env[k]);}+/**+ * ONE shared sunset-marker primitive for every human-facing providers surface+ * (list status cell, explain table rows, env block header) so the renderings+ * can't drift. `sunsetMarkerText` is the string; `sunsetMarker` is the+ * recipe-shaped convenience (null for recipes without an announced shutdown).+ */+export function sunsetMarkerText(date: string, replacementEmbedding?: string | null): string {+ return `⚠ DEPRECATED — hosted API ends ${date}` + (replacementEmbedding ? `; use ${replacementEmbedding}` : '');+}++export function sunsetMarker(recipe: Pick<Recipe, 'sunset'>): string | null {+ if (!recipe.sunset) return null;+ return sunsetMarkerText(recipe.sunset.date, recipe.sunset.replacement?.embedding);+}++/**+ * Pure formatter for `gbrain providers env <id>` so the output is testable+ * without spawning the CLI (runEnv itself process.exits).+ *+ * Sunset-aware: a provider with an announced shutdown gets the deprecation+ * block + the canonical migration command INSTEAD of the signup funnel+ * (setup_url / setup_hint) — three weeks before a provider dies, "get an API+ * key" is the wrong guidance. Key STATUS still renders above so existing+ * users can see what's configured.+ */+export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process.env): string {+ const lines: string[] = [];+ lines.push(`${recipe.name} (${recipe.id})`);+ lines.push('');+ const required = recipe.auth_env?.required ?? [];+ const optional = recipe.auth_env?.optional ?? [];+ if (required.length > 0) {+ lines.push('Required:');+ for (const k of required) {+ lines.push(` ${k.padEnd(32)} ${env[k] ? '✓ set' : '✗ not set'}`);+ }+ } else {+ lines.push('Required: (none)');+ }+ if (optional.length > 0) {+ lines.push('');+ lines.push('Optional:');+ for (const k of optional) {+ lines.push(` ${k.padEnd(32)} ${env[k] ? '✓ set' : '✗ not set'}`);+ }+ }+ const marker = sunsetMarker(recipe);+ if (marker) {+ const s = recipe.sunset!;+ lines.push('');+ lines.push(marker);+ if (s.message) lines.push(` ${s.message}`);+ if (s.replacement) {+ const parts: string[] = [];+ if (s.replacement.embedding) parts.push(`${s.replacement.embedding} (embedding)`);+ if (s.replacement.reranker) parts.push(`${s.replacement.reranker} (reranker)`);+ if (parts.length > 0) lines.push(` Replacement: ${parts.join(', ')}`);+ }+ lines.push(` Migrate: ${renderCanonicalMigrationCommands().recommendedDryRun}`);+ return lines.join('\n');+ }+ if (recipe.auth_env?.setup_url) {+ lines.push('');+ lines.push(`Setup: ${recipe.auth_env.setup_url}`);+ }+ if (recipe.setup_hint) {+ lines.push('');+ lines.push(recipe.setup_hint);+ }+ return lines.join('\n');+}+/*** Pure formatter for the recipe matrix shown by `gbrain providers list` and* the new `init-provider-picker` (D1+D2 — picker reuses this so its display@@ -86,12 +159,10 @@ export function formatRecipeTable(recipes: Recipe[], env: NodeJS.ProcessEnv = prconst ready = envReady(r, env);// 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'}`;+ // Marker text is the shared sunsetMarker so list/explain/env can't drift.+ const status =+ sunsetMarker(r) ??+ (ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`);rows.push(r.id.padEnd(idCol) +r.tier.padEnd(18) +@@ -287,32 +358,7 @@ function runEnv(args: string[]): void {console.error(`Unknown provider: ${id}. Run \`gbrain providers list\` to see known providers.`);process.exit(1);}- console.log(`${recipe.name} (${recipe.id})`);- console.log('');- const required = recipe.auth_env?.required ?? [];- const optional = recipe.auth_env?.optional ?? [];- if (required.length > 0) {- console.log('Required:');- for (const k of required) {- const set = !!process.env[k];- console.log(` ${k.padEnd(32)} ${set ? '✓ set' : '✗ not set'}`);- }- } else {- console.log('Required: (none)');- }- if (optional.length > 0) {- console.log('\nOptional:');- for (const k of optional) {- const set = !!process.env[k];- console.log(` ${k.padEnd(32)} ${set ? '✓ set' : '✗ not set'}`);- }- }- if (recipe.auth_env?.setup_url) {- console.log(`\nSetup: ${recipe.auth_env.setup_url}`);- }- if (recipe.setup_hint) {- console.log(`\n${recipe.setup_hint}`);- }+ console.log(formatEnvOutput(recipe));}async function runExplain(args: string[]): Promise<void> {@@ -429,7 +475,14 @@ async function runExplain(args: string[]): Promise<void> {for (const o of options.filter(x => x.touchpoint === 'embedding')) {const cost = o.cost_per_1m_tokens_usd !== undefined ? `$${o.cost_per_1m_tokens_usd}/1M` : '—';const dims = o.dims ? `${o.dims}d` : '—';- console.log(` ${o.env_ready ? '✓' : '✗'} ${o.id.padEnd(44)} ${dims.padEnd(8)} ${cost.padEnd(10)} ${o.tier}`);+ // A sunsetting provider must not read as a green-check cheap option in+ // the HUMAN table (the deprecation used to live only in cons/JSON).+ // Rendered via the shared primitive so list/env/explain can't drift, and+ // the lead marker is ⚠ regardless of key readiness — "ready" on a dying+ // API is not a state to advertise (mirrors formatRecipeTable's status).+ const dep = o.deprecated ? ` ${sunsetMarkerText(o.deprecated.date, o.deprecated.replacement)}` : '';+ const lead = o.deprecated ? '⚠' : o.env_ready ? '✓' : '✗';+ console.log(` ${lead} ${o.id.padEnd(44)} ${dims.padEnd(8)} ${cost.padEnd(10)} ${o.tier}${dep}`);}console.log('');console.log('Expansion options:');diff --git a/src/commands/ze-switch.ts b/src/commands/ze-switch.tsindex 9bcb9033cb..90438fbdea 100644--- a/src/commands/ze-switch.ts+++ b/src/commands/ze-switch.ts@@ -1,239 +1,272 @@/**- * v0.36.0.0 — `gbrain ze-switch` CLI lever for the ZeroEntropy default switch.+ * `gbrain ze-switch` — RETIRED refusal/redirect shim.*- * Subcommands / flags:- * gbrain ze-switch Run the interactive prompt- * gbrain ze-switch --dry-run Plan only; change nothing- * gbrain ze-switch --json Machine-readable envelope- * gbrain ze-switch --non-interactive Switch without prompting- * (errors if ZEROENTROPY_API_KEY missing- * unless --ignore-missing-key is also set)- * gbrain ze-switch --resume Finish a half-applied switch (recovery)- * gbrain ze-switch --force Bypass the `prompt_shown` gate- * (use after `n` / never-ask-again)- * gbrain ze-switch --undo Reverse: restore prior model + dim- * + reranker state. Cost-warning prompt- * appears before any change.- * gbrain ze-switch --undo --non-interactive --confirm-reembed- * Scripted undo path (also pays for re-embed)+ * ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE. Every+ * invocation refuses or redirects; nothing here mutates the brain:+ *+ * gbrain ze-switch --help Truthful usage (exit 0, engine-free)+ * gbrain ze-switch --undo [--json] Print the exact migration command that+ * returns this brain to its pre-switch+ * provider (from the stored snapshot).+ * Guidance only — exit 1, nothing changes.+ * anything else Refusal naming the canonical migration.+ *+ * Why the legacy actions are gone: the forward switch/resume have been+ * sunset-refused since v0.46.3, and the undo ACTION wrote DB-plane config+ * (engine.setConfig) that the post-v0.37 file-plane-canonical embed pipeline+ * never reads — it could rebuild the schema (dropping every vector) while the+ * runtime kept resolving the old model. Printing the verified, resumable+ * `gbrain migrate embeddings` command is strictly safer than acting.+ *+ * The whole command is deleted in the v0.47 September removal release.*/import type { BrainEngine } from '../core/engine.ts';import {- planRetrievalUpgrade,- applyRetrievalUpgrade,- resumeRetrievalUpgrade,- undoRetrievalUpgrade,- formatEnvOverrideWarning,- type ApplyResult,-} from '../core/retrieval-upgrade-planner.ts';-import {- runRetrievalUpgradePrompt,- runUndoPrompt,-} from '../core/retrieval-upgrade-prompt.ts';--interface Flags {- dryRun: boolean;- json: boolean;- nonInteractive: boolean;- resume: boolean;- force: boolean;- undo: boolean;- confirmReembed: boolean;- ignoreMissingKey: boolean;- ignoreEnvOverride: boolean;+ ZEROENTROPY_SUNSET_DATE,+ renderCanonicalMigrationCommands,+} from '../core/ai/defaults.ts';+import { getCliOptions } from '../core/cli-options.ts';++/** Config row written by the pre-v0.46.3 forward switch (the literal matches+ * KEY_PREVIOUS_SNAPSHOT in retrieval-upgrade-planner.ts; kept local so the+ * shim does not drag the retired planner module into its import graph). */+const KEY_PREVIOUS_SNAPSHOT = 'ze_switch_previous_snapshot';++interface ZeSwitchSnapshot {+ embedding_model: string;+ embedding_dimensions: number;+ search_reranker_enabled?: boolean;+ search_reranker_model?: string | null;}-function parseFlags(args: string[]): Flags {- return {- dryRun: args.includes('--dry-run'),- json: args.includes('--json'),- nonInteractive: args.includes('--non-interactive') || args.includes('--yes'),- resume: args.includes('--resume'),- force: args.includes('--force'),- undo: args.includes('--undo'),- confirmReembed: args.includes('--confirm-reembed'),- ignoreMissingKey: args.includes('--ignore-missing-key'),- // v0.41.2.1: escape hatch for power users running parallel experiments- // with GBRAIN_EMBEDDING_MODEL set. Loud stderr line when used.- ignoreEnvOverride: args.includes('--ignore-env-override'),- };+// Retired forward-switch flags — kept as quoted literals ONLY so the+// generated CLI_FLAG_REGISTRY row keeps accepting them and old scripts reach+// the refusal message naming the migration instead of dying pre-dispatch+// with an unknown-flag error (cli.ts validates against the row BEFORE+// dispatch; the row is generated from these literals, and safety flags like+// '--dry-run' need quoted consumption evidence to survive regeneration).+// The shim never consults them — every non-help/undo invocation refuses.+// '--markdown' rode the pre-shim row (generator over-scan); kept for the+// same old-scripts-reach-the-refusal reason. The registry-superset pin in+// test/ze-switch-cli.test.ts makes any drop of this list loud.+export const RETIRED_FLAGS = [+ '--dry-run',+ '--resume',+ '--force',+ '--non-interactive',+ '--yes',+ '--ignore-missing-key',+ '--ignore-env-override',+ '--confirm-reembed',+ '--markdown',+];++/** The `--brain <id>` selector is parsed and STRIPPED by the global CLI+ * option layer before dispatch, so any command this shim tells the user to+ * run must carry it explicitly — otherwise `ze-switch --brain team-x --undo`+ * reads team-x's snapshot but the printed migrate command targets the+ * ambient/default brain (a paid re-embed of the wrong corpus). */+function brainSuffix(): string {+ const brain = getCliOptions().brain;+ return brain ? ` --brain ${brain}` : '';}function printHelp() {- process.stdout.write(`Usage: gbrain ze-switch [flags]+ const cmds = renderCanonicalMigrationCommands();+ process.stdout.write(`Usage: gbrain ze-switch [--undo] [--json]-Switch the brain's embedding + reranker defaults to ZeroEntropy.+RETIRED — ZeroEntropy shuts down its hosted API on ${ZEROENTROPY_SUNSET_DATE}.+Switching a brain ONTO ZeroEntropy is refused (exit 1, reason+provider_sunset), and the legacy dry-run/resume/undo ACTIONS no longer run.+Every invocation refuses or redirects; nothing changes your brain.Flags:- --dry-run Plan only; change nothing.- --json Machine-readable output.- --non-interactive Skip prompts; apply directly (CI / scripts).- --resume Finish a half-applied switch (crash recovery).- --force Bypass the prompt_shown gate (use after --undo or "never ask").- --undo Reverse the switch: restore prior model + dim + reranker.- --confirm-reembed Required with --undo --non-interactive (re-embed pays cost).- --ignore-missing-key Allow --non-interactive without ZEROENTROPY_API_KEY set.- --ignore-env-override Apply even when GBRAIN_EMBEDDING_* env vars would- override the target at runtime (use if you know why).- --help Show this help.+ --undo Print the exact migration command that returns this brain to its+ pre-switch provider (read from the stored switch snapshot). No+ changes are made; run the printed command yourself. Exit 1.+ --json Machine-readable envelope on stdout.+ --help This help. Exit 0.++To LEAVE ZeroEntropy (the maintained path):+ ${cmds.recommendedDryRun} # cost preview+ ${cmds.recommended}+ Playbook: skills/migrations/v0.46.3.0.md++Retired flags — still accepted so old scripts get the refusal above instead+of an unknown-flag error: ${RETIRED_FLAGS.join(' ')}++This command is deleted in the September (v0.47) removal release.`);}-/**- * Render an ApplyResult; if status is 'refused' (env-override gate),- * write the ASCII warning box to stderr AND exit non-zero. Pure data- * stays in the JSON envelope; the box is for human readers.- */-function renderApplyResult(result: ApplyResult, json: boolean): void {- if (result.status === 'refused' && result.reason === 'env_override') {- if (json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.error(formatEnvOverrideWarning(result.warning));- console.error(`\nSwitch status: refused (env_override)`);- }- process.exit(1);- }+function refusalEnvelope(+ extraMessage?: string,+ opts: { omitUndoHint?: boolean } = {},+): {+ status: 'refused';+ reason: 'provider_sunset';+ /** The LIVE canonical migration command — what an agent should run. */+ migrate: string;+ /** The cost-preview variant — run this first. */+ migrate_preview: string;+ message: string;+} {+ const cmds = renderCanonicalMigrationCommands();+ const brain = brainSuffix();+ const live = `${cmds.recommended}${brain}`;+ const preview = `${cmds.recommendedDryRun}${brain}`;+ const message =+ (extraMessage ? `${extraMessage}\n` : '') ++ `ze-switch is retired: ZeroEntropy shuts down its hosted API on ${ZEROENTROPY_SUNSET_DATE}.\n` ++ `To LEAVE ZeroEntropy: ${preview} # cost preview\n` ++ ` then: ${live}\n` ++ `Playbook: skills/migrations/v0.46.3.0.md` ++ // Never point a failed --undo back at --undo (guidance loop).+ (opts.omitUndoHint+ ? ''+ : `\nTo see the command that returns this brain to its pre-switch provider: gbrain ze-switch --undo`);+ return { status: 'refused', reason: 'provider_sunset', migrate: live, migrate_preview: preview, message };+}++/** Emit the envelope (stdout JSON or stderr message) and exit 1. */+function emitAndExit(payload: { message: string } & Record<string, unknown>, json: boolean): never {if (json) {- console.log(JSON.stringify(result, null, 2));+ console.log(JSON.stringify(payload));} else {- console.log(`Switch status: ${result.status}`);+ console.error(payload.message);}+ process.exit(1);}-export async function runZeSwitch(args: string[], engine: BrainEngine): Promise<void> {- if (args.includes('--help') || args.includes('-h')) {- printHelp();- process.exit(0);- }+/** Model ids are `provider:model` tokens; the tail may nest (`ollama:model:tag`,+ * `openrouter:google/gemma`, `nvidia:nvidia/nv-embedqa-e5-v5`). The snapshot+ * row is data-plane content (writable via config set / direct DB / a mounted+ * brain), and its fields land verbatim in a command the user or a downstream+ * agent is told to RUN — so validate before interpolating and degrade to the+ * plain refusal on anything suspicious. Leading alphanumeric + no whitespace+ * means a value like `--force-sunset-target` can never inject a flag. */+const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*:[A-Za-z0-9._/:-]+$/;- 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,- renderCanonicalMigrationCommands,- } = 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: ${renderCanonicalMigrationCommands().recommendedDryRun}\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);- }+type SnapshotReadResult =+ | { kind: 'ok'; snapshot: ZeSwitchSnapshot }+ | { kind: 'missing' }+ | { kind: 'invalid' }+ | { kind: 'read_error' };+function parseSnapshot(raw: string): ZeSwitchSnapshot | null {try {- // --dry-run: just plan, never apply.- if (flags.dryRun) {- const plan = await planRetrievalUpgrade(engine);- if (flags.json) {- console.log(JSON.stringify({ status: 'planned', plan }, null, 2));- } else {- console.log(`Current model: ${plan.current_embedding_model} (${plan.current_dim}d)`);- console.log(`Target model: ${plan.target_embedding_model ?? '(no change)'}`);- console.log(`Target dim: ${plan.target_dim ?? '(no change)'}`);- console.log(`Pages pending: chunker=${plan.pages_pending_chunker}, dim=${plan.pages_pending_dim}`);- console.log(`Est cost: $${plan.est_cost_usd.toFixed(2)}`);- console.log(`Est minutes: ${plan.est_minutes}`);- console.log(`Schema change: ~${plan.est_schema_change_seconds}s`);- console.log(`Offered: ${plan.ze_switch_offered}`);- }- return;+ const p = JSON.parse(raw) as ZeSwitchSnapshot;+ if (+ p &&+ typeof p.embedding_model === 'string' &&+ MODEL_ID_RE.test(p.embedding_model) &&+ Number.isInteger(p.embedding_dimensions) &&+ p.embedding_dimensions > 0 &&+ // A string "false" would pass a truthiness check and then FAIL the+ // strict ===false test below, re-enabling a reranker the snapshot says+ // was off — require boolean or absent.+ (p.search_reranker_enabled == null || typeof p.search_reranker_enabled === 'boolean') &&+ (p.search_reranker_model == null ||+ (typeof p.search_reranker_model === 'string' && MODEL_ID_RE.test(p.search_reranker_model)))+ ) {+ return p;}+ } catch {+ /* corrupt JSON is `invalid` — the caller words the refusal */+ }+ return null;+}- // --resume: complete a half-applied switch.- if (flags.resume) {- if (flags.ignoreEnvOverride) {- console.error('[ze-switch] WARNING: --ignore-env-override is set; env vars will silently override the switch at runtime.');- }- const result = await resumeRetrievalUpgrade(engine, {- ignoreEnvOverride: flags.ignoreEnvOverride,- });- // v0.41.2.1: route through the env-override-aware renderer so- // refused-status emits the ASCII warning box + exits non-zero.- if (result.status === 'refused' && result.reason === 'env_override') {- renderApplyResult(result, flags.json); // exits non-zero- }- if (flags.json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.log(`Resume status: ${result.status}`);- }- process.exit(result.status === 'applied' || result.status === 'skipped_already_applied' ? 0 : 1);- }+/** Pure builder for the undo redirect commands (exported for tests). */+export function buildUndoCommands(+ snapshot: ZeSwitchSnapshot,+ brainArg: string,+): { live: string; preview: string } {+ // Fold the pre-switch reranker into the same run: `--reranker` takes a+ // model id or `off`; omitted means the migration's own default.+ // enabled===false WINS over a lingering model id — the pre-switch brain+ // had reranking off, and `migrate embeddings --reranker <model>` would+ // re-enable it (the retired undo restored `enabled` independently).+ const rerankerArg =+ snapshot.search_reranker_enabled === false+ ? ' --reranker off'+ : snapshot.search_reranker_model+ ? ` --reranker ${snapshot.search_reranker_model}`+ : '';+ const live = `gbrain migrate embeddings --to ${snapshot.embedding_model} --dim ${snapshot.embedding_dimensions}${rerankerArg}${brainArg}`;+ return { live, preview: `${live} --dry-run` };+}- // --undo: reverse switch.- if (flags.undo) {- if (flags.nonInteractive) {- if (!flags.confirmReembed) {- console.error('--undo --non-interactive requires --confirm-reembed (undo re-embeds at the prior width — costs real money).');- process.exit(1);- }- const result = await undoRetrievalUpgrade(engine);- if (flags.json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.log(`Undo status: ${result.status}`);+/** cli.ts SELF_HELP_WITHOUT_ENGINE adapter: that record's handlers take+ * (engine, args); runZeSwitch takes (args, engine). Help never touches the+ * engine, so null is safe here. */+export function runZeSwitchSelfHelp(_engine: never, args: string[]): Promise<void> {+ return runZeSwitch(args, null);+}++export async function runZeSwitch(args: string[], engine: BrainEngine | null): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) {+ printHelp();+ process.exit(0);+ }++ // Both --json spellings, mirroring cli.ts's own convention.+ const json = args.some((a) => a === '--json' || (a.startsWith('--json=') && a !== '--json=false'));++ if (args.includes('--undo')) {+ // Read the pre-switch snapshot the old forward path stored. A missing,+ // corrupt, invalid-shape, or unreadable snapshot degrades to the plain+ // refusal (there is nothing to redirect to); `redirected` is reserved+ // for a validated snapshot. The failure states word the refusal+ // differently — telling the operator of a switched brain whose snapshot+ // failed validation that "no switch was recorded" would be false, and a+ // null engine here means the brain could not be reached at all.+ let read: SnapshotReadResult = engine ? { kind: 'missing' } : { kind: 'read_error' };+ if (engine) {+ try {+ const raw = await engine.getConfig(KEY_PREVIOUS_SNAPSHOT);+ if (raw) {+ const parsed = parseSnapshot(raw);+ read = parsed ? { kind: 'ok', snapshot: parsed } : { kind: 'invalid' };}- process.exit(result.status === 'undone' ? 0 : 1);+ } catch {+ read = { kind: 'read_error' };}- // Interactive undo: shows cost-warning prompt.- const result = await runUndoPrompt(engine);- if (flags.json) {- console.log(JSON.stringify(result, null, 2));- }- process.exit(result.status === 'undone' ? 0 : 1);}- // --non-interactive: apply without prompting.- if (flags.nonInteractive) {- if (!process.env.ZEROENTROPY_API_KEY && !flags.ignoreMissingKey) {- const config = await engine.getConfig('zeroentropy_api_key');- if (!config) {- console.error('ZEROENTROPY_API_KEY not set. Pass --ignore-missing-key to switch anyway (embeddings will fail until you set a key).');- process.exit(1);- }- }- if (flags.ignoreEnvOverride) {- console.error('[ze-switch] WARNING: --ignore-env-override is set; env vars will silently override the switch at runtime.');- }- const plan = await planRetrievalUpgrade(engine);- const result = await applyRetrievalUpgrade(engine, plan, {- ignoreEnvOverride: flags.ignoreEnvOverride,- });- // v0.41.2.1: render env-override refusal with ASCII box + exit non-zero.- if (result.status === 'refused' && result.reason === 'env_override') {- renderApplyResult(result, flags.json); // exits non-zero- }- if (flags.json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.log(`Switch status: ${result.status}`);- }- process.exit(- result.status === 'applied' || result.status === 'skipped_already_applied' || result.status === 'skipped_no_work'- ? 0- : 1,+ if (read.kind === 'ok') {+ const { live, preview } = buildUndoCommands(read.snapshot, brainSuffix());+ const message =+ `ze-switch no longer undoes in place (the retired action wrote config the runtime does not read).\n` ++ `To return this brain to its pre-switch provider, run:\n` ++ ` ${preview} # cost preview\n` ++ ` ${live}\n` ++ `(This reflects the recorded pre-switch snapshot; the preview shows the live\n` ++ ` current->target plan and the migration verifies against the database before\n` ++ ` changing anything — a brain that already migrated will report nothing to do.)`;+ emitAndExit(+ {+ status: 'redirected',+ reason: 'provider_sunset',+ undo_command: live,+ undo_preview: preview,+ message,+ },+ json,);}- // Interactive mode.- const result = await runRetrievalUpgradePrompt(engine, { force: flags.force });- if (flags.json) {- console.log(JSON.stringify(result, null, 2));- }- process.exit(result.status === 'applied' || result.status === 'declined_this_run' || result.status === 'declined_forever' || result.status === 'non_tty_skip' || result.status === 'not_offered' ? 0 : 1);- } finally {- // Engine lifecycle is owned by the dispatcher.+ const undoFailure =+ read.kind === 'invalid'+ ? 'A switch snapshot exists but is unreadable or failed validation — inspect the ze_switch_previous_snapshot config row before trusting any undo guidance.'+ : read.kind === 'read_error'+ ? 'Could not read the switch snapshot (no brain configured, or the config read failed) — check the brain connection and retry.'+ : 'No prior switch snapshot recorded — nothing to undo.';+ emitAndExit(refusalEnvelope(undoFailure, { omitUndoHint: true }), json);}++ // Every other invocation — bare, --dry-run, --resume, --non-interactive,+ // --force, any combination — refuses.+ emitAndExit(refusalEnvelope(), json);}diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.tsindex c5e815d5e6..adeaddd316 100644--- a/src/core/ai/dims.ts+++ b/src/core/ai/dims.ts@@ -72,8 +72,8 @@ export function isValidZeroEntropyDim(dims: number): boolean {// Matryoshka — any positive integer up to the model's native size. When a// brain is configured with `embedding_dimensions` OUTSIDE that range, OpenAI// returns HTTP 400 at first embed. We catch it locally with a paste-ready-// fix so users don't see opaque "vector dimension mismatch" errors after-// `gbrain ze-switch --undo` lands them on OpenAI at the wrong dim.+// fix so users don't see opaque "vector dimension mismatch" errors after a+// `gbrain migrate embeddings --to openai:...` lands them at the wrong dim.const OPENAI_TEXT3_MAX_DIMS: Record<string, number> = {'text-embedding-3-small': 1536,'text-embedding-3-large': 3072,diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 2b3e0e5c07..6b8a9e3702 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -27,7 +27,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'brainstorm': ['--aliases', '--all', '--brain', '--chunker-debug', '--code', '--compile', '--fast', '--file', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-extract', '--no-save', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--yes'],'cache': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],'calibration': ['--ab', '--aliases', '--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', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--holder', '--http', '--image', '--include-null-signature', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--phase', '--progress-interval', '--progress-json', '--quiet', '--regenerate', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--trusted-extraction', '--undo-wave', '--url', '--with-calibration', '--with-db', '--yes'],- 'call': ['--aliases', '--all', '--all-sources', '--as-context', '--auto-fix', '--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-extract', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--page', '--param', '--params', '--password', '--path', '--pattern', '--pending', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--thin', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],+ 'call': ['--aliases', '--all', '--all-sources', '--as-context', '--auto-fix', '--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-extract', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--page', '--param', '--params', '--password', '--path', '--pattern', '--pending', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--thin', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],'capture': ['--aliases', '--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', '--depth', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--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', '--quiet', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--trusted-extraction', '--type', '--url', '--what', '--where', '--who', '--with-db', '--yes'],'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],@@ -40,8 +40,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'config': ['--aliases', '--all', '--brain', '--column', '--coverage-override', '--detail', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--pattern', '--pending', '--pglite', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--surface', '--thin', '--token-ttl', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--json', '--name', '--oauth', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'conversation-parser': ['--aliases', '--all', '--brain', '--help', '--include-null-signature', '--json', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin'],- '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', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--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-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--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-name', '--token-ttl', '--top-k', '--type', '--undo', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--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', '--dim', '--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-guard', '--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'],+ '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', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--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-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--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-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--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', '--dim', '--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-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--take', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--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', '--source-guard', '--stale', '--supersessions', '--thin', '--timeout', '--workers'],'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--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', '--dim', '--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'],@@ -65,8 +65,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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', '--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', '--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', '--nice', '--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', '--reranker', '--reranking', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--rollback', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--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', '--dim', '--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'],+ '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', '--nice', '--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', '--reranker', '--reranking', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--rollback', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],+ 'models': ['--aliases', '--all', '--brain', '--ctx-size', '--detail', '--dim', '--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', '--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', '--dim', '--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'],@@ -75,7 +75,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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', '--dim', '--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'],+ 'providers': ['--brain', '--ctx-size', '--dim', '--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', '--yes'],'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', '--source-id', '--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', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--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-guard', '--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', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--reset', '--resolve', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--version', '--yes'],+ 'retrieval-upgrade': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--reset', '--resolve', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--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-guard', '--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', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--token-ttl', '--window-turns'],- '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'],+ 'ze-switch': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--no-extract', '--non-interactive', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--undo', '--yes'],};diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.tsindex 1873f89ff1..14657a8063 100644--- a/src/core/embedding-migration.ts+++ b/src/core/embedding-migration.ts@@ -2,9 +2,8 @@* Provider-agnostic embedding migration (#3390).** `gbrain migrate embeddings --to <provider:model>` re-embeds a brain onto- * any configured provider — the forward path off a sunsetting provider that- * `ze-switch` (ZE-only target) and `ze-switch --undo` (needs a snapshot fresh- * installs don't have) cannot cover.+ * any configured provider — the ONE forward path off a sunsetting provider+ * (the retired ze-switch is a refusal/redirect shim that points here).** This module is the v0.47 SURVIVOR: the migration primitives live HERE* (runSchemaTransition, transitionDimPinnedColumn, detectEnvOverride and thediff --git a/src/core/retrieval-upgrade-planner.ts b/src/core/retrieval-upgrade-planner.tsindex 670bc14ba0..9992491ec5 100644--- a/src/core/retrieval-upgrade-planner.ts+++ b/src/core/retrieval-upgrade-planner.ts@@ -26,11 +26,11 @@* ze_switch_declined_at : ISO ts when user said "never ask again"* ze_switch_previous_snapshot : JSON snapshot for --undo (D16)*- * State diagram:+ * RETIRED state machine (historical — no CLI path reaches it anymore):** [fresh brain]* |- * | user picks "s" or runs `gbrain ze-switch`+ * | (pre-v0.46.3) forward switch requested* v* prompt_shown=true, requested=true* |@@ -40,23 +40,19 @@* |* | config writes (embedding_model, dim, reranker)* v- * applied=true -> stable. Re-embed via `gbrain embed --stale` or autopilot.+ * applied=true -> stable.*- * Crash between schema and config writes:- * requested=true, applied=false, schema is at target width.- * Doctor's `embedding_width_consistency` detects + suggests `--resume`.- *- * "Never ask again" path:- * prompt_shown=true, declined_at=<iso>. Re-asked after 90 days (C3).- *- * Undo path:- * ze_switch_previous_snapshot JSON drives reverse schema + config.+ * Every arrow above is CLI-unreachable today: `gbrain ze-switch` is a pure+ * refusal/redirect shim (the sunset refusal landed in v0.46.3; the undo/+ * dry-run actions were retired in the interim ZE cleanup because apply/undo+ * write DB-plane config the post-v0.37 file-plane-canonical runtime never+ * reads). The functions below survive ONLY as test vehicles — they carry the+ * multimodal-column preservation pins and the env-override gate cases until+ * the v0.47 removal deletes this file wholesale.** The planner is intentionally NOT a migration in the MIGRATIONS array.- * Migrations are forward-only and run for every brain on every upgrade.- * The ZE switch is conditional (user-requested), idempotent (re-runnable),- * and reversible (--undo). Mixing it into MIGRATIONS would muddy the- * ledger semantics (see plan D12 for full rationale).+ * Migrations are forward-only and run for every brain on every upgrade;+ * this machine was conditional, idempotent, and reversible (see plan D12).*/import type { BrainEngine } from './engine.ts';@@ -81,7 +77,7 @@ export type { EnvOverrideWarning };// Constants// ============================================================================-/** v0.36.0.0 cutover target: ZeroEntropy zembed-1 at 1024d via Matryoshka. */+/** v0.36.0.0 cutover target: ZeroEntropy zembed-1 at 1280d via Matryoshka. */export const ZE_TARGET_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';export const ZE_TARGET_EMBEDDING_DIM = 1280;export const ZE_TARGET_RERANKER_MODEL = 'zeroentropyai:zerank-2';@@ -286,8 +282,9 @@ export async function planRetrievalUpgrade(engine: BrainEngine): Promise<Retriev* 5. Set ze_switch_applied = true** Crash between (3) and (4) leaves the schema at the target width but the- * config at the source. Doctor's `embedding_width_consistency` detects this- * and suggests `gbrain ze-switch --resume`.+ * config at the source. Doctor's `embedding_width_consistency` detects the+ * drift and prints the engine-branched recovery recipe (there is no CLI+ * resume anymore — the ze-switch shim refuses everything).*/export async function applyRetrievalUpgrade(engine: BrainEngine,diff --git a/src/core/retrieval-upgrade-prompt.ts b/src/core/retrieval-upgrade-prompt.tsdeleted file mode 100644index 9fb0c1fde6..0000000000--- a/src/core/retrieval-upgrade-prompt.ts+++ /dev/null@@ -1,285 +0,0 @@-/**- * v0.36.0.0 — Interactive prompt UI for the retrieval upgrade (D10 + D6 + C2).- *- * Wires the RetrievalUpgradePlanner to a TTY prompt that:- * - Shows the comparison numbers from the v0.36.0.0 wave- * - Presents a two-line cost split (D10): schema change + re-embed- * - Includes the privacy callout (C2) when balanced-mode reranker flips on- * - Honors TTY detection (non-TTY = skip, informational stderr line)- * - Default-on-Enter = STAY (safest); explicit 's' = switch, 'l' = later,- * 'n' = never ask again- *- * Used by:- * - src/commands/upgrade.ts:runPostUpgrade (post-migration call site)- * - src/commands/ze-switch.ts (manual CLI lever)- */--import type { BrainEngine } from './engine.ts';-import {- planRetrievalUpgrade,- applyRetrievalUpgrade,- recordDeclinedThisRun,- recordDeclinedForever,- resumeRetrievalUpgrade,- undoRetrievalUpgrade,- type RetrievalUpgradeState,- type ApplyResult,- type ZeSwitchSnapshot,- KEY_PROMPT_SHOWN,- KEY_APPLIED,- KEY_REQUESTED,- ZE_TARGET_EMBEDDING_MODEL,- ZE_TARGET_EMBEDDING_DIM,-} from './retrieval-upgrade-planner.ts';--// ============================================================================-// Public API-// ============================================================================--export interface PromptOpts {- /** Override stdin TTY detection for tests. */- isTTY?: boolean;- /** Override the read function for tests (single keypress). */- readKey?: () => Promise<string>;- /** Where to write the prompt. Defaults to process.stderr. */- write?: (line: string) => void;- /** Bypass the `prompt_shown` gate (for `gbrain ze-switch --force`). */- force?: boolean;-}--export type PromptResult =- | { status: 'applied'; plan: RetrievalUpgradeState }- | { status: 'declined_this_run'; plan: RetrievalUpgradeState }- | { status: 'declined_forever'; plan: RetrievalUpgradeState }- | { status: 'not_offered'; plan: RetrievalUpgradeState; reason: string }- | { status: 'non_tty_skip'; plan: RetrievalUpgradeState }- | { status: 'failed'; plan: RetrievalUpgradeState; reason: string };--/**- * Run the v0.36.0.0 retrieval-upgrade prompt. Returns a tagged-union outcome- * so callers can dispatch without parsing strings (mirrors D15).- */-export async function runRetrievalUpgradePrompt(- engine: BrainEngine,- opts: PromptOpts = {},-): Promise<PromptResult> {- const writeFn = opts.write ?? ((line: string) => process.stderr.write(line + '\n'));- const isTTY = typeof opts.isTTY === 'boolean'- ? opts.isTTY- : Boolean(process.stdin.isTTY);-- // Don't re-ask within the same brain unless --force.- if (!opts.force) {- const shown = (await engine.getConfig(KEY_PROMPT_SHOWN)) === 'true';- const applied = (await engine.getConfig(KEY_APPLIED)) === 'true';- if (shown || applied) {- const plan = await planRetrievalUpgrade(engine);- return { status: 'not_offered', plan, reason: applied ? 'already_applied' : 'prompt_shown' };- }- }-- const plan = await planRetrievalUpgrade(engine);-- // Nothing to do.- if (!plan.ze_switch_offered) {- return {- status: 'not_offered',- plan,- reason: plan.ze_switch_already_declined ? 'declined' : 'not_eligible',- };- }-- // Show banner regardless of TTY so non-TTY upgrades see what they skipped.- writeFn(formatBanner(plan));-- if (!isTTY) {- writeFn('[ze-switch] non-TTY environment; skipping prompt. Run `gbrain ze-switch` manually when ready.');- return { status: 'non_tty_skip', plan };- }-- // Single-keypress prompt. Enter = stay (safest default).- const key = await (opts.readKey ?? defaultReadKey)();- const normalized = key.toLowerCase().trim();-- if (normalized === 's') {- // v0.41.2.1 — interactive path does NOT pass ignoreEnvOverride; if the- // user has env vars set, the apply call returns 'refused' with the- // structured warning. The prompt surfaces the ASCII box and surfaces- // `failed` status so the CLI exits non-zero. Power users who really- // want to override use the non-interactive `--ignore-env-override`.- const result = await applyRetrievalUpgrade(engine, plan);- if (result.status === 'applied') {- writeFn('[ze-switch] Schema rebuilt at 1024d. Run `gbrain embed --stale` to refill embeddings (or wait for autopilot).');- return { status: 'applied', plan };- }- if (result.status === 'refused' && result.reason === 'env_override') {- // Lazy-import to avoid the prompt module pulling in the planner- // module's full surface at module-load time.- const { formatEnvOverrideWarning } = await import('./retrieval-upgrade-planner.ts');- writeFn(formatEnvOverrideWarning(result.warning));- return { status: 'failed', plan, reason: 'env_override (use --ignore-env-override to apply anyway)' };- }- if (result.status === 'failed') {- return { status: 'failed', plan, reason: result.reason };- }- // skipped_* shouldn't happen here (we just planned and saw offered=true).- return { status: 'failed', plan, reason: `unexpected apply status: ${result.status}` };- }- if (normalized === 'n') {- await recordDeclinedForever(engine);- writeFn('[ze-switch] Will not ask again. Re-enable with `gbrain ze-switch --force`.');- return { status: 'declined_forever', plan };- }- // Enter, 'l', or anything else = defer to next upgrade.- // Per C3 the planner re-asks on the next run; mark prompt_shown=false to- // re-enable. We DON'T touch the config here; absence of prompt_shown means- // re-ask. The 'l' case is identical.- return { status: 'declined_this_run', plan };-}--/** Mirror of runRetrievalUpgradePrompt for --undo (D16 cost-warning prompt). */-export async function runUndoPrompt(- engine: BrainEngine,- opts: PromptOpts = {},-): Promise<- | { status: 'undone'; snapshot: ZeSwitchSnapshot }- | { status: 'aborted' }- | { status: 'non_tty_skip' }- | { status: 'no_snapshot' }- | { status: 'failed'; reason: string }-> {- const writeFn = opts.write ?? ((line: string) => process.stderr.write(line + '\n'));- const isTTY = typeof opts.isTTY === 'boolean'- ? opts.isTTY- : Boolean(process.stdin.isTTY);-- // Read snapshot just to show the cost warning.- const snapshotStr = await engine.getConfig('ze_switch_previous_snapshot');- if (!snapshotStr) {- writeFn('[ze-switch --undo] No prior config snapshot found (brain was never switched). Nothing to undo.');- return { status: 'no_snapshot' };- }- let snapshot: ZeSwitchSnapshot;- try {- snapshot = JSON.parse(snapshotStr) as ZeSwitchSnapshot;- } catch (err) {- return { status: 'failed', reason: `corrupt snapshot: ${err instanceof Error ? err.message : String(err)}` };- }-- const plan = await planRetrievalUpgrade(engine);- writeFn(formatUndoBanner(snapshot, plan.pages_pending_dim || 0));-- if (!isTTY) {- writeFn('[ze-switch --undo] non-TTY environment; refusing without --confirm-reembed.');- return { status: 'non_tty_skip' };- }-- const key = await (opts.readKey ?? defaultReadKey)();- if (key.toLowerCase().trim() !== 's') {- writeFn('[ze-switch --undo] aborted (you must press `s` to confirm).');- return { status: 'aborted' };- }-- const result = await undoRetrievalUpgrade(engine);- if (result.status === 'undone') {- writeFn(`[ze-switch --undo] Restored ${snapshot.embedding_model} at ${snapshot.embedding_dimensions}d. Run \`gbrain embed --stale\` to refill embeddings.`);- return result;- }- return result;-}--/** Programmatic resume helper used by the CLI's --resume flag. */-export async function runResume(engine: BrainEngine): Promise<ApplyResult> {- return resumeRetrievalUpgrade(engine);-}--// ============================================================================-// Banner formatting (pure; testable)-// ============================================================================--/**- * Format the upgrade banner per D10 (two-line cost split) + C2 (privacy- * callout). Pure — returns a string; the caller emits to stderr.- */-export function formatBanner(plan: RetrievalUpgradeState): string {- const lines: string[] = [];- lines.push('────────────────────────────────────────────────────────────');- lines.push('v0.36.0.0 ships a new default: ZeroEntropy');- lines.push('');- lines.push('Real-corpus benchmark across 20 queries on a 17K-page brain:');- lines.push(' • Wins 11/20 queries head-to-head (OpenAI 6, Voyage 4)');- lines.push(' • Fastest: 442ms vs OpenAI 973ms (2.2× faster)');- lines.push(' • Cheapest: $0.05/M tokens vs OpenAI $0.13/M (2.6× cheaper)');- lines.push(' (sale rate $0.025/M may be promotional, subject to change)');- lines.push(' • zerank-2 reshuffles 60% of top-1 results (real value)');- lines.push(' • Only 10–18% overlap between providers — they see different');- lines.push(' things, so a pair compounds');- lines.push('');- lines.push(`Your current setup: ${plan.current_embedding_model} (${plan.current_dim}d)`);- lines.push(`Target: ${ZE_TARGET_EMBEDDING_MODEL} (${ZE_TARGET_EMBEDDING_DIM}d via Matryoshka)`);- lines.push('');-- // D10: two-line cost split — schema change vs re-embed.- const dollars = plan.est_cost_usd > 0 ? `~$${plan.est_cost_usd.toFixed(2)}` : 'estimate unavailable';- const pages = Math.max(plan.pages_pending_chunker, plan.pages_pending_dim);- lines.push(`Schema change: ~${plan.est_schema_change_seconds}s (drops + recreates embedding column with new index)`);- lines.push(`Re-embed: ~${plan.est_minutes}min and ${dollars} for ${pages.toLocaleString()} pages`);- lines.push(' (runs via `gbrain embed --stale` or autopilot — you can walk away)');-- // C2: privacy callout for the balanced-mode reranker flip.- lines.push('');- lines.push('Heads-up: reranking on this default sends your query and top-30');- lines.push('search snippets to api.zeroentropy.dev. Disable any time with');- lines.push('`gbrain config set search.reranker.enabled false`.');-- lines.push('');- lines.push('Options:');- lines.push(' [Enter] Stay on current provider for now (default — safe)');- lines.push(' s Switch to ZeroEntropy (RECOMMENDED)');- lines.push(' l Decide later (ask me again on next upgrade)');- lines.push(' n Never ask again');- lines.push('────────────────────────────────────────────────────────────');- return lines.join('\n');-}--/** Cost-warning prompt before --undo runs. D16 symmetric UX. */-export function formatUndoBanner(snapshot: ZeSwitchSnapshot, pageCount: number): string {- const lines: string[] = [];- lines.push('────────────────────────────────────────────────────────────');- lines.push('Undo the v0.36.0.0 ZeroEntropy switch?');- lines.push('');- lines.push(`Will restore: ${snapshot.embedding_model} (${snapshot.embedding_dimensions}d)`);- lines.push(` reranker_enabled = ${snapshot.search_reranker_enabled}`);- if (snapshot.search_reranker_model) {- lines.push(` reranker_model = ${snapshot.search_reranker_model}`);- }- lines.push('');- lines.push(`This will re-embed ~${pageCount.toLocaleString()} pages at the prior width.`);- lines.push('Same re-embed bill as the forward switch (in reverse).');- lines.push('');- lines.push(' s Confirm undo');- lines.push(' [any] Abort');- lines.push('────────────────────────────────────────────────────────────');- return lines.join('\n');-}--// ============================================================================-// Keypress reader (mockable for tests)-// ============================================================================--async function defaultReadKey(): Promise<string> {- return new Promise((resolve) => {- const stdin = process.stdin;- stdin.setRawMode?.(true);- stdin.resume();- stdin.setEncoding('utf8');- const onData = (chunk: string) => {- stdin.setRawMode?.(false);- stdin.pause();- stdin.removeListener('data', onData);- // Strip trailing newline; treat Enter as empty string.- resolve(chunk === '\r' || chunk === '\n' || chunk === '\r\n' ? '' : chunk.replace(/[\r\n]/g, ''));- };- stdin.on('data', onData);- });-}diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 01065687c4..7aa46d82ee 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.11.0 -->+<!-- gbrain-template-stamp: 0.46.12.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/canonical-migration-command.test.ts b/test/canonical-migration-command.test.tsindex 16177a6ec3..7326f3d736 100644--- a/test/canonical-migration-command.test.ts+++ b/test/canonical-migration-command.test.ts@@ -152,6 +152,9 @@ describe('canonical migration command (single home: ai/defaults.ts)', () => {'src/commands/upgrade.ts','src/core/ze-exposure.ts','src/commands/ze-switch.ts',+ // Interim ZE cleanup: providers env prints the off-ramp for sunsetting+ // recipes instead of the signup funnel.+ 'src/commands/providers.ts',];for (const rel of consumers) {const text = readFileSync(join(import.meta.dir, '..', rel), 'utf-8');diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.tsindex 4a98ee7140..d63c66c30a 100644--- a/test/cli-help-without-brain.serial.test.ts+++ b/test/cli-help-without-brain.serial.test.ts@@ -29,6 +29,9 @@ const HELP_WITHOUT_BRAIN = ['jobs',// #4152: dream answers --help (and the retriage subverb help) engine-free.'dream',+ // ZE interim cleanup: the retired ze-switch shim answers --help engine-free+ // (truthful sunset copy + the canonical migration command).+ 'ze-switch',];/**diff --git a/test/doctor-ze-checks.test.ts b/test/doctor-ze-checks.test.tsindex 0bbbfa7e6c..29da2ad9ac 100644--- a/test/doctor-ze-checks.test.ts+++ b/test/doctor-ze-checks.test.ts@@ -52,7 +52,7 @@ describe('checkZeEmbeddingHealth', () => {expect(check.message).toContain('not ZeroEntropy');});- test('on ZE + no key: warns with setup hint', async () => {+ test('on ZE + no key: warns migration-first (no signup funnel)', async () => {configureGateway({embedding_model: 'zeroentropyai:zembed-1',embedding_dimensions: 1280,@@ -65,7 +65,10 @@ describe('checkZeEmbeddingHealth', () => {const check = await checkZeEmbeddingHealth(engine);expect(check.status).toBe('warn');expect(check.message).toContain('ZEROENTROPY_API_KEY');- expect(check.message).toContain('zeroentropy.dev');+ // Migration-first: the fix for a missing key on a sunsetting provider+ // is the off-ramp, never a signup link.+ expect(check.message).toContain('migrate embeddings');+ expect(check.message).not.toContain('dashboard.zeroentropy.dev');});});diff --git a/test/providers.test.ts b/test/providers.test.tsindex 1b41fa8c30..2fc6222714 100644--- a/test/providers.test.ts+++ b/test/providers.test.ts@@ -2,11 +2,12 @@* `gbrain providers` — pure formatter + envReady tests.** `runTest` and `runExplain` aren't covered here because they touch the- * gateway / loadConfig; E2E exercises those.+ * gateway / loadConfig; E2E exercises those. The sunset-aware env block and+ * the shared marker ARE covered — they're pure formatters by design.*/import { describe, test, expect } from 'bun:test';-import { formatRecipeTable, envReady } from '../src/commands/providers.ts';+import { formatRecipeTable, formatEnvOutput, sunsetMarker, sunsetMarkerText, envReady } from '../src/commands/providers.ts';import { listRecipes, getRecipe } from '../src/core/ai/recipes/index.ts';import type { Recipe } from '../src/core/ai/types.ts';@@ -98,3 +99,108 @@ describe('formatRecipeTable', () => {expect(lines[3]).toContain('voyage:voyage-4');});});++describe('sunsetMarker (the one shared deprecation string)', () => {+ test('null for a living provider', () => {+ expect(sunsetMarker(getRecipe('voyage')!)).toBeNull();+ expect(sunsetMarker(getRecipe('openai')!)).toBeNull();+ });++ test('marker for a sunsetting provider names the date and replacement', () => {+ const m = sunsetMarker(getRecipe('zeroentropyai')!);+ expect(m).toContain('DEPRECATED');+ expect(m).toContain('2026-09-04');+ expect(m).toContain('voyage:voyage-4');+ });++ test('no replacement metadata → date-only marker, never "undefined"', () => {+ const m = sunsetMarker({ sunset: { date: '2027-01-01', message: 'x' } } as Pick<Recipe, 'sunset'>);+ expect(m).toContain('2027-01-01');+ expect(m).not.toContain('undefined');+ });++ test('sunsetMarkerText primitive (explain-row consumer): with and without replacement', () => {+ expect(sunsetMarkerText('2026-09-04', 'voyage:voyage-4')).toBe(+ '⚠ DEPRECATED — hosted API ends 2026-09-04; use voyage:voyage-4',+ );+ expect(sunsetMarkerText('2026-09-04')).toBe('⚠ DEPRECATED — hosted API ends 2026-09-04');+ expect(sunsetMarkerText('2026-09-04', null)).not.toContain('undefined');+ });+});++describe('formatEnvOutput (providers env <id>)', () => {+ test('sunsetting provider: DEPRECATED + migrate command, NO signup funnel', () => {+ const ze = getRecipe('zeroentropyai')!;+ const out = formatEnvOutput(ze, {});+ expect(out).toContain('DEPRECATED');+ expect(out).toContain('2026-09-04');+ expect(out).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run');+ // The signup funnel must be gone three weeks before shutdown:+ expect(out).not.toContain('dashboard.zeroentropy.dev');+ expect(out).not.toContain('Get an API key');+ // Key STATUS still renders so existing users can see what's configured:+ expect(out).toContain('ZEROENTROPY_API_KEY');+ expect(out).toContain('✗ not set');+ });++ test('sunsetting provider with a key set still shows ✓ set', () => {+ const ze = getRecipe('zeroentropyai')!;+ const out = formatEnvOutput(ze, { ZEROENTROPY_API_KEY: 'sk-fake' });+ expect(out).toContain('✓ set');+ expect(out).toContain('DEPRECATED');+ });++ test('living provider control: setup funnel intact', () => {+ const voyage = getRecipe('voyage')!;+ const out = formatEnvOutput(voyage, {});+ expect(out).not.toContain('DEPRECATED');+ expect(out).toContain('Setup:');+ });++ test('sunset recipe without replacement metadata prints no "undefined"', () => {+ const fake = {+ id: 'fake-sunset',+ name: 'Fake Sunset',+ tier: 'native',+ touchpoints: {},+ auth_env: { required: ['FAKE_KEY'] },+ sunset: { date: '2027-01-01', message: 'Fake is shutting down.' },+ } as unknown as Recipe;+ const out = formatEnvOutput(fake, {});+ expect(out).toContain('DEPRECATED');+ expect(out).not.toContain('undefined');+ expect(out).not.toContain('Replacement:');+ expect(out).toContain('migrate embeddings');+ });++ test('sunset block positively asserts message + Replacement line (ZE fixture)', () => {+ const out = formatEnvOutput(getRecipe('zeroentropyai')!, {});+ expect(out).toContain('ZeroEntropy is shutting down its hosted API.');+ expect(out).toContain('Replacement: voyage:voyage-4 (embedding), voyage:rerank-2.5 (reranker)');+ });++ test('keyless recipe (ollama): Required: (none) arm renders', () => {+ const ollama = getRecipe('ollama')!;+ const out = formatEnvOutput(ollama, {});+ expect(out).toContain('Required: (none)');+ expect(out).not.toContain('DEPRECATED');+ });++ test('optional-env arm renders when a recipe declares optional vars', () => {+ const fake = {+ id: 'fake-optional',+ name: 'Fake Optional',+ tier: 'native',+ touchpoints: {},+ auth_env: { required: ['FAKE_KEY'], optional: ['FAKE_ORG'], setup_url: 'https://example.com' },+ setup_hint: 'Get a key at example.com.',+ } as unknown as Recipe;+ const out = formatEnvOutput(fake, { FAKE_ORG: 'org-1' });+ expect(out).toContain('Optional:');+ expect(out).toContain('FAKE_ORG');+ expect(out).toContain('✓ set');+ // Living provider keeps its funnel:+ expect(out).toContain('Setup: https://example.com');+ expect(out).toContain('Get a key at example.com.');+ });+});diff --git a/test/ze-switch-cli.test.ts b/test/ze-switch-cli.test.tsindex 03c2d39bdd..8ea07a43d0 100644--- a/test/ze-switch-cli.test.ts+++ b/test/ze-switch-cli.test.ts@@ -1,33 +1,38 @@/**- * v0.46.3 — `gbrain ze-switch` CLI tests (post-sunset-refusal contract).+ * `gbrain ze-switch` — refusal/redirect shim contract.*- * 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+ * ZeroEntropy's hosted API shuts down 2026-09-04. The command is a pure shim:+ * every invocation refuses or redirects, nothing mutates the brain. Pins:+ * - --help exits 0 with truthful copy: the canonical migration command, the+ * sunset date, and NO forward-switch encouragement+ * - every non-help invocation exits 1 (bare, --dry-run, --resume,+ * --non-interactive, --force, flag combos)+ * - --json refusal envelope: {status: 'refused', reason: 'provider_sunset',+ * migrate: <canonical dry-run command>}+ * - --undo with a stored snapshot REDIRECTS: prints the exact migrate+ * command that returns the brain to its pre-switch provider, exit 1,+ * {status: 'redirected', undo_command} in --json — it does NOT act (the+ * retired undo action wrote DB-plane config the file-plane-canonical+ * runtime never read)+ * - --undo without a snapshot (or with a corrupt one) refuses+ * - retired flags are still parsed: they reach the refusal message, not a+ * pre-dispatch unknown-flag error (registry row keeps them)** 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';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';-import { withEnv } from './helpers/with-env.ts';-import { runZeSwitch } from '../src/commands/ze-switch.ts';-import {- KEY_APPLIED,- KEY_REQUESTED,- KEY_PREVIOUS_SNAPSHOT,- ZE_TARGET_EMBEDDING_DIM,-} from '../src/core/retrieval-upgrade-planner.ts';+import { runZeSwitch, RETIRED_FLAGS, buildUndoCommands } from '../src/commands/ze-switch.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';+import { KEY_APPLIED, KEY_REQUESTED, KEY_PREVIOUS_SNAPSHOT } from '../src/core/retrieval-upgrade-planner.ts';++const REPO = new URL('..', import.meta.url).pathname;let engine: PGLiteEngine;@@ -88,27 +93,13 @@ function captureExit<T>(fn: () => Promise<T>): Promise<{ exitCode: number; stdou});}-async function seedPages(n: number) {- for (let i = 0; i < n; i++) {- await engine.putPage(`seed/page-${i}`, {- title: `Seed ${i}`,- compiled_truth: `Body text ${i} with enough chars to flow through cost math.`,- timeline: '',- type: 'note',- });- }-}-async function setLegacyConfig() {await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');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() {+/** Seed the snapshot a pre-v0.46.3 forward switch would have left behind. */+async function seedAppliedSwitch(overrides: Record<string, unknown> = {}) {await engine.setConfig(KEY_PREVIOUS_SNAPSHOT,JSON.stringify({@@ -116,137 +107,292 @@ async function seedAppliedSwitch() {embedding_dimensions: 1536,search_reranker_enabled: false,search_reranker_model: null,+ ...overrides,}),);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));+ await engine.setConfig('embedding_dimensions', '1280');}-describe('--help', () => {- test('exits 0 with usage text', async () => {- const r = await captureExit(() => runZeSwitch(['--help'], engine));+describe('--help (truthful, engine-free)', () => {+ test('exits 0 with the canonical migration command and the sunset date', async () => {+ // engine=null mirrors the dispatcher's SELF_HELP_WITHOUT_ENGINE path:+ // help must never touch the engine.+ const r = await captureExit(() => runZeSwitch(['--help'], null));expect(r.exitCode).toBe(0);expect(r.stdout).toContain('gbrain ze-switch');- expect(r.stdout).toContain('--dry-run');- expect(r.stdout).toContain('--undo');+ expect(r.stdout).toContain('RETIRED');+ expect(r.stdout).toContain('2026-09-04');+ expect(r.stdout).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');+ expect(r.stdout).toContain('skills/migrations/v0.46.3.0.md');+ // The hostile-QA negative: the old encouraging sentence must never return.+ expect(r.stdout).not.toContain('Switch the brain\'s embedding + reranker defaults to ZeroEntropy');});});-describe('--dry-run (read-only, still allowed)', () => {- test('human output prints plan, changes nothing', async () => {- await setLegacyConfig();- await seedPages(150);+describe('every non-help invocation refuses (exit 1, nothing changes)', () => {+ const refusedInvocations: string[][] = [+ [],+ ['--dry-run'],+ ['--resume'],+ ['--non-interactive'],+ ['--force'],+ ['--yes'],+ ['--non-interactive', '--ignore-missing-key'],+ ['--ignore-env-override'],+ // The old gate's bypass combos (dry-run/undo used to pass): now refused+ // or redirected, never silently ignored.+ ['--dry-run', '--resume'],+ ['--confirm-reembed'],+ ];- const r = await captureExit(() => runZeSwitch(['--dry-run'], engine));- expect(r.exitCode).toBe(0);- expect(r.stdout).toContain('Current model');- expect(r.stdout).toContain('Target model');- // Nothing changed:- expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();- });-});--describe('forward switch — REFUSED (provider sunset)', () => {- test('--non-interactive refuses with exit 1 and the escape route', async () => {- await setLegacyConfig();- await seedPages(150);- await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake' }, async () => {- const r = await captureExit(() => runZeSwitch(['--non-interactive'], engine));+ for (const args of refusedInvocations) {+ test(`ze-switch ${args.join(' ') || '(bare)'} refuses`, async () => {+ await setLegacyConfig();+ const r = await captureExit(() => runZeSwitch(args, engine));expect(r.exitCode).toBe(1);expect(r.stderr).toContain('2026-09-04');- expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4');- // Nothing was applied:+ expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');+ // Nothing was applied or mutated:expect(await engine.getConfig(KEY_APPLIED)).toBeNull();expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');});- });+ }- test('--ignore-missing-key does not bypass the refusal', async () => {+ test('--json refusal envelope carries reason provider_sunset + the migrate command', async () => {await setLegacyConfig();- await seedPages(150);- const r = await captureExit(() =>- runZeSwitch(['--non-interactive', '--ignore-missing-key'], engine),+ const r = await captureExit(() => runZeSwitch(['--dry-run', '--json'], engine));+ expect(r.exitCode).toBe(1);+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('refused');+ expect(env.reason).toBe('provider_sunset');+ expect(env.migrate).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');+ // The retired dry-run plan envelope is gone for good:+ expect(env.status).not.toBe('planned');+ expect(env.plan).toBeUndefined();+ });+});++describe('--undo (redirect: prints the return-path command, never acts)', () => {+ test('with a snapshot: prints the exact migrate command, exit 1, config untouched', async () => {+ await seedAppliedSwitch();+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain(+ 'gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536 --reranker off --dry-run',);+ // Guidance only — the brain still points at ZE until the user runs it:+ expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');+ expect(await engine.getConfig(KEY_APPLIED)).toBe('true');+ });++ test('with a snapshot carrying a reranker model: folds --reranker <model> in', async () => {+ await seedAppliedSwitch({ search_reranker_enabled: true, search_reranker_model: 'voyage:rerank-2.5' });+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));expect(r.exitCode).toBe(1);- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();+ expect(r.stderr).toContain('--reranker voyage:rerank-2.5');});- test('--force does not bypass the refusal either', async () => {- await setLegacyConfig();- const r = await captureExit(() => runZeSwitch(['--force'], engine));+ test('enabled:false WINS over a lingering model id — prints --reranker off', async () => {+ // The pre-switch brain had reranking disabled with a model still set (the+ // documented set-model-first intermediate state). `--reranker <model>`+ // would re-enable it; fidelity demands off.+ await seedAppliedSwitch({ search_reranker_enabled: false, search_reranker_model: 'voyage:rerank-2.5' });+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));expect(r.exitCode).toBe(1);- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();+ expect(r.stderr).toContain('--reranker off');+ expect(r.stderr).not.toContain('--reranker voyage:rerank-2.5');});- test('--json refusal envelope carries reason provider_sunset', async () => {- await setLegacyConfig();- const r = await captureExit(() =>- runZeSwitch(['--non-interactive', '--ignore-missing-key', '--json'], engine),- );+ test('enabled with no model: no --reranker token (migration default applies)', async () => {+ await seedAppliedSwitch({ search_reranker_enabled: true, search_reranker_model: null });+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536');+ expect(r.stderr).not.toContain('--reranker');+ });++ test('junk-typed dims in the snapshot degrade to the refusal (never printed)', async () => {+ await seedAppliedSwitch({ embedding_dimensions: 'abc' as unknown as number });+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));+ expect(r.exitCode).toBe(1);+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('refused');+ expect(r.stdout).not.toContain('--dim abc');+ });++ test('shell-metachar model id in the snapshot degrades to the refusal (injection guard)', async () => {+ await seedAppliedSwitch({ embedding_model: 'x; curl evil.example|sh' });+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));+ expect(r.exitCode).toBe(1);+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('refused');+ expect(r.stdout).not.toContain('curl evil.example');+ });++ test('a throwing engine.getConfig degrades to the refusal, not a crash', async () => {+ const broken = { getConfig: () => Promise.reject(new Error('db exploded')) } as unknown as PGLiteEngine;+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], broken));expect(r.exitCode).toBe(1);const env = JSON.parse(r.stdout);expect(env.status).toBe('refused');expect(env.reason).toBe('provider_sunset');});- 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');+ test('--undo --json emits the redirected envelope with live + preview commands', async () => {+ await seedAppliedSwitch();+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));+ expect(r.exitCode).toBe(1);+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('redirected');+ expect(env.reason).toBe('provider_sunset');+ // undo_command is the LIVE command (an agent executing it must actually+ // migrate, not exit-0 on a preview); undo_preview carries --dry-run.+ expect(env.undo_command).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536');+ expect(env.undo_command).not.toContain('--dry-run');+ expect(env.undo_preview).toContain('--dry-run');+ });- const r = await captureExit(() => runZeSwitch(['--resume'], engine));+ test('nested model ids (ollama tag / openrouter path) validate and redirect', async () => {+ await seedAppliedSwitch({ embedding_model: 'ollama:nomic-embed-text:v1.5' });+ let r = await captureExit(() => runZeSwitch(['--undo'], engine));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');+ expect(r.stderr).toContain('--to ollama:nomic-embed-text:v1.5');++ await seedAppliedSwitch({ embedding_model: 'openrouter:google/gemma-2-9b' });+ r = await captureExit(() => runZeSwitch(['--undo'], engine));+ expect(r.stderr).toContain('--to openrouter:google/gemma-2-9b');});-});-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),- );+ test('string "false" reranker-enabled fails validation (would re-enable a paid reranker)', async () => {+ await seedAppliedSwitch({ search_reranker_enabled: 'false' as unknown as boolean, search_reranker_model: 'voyage:rerank-2.5' });+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));expect(r.exitCode).toBe(1);+ expect(JSON.parse(r.stdout).status).toBe('refused');});- test('--non-interactive without --confirm-reembed exits 1', async () => {- const r = await captureExit(() => runZeSwitch(['--undo', '--non-interactive'], engine));+ test('--json=true spelling is honored (mirrors cli.ts convention)', async () => {+ const r = await captureExit(() => runZeSwitch(['--dry-run', '--json=true'], engine));expect(r.exitCode).toBe(1);- expect(r.stderr).toContain('confirm-reembed');+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('refused');});- test('with snapshot + --confirm-reembed: reverses the switch', async () => {- await seedPages(150);- await seedAppliedSwitch();- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');+ test('without a snapshot: refuses with the canonical migration', async () => {+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('No prior switch snapshot recorded');+ expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');+ });++ test('with a corrupt snapshot: degrades to the refusal, no crash', async () => {+ await engine.setConfig(KEY_PREVIOUS_SNAPSHOT, '{not json');+ const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));+ expect(r.exitCode).toBe(1);+ const env = JSON.parse(r.stdout);+ expect(env.status).toBe('refused');+ expect(env.reason).toBe('provider_sunset');+ });+ test('legacy scripted undo spelling gets guidance, not action', async () => {+ await seedAppliedSwitch();const r = await captureExit(() =>runZeSwitch(['--undo', '--non-interactive', '--confirm-reembed'], engine),);- expect(r.exitCode).toBe(0);- // Reverted to prior model.- expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');- expect(await engine.getConfig('embedding_dimensions')).toBe('1536');- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large');+ // The retired action would have reverted config; the shim must not:+ expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');+ });++ test('a failed --undo never points back at --undo (guidance-loop guard)', async () => {+ const r = await captureExit(() => runZeSwitch(['--undo'], engine));+ expect(r.exitCode).toBe(1);+ expect(r.stderr).not.toContain('gbrain ze-switch --undo');});});-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);+describe('buildUndoCommands (pure builder)', () => {+ const snap = {+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ search_reranker_enabled: false,+ search_reranker_model: null,+ };++ test('carries the explicit --brain selector into BOTH commands', () => {+ // --brain is stripped pre-dispatch by the global option layer; without+ // this, `ze-switch --brain team-x --undo` reads team-x's snapshot but the+ // printed command re-embeds the DEFAULT brain (paid work, wrong corpus).+ const { live, preview } = buildUndoCommands(snap, ' --brain team-x');+ expect(live).toContain('--brain team-x');+ expect(preview).toContain('--brain team-x');+ expect(preview).toContain('--dry-run');+ expect(live).not.toContain('--dry-run');+ });++ test('no brain selector → no --brain token', () => {+ const { live } = buildUndoCommands(snap, '');+ expect(live).not.toContain('--brain');});});++describe('registry + dispatch contract (the layer in-process calls bypass)', () => {+ test('every retired flag is in the generated ze-switch registry row', () => {+ // The refusal-instead-of-unknown-flag promise lives in the GENERATED row,+ // not in the shim: a help-copy trim that dropped the quoted literals+ // would regenerate the row without them and old scripts would die+ // pre-dispatch. This pin makes that failure loud.+ const row = CLI_FLAG_REGISTRY['ze-switch'] ?? [];+ for (const f of RETIRED_FLAGS) {+ expect(row).toContain(f);+ }+ });++ test('spawned CLI: a retired flag reaches the refusal even with NO brain configured', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-zeswitch-nobrain-'));+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };+ delete env.GBRAIN_DATABASE_URL;+ delete env.DATABASE_URL;+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'ze-switch', '--resume'], {+ cwd: REPO,+ env,+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ const code = await proc.exited;+ const all = out + err;+ expect(code).toBe(1);+ expect(all).not.toContain('unknown flag');+ expect(all).not.toContain('No brain configured');+ expect(all).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');+ }, 30_000);++ test('spawned CLI: --undo --json on a brainless machine still gets the envelope', async () => {+ // connectEngine would print plain "No brain configured" and exit before+ // the shim ran — the dispatch pre-checks config and degrades to a null+ // engine so --json callers always get machine-readable truth.+ const home = mkdtempSync(join(tmpdir(), 'gbrain-zeswitch-undo-'));+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };+ delete env.GBRAIN_DATABASE_URL;+ delete env.DATABASE_URL;+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'ze-switch', '--undo', '--json'], {+ cwd: REPO,+ env,+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);+ const code = await proc.exited;+ expect(code).toBe(1);+ const envlp = JSON.parse(out.trim().split('\n').pop()!);+ expect(envlp.status).toBe('refused');+ expect(envlp.reason).toBe('provider_sunset');+ }, 30_000);+});