Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.10.0 feat(migrate): guess-free embedding + reranker migration — DB-verified skip, truthful coverage, one canonical command (#4189)

Garry Tan871ce3c2669c
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 0edca83ecd..9fe12df507 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.9.1",
+ "version": "0.46.10.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", "url": "https://github.com/garrytan" },
"homepage": "https://github.com/garrytan/gbrain",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 5e2ed1817b..ec0a3fa7d6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.9.1",
+ "version": "0.46.10.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", "url": "https://github.com/garrytan" },
"homepage": "https://github.com/garrytan/gbrain",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 01ee57d893..15d12c14be 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.9.1 -->
+<!-- gbrain-runbook-stamp: 0.46.10.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf7bdadbea..c493ae8c09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,114 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.10.0] - 2026-08-16
+
+**Switching embedding and reranking providers is now one guess-free
+command.** `gbrain migrate embeddings` verifies against the database —
+column widths, stale censuses, config planes, and the migration marker —
+so a stale environment variable or config value can never fake a
+completed migration, and every surface that mentions migrating prints
+the same canonical, paste-ready command.
+
+### Added
+- **`gbrain migrate embeddings --status [--json]`** — read-only status:
+ per-plane model resolution (env presence, file, DB — API keys shown as
+ set/unset booleans only), actual column widths, NULL-vector and
+ signature censuses, the in-flight marker with the exact resume
+ command, and the last completion's smoke-check outcome. Never embeds,
+ never refuses on env.
+- **`--reranker auto|off|keep|<provider:model>`** — the reranker rides
+ the same migration flow. `auto` resolves the ACTIVE reranker through
+ the search-mode bundle defaults (not just explicitly-set keys), probes
+ the target reranker live before any write, and lands the config write
+ and query-cache purge in one transaction. When the target provider
+ ships no reranker, the plan prints the exact follow-up command instead
+ of silently enabling a third provider. Invalid values refuse with the
+ list of valid reranker recipes before anything runs.
+- **`--retarget`** — abandoning a different in-flight migration target
+ is an explicit decision; the refusal names both the resume and
+ retarget commands, and the marker keeps a history of superseded
+ targets.
+- **Post-migration smoke check.** Completion runs a self-retrieval probe
+ (sampled pages must find themselves; warn-only, never blocks or
+ re-bills) and stamps the outcome into the completion marker, where
+ `--status` reads it without re-spending.
+- **Doctor: `embedding_migration_state` check** — warns with the exact
+ resume + status commands while a migration is in flight or was
+ interrupted. Two companion notes land in existing checks: the
+ env-override check now notes when env vars agree with stored config
+ (they still override the file plane at runtime), and the embeddings
+ coverage check notes when the read path uses a custom embedding column.
+- **One canonical migration command.** Every surface that suggests
+ migrating (upgrade banner, init, doctor, advisor, sunset notices,
+ docs) renders through one shared helper, with a drift-guard test
+ sweeping src + docs.
+- **Migration plan honesty.** The plan header names the exact brain/DB
+ target (redacted) and scope; renders a DESTRUCTIVE warning whenever a
+ rebuild will drop stored vectors (including the absent-column case);
+ reports pages that will re-embed at a lower context tier; warns when
+ live workers or queued embed jobs could write outside the migration
+ locks; and notes when the target width exceeds the ANN-index cap
+ (search falls back to exact scan).
+
+### Changed
+- **The "nothing to migrate" skip is DB-verified.** Completion now
+ requires the column width, every dim-pinned companion column, the
+ wide stale census (pages with no recorded signature included), the
+ chunkless-page census, the marker, and the config planes to all agree
+ with the target. Config and env values alone can no longer produce a
+ false "Nothing to migrate".
+- **Coverage tells the truth.** `gbrain stats` embedded counts, health
+ embed-coverage, and doctor's embeddings check now key on the stored
+ vector itself rather than bookkeeping timestamps, and skip-marked
+ chunks are excluded from both sides of the ratio (an all-skip brain
+ reads 100%, not 0%-with-nothing-to-do).
+- **Env vars are handled honestly.** Env pinning the same target
+ proceeds with a loud keep-in-sync notice; env disagreeing still
+ refuses with the override box. On a brain with no config file, a fully
+ pinning env is accepted as canonical — and nothing env-sourced (keys,
+ URLs) is ever written into the config file.
+- **Background embed parity.** `gbrain embed --background` now carries
+ catch-up, include-null-signature, batch-size, and priority into the
+ job payload; the job handlers read all of them. The doc-recommended
+ migration follow-up command behaves identically foreground and
+ background.
+- **Schema transitions are safer.** Each dim-pinned column is checked
+ and repaired independently; a same-width re-run or resume never drops
+ stored vectors; targets above the ANN-index dimension cap skip index
+ creation cleanly instead of failing DDL.
+- **Migrations single-flight properly.** A brain-wide migration lock
+ plus per-source locks (sorted, archived included) are held across the
+ drain with a heartbeat; losing the lock aborts cleanly and resumably
+ instead of racing another writer. Completion bookkeeping is
+ transactional — a crash can't lose both the resume marker and the
+ receipt.
+- **`doctor --remediate`** includes the unsigned-page cohort in its
+ embed step and its cost estimate when that cohort is non-empty.
+- **Unknown-provenance honesty.** When the embedding gateway can't
+ resolve a model, nothing stamps a fabricated signature; those pages
+ are counted as unknown provenance and picked up by the widened
+ censuses.
+
+### Fixed
+- Five surfaces printed five different migration command strings — some
+ with unsubstituted placeholders or invalid widths for the suggested
+ model. All render the canonical command now.
+- Doctor's embeddings hint named a flag that doesn't exist; it now
+ prescribes the real remediation.
+- The migration playbook gained an env preflight, a quiesce step, a
+ recovery section, an exit-code table, and a DB-verified verify step
+ (skills/migrations/v0.46.3.0.md).
+
+**To take advantage of v0.46.10.0:** upgrade and re-run `gbrain doctor`.
+Embedding-coverage numbers become truthful on upgrade — a brain that
+previously reported inflated coverage may show lower numbers or a new
+doctor warning; that is the pre-existing state becoming visible, not a
+regression. The fix is one command: `gbrain embed --stale` (add
+`--include-null-signature` if doctor reports unsigned pages). If you are
+mid-migration off a sunsetting provider, `gbrain migrate embeddings
+--status` shows exactly where you are and the exact resume command.
+
## [0.46.9.1] - 2026-08-16
**Coverage is now measured, honestly, on every PR — and the six giant modules stopped growing.**
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 35e0321316..f95edb9760 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -66,7 +66,9 @@ Ask the user for these. gbrain defaults to the Voyage embedding + reranker stack
(`voyage:voyage-4` @ 1024d + `voyage:rerank-2.5` — one key covers both); OpenAI is the
main alternative, chosen at init via `--embedding-model <provider:model>`. ZeroEntropy
is deprecated (its hosted API shuts down 2026-09-04): init auto-pick and the picker
-exclude it, and every ZE embed/rerank prints a deprecation warning.
+exclude it, and every ZE embed/rerank prints a deprecation warning. **Existing brain
+still on ZeroEntropy (or any need to switch embedding/reranker models later)?** Follow
+the playbook at `skills/migrations/v0.46.3.0.md` — one command migrates both.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
diff --git a/README.md b/README.md
index e9d98ea7fb..2e0de76261 100644
--- a/README.md
+++ b/README.md
@@ -365,7 +365,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain now repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](docs/ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](docs/INSTALL.md#pglite-crashes-on-macos-26x-tahoe).
-**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
**Hourly cron sync keeps timing out on a federated brain?** Switch your
cron to a per-source loop with shell `timeout(1)` doing the OS-level kill
diff --git a/TODOS.md b/TODOS.md
index c81bf75f87..d1b5aed9e0 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -162,6 +162,33 @@ Staged-deletion discipline (ship replacements → migrate call sites → update
zerank-2) for users who want max rerank quality on a dedicated key. Wire shape
differs from the ZE/voyage dialect — needs its own `top_param`/response mapping
audit. Filed from the v0.46.3 CEO review (deferred cherry-pick).
+- [ ] **P3 — Standalone reranker config-set should purge the query cache.**
+ `gbrain config set search.reranker.model ...` (the playbook's manual path)
+ changes rank order but leaves cached result sets until the 3600s TTL expires.
+ The in-migration path (`migrate embeddings --reranker`) already purges in the
+ same transaction — mirror that on the bare config-set path (or fold the
+ reranker model into the knobs hash, the same contamination class as
+ graph_signals/relational). Filed from the migration-hardening wave review.
+- [ ] **P2 — Facts re-embed backfill command.** A dimension transition drops
+ `facts.embedding`; facts regenerate only on their next write/`gbrain extract`
+ pass. `migrate embeddings --status` + the completion output now report the
+ pending census, but there is no command to proactively re-embed the backlog.
+ Filed from the migration-hardening wave (outside-voice C5).
+- [ ] **P2 — Tier-preserving re-embed.** A bulk stale re-embed (embedding
+ migration included) lands per_chunk_synopsis pages at the TITLE context tier
+ (embedding-context.ts:211, embed.ts restamp) — a retrieval-quality downgrade
+ the migration now REPORTS (plan consent line + completion count) but cannot
+ avoid. A tier-preserving mode needs its own LLM-spend consent design (synopsis
+ regeneration costs per page). Filed from the migration-hardening wave
+ (outside-voice C6).
+- [ ] **P3 — `gbrain config set embedding_model` refusal still prescribes
+ wipe-and-reinit.** The v0.37.11.0 hard-refuse in `src/commands/config.ts`
+ prints `mv brain.pglite` + re-init (PGLite) / "see docs/embedding-migrations.md"
+ (Postgres) as the switch recipe. The supported path is now `gbrain migrate
+ embeddings --to <provider:model> --dim <N>` on both engines — render this
+ surface via `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) and
+ add it to `test/canonical-migration-command.test.ts`'s sweep so it can't drift
+ again. Filed from the v0.46.9.0 /document-release audit.
## Issues #5+#6 follow-ups (pool starvation + process isolation; plan: ~/.claude/plans/system-instruction-you-are-working-witty-moore.md)
diff --git a/VERSION b/VERSION
index c97ece44cc..0c670e6ec5 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.9.1
\ No newline at end of file
+0.46.10.0
\ No newline at end of file
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index d3ceccfa96..6cb1a40d28 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -56,7 +56,7 @@ export OPENAI_API_KEY=sk-... # alternative embeddings; also used for ch
export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search via query expansion
```
-`ZEROENTROPY_API_KEY` is still honored but deprecated — the ZeroEntropy hosted API shuts down 2026-09-04 (see [`docs/ai-providers/zeroentropy.md`](ai-providers/zeroentropy.md) for the off-ramp).
+`ZEROENTROPY_API_KEY` is still honored but deprecated — the ZeroEntropy hosted API shuts down 2026-09-04. Off-ramp: the agent playbook at [`skills/migrations/v0.46.3.0.md`](../skills/migrations/v0.46.3.0.md) (one command migrates embeddings + reranker) with the full reference in [`docs/guides/embedding-migration.md`](guides/embedding-migration.md).
Common follow-ups:
diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
index 4da58eeb2d..e9fc9bc1ae 100644
--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md
+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
@@ -6,7 +6,7 @@
> that `gbrain upgrade` / `gbrain post-upgrade` route through), plus
> `CHANGELOG.md` for what each release changed. Use this file only to catch a
> long-diverged fork up through the versions it covers; for anything after
-> v0.36.5.0, walk the migration files and CHANGELOG instead.
+> v0.36.5.0, walk the migration files and CHANGELOG instead. Time-critical example: the ZeroEntropy shutdown (2026-09-04) — every fork still embedding or reranking through `zeroentropyai:*` must run `skills/migrations/v0.46.3.0.md` before that date.
GBrain ships skills in `skills/`. Downstream agents (custom OpenClaw deployments,
agent forks of any kind) often **copy** these skill files into their own workspace and
diff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.md
index 5677ec7abc..577a47e6e4 100644
--- a/docs/ai-providers/zeroentropy.md
+++ b/docs/ai-providers/zeroentropy.md
@@ -65,56 +65,45 @@ alongside OpenAI and Voyage.
export ZEROENTROPY_API_KEY=<your-key>
```
-## Embedding switch — zembed-1
+## Leaving ZeroEntropy (the off-ramp)
-**Important:** `gbrain config set embedding_model …` is NOT a live
-gateway switch. `embedding_model` and `embedding_dimensions` size the
-schema and must be stable across engine connects, so they only resolve
-from the **file plane** (`~/.gbrain/config.json`) and the **env plane**
-(`GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS`). The DB plane
-is intentionally ignored for these two keys (same posture as today's
-Voyage setup).
-
-### Option A — file plane (recommended for stable installs)
-
-Edit `~/.gbrain/config.json`:
-
-```json
-{
- "embedding_model": "zeroentropyai:zembed-1",
- "embedding_dimensions": 2560
-}
-```
-
-Valid dims: `2560` (default), `1280`, `640`, `320`, `160`, `80`, `40`.
-Matryoshka-style — smaller trades quality for storage monotonically.
-Pick the largest that fits your column width.
-
-### Option B — env plane (CI / Docker)
+The switch-ONTO instructions that used to live here are gone — following
+them would strand a brain on a dead API. The maintained off-ramp is the
+agent playbook at `skills/migrations/v0.46.3.0.md`; the one command
+(embeddings + reranker in the same consented run):
```bash
-export GBRAIN_EMBEDDING_MODEL=zeroentropyai:zembed-1
-export GBRAIN_EMBEDDING_DIMENSIONS=2560
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run # cost preview
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
```
-### Re-embed
+Plane note (still true, and the reason NOT to hand-edit config for this):
+`embedding_model` / `embedding_dimensions` resolve from the **file plane**
+(`~/.gbrain/config.json`) and the **env plane** (`GBRAIN_EMBEDDING_MODEL` /
+`GBRAIN_EMBEDDING_DIMENSIONS`) — never the DB plane — because they size the
+schema. The migration command writes the right planes for you and verifies
+the database before claiming anything is done. Check state any time with
+`gbrain migrate embeddings --status`.
-Switching embedding models invalidates the vector index. Re-embed:
+### Re-embed
-```bash
-gbrain embed --stale --limit 50 # smoke a small batch
-gbrain embed --stale # full re-embed
-```
+The migration command drains the re-embed itself and refuses to declare
+completion until the database verifies — there is no separate embed step
+on the off-ramp path. If a run is killed mid-drain, `gbrain migrate
+embeddings --status` prints the exact resume command. Self-hosters keeping
+`zeroentropyai:zembed-1` via `provider_base_urls` re-embed nothing (the
+embedding signature is unchanged).
### Verify
```bash
-gbrain models doctor --json | jq '.probes[] | select(.touchpoint=="embedding_config")'
+gbrain migrate embeddings --status
```
-Expected: `status: "ok"`. Invalid dims (e.g. `1024`, `1536`, `3072`)
-surface as `status: "config"` with a paste-ready
-`gbrain config set embedding_dimensions <one of 2560|1280|640|320|160|80|40>` fix hint.
+Read-only and spend-free: reports every config plane, actual column
+widths, the NULL-vector and signature censuses, the in-flight marker, and
+the last completion's smoke-check outcome. Step 5 of the playbook
+(`skills/migrations/v0.46.3.0.md`) walks the full DB-verified check.
## Reranker switch — zerank-2
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 63057162fd..ffbfef31d6 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -206,10 +206,10 @@ 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` — `runSchemaTransition(engine, targetDim)` (exported) is the ONE atomic dimension-transition path, shared by `ze-switch` and `gbrain migrate embeddings`. In a single transaction it rebuilds ALL THREE dim-pinned text-embedding-space columns at `targetDim` — `content_chunks.embedding`, `query_cache.embedding`, `facts.embedding` — preserving each column's declared type (`vector` vs `halfvec`, probed from `information_schema`) and recreating its HNSW index with the matching opclass, gated on `hnswIndexExpected` (above the per-type dim ceiling pgvector refuses the index and exact scans remain the path). query_cache + facts are created at brain-birth width by `migrate.ts` and NO migration ever ALTERs them, so omitting either leaves it silently broken: a narrow `query_cache.embedding` makes every `store()`/`lookup()` fail inside the cache's own error-swallowing (permanent 0% hit rate), and a narrow `facts.embedding` fails every per-fact embed write (the doctor check that would warn is skipped on PGLite, the default engine). `content_chunks.embedding_image` / `embedding_multimodal` are the deliberate exception — separate multimodal models, dimensions independent of the text model. Pinned by `test/embedding-migration.test.ts` (all three widths + a real INSERT at the new width into each) and `test/e2e/migrate-embeddings-postgres.test.ts`.
-- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core (#3390): `planEmbeddingMigration` (workload counts via the widened stale predicates with the TARGET signature + `includeNullSignature`, so a mid-migration re-plan counts only what remains; cost via `embedding-pricing.ts`; `null_signature_chunks` split out for #3391 visibility; reranker-on-outgoing-provider warning), `applyEmbeddingMigration` (env-override gate BEFORE any mutation → in-flight state marker `embedding_migration.state` → `runSchemaTransition` when the ACTUAL column width differs from target → DB-plane `embedding_model`/`embedding_dimensions` → `persistConfig` callback for the file plane → `invalidateStaleSignatureEmbeddings({includeNullSignature: true})` → `SemanticQueryCache.clear()`), `completeEmbeddingMigration` (clears the marker + stamps `embedding_migration.completed`; call only at zero backlog), `resolveMigrationTarget` (validates `provider:model` via `resolveRecipe`, dims via `embeddingDimsForModel` or explicit `--dim`), `migrationSignature` (matches `currentEmbeddingSignature()` shape). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Reuses `runSchemaTransition` (now exported from `retrieval-upgrade-planner.ts`) so ze-switch and the migration share ONE dimension-transition path. `reconcilePageSignatures(engine, plan)` runs after the re-embed drain and BEFORE the completion probe: it stamps the target signature on every page that has zero NULL-embedding chunks, covering pages whose chunks straddle a `listStaleChunks` batch boundary (the embed loop only stamps when `stale.length === existing.length`, so a split page is embedded correctly but never stamped — without the reconcile a >1-batch brain reports "incomplete" and the re-run re-invalidates and re-pays for those pages). Sound only because apply() invalidated everything not already in the target space; pages with a remaining NULL chunk stay unstamped so a real embed failure still surfaces. Invalidation is ordered BEFORE the config writes so a crash on a same-dim swap leaves rows merely stale (empty results) rather than new-space queries scored against old-space vectors (silently wrong). Pinned by `test/embedding-migration.test.ts` (PGLite) + `test/e2e/migrate-embeddings-postgres.test.ts` (real pgvector).
+- `src/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/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] [--pace[=mode]] [--ignore-env-override] [--force-sunset-target]` (alias: `gbrain retrieval-upgrade`, the command README/doctor promised since v0.36). `resolveMigrationTarget` refuses a target whose recipe carries `sunset` metadata — a paid full re-embed onto a provider with an announced shutdown would strand the brain; `--force-sunset-target` is the loud escape hatch for self-hosters running a wire-compatible endpoint behind a `provider_base_urls` override. Flow: plan → render (stderr when `--json` so stdout stays JSON-clean) → consent gate (TTY y/N prompt or `--yes`; non-TTY without `--yes` refuses exit 2, mirroring the reindex-code cost gate) → live probe (one embed against the TARGET model/dims BEFORE any mutation — bad key/model/dim fails with nothing changed) → `applyEmbeddingMigration` with `persistEmbeddingFileConfig` (writes `~/.gbrain/config.json` + reconfigures the in-process gateway — the gateway reads file/env, NOT the DB plane) → `runEmbedCore({stale, catchUp, singleFlight, includeNullSignature, pace})` → drain check → `completeEmbeddingMigration` or exit 1 with the resume hint (re-run the same command). When the re-embed was skipped because another backfill holds the per-source single-flight lock (`EmbedResult.lock_skipped` — the state a hard-killed run leaves behind for up to the 60-min lock TTL), the exit-1 message says so instead of misreporting embed failures, since an immediate re-run cannot resume until the lock expires. Also surfaced as the `migrate_embeddings` op (scope admin, localOnly, hidden cliHints; handler hard-refuses `ctx.remote !== false` and returns `needs_confirmation` + plan without `yes: true`). Pinned by `test/migrate-embeddings-flow.serial.test.ts` (full lifecycle incl. interrupted-run resume on PGLite) + `test/provider-sunset-doctor.serial.test.ts` (lock-skip visibility). Discovery surfaces for brains pinned to a sunsetting provider: the `provider_sunset` doctor check (every run; TARGET-AWARE paste-ready commands — the Voyage target at its valid 1024 width, noting when the brain's actual width via `readContentChunksEmbeddingDim` isn't valid there, plus the OpenAI keep-width alternative when the width is ≤1536; warn before the date, fail after it ONLY when embedded vectors actually exist on the dead provider — zero-vector brains stay warn so doctor-as-CI-gate keeps exiting 0; reranker exposure resolved via `resolveSearchMode`, the plane search actually reranks with, not the gateway plane; ZE-backed custom `embedding_columns` entries flagged via `detectZeCustomColumns` — no automated off-ramp, the message points at the playbook; suppress via `doctor.suppress_provider_sunset`, registered in `KNOWN_CONFIG_KEYS`; self-host escape hatch given equal billing) and the one-shot `gbrain upgrade` banner (`ze_sunset_notice_shown`, same reranker resolution); the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `src/core/ai/defaults.ts`, and `checkProviderSunset(engine, now?)` takes an injectable clock so tests pin both date branches.
+- `src/commands/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/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).
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.md
index 0323b0f720..e861dc7be0 100644
--- a/docs/embedding-migrations.md
+++ b/docs/embedding-migrations.md
@@ -1,5 +1,16 @@
# Switching embedding models or dimensions on an existing brain
+> **Use the command, not the recipes:** `gbrain migrate embeddings --to
+> <provider:model> --dim <N>` is the supported path — it handles the schema
+> transition (all three dim-pinned columns), NULL-signature pages, the
+> reranker companion switch, the query cache, locks, and resume-after-kill,
+> and verifies the database before declaring anything done. Preview with
+> `--dry-run`; inspect state with `--status`. Leaving ZeroEntropy: follow
+> `skills/migrations/v0.46.3.0.md`. The manual recipes below remain as the
+> appendix for unusual situations (they are what the dimension-mismatch
+> error messages link to).
+
+
GBrain stores embeddings in a fixed-dimension `vector(N)` column on
`content_chunks`. If you switch to a model with a different dimension
(e.g. `openai:text-embedding-3-large` 1536 → `voyage:voyage-4` 1024, or
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index f1456871e1..8f67976951 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -112,10 +112,16 @@ ingestion — not just new content.
3. **Live probe.** One tiny embed against the TARGET provider before any
mutation — validates the API key, model id, and dimension support in a
single call. A bad key fails here, with nothing changed.
-4. **Env-override gate.** Refuses when `GBRAIN_EMBEDDING_MODEL` /
- `GBRAIN_EMBEDDING_DIMENSIONS` would silently defeat the switch at
- runtime (the same guard `ze-switch` uses). `--ignore-env-override` for
- people running deliberate experiments.
+4. **Env-override gate.** When `GBRAIN_EMBEDDING_MODEL` /
+ `GBRAIN_EMBEDDING_DIMENSIONS` are set and DISAGREE with the target, the
+ live run refuses (config-says-new / runtime-embeds-old is the #1421 damage
+ class); `--ignore-env-override` for deliberate experiments. When they
+ AGREE with the target the run proceeds with a loud notice (env-first
+ deployments are legitimate; keep the env in sync everywhere gbrain runs).
+ Nothing load-bearing trusts the env either way: the "nothing to migrate"
+ decision verifies the DATABASE (column widths, NULL censuses, signature
+ census, the un-merged file plane), so a pre-set env var cannot fake a
+ completed 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
@@ -153,7 +159,10 @@ pages fail to embed), re-run the **same command**: chunks already embedded on
the target are never re-embedded, the schema/config steps no-op, and the run
continues where it stopped. An in-flight marker (`embedding_migration.state`
in DB config) records the target; it is cleared only when the backlog drains
-to zero.
+to zero. Re-running with a DIFFERENT `--to` target while a migration is in
+flight refuses and names both options: the exact resume command for the
+original target, or the same command with `--retarget` to abandon it
+deliberately (the marker records the superseded target in its history).
One caveat after a HARD kill (SIGKILL, crash, power loss — not Ctrl-C): the
run's per-source single-flight embed lock is left behind, and an immediate
@@ -197,12 +206,31 @@ vector spaces in one index, degrading retrieval with nothing in the logs.
## Reranker
-Migrating embeddings does not touch the reranker. If
-`search.reranker.model` (or the mode-bundle fallback) resolves to the
-outgoing provider, the plan prints a warning; point it at the recommended
-replacement — `gbrain config set search.reranker.model voyage:rerank-2.5`
-(needs `VOYAGE_API_KEY`) — or disable it
-(`gbrain config set search.reranker.enabled false`).
+The migration handles the reranker in the same run (`--reranker auto` is the
+default): when the ACTIVE reranker — resolved through the mode bundles, so
+the common no-explicit-config case counts — is on the outgoing provider or a
+sunsetting one, and the target provider ships a reranker, the run probes it
+live and switches `search.reranker.model` under the same consent gate (config
+write + query-cache purge in one transaction). Overrides: `--reranker off`
+disables reranking, `--reranker keep` leaves it, `--reranker
+<provider:model>` picks explicitly (validated before anything runs). When the
+target provider has no reranker (OpenAI), the run prints an ACTION line with
+the exact commands instead of silently enabling a third provider:
+`gbrain config set search.reranker.model voyage:rerank-2.5` (needs
+`VOYAGE_API_KEY`) or `gbrain config set search.reranker.enabled false`. A
+failed reranker probe keeps the previous config and is reported as
+`switch_failed` — never silent, never fatal to the migration.
+
+## Status (read-only, spend-free)
+
+`gbrain migrate embeddings --status [--json]` reports every config plane (env
+presence, file, DB — API keys as presence booleans only), actual column
+widths (including `facts` / `query_cache`), NULL and chunkless censuses, the
+page-signature census, the in-flight marker with the exact resume command,
+and the last completion record including its smoke-check outcome. It is the
+mid-incident "where am I?" surface; `gbrain doctor`'s
+`embedding_migration_state` check surfaces the same marker on every doctor
+run.
## Custom embedding columns
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 95d74711d8..dd7260d46f 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -46,7 +46,7 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
## If first import fails
-If `gbrain import` fails with `expected N dimensions, not M`, run `gbrain doctor`. The output will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. **You should not need to delete `~/.gbrain`.** The bug-class that historically forced `rm -rf` recoveries is closed as of v0.37.
+If `gbrain import` fails with `expected N dimensions, not M`, run `gbrain doctor`. The output will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch. **You should not need to delete `~/.gbrain`.** The bug-class that historically forced `rm -rf` recoveries is closed as of v0.37.
The doctor distinguishes two repair paths:
@@ -55,10 +55,13 @@ The doctor distinguishes two repair paths:
gbrain init --force --pglite --embedding-model <provider>:<model> --embedding-dimensions <N>
```
-- **Non-empty brain** — migrate cleanly with the supported reindex path:
+- **Non-empty brain** — migrate cleanly with the supported migration path
+ (resumable; preview cost with `--dry-run` first):
```
- gbrain retrieval-upgrade --to <provider>:<model> --reindex
+ gbrain migrate embeddings --to <provider>:<model> --dim <N>
```
+ Leaving ZeroEntropy specifically: `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024`
+ (the full playbook is `skills/migrations/v0.46.3.0.md`).
## Decision tree
@@ -95,7 +98,7 @@ Voyage also serves the hosted rerankers `rerank-2.5` ($0.05/M) and `rerank-2.5-l
gbrain init --pglite --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024
```
-To switch an existing brain, use `gbrain reinit-pglite --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024` (PGLite) or follow `docs/embedding-migrations.md` (Postgres). `gbrain config set embedding_model` is refused — the schema column has to resize.
+To switch an existing brain, run `gbrain migrate embeddings --to voyage:voyage-code-3 --dim 1024` (works on both engines; resumable, cost-previewed with `--dry-run` — see [`docs/guides/embedding-migration.md`](../guides/embedding-migration.md)). `gbrain config set embedding_model` is refused — the schema column has to resize, and the migration command is the path that does that safely.
`gbrain reindex --code` will print a recommendation when run against a brain whose configured embedding model isn't code-tuned; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another model (single-vendor procurement, compliance, etc.).
diff --git a/llms-full.txt b/llms-full.txt
index 4ed29dbe9e..b60e678368 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1113,7 +1113,9 @@ Ask the user for these. gbrain defaults to the Voyage embedding + reranker stack
(`voyage:voyage-4` @ 1024d + `voyage:rerank-2.5` — one key covers both); OpenAI is the
main alternative, chosen at init via `--embedding-model <provider:model>`. ZeroEntropy
is deprecated (its hosted API shuts down 2026-09-04): init auto-pick and the picker
-exclude it, and every ZE embed/rerank prints a deprecation warning.
+exclude it, and every ZE embed/rerank prints a deprecation warning. **Existing brain
+still on ZeroEntropy (or any need to switch embedding/reranker models later)?** Follow
+the playbook at `skills/migrations/v0.46.3.0.md` — one command migrates both.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
@@ -1593,6 +1595,7 @@ wins; fix the row.
| "agent workspace bootstrap", "install gbrain into this agent workspace", "gbrain bootstrap", "paste-in install", "set up the maintenance sweep" | Run `gbrain bootstrap` (paste-in workspace install: interview + identity files + hooks + sweep). See `docs/guides/bootstrap.md` |
| "wire this box's coding agents to the brain", "framework-spawned sessions need brain access", "wire gbrain hooks without a workspace", "hook Claude Code/Codex to the running serve" | Run `gbrain bootstrap harness --yes` (machine-level wiring to a running `serve --http`: scoped token + user-scope MCP + headless pre-approval + hooks; no agent.json). See the "Local harness mode" section of `docs/guides/bootstrap.md` |
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
+| "Switch embedding provider" / "migrate my embeddings" / "switch reranker" / "ZeroEntropy" / "provider_sunset" / "search stopped working after a provider shutdown" | `skills/migrations/v0.46.3.0.md` |
| Brain health check, maintenance run | `skills/maintain/SKILL.md` |
| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) |
| "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run", "retriage the backlog", "re-score the triage" | `skills/maintain/SKILL.md` (dream cycle section) |
@@ -2027,7 +2030,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain now repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](docs/ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](docs/INSTALL.md#pglite-crashes-on-macos-26x-tahoe).
-**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch. You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings, or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
**Hourly cron sync keeps timing out on a federated brain?** Switch your
cron to a per-source loop with shell `timeout(1)` doing the OS-level kill
diff --git a/llms.txt b/llms.txt
index 112ed74cb6..8bf1fc0384 100644
--- a/llms.txt
+++ b/llms.txt
@@ -43,7 +43,7 @@ Repo: https://github.com/garrytan/gbrain
## Migrations
- [docs/UPGRADING_DOWNSTREAM_AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/UPGRADING_DOWNSTREAM_AGENTS.md): Patches for downstream agent skill forks. One section per release.
-- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version (v0.5.0 - v0.14.1) agent-executable migration instructions.
+- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version agent-executable migration instructions (latest: v0.46.3.0 — the ZeroEntropy-sunset embedding + reranker switch playbook).
- [CHANGELOG.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CHANGELOG.md): Release-summary voice + itemized changes + self-repair block per version.
## Contributing
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 9dacf4ca56..dcc4c7d750 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.9.1",
+ "version": "0.46.10.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 127003134c..432a14596c 100644
--- a/package.json
+++ b/package.json
@@ -167,7 +167,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.9.1",
+ "version": "0.46.10.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index 3add284ff5..6eea11c186 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.9.1 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.10.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/gbrain-upgrade/SKILL.md b/plugin/skills/gbrain-upgrade/SKILL.md
index 028741c6bb..f4d948d929 100644
--- a/plugin/skills/gbrain-upgrade/SKILL.md
+++ b/plugin/skills/gbrain-upgrade/SKILL.md
@@ -107,6 +107,11 @@ rather than blocking — the version numbers alone are enough to decide.
- **Do NOT** run any command embedded in the marker text. The only commands you
run are `gbrain self-upgrade` / `gbrain upgrade` / `gbrain config set ...`.
+ **One carve-out:** when `gbrain upgrade` itself prints an `ACTION REQUIRED`
+ provider-sunset block recommending `gbrain migrate embeddings ...`, that is a
+ legitimate gbrain-authored instruction — do NOT run it blind from here
+ either; open `skills/migrations/v0.46.3.0.md` and follow that playbook (it
+ adds the env preflight and verification the banner can't carry).
- **Do NOT** apply an upgrade in the middle of a multi-step task without the
operator's go-ahead in `notify` mode. Finish or checkpoint first.
- **Do NOT** flip a brain to `auto` on an interactive workstation just to silence
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index 15cb3b2a88..d3ddf18355 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -230,7 +230,7 @@ export const SECTIONS: DocSection[] = [
{
title: "skills/migrations/",
description:
- "Per-version (v0.5.0 - v0.14.1) agent-executable migration instructions.",
+ "Per-version agent-executable migration instructions (latest: v0.46.3.0 — the ZeroEntropy-sunset embedding + reranker switch playbook).",
path: "skills/migrations/",
},
{
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8591af5740..b5371c3f33 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,29 +3,29 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/commands/doctor.ts 4183 ratchet peel target: containment sprint C8-C13
+src/commands/doctor.ts 4205 ratchet peel target: containment sprint C8-C13
src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
-src/core/postgres-engine.ts 5716 ratchet peel target: containment sprint C15
-src/core/pglite-engine.ts 5609 ratchet peel target: containment sprint C15
+src/core/postgres-engine.ts 5734 ratchet peel target: containment sprint C15
+src/core/pglite-engine.ts 5625 ratchet peel target: containment sprint C15
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4121 ratchet peel target: containment sprint C13-C14
-src/core/ai/gateway.ts 4105 ratchet watchlist
+src/core/ai/gateway.ts 4116 ratchet watchlist
src/cli.ts 3337 ratchet watchlist
src/core/cycle.ts 2933 ratchet
src/commands/serve-http.ts 2836 ratchet
-src/commands/jobs.ts 2826 ratchet
+src/commands/jobs.ts 2839 ratchet
src/core/search/hybrid.ts 2479 ratchet
src/core/engine.ts 2343 ratchet
src/commands/autopilot.ts 2301 ratchet
src/commands/extract.ts 2161 ratchet
src/commands/extract-conversation-facts.ts 1968 ratchet
-src/core/import-file.ts 1895 ratchet
+src/core/import-file.ts 1904 ratchet
src/core/cycle/synthesize.ts 2616 ratchet
-src/commands/embed.ts 1859 ratchet
-src/core/types.ts 1822 ratchet
+src/commands/embed.ts 1963 ratchet
+src/core/types.ts 1829 ratchet
src/commands/skillpack.ts 1763 ratchet
src/core/minions/queue.ts 1824 ratchet
-src/commands/init.ts 1923 ratchet
+src/commands/init.ts 1932 ratchet
src/commands/integrations.ts 1675 ratchet
src/core/minions/handlers/subagent.ts 1643 ratchet
src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 1500 cap on master)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 9e4016f219..3f6d1d2798 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -29,6 +29,7 @@ test/brain-score-breakdown.test.ts linkable scope — archive pages do not drag
test/brainstorm-timeout.test.ts orchestrator entry-point wrap (CV11 single-point classification) 2 bun-file
test/build-llms.test.ts CLAUDE.md restructure content contracts 5 readFileSync
test/build-llms.test.ts build-llms generator 7 readFileSync
+test/canonical-migration-command.test.ts canonical migration command (single home: ai/defaults.ts) 5 doctor-source-helper
test/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync
test/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSync
test/check-update.test.ts check-update CLI 3 bun-file
@@ -113,6 +114,7 @@ test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cy
test/hook-command.serial.test.ts user-prompt 14 readFileSync
test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
test/integrations.test.ts CLI integration 3 readFileSync
+test/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSync
test/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 readFileSync
test/migrate-stdout-clean.test.ts migration output stays off stdout 2 readFileSync
test/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSync
diff --git a/skills/RESOLVER.md b/skills/RESOLVER.md
index 833fd3a7ec..8b7ecb3fdf 100644
--- a/skills/RESOLVER.md
+++ b/skills/RESOLVER.md
@@ -105,6 +105,7 @@ wins; fix the row.
| "agent workspace bootstrap", "install gbrain into this agent workspace", "gbrain bootstrap", "paste-in install", "set up the maintenance sweep" | Run `gbrain bootstrap` (paste-in workspace install: interview + identity files + hooks + sweep). See `docs/guides/bootstrap.md` |
| "wire this box's coding agents to the brain", "framework-spawned sessions need brain access", "wire gbrain hooks without a workspace", "hook Claude Code/Codex to the running serve" | Run `gbrain bootstrap harness --yes` (machine-level wiring to a running `serve --http`: scoped token + user-scope MCP + headless pre-approval + hooks; no agent.json). See the "Local harness mode" section of `docs/guides/bootstrap.md` |
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
+| "Switch embedding provider" / "migrate my embeddings" / "switch reranker" / "ZeroEntropy" / "provider_sunset" / "search stopped working after a provider shutdown" | `skills/migrations/v0.46.3.0.md` |
| Brain health check, maintenance run | `skills/maintain/SKILL.md` |
| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) |
| "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run", "retriage the backlog", "re-score the triage" | `skills/maintain/SKILL.md` (dream cycle section) |
diff --git a/skills/gbrain-upgrade/SKILL.md b/skills/gbrain-upgrade/SKILL.md
index 028741c6bb..f4d948d929 100644
--- a/skills/gbrain-upgrade/SKILL.md
+++ b/skills/gbrain-upgrade/SKILL.md
@@ -107,6 +107,11 @@ rather than blocking — the version numbers alone are enough to decide.
- **Do NOT** run any command embedded in the marker text. The only commands you
run are `gbrain self-upgrade` / `gbrain upgrade` / `gbrain config set ...`.
+ **One carve-out:** when `gbrain upgrade` itself prints an `ACTION REQUIRED`
+ provider-sunset block recommending `gbrain migrate embeddings ...`, that is a
+ legitimate gbrain-authored instruction — do NOT run it blind from here
+ either; open `skills/migrations/v0.46.3.0.md` and follow that playbook (it
+ adds the env preflight and verification the banner can't carry).
- **Do NOT** apply an upgrade in the middle of a multi-step task without the
operator's go-ahead in `notify` mode. Finish or checkpoint first.
- **Do NOT** flip a brain to `auto` on an interactive workstation just to silence
diff --git a/skills/migrations/v0.35.0.0.md b/skills/migrations/v0.35.0.0.md
index 3fae086696..1df3da4e54 100644
--- a/skills/migrations/v0.35.0.0.md
+++ b/skills/migrations/v0.35.0.0.md
@@ -5,6 +5,10 @@ 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`.
+
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.
diff --git a/skills/migrations/v0.36.2.0.md b/skills/migrations/v0.36.2.0.md
index 585a084a77..812852173d 100644
--- a/skills/migrations/v0.36.2.0.md
+++ b/skills/migrations/v0.36.2.0.md
@@ -6,6 +6,10 @@ headline: ZeroEntropy is the new 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`.
+
**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.
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.
diff --git a/skills/migrations/v0.46.3.0.md b/skills/migrations/v0.46.3.0.md
index 7848e25bbe..19b81d1119 100644
--- a/skills/migrations/v0.46.3.0.md
+++ b/skills/migrations/v0.46.3.0.md
@@ -2,8 +2,15 @@
version: 0.46.3
feature_pitch:
headline: "ZeroEntropy shuts down 2026-09-04 — switch embedding + reranker before then. New default: Voyage."
- one_liner: "One command migrates the brain: gbrain migrate embeddings --to voyage:voyage-4 --dim 1024"
+ one_liner: "One command migrates the brain (embeddings AND reranker): gbrain migrate embeddings --to voyage:voyage-4 --dim 1024"
user_action_required: true
+triggers:
+ - "switch embedding provider"
+ - "migrate my embeddings"
+ - "switch reranker"
+ - "ZeroEntropy"
+ - "provider_sunset"
+ - "search stopped working after a provider shutdown"
---
# v0.46.3 migration — ZeroEntropy shutdown (ACTION REQUIRED before 2026-09-04)
@@ -23,7 +30,7 @@ user's/agent's explicit call.
Run the steps below when the user says anything like:
- "ZeroEntropy" / "zembed" / "zerank" anything
-- "migrate my embeddings" / "switch embedding provider"
+- "migrate my embeddings" / "switch embedding provider" / "switch reranker"
- "search stopped working" / "embedding provider error" (after 2026-09-04)
- "doctor says provider_sunset" / "gbrain is warning about a provider"
- after any `gbrain upgrade` that printed the ACTION REQUIRED sunset block
@@ -31,21 +38,64 @@ Run the steps below when the user says anything like:
Also proactively surface it when `~/.gbrain/migrations/pending-host-work.jsonl`
contains a `"migration": "0.46.3"` entry.
+## Step 0 — env preflight (do this FIRST, it prevents the worst failure mode)
+
+```bash
+env | grep GBRAIN_EMBEDDING
+```
+
+`GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS` **override the file
+plane at runtime** for every gbrain process. Three cases:
+
+- **Nothing printed** — proceed to Step 0.5.
+- **Set and equal to the target** (e.g. `voyage:voyage-4` / `1024`): the
+ migration proceeds with a notice and also writes the file plane. Keep the
+ env in sync everywhere gbrain runs (cron, workers, other shells) — or
+ `unset` it so the file plane is the single source of truth. Env-canonical
+ deployments (containers with no `~/.gbrain/config.json`) are supported: the
+ env IS the config there.
+- **Set and different from the target**: the live run REFUSES (this is the
+ guard against config-says-new/runtime-embeds-old damage). Fix before
+ running:
+
+ ```bash
+ unset GBRAIN_EMBEDDING_MODEL GBRAIN_EMBEDDING_DIMENSIONS
+ ```
+
+The command never trusts these vars for its "nothing to migrate" decision —
+it verifies the database directly — so a pre-set env var can no longer fake a
+completed migration. But an env var pointing elsewhere WILL poison future
+embeds in other processes, which is why the mismatch refuses.
+
+## Step 0.5 — quiesce embed writers
+
+```bash
+gbrain jobs list --status running 2>/dev/null; gbrain jobs list --status waiting 2>/dev/null
+```
+
+Stop the minion worker (or let embed/embed-catch-up/embed-backfill jobs
+drain) before migrating. The migration takes the brain-wide migration lock +
+every per-source embed lock, but generic embed jobs submitted DURING the run
+don't take those locks — anything they write in the old space is caught by
+the final census and re-embedded (costing you twice). The plan output warns
+when live workers/jobs are detected.
+
## Step 1 — confirm exposure
```bash
gbrain doctor --json | jq '.checks[] | select(.name=="provider_sunset")'
```
-`warn`/`fail` mentioning zeroentropyai = exposed. `ok` = already migrated
-(nothing to do; remove the pending-host-work entry).
+`warn`/`fail` mentioning zeroentropyai = exposed. `ok` = likely done — verify
+with `gbrain migrate embeddings --status` (Step 5) before clearing the
+pending-host-work entry; doctor alone can be fooled by env overrides, the
+status command cannot.
## Step 2 — pick the target by which key exists
**Preferred — Voyage** (`VOYAGE_API_KEY` in env, or `voyage_api_key` in
`~/.gbrain/config.json`). One key covers embedding + reranking + the
-multimodal model, and voyage-4 is the current hosted retrieval-quality
-leader. To set the key: `export VOYAGE_API_KEY=...` or edit
+multimodal model. To set the key: `export VOYAGE_API_KEY=...` or edit
`~/.gbrain/config.json` directly — do NOT use `gbrain config set
voyage_api_key` (that writes the DB plane, which the embedding pipeline never
reads).
@@ -72,19 +122,38 @@ gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --yes
**Neither key** — get one of the two (Voyage: https://dash.voyageai.com/api-keys),
or self-host (below).
-## Step 3 — reranker
+## Step 3 — reranker (handled IN the same command)
+
+The migration handles the reranker automatically (`--reranker auto` is the
+default): when the brain's ACTIVE reranker — including the mode-bundle
+default `zeroentropyai:zerank-2` that most ZE brains ride without any
+explicit config — is exposed, and the target provider ships a reranker, the
+run probes it live and switches `search.reranker.model` in the same consented
+pass. Overrides:
+
+```bash
+--reranker off # disable reranking instead
+--reranker keep # leave reranker config untouched
+--reranker voyage:rerank-2.5 # explicit model (validated before anything runs)
+```
-If the doctor/notice flagged the reranker (balanced/tokenmax modes rerank with
-ZE zerank-2 by default until the removal release):
+Migrating to a provider with no reranker (OpenAI)? The run prints an ACTION
+line with the exact commands instead of silently enabling a third provider:
```bash
gbrain config set search.reranker.model voyage:rerank-2.5 # needs VOYAGE_API_KEY
-# or turn reranking off:
-gbrain config set search.reranker.enabled false
+gbrain config set search.reranker.enabled false # or turn it off
```
-Without either, reranking silently fails open (no rerank, autocut off) after
-the shutdown date — search still works, ordering quality drops.
+**Why the plane asymmetry:** embedding config lives on the FILE/ENV planes
+(it sizes the schema, so it must be stable across engine connects — never
+`gbrain config set embedding_model`), while reranker config lives on the DB
+plane (`gbrain config set search.reranker.*` is correct there). The migration
+writes each to its right plane; you only need to know this when doing it by
+hand.
+
+Without a working reranker, reranking fails open after the shutdown date —
+search still works, ordering quality drops, and each search pays the timeout.
## Step 4 — custom embedding columns (rare)
@@ -94,15 +163,58 @@ primary column only). Re-declare the column config on the new provider and
re-embed its content, or drop the column config. A write-side custom-column
migration is a filed follow-up (TODOS.md).
-## Step 5 — verify
+## Step 5 — verify (trust the database, not the env)
+
+```bash
+gbrain migrate embeddings --status
+```
+
+Read the output top to bottom — it shows every config plane (env presence,
+file, DB), the actual column widths, how many chunks/facts still lack
+vectors, the page-signature census, and the smoke-check outcome from the
+completed migration. Converged looks like: column at the target width, 0
+chunks missing, signature census all on the target, no migration in flight.
+
+Then:
```bash
gbrain doctor --json | jq '.checks[] | select(.name=="provider_sunset") | .status' # → "ok"
gbrain search "anything you know is in the brain" # sanity check
```
+Facts note: fact vectors regenerate on their next write / `gbrain extract`
+pass — `--status` shows the pending count; it is not a failure.
+
Then remove/mark the `0.46.3` entry in
-`~/.gbrain/migrations/pending-host-work.jsonl` as done.
+`~/.gbrain/migrations/pending-host-work.jsonl` as done — edit the file and
+change that entry's `"status"` to `"done"` (or delete the line). There is no
+CLI for this yet (filed follow-up).
+
+## Recovery — when a run is killed, fails, or something looks wrong
+
+**Exit codes:** `0` = completed (or verified nothing-to-do), `1` = incomplete /
+refused / failed (message says which), `2` = non-TTY without `--yes`.
+
+- **Killed / crashed mid-run** → re-run the SAME command. The NULL-embedding
+ column is the checkpoint; already-migrated chunks are never re-embedded or
+ re-billed. `gbrain migrate embeddings --status` shows the in-flight marker
+ and prints the exact resume command.
+- **"Migration paused ... lock"** → another embed backfill holds a per-source
+ lock. Check `gbrain jobs list`; a hard-killed run's lock expires within 60
+ minutes — re-run then.
+- **"lock was lost mid-drain"** → another process stole the lock (mutual
+ exclusion ended); partial progress is banked. Re-run once the other holder
+ finishes.
+- **Refused: a migration to X is still in flight** → resume THAT target with
+ the printed command, or abandon it deliberately with `--retarget`.
+- **Wrong `--dim` on the first pass** → re-run with the right `--dim`; the
+ column rebuilds at the new width and the re-embed runs again (vectors at
+ the wrong width are unusable — this re-bill is unavoidable).
+- **Deferred the re-embed with `--no-embed`** → finish with:
+ `gbrain embed --stale --catch-up --include-null-signature`
+ (`--background` carries all of these flags into the job).
+- **Only want status, never mutation** → `gbrain migrate embeddings --status`
+ is read-only and spend-free.
## Self-hosting (zero re-embed, advanced)
@@ -135,6 +247,7 @@ your base-URL override in place, pass `--force-sunset-target` to proceed.
- The brain is keyless (`embedding_disabled: true`) with no ZE reranker or
custom columns — nothing to migrate.
-- `provider_sunset` already reports `ok` — done; just clear the pending entry.
+- `gbrain migrate embeddings --status` shows convergence on a non-ZE target
+ AND `provider_sunset` reports `ok` — done; just clear the pending entry.
- You only mounted someone else's brain: the migration is host-scoped; the
brain's owner migrates it (their upgrade banner + doctor nag them).
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 456ca660bc..1aae154fef 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -1,5 +1,5 @@
{
- "RESOLVER.md": "36b43c65a41e6fce894b9559db2bce0a53f06a99450410e498323c12e12e92bb",
+ "RESOLVER.md": "e16588f3197cc9b8b62c95494dd4a85b8bfb143add215cde696a9079664d1ba0",
"_AGENT_README.md": "62613f7f1e061576b6c1b18844f59bd35f2df96ca5c45c8c41fae0772b9ce4d3",
"_brain-filing-rules.json": "cf850df6a7425464c6d63b3ace71991cc93497fa0cc8cd21acd31883e17939c6",
"_brain-filing-rules.md": "2d2d75b7c76081c56f41b2c0a5a978c355ce957300f9b0a5575dc4079ef1f877",
@@ -82,7 +82,7 @@
"functional-area-resolver/SKILL.md": "52df04bc4f8e678f931c3b2078b2126524e6d2d72676ad46b6b710d13271b46c",
"functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028",
"gbrain-advisor/SKILL.md": "c15c7a88bee2c96733d718a168dd9afcb123b7b6b2c0014c5260d37c72e8736a",
- "gbrain-upgrade/SKILL.md": "4cd6d42c6ac57b66ab5d9066d83ec8209a47b35363ce2c0722eb6515ace7b17d",
+ "gbrain-upgrade/SKILL.md": "dcd1ee1d12d500fc1f56d1545c3f05fc305619f295dba53ea1843ae9d820ae1e",
"idea-ingest/SKILL.md": "01ef449b7d5df52553cfd7c05d1365085058eda32de4fad3e67a22311ccd49f5",
"idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de",
"idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41",
@@ -119,14 +119,14 @@
"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": "0fc21dc0b098f87fff1ac79a669b00a3d69ab1510ebfc5eac4a66f5c6d783809",
+ "migrations/v0.35.0.0.md": "1f4083b6447ae694776f35b70ec6c259b03987cb35a8ee4376c8f51db6bb06ce",
"migrations/v0.35.7.0.md": "c6d4454bd39e2aa243b3b3d9bc72fe5a4fd25d097be7be2bb14b25604b5c2cc5",
- "migrations/v0.36.2.0.md": "1b59328240ae19c5e7e8d3eafda245809cca1fea27146607334dbee53cbeb270",
+ "migrations/v0.36.2.0.md": "becedef44dc377cf95c83ddc479c9ab19f15a984f716fc0b041ba7cde6886f14",
"migrations/v0.36.5.0.md": "a01a722202dfc3c799693596750c8bee611fe4dafe3cb662f6b4cd0b635cb429",
"migrations/v0.40.3.0.md": "5f500f8c543c2b6f41778b0bd3beedada68f7284f7933ad8b769322b433a8fe9",
"migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5",
"migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b",
- "migrations/v0.46.3.0.md": "7762212509ea3f954b31ae4ebb9ee8fc1e497ac021c633fa95631f03a2eaaecc",
+ "migrations/v0.46.3.0.md": "0438f52f423b8f99832d0098fde94188af38eff603a956c67014e5e9bb8572f6",
"migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 9472da5101..5e39071bb6 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -97,6 +97,7 @@ export {
checkSearchMode,
checkEvalDrift,
checkEmbeddingEnvOverride,
+ checkEmbeddingMigrationState,
checkSubagentCapability,
computeConversationParserProbeHealthCheck,
computeNightlyQualityProbeHealthCheck,
@@ -173,6 +174,7 @@ import {
checkSearchMode,
checkEvalDrift,
checkEmbeddingEnvOverride,
+ checkEmbeddingMigrationState,
checkSubagentCapability,
computeConversationParserProbeHealthCheck,
computeNightlyQualityProbeHealthCheck,
@@ -1917,12 +1919,26 @@ export async function buildChecks(
try {
const health = await engine.getHealth();
const pct = (health.embed_coverage * 100).toFixed(0);
+ // Coverage + missing now share one source (the stored vector over
+ // eligible chunks), so the two numbers can no longer contradict each
+ // other. When the READ path rides a custom active column, say so — this
+ // check reports the default write-side column; the active-column truth
+ // lives in embedding_column_registry.
+ let carveOut = '';
+ try {
+ const activeCol = await engine.getConfig('search_embedding_column');
+ if (activeCol && activeCol !== 'embedding') {
+ carveOut = ` (read path uses '${activeCol}'; see embedding_column_registry)`;
+ }
+ } catch {
+ // Config read is best-effort; the coverage numbers stand alone.
+ }
if (health.embed_coverage >= 0.9) {
- checks.push({ name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${health.missing_embeddings} missing` });
+ checks.push({ name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${health.missing_embeddings} missing${carveOut}` });
} else if (health.embed_coverage > 0) {
- checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${health.missing_embeddings} missing. Run: gbrain embed --stale` });
+ checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${health.missing_embeddings} missing. Run: gbrain embed --stale${carveOut}` });
} else {
- checks.push({ name: 'embeddings', status: 'warn', message: 'No embeddings yet. Run: gbrain embed --stale' });
+ checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet. Run: gbrain embed --stale${carveOut}` });
}
} catch {
checks.push({ name: 'embeddings', status: 'warn', message: 'Could not check embedding health' });
@@ -2221,11 +2237,13 @@ export async function buildChecks(
// Only warn when there's a real coverage gap. Empty brain (0 chunks)
// is a normal state for new installs — skip the gate entirely.
if (total > 0 && pct < 90) {
+ // NOTE: there is NO per-column embed flag (write-side custom-column
+ // support is a filed follow-up) — the old hint prescribed one.
coverageWarn =
`Active column '${activeCol}' is ${pct.toFixed(1)}% populated. ` +
`Search quality silently degraded on un-embedded chunks. ` +
- `Fix: gbrain embed --column ${activeCol} --stale (write-side support v2) ` +
- `OR gbrain config set search_embedding_column embedding`;
+ `Fix: gbrain config set search_embedding_column embedding (read the default column), ` +
+ `then gbrain embed --stale; per-column write-side backfill is a filed follow-up (TODOS.md)`;
}
}
@@ -2266,6 +2284,10 @@ export async function buildChecks(
progress.heartbeat('embedding_env_override');
checks.push(await checkEmbeddingEnvOverride(engine));
+ // Surface the migration state marker (previously write-only): a live
+ // marker = mid-migration brain, with the exact resume + status commands.
+ checks.push(await checkEmbeddingMigrationState(engine));
+
// 9. Graph health (link + timeline coverage on entity pages).
// dead_links removed in v0.10.1: ON DELETE CASCADE on link FKs makes it always 0.
//
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 55dbf1a458..7f2ef79f1a 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -381,21 +381,18 @@ export async function checkProviderSunset(engine: BrainEngine, now: number = Dat
: `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE}. No embedded vectors exist yet, so retrieval is not impacted — but embedding will fail until the config points elsewhere.`
: `embedding_model="${model}": the hosted API shuts down on ${ZEROENTROPY_SUNSET_DATE}. On that date semantic retrieval stops entirely — existing vectors become unqueryable (query embedding uses the same endpoint), not just new content.`,
);
- // v0.46.3: the paste-ready fix is TARGET-AWARE on dimensions. Voyage's
- // valid widths are {256, 512, 1024, 2048} — blindly preserving this
- // brain's actual width (usually 1280) would emit a command Voyage
- // rejects. OpenAI text-3 supports flexible widths up to its native
- // size, so the keep-width form is offered only when valid there.
- const openaiDimFlag = dims && dims <= 1536 ? ` --dim ${dims}` : ' --dim 1536';
- const openaiKeepsWidth = !!(dims && dims <= 1536);
+ // v0.46.3: the paste-ready fix is TARGET-AWARE on dimensions via the
+ // canonical renderer (defaults.ts) — Voyage's valid widths are
+ // {256, 512, 1024, 2048}, so the recommended command always carries
+ // --dim 1024; the keep-width OpenAI form renders only when valid there.
+ const { renderCanonicalMigrationCommands } = await import('../../../core/ai/defaults.ts');
+ const cmds = renderCanonicalMigrationCommands({ colDims: dims ?? null });
parts.push(
`Two fixes, either works: ` +
`[1] self-host the same model — zembed-1 weights are Apache-2.0; keep the zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible server — the id speaks ZE's /models/embed dialect). Keeps every existing vector, no re-embed (docs/guides/embedding-migration.md). ` +
- `[2] migrate (resumable; preview cost first): ` +
- `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` +
- (dims && dims !== 1024 ? ` (${dims} is not a valid Voyage width — the migration rebuilds the index at 1024)` : '') +
- `; OpenAI alternative${openaiKeepsWidth ? ` keeps this brain's ${dims}d width` : ''}: ` +
- `gbrain migrate embeddings --to openai:text-embedding-3-small${openaiDimFlag} --dry-run.`,
+ `[2] migrate (resumable; preview cost first): ${cmds.recommendedDryRun}` +
+ (cmds.note ? ` ${cmds.note}` : '') +
+ (cmds.openaiAlternative ? ` Keep-width alternative: ${cmds.openaiAlternative}.` : ''),
);
}
if (onSunsetReranker) {
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 5e11099811..86194032b7 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -153,10 +153,15 @@ export async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Ch
mismatches.push({ key: 'GBRAIN_EMBEDDING_DIMENSIONS', env: envDim, db: dbDim });
}
if (mismatches.length === 0) {
+ // Informational nuance (D10): agreeing env vars are still an override —
+ // the file plane is the durable home; say so instead of a bare ok.
+ const envSet = Boolean(envModel || envDim);
return {
name: 'embedding_env_override',
status: 'ok',
- message: 'env vars agree with DB config',
+ message: envSet
+ ? 'env vars agree with DB config today — note they override the file plane at runtime; prefer the file plane (or keep env in sync everywhere gbrain runs)'
+ : 'env vars agree with DB config',
};
}
return {
@@ -170,6 +175,53 @@ export async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Ch
};
}
+/**
+ * Surface the (previously write-only) embedding-migration state marker: a
+ * live marker means a migration is in flight or was interrupted — the brain
+ * is mid-transition and retrieval may be degraded until it drains. Warn with
+ * the exact resume + status commands.
+ */
+export async function checkEmbeddingMigrationState(engine: BrainEngine): Promise<Check> {
+ try {
+ const { readMigrationState, migrationSignature, renderResumeCommand } = await import('../../../core/embedding-migration.ts');
+ const marker = await readMigrationState(engine);
+ if (marker.corrupt) {
+ return {
+ name: 'embedding_migration_state',
+ status: 'warn',
+ message: 'embedding-migration state marker is corrupt. Inspect: gbrain migrate embeddings --status; re-running the migration rewrites it.',
+ };
+ }
+ if (!marker.state) {
+ return { name: 'embedding_migration_state', status: 'ok', message: 'no embedding migration in flight' };
+ }
+ const s = marker.state;
+ let staleNote = '';
+ try {
+ const stale = await engine.countStaleChunks({
+ signature: migrationSignature(s.to_model, s.to_dims),
+ includeNullSignature: true,
+ });
+ staleNote = `; ${stale} chunk(s) not yet in the target space`;
+ } catch { /* count is best-effort */ }
+ return {
+ name: 'embedding_migration_state',
+ status: 'warn',
+ message:
+ `an embedding migration to ${s.to_model} (${s.to_dims}d) started ${s.started_at} is in flight or was interrupted${staleNote}. ` +
+ `Resume: ${renderResumeCommand(s)}. ` +
+ `Status: gbrain migrate embeddings --status`,
+ details: { to_model: s.to_model, to_dims: s.to_dims, started_at: s.started_at },
+ };
+ } catch (err) {
+ return {
+ name: 'embedding_migration_state',
+ status: 'warn',
+ message: `could not read migration state: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+}
+
export async function checkSubagentCapability(engine: BrainEngine): Promise<Check> {
try {
const { classifyCapabilities } = await import('../../../core/ai/capabilities.ts');
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index ad790b3359..8a001e98c5 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -26,6 +26,7 @@ import {
checkSubagentHealth,
checkBatchRetryHealth,
checkEmbeddingEnvOverride,
+ checkEmbeddingMigrationState,
checkSubagentCapability,
checkVolunteerChannels,
checkSyncFreshness,
@@ -329,6 +330,10 @@ export async function doctorReportRemote(
// 716K-chunk damage incident from PR #1421's description.
checks.push(await checkEmbeddingEnvOverride(engine));
+ // Surface the migration state marker (previously write-only): a live
+ // marker = mid-migration brain, with the exact resume + status commands.
+ checks.push(await checkEmbeddingMigrationState(engine));
+
// v0.31.12 subagent runtime enforcement (Layer 3 of 3 — Codex F13).
// The subagent loop requires native tool-calling. If models.subagent,
// models.tier.subagent, or models.default resolves to a limited provider, warn here
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index f392d178fd..713719722c 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -162,6 +162,16 @@ export interface EmbedOpts {
* `gbrain embed --stale --include-null-signature` set this.
*/
includeNullSignature?: boolean;
+ /**
+ * Migration-hardening: locks the CALLER already holds (the migration
+ * orchestrator acquires the per-source embed-backfill locks up front, before
+ * the schema transition, and holds them through the drain). When set with
+ * `singleFlight`, the drain does NOT re-acquire the same keys — re-acquiring
+ * would always fail against our own holder and misreport `lock_skipped`
+ * ("Migration paused") on every run. Ownership stays with the caller: this
+ * function refreshes them (heartbeat) but never releases them.
+ */
+ heldLocks?: DbLockHandle[];
}
/**
@@ -215,6 +225,14 @@ export interface EmbedResult {
* misreporting embed failures.
*/
lock_skipped?: boolean;
+ /**
+ * Set when the single-flight lock heartbeat discovered the lock was stolen
+ * (refresh matched 0 rows) or kept erroring: mutual exclusion is gone, so
+ * the drain ABORTED with partial progress banked rather than racing the
+ * new holder. Resumable — re-run the same command once the other holder
+ * finishes (the fenced refresh means we can never steal it back silently).
+ */
+ lock_lost?: boolean;
/**
* E1 (paced-backfill): end-of-run pacing telemetry. Present ONLY when pacing
* was active (enabled bundle). The number the operator could not get from an
@@ -360,8 +378,15 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
// sorted (deterministic) order to avoid acquire-order deadlock. Released in
// the finally below. Skipped for dryRun and when the caller didn't opt in
// (cycle / catch-up / sync-auto-embed callers never single-flight).
+ //
+ // Migration hardening: when the caller ALREADY holds the locks
+ // (opts.heldLocks — the migrate-embeddings orchestrator acquires them
+ // before the schema transition), use those instead of re-acquiring — a
+ // re-acquire would always fail against our own holder and misreport
+ // lock_skipped. Ownership stays with the caller (no release here).
const sfLocks: DbLockHandle[] = [];
- if (opts.singleFlight && opts.stale && !opts.dryRun) {
+ const callerHeld = opts.heldLocks !== undefined && opts.heldLocks.length > 0;
+ if (callerHeld === false && opts.singleFlight && opts.stale && !opts.dryRun) {
let lockSourceIds: string[];
if (opts.sourceId) {
lockSourceIds = [opts.sourceId];
@@ -400,6 +425,57 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
}
}
+ // Lock heartbeat (round-2 C3/#5): the TTL is 60 minutes and million-chunk
+ // drains run longer, so without refresh another process could steal the
+ // lock mid-drain and mutual exclusion silently ends. Refresh every 5
+ // minutes; a refresh that returns false (fenced predicate matched 0 rows
+ // = stolen/released) or that keeps THROWING (3 consecutive transient
+ // errors) aborts the drain — continuing without the lock is the one
+ // thing this machinery exists to prevent. Covers both our own sfLocks
+ // and caller-held locks (the migration's).
+ const activeLocks: DbLockHandle[] = callerHeld ? [...(opts.heldLocks ?? [])] : sfLocks;
+ const lockAbort = new AbortController();
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
+ // Test seam: default 5 min; tests shrink it to exercise the loss path.
+ const heartbeatMs = Number(process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS) > 0
+ ? Number(process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS)
+ : 5 * 60 * 1000;
+ if (activeLocks.length > 0 && !opts.dryRun) {
+ let consecutiveErrors = 0;
+ let beating = false;
+ heartbeat = setInterval(() => {
+ if (beating) return; // a slow tick must not stack
+ beating = true;
+ void (async () => {
+ try {
+ if (lockAbort.signal.aborted) return;
+ for (const h of activeLocks) {
+ const ok = await h.refresh();
+ if (!ok) {
+ result.lock_lost = true;
+ serr(' [embed] single-flight lock was stolen or released mid-run; aborting the drain (partial progress is banked — re-run to resume).');
+ if (heartbeat !== undefined) clearInterval(heartbeat);
+ lockAbort.abort();
+ return;
+ }
+ }
+ consecutiveErrors = 0;
+ } catch {
+ consecutiveErrors += 1;
+ if (consecutiveErrors >= 3) {
+ result.lock_lost = true;
+ serr(' [embed] lock heartbeat failed 3 consecutive times; aborting the drain rather than running without mutual exclusion.');
+ if (heartbeat !== undefined) clearInterval(heartbeat);
+ lockAbort.abort();
+ }
+ } finally {
+ beating = false;
+ }
+ })();
+ }, heartbeatMs);
+ }
+ const drainSignal = anySignal(lockAbort.signal, opts.signal);
+
// Resolve DB-contention pacing (env > config > bundle; env is the
// incident escape hatch). dryRun skips it — no writes to pace. A
// disabled bundle yields a no-op pacer (zero overhead on the hot path).
@@ -443,8 +519,13 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
paceMaxConcurrency,
quiet: opts.quiet,
includeNullSignature: opts.includeNullSignature,
- }, opts.signal);
+ }, drainSignal);
+ } catch (e) {
+ // A heartbeat-triggered abort is a clean, resumable stop (lock_lost is
+ // already set + explained on stderr) — not an error to propagate.
+ if (!(result.lock_lost && e instanceof AbortError)) throw e;
} finally {
+ if (heartbeat !== undefined) clearInterval(heartbeat);
// E1: surface pacing telemetry (human + structured) when pacing was on.
const snap = pacer.snapshot();
if (snap.enabled) {
@@ -563,12 +644,21 @@ export async function runEmbed(engine: BrainEngine, args: string[]): Promise<Emb
paramBuilder: (cleanArgs) => {
const slugsI = cleanArgs.indexOf('--slugs');
const srcI = cleanArgs.indexOf('--source');
+ const bsI = cleanArgs.indexOf('--batch-size');
+ const bsRaw = bsI >= 0 ? parseInt(cleanArgs[bsI + 1] ?? '', 10) : NaN;
+ const prI = cleanArgs.indexOf('--priority');
return {
all: cleanArgs.includes('--all'),
stale: cleanArgs.includes('--stale'),
dryRun: cleanArgs.includes('--dry-run'),
slugs: slugsI >= 0 ? cleanArgs.slice(slugsI + 1).filter(a => !a.startsWith('--')) : undefined,
sourceId: srcI >= 0 ? cleanArgs[srcI + 1] : undefined,
+ // Background parity (D7): these four used to be silently DROPPED,
+ // degrading the documented recovery command to a plain stale run.
+ catchUp: cleanArgs.includes('--catch-up'),
+ includeNullSignature: cleanArgs.includes('--include-null-signature'),
+ ...(Number.isFinite(bsRaw) && bsRaw > 0 && { batchSize: Math.min(10_000, bsRaw) }),
+ ...(prI >= 0 && cleanArgs[prI + 1] === 'recent' && { priority: 'recent' }),
// CX1+CX5: carry explicit pace overrides into the `embed` job payload
// (the job name CLI --background actually submits). The handler
// re-resolves env > config > bundle at execution.
@@ -704,8 +794,12 @@ async function embedPage(
}
}
- // Embed chunks without embeddings
- const toEmbed = chunks.filter(c => !c.embedded_at);
+ // Embed chunks without embeddings. embedding_is_null is the stored-vector
+ // truth: a schema rebuild NULLs vectors without touching embedded_at, so
+ // keying on embedded_at alone silently no-ops ("all chunks already
+ // embedded") on a rebuild-darkened page. Older callers that selected chunks
+ // without the boolean fall back to embedded_at.
+ const toEmbed = chunks.filter(c => !c.embedded_at || c.embedding_is_null === true);
result.total_chunks += chunks.length;
result.skipped += chunks.length - toEmbed.length;
@@ -770,7 +864,12 @@ async function embedPage(
// such a page and then stamps it. #3037: a partial failure leaves failed
// chunks NULL, so don't stamp then either.
if (failed === 0 && toEmbed.length === chunks.length) {
- await engine.setPageEmbeddingSignature(slug, { sourceId, signature: currentEmbeddingSignature() });
+ // D9 honesty: no stamp when the gateway is unconfigured — a wrong
+ // signature is worse than none (NULL = unknown provenance).
+ const stampSig = currentEmbeddingSignature();
+ if (stampSig) {
+ await engine.setPageEmbeddingSignature(slug, { sourceId, signature: stampSig });
+ }
// #3507: a fully re-embedded per_chunk_synopsis page landed at the
// title tier — keep the stamped mode honest.
await restampIfDemotedToTitleTier(engine, page, slug, page.source_id);
@@ -832,7 +931,9 @@ async function embedAll(
// v0.41.31: current embedding provenance signature. Stamped onto pages
// when their chunks are (re)embedded so a later model/dimension swap is
// detectable as stale.
- const signature = currentEmbeddingSignature();
+ // null when the gateway is unconfigured: skip stamping + signature-widened
+ // invalidation entirely (a wrong stamp is worse than none — D9 honesty).
+ const signature = currentEmbeddingSignature() ?? undefined;
// ─────────────────────────────────────────────────────────────
// Stale-only fast path: avoid the listPages + per-page getChunks
// bomb that pulled every page row + every chunk's embedding column
@@ -944,11 +1045,14 @@ async function embedAll(
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
// v0.41.31: stamp embedding provenance so a later model swap is
// detectable as stale. #3037: not on partial failure — failed chunks
- // stay NULL under unknown provenance.
+ // stay NULL under unknown provenance. D9: no stamp without a gateway
+ // (signature undefined) — a wrong stamp is worse than none.
if (failed === 0) {
- await observed(pacer, () =>
- engine.setPageEmbeddingSignature(page.slug, { sourceId: pageSourceId, signature }),
- );
+ if (signature) {
+ await observed(pacer, () =>
+ engine.setPageEmbeddingSignature(page.slug, { sourceId: pageSourceId, signature }),
+ );
+ }
// #3507: --all fully re-embeds; a per_chunk_synopsis page landed at
// the title tier — keep the stamped mode honest. #3037: gated on
// failed === 0 — a partially-failed page was NOT fully re-embedded,
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 478a4e1e48..0b3f4ad9cf 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -392,13 +392,18 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
// proceed (D3: hide + warn, allow explicit).
if (out.embedding_model) {
const { getRecipe } = await import('../core/ai/recipes/index.ts');
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_MODEL, renderCanonicalMigrationCommands } =
+ await import('../core/ai/defaults.ts');
const sunsetRecipe = getRecipe(out.embedding_model.split(':')[0]);
if (sunsetRecipe?.sunset) {
const rep = sunsetRecipe.sunset.replacement?.embedding;
+ const initMigrateCmd = rep === NEW_INSTALL_DEFAULT_EMBEDDING_MODEL || !rep
+ ? renderCanonicalMigrationCommands().recommendedDryRun
+ : `gbrain migrate embeddings --to ${rep} --dry-run`;
console.error(
`WARNING: ${sunsetRecipe.name} stops working on ${sunsetRecipe.sunset.date}. ` +
`Proceeding because you asked explicitly${rep ? `, but the recommended provider is ${rep}` : ''}. ` +
- `Migrate before that date: gbrain migrate embeddings --to ${rep ?? '<provider:model>'} --dry-run`,
+ `Migrate before that date: ${initMigrateCmd}`,
);
}
}
@@ -718,7 +723,8 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
const tp = r.touchpoints.embedding!;
const model = tp.default_model ?? tp.models[0];
const fullModel = `${r.id}:${model}`;
- const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } =
+ const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS,
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL, renderCanonicalMigrationCommands } =
await import('../core/ai/defaults.ts');
const { embeddingDimsForModel } = await import('../core/ai/model-resolver.ts');
// Legacy brains ride the legacy width (their stored vectors live there).
@@ -727,11 +733,14 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
: embeddingDimsForModel(r, model);
out.embedding_model = fullModel;
out.embedding_dimensions = dims;
+ const keepMigrateCmd = r.sunset!.replacement?.embedding === NEW_INSTALL_DEFAULT_EMBEDDING_MODEL
+ || !r.sunset!.replacement?.embedding
+ ? renderCanonicalMigrationCommands({ colDims: dims }).recommendedDryRun
+ : `gbrain migrate embeddings --to ${r.sunset!.replacement.embedding} --dry-run`;
console.error(
`WARNING: this brain currently embeds via ${r.name}, which stops working on ` +
`${r.sunset!.date}. Keeping ${fullModel} (${dims}d) so nothing breaks today — ` +
- `migrate before that date: gbrain migrate embeddings --to ` +
- `${r.sunset!.replacement?.embedding ?? '<provider:model>'} --dry-run`,
+ `migrate before that date: ${keepMigrateCmd}`,
);
return;
}
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 399d81e9b9..cb03a768ce 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -2011,6 +2011,15 @@ export async function registerBuiltinHandlers(
// invocation whose whole point was to do neither.
dryRun: !!job.data.dryRun,
sourceId: typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined,
+ // Background parity (D7): the doc-recommended recovery
+ // `embed --stale --catch-up --include-null-signature --background`
+ // used to silently DEGRADE — the payload dropped these four, so the
+ // job ran as a plain 30-min-budget stale pass with the grandfather
+ // clause intact. Serialize + read them like every other embed knob.
+ catchUp: !!job.data.catchUp,
+ includeNullSignature: !!job.data.includeNullSignature,
+ batchSize: typeof job.data.batchSize === 'number' ? job.data.batchSize : undefined,
+ priority: job.data.priority === 'recent' ? 'recent' : undefined,
// CX1+CX5: pace overrides ride in the job payload as explicit overrides
// only; runEmbedCore re-resolves env > config > bundle at execution so
// GBRAIN_PACE_* still wins during an incident.
@@ -2711,6 +2720,7 @@ export async function registerBuiltinHandlers(
sourceId?: string;
batchSize?: number;
priority?: 'recent';
+ includeNullSignature?: boolean;
};
return await runEmbedCore(engine, {
stale: true,
@@ -2718,6 +2728,9 @@ export async function registerBuiltinHandlers(
batchSize: data.batchSize,
priority: data.priority,
sourceId: data.sourceId,
+ // D7/D12: submitters that detected a NULL-signature cohort thread the
+ // widening through; absent = grandfather clause stays (unchanged).
+ includeNullSignature: !!data.includeNullSignature,
});
});
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index c1d49de515..a7fe194f90 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -6,20 +6,31 @@
* Also reachable as `gbrain retrieval-upgrade` — the command README.md and
* doctor.ts have promised since v0.36 but which never had a dispatch branch.
*
- * Flow (everything heavy is reused, see src/core/embedding-migration.ts):
- * 1. plan — chunk/char counts via the widened stale predicates,
- * cost estimate from embedding-pricing.ts
- * 2. preflight— print estimate; require --yes or interactive confirm
- * (non-TTY without --yes refuses with exit 2, mirroring the
- * reindex-code cost gate in docs/operations/spend-controls.md)
- * 3. probe — one live embed against the TARGET provider BEFORE any
- * mutation (validates key + model + dims in one shot)
- * 4. apply — schema transition (dim change), config (DB + file plane),
- * #3391 NULL-signature-inclusive invalidation, cache purge
- * 5. re-embed — runEmbedCore --stale --catch-up with single-flight locks,
- * pacing (--pace), progress reporting. Resumable: a killed
- * run re-runs the SAME command; the NULL-embedding cursor is
- * the checkpoint and steps 3-4 no-op on the second pass.
+ * This file is the orchestrator (planMigrationFlow + executeMigrationFlow);
+ * every heavy primitive lives in src/core/embedding-migration.ts and is
+ * shared with the `migrate_embeddings` op, doctor, and `--status`.
+ *
+ * Execute flow:
+ * 1. global migration lock (GLOBAL_MIGRATION_LOCK_ID) — serializes whole
+ * migrations, including empty-brain runs that lock zero sources
+ * 2. retarget gate — a live marker for a DIFFERENT target refuses without
+ * --retarget; same-target resumes (started_at preserved)
+ * 3. per-source embed-backfill locks, all sources sorted (includeArchived),
+ * held across the drain via heldLocks + a heartbeat that aborts on loss
+ * 4. probe — one live embed against the TARGET provider BEFORE any mutation
+ * 5. apply — schema transition (per-column width repair), config (DB +
+ * file plane; env-canonical when no file exists), NULL-signature-
+ * inclusive invalidation, query-cache purge, marker v2 write
+ * 6. reranker companion — probe + one-tx config write + cache purge
+ * 7. re-embed drain — runEmbedCore --stale --catch-up under the held locks
+ * 8. reconcile signatures, then verifyMigrationComplete (DB reality, not
+ * config), verifySearchRoundTrip smoke check, transactional completion
+ * bookkeeping (live-marker delete + completed-marker write, one tx)
+ *
+ * Resumable: a killed run re-runs the SAME command; the NULL-embedding cursor
+ * is the checkpoint and already-converged steps no-op on the second pass.
+ * `--status` is a separate read-only branch (readMigrationStatus) that never
+ * embeds and never refuses on env.
*/
import type { BrainEngine } from '../core/engine.ts';
@@ -29,11 +40,39 @@ import {
applyEmbeddingMigration,
completeEmbeddingMigration,
reconcilePageSignatures,
+ verifyMigrationComplete,
+ readMigrationState,
+ detectEnvPresence,
+ detectEnvOverride,
+ envFullyPinsTarget,
+ migrationSignature,
+ renderResumeCommand,
+ formatEnvOverrideWarning,
+ resolveRerankerPlan,
+ applyRerankerAction,
+ readMigrationStatus,
+ verifySearchRoundTrip,
MIGRATION_STATE_KEY,
type EmbeddingMigrationPlan,
+ type MigrationVerify,
+ type MigrationState,
+ type EnvOverrideWarning,
+ type RerankerPlan,
+ type VerifySearchOutcome,
} from '../core/embedding-migration.ts';
-import { formatEnvOverrideWarning } from '../core/retrieval-upgrade-planner.ts';
-import { parsePaceArgs, runEmbedCore } from './embed.ts';
+import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';
+import { embedBackfillLockId, EMBED_BACKFILL_LOCK_TTL_MIN } from '../core/embed-backfill-lock.ts';
+import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from '../core/vector-index.ts';
+import { redactPgUrl } from '../core/url-redact.ts';
+import { parsePaceArgs, runEmbedCore, type EmbedResult } from './embed.ts';
+
+/**
+ * Brain-wide migration lock (round-2 #4): serializes whole migrations so two
+ * concurrent runs can't race marker writes + DDL through the read-then-write
+ * window (per-source embed locks don't cover empty brains, which lock zero
+ * sources). Same DbLock machinery + TTL as the embed backfill locks.
+ */
+export const GLOBAL_MIGRATION_LOCK_ID = 'gbrain-embedding-migration';
export interface MigrateEmbeddingsFlags {
to?: string;
@@ -44,6 +83,9 @@ export interface MigrateEmbeddingsFlags {
noEmbed: boolean;
ignoreEnvOverride: boolean;
forceSunsetTarget: boolean;
+ retarget: boolean;
+ /** auto (default) | off | keep | <provider:model> */
+ reranker?: string;
batchSize?: number;
pace?: ReturnType<typeof parsePaceArgs>;
}
@@ -52,6 +94,8 @@ export function parseMigrateEmbeddingsFlags(args: string[]): MigrateEmbeddingsFl
const toIdx = args.indexOf('--to');
const dimIdx = args.indexOf('--dim');
const dimRaw = dimIdx >= 0 ? parseInt(args[dimIdx + 1] ?? '', 10) : NaN;
+ const rrIdx = args.indexOf('--reranker');
+ const reranker = rrIdx >= 0 ? args[rrIdx + 1] : undefined;
const bsIdx = args.indexOf('--batch-size');
const bsRaw = bsIdx >= 0 ? parseInt(args[bsIdx + 1] ?? '', 10) : NaN;
const batchSize = Number.isFinite(bsRaw) && bsRaw > 0 ? Math.min(10_000, bsRaw) : undefined;
@@ -64,6 +108,8 @@ export function parseMigrateEmbeddingsFlags(args: string[]): MigrateEmbeddingsFl
noEmbed: args.includes('--no-embed'),
ignoreEnvOverride: args.includes('--ignore-env-override'),
forceSunsetTarget: args.includes('--force-sunset-target'),
+ retarget: args.includes('--retarget'),
+ ...(reranker !== undefined && { reranker }),
...(batchSize !== undefined && { batchSize }),
pace: parsePaceArgs(args),
};
@@ -94,6 +140,20 @@ Flags:
--force-sunset-target Allow migrating ONTO a provider with an announced
shutdown (e.g. a self-hosted wire-compatible endpoint
behind a provider_base_urls override).
+ --retarget Abandon a DIFFERENT in-flight migration target and
+ start this one (the refusal message names both the
+ resume and retarget commands).
+ --reranker <v> Reranker companion action: auto (default; switch to
+ the target provider's reranker when the current one
+ is exposed by this migration), off (disable
+ reranking), keep (leave it), or an explicit
+ provider:model (e.g. voyage:rerank-2.5). Reranker
+ config lives on the DB plane, unlike embedding
+ config (file/env planes).
+ --status Read-only migration status: config planes (env/file/DB,
+ key PRESENCE only), column widths, NULL censuses,
+ signature census, in-flight marker + exact resume
+ command, last completion + smoke-check outcome.
--help Show this help.
A killed run is resumable: re-run the same command. Already-migrated chunks
@@ -101,20 +161,63 @@ are never re-embedded twice.
`);
}
-function renderPlan(plan: EmbeddingMigrationPlan): string {
+function renderPlan(ctx: MigrationPlanContext): string {
+ const { plan, verify, envPresence, envMatchesTarget, identity, concurrentWriters } = ctx;
const lines: string[] = [];
lines.push('Embedding migration plan');
+ // Wrong-brain visibility: which database this run is actually pointed at.
+ lines.push(` Brain: ${identity.engine} (${identity.target}); scope: brain-wide (all sources)`);
lines.push(` From: ${plan.from_model} (${plan.from_dims}d${plan.column_dims !== null && plan.column_dims !== plan.from_dims ? `; column is actually ${plan.column_dims}d` : ''})`);
lines.push(` To: ${plan.to_model} (${plan.to_dims}d)`);
+ // DB-reality census: what pages say they were embedded with (env can lie
+ // about From; the census cannot).
+ if (plan.signature_census.length > 0) {
+ const census = plan.signature_census
+ .map((c) => `${c.signature ?? '(none recorded)'}: ${c.pages}`)
+ .join(', ');
+ lines.push(` Page signatures: ${census}`);
+ }
+ if (envPresence.present) {
+ if (envMatchesTarget) {
+ lines.push(' NOTICE: GBRAIN_EMBEDDING_* env vars pin this target and override the file');
+ lines.push(' plane at runtime. The migration also writes the file plane — keep the');
+ lines.push(' env in sync (or unset it) so every gbrain process agrees.');
+ } else {
+ lines.push(' WARNING: GBRAIN_EMBEDDING_* env vars are set and do not fully pin the target —');
+ lines.push(' a live run refuses when they contradict it (see the env-override box).');
+ }
+ }
if (plan.dim_change) {
- lines.push(` DESTRUCTIVE: the embedding column is rebuilt at ${plan.to_dims}d, which DELETES`);
- lines.push(' every stored embedding vector in this brain. They are not recoverable —');
- lines.push(' going back to the old provider means paying for a second full re-embed.');
- lines.push(' Until the re-embed finishes, semantic search is degraded to lexical-only.');
- lines.push(` The query cache and fact embeddings are rebuilt at ${plan.to_dims}d too`);
- lines.push(' (cache refills on next query; facts re-embed on their next write).');
+ const hasVectors = plan.column_dims !== null;
+ if (hasVectors) {
+ lines.push(` DESTRUCTIVE: the embedding column is rebuilt at ${plan.to_dims}d, which DELETES`);
+ lines.push(' every stored embedding vector in this brain. They are not recoverable —');
+ lines.push(' going back to the old provider means paying for a second full re-embed.');
+ lines.push(' Until the re-embed finishes, semantic search is degraded to lexical-only.');
+ lines.push(` The query cache and fact embeddings are rebuilt at ${plan.to_dims}d too`);
+ lines.push(' (cache refills on next query; facts re-embed on their next write/extract).');
+ } else {
+ // Absent/unreadable column: nothing stored to lose, but the DDL still
+ // runs — say so instead of silently skipping the warning (dim-honesty).
+ lines.push(` Schema: the embedding column will be (re)built at ${plan.to_dims}d (no stored`);
+ lines.push(' vectors were detected, so nothing is deleted).');
+ }
+ if (plan.to_dims > PGVECTOR_HNSW_VECTOR_MAX_DIMS) {
+ lines.push(` Note: pgvector HNSW indexes cap at ${PGVECTOR_HNSW_VECTOR_MAX_DIMS}d — at ${plan.to_dims}d no ANN index is`);
+ lines.push(' created and vector search runs as an exact scan (slower on large brains).');
+ }
+ }
+ if (ctx.customSearchColumn) {
+ lines.push(` WARNING: search_embedding_column is '${ctx.customSearchColumn}', not 'embedding'. This migration`);
+ lines.push(" rebuilds the default 'embedding' column only — the read path keeps using");
+ lines.push(` '${ctx.customSearchColumn}' (see doctor's embedding_column_registry check).`);
}
lines.push(` Chunks to re-embed: ${plan.chunks_to_embed}${plan.null_signature_chunks > 0 ? ` (includes ${plan.null_signature_chunks} on pages with no recorded embedding signature)` : ''}`);
+ if (plan.synopsis_tier_pages > 0) {
+ lines.push(` Context tier: ${plan.synopsis_tier_pages} page(s) currently embedded at the per_chunk_synopsis`);
+ lines.push(' tier will re-embed at the TITLE tier (a retrieval-quality downgrade for');
+ lines.push(' those pages; tier-preserving re-embed is a filed follow-up).');
+ }
lines.push(
plan.price_known
? ` Estimated cost: $${plan.est_cost_usd.toFixed(2)} (${plan.total_chars} chars at the ${plan.to_model} rate)`
@@ -123,12 +226,76 @@ function renderPlan(plan: EmbeddingMigrationPlan): string {
if (plan.resuming) {
lines.push(' Resuming: a prior migration to this target was interrupted; continuing it.');
}
- if (plan.reranker_warning) {
+ if (concurrentWriters.workers > 0 || concurrentWriters.embedJobs > 0) {
+ lines.push(` WARNING: ${concurrentWriters.workers} live minion worker(s) and ${concurrentWriters.embedJobs} waiting/running`);
+ lines.push(' embed job(s) detected. Generic embed/cycle jobs do not take the migration');
+ lines.push(' locks — stop the worker (or let the queue drain) first, or their writes');
+ lines.push(' will be counted stale by the final census and re-embedded.');
+ }
+ const rr = ctx.rerankerPlan;
+ if (rr.action.kind === 'switch') {
+ lines.push(` Also switching search.reranker.model -> ${rr.action.to} (DB plane — unlike`);
+ lines.push(' embedding config, which lives in the file plane). Probed live before the write.');
+ } else if (rr.action.kind === 'disable') {
+ lines.push(' Also disabling reranking (search.reranker.enabled false).');
+ } else if (rr.action.suggestion !== null) {
+ lines.push(` ACTION: the target provider ships no reranker; the exposed reranker stays on`);
+ lines.push(` ${rr.exposed?.model ?? 'the current model'}. Switch or disable it yourself:`);
+ lines.push(` gbrain config set search.reranker.model ${rr.action.suggestion}`);
+ lines.push(' gbrain config set search.reranker.enabled false');
+ } else if (plan.reranker_warning) {
lines.push(` WARNING: ${plan.reranker_warning}`);
}
+ if (!verify.complete && verify.blockers.length > 0) {
+ lines.push(' Outstanding work:');
+ for (const b of verify.blockers) lines.push(` - ${b}`);
+ }
return lines.join('\n');
}
+/** One home for the retarget-refusal copy (pre-plan gate + in-lock gate). */
+function printRetargetRefusal(state: MigrationState): void {
+ serr(`Refusing: a migration to ${state.to_model} (${state.to_dims}d) started ${state.started_at} is still in flight.`);
+ serr(` Resume it: ${renderResumeCommand(state)}`);
+ serr(` Abandon it: re-run this command with --retarget (the abandoned target is recorded in the marker history)`);
+}
+
+/** One home for the dense schema/invalidation/cache summary line. */
+function renderApplySummary(
+ result: { schema_transitioned: boolean; pinned_repaired: string[]; invalidated: number; cache_cleared: number },
+ plan: EmbeddingMigrationPlan,
+): string {
+ const schema = result.schema_transitioned
+ ? `rebuilt at ${plan.to_dims}d`
+ : result.pinned_repaired.length > 0
+ ? `repaired (${result.pinned_repaired.join(', ')})`
+ : 'unchanged';
+ return ` [migrate] schema ${schema}; ${result.invalidated} chunk(s) invalidated; query cache purged (${result.cache_cleared} row(s)).`;
+}
+
+function renderRerankerOutcome(outcome: RerankerOutcome): string[] {
+ switch (outcome.action) {
+ case 'switched':
+ return [` [migrate] reranker switched to ${outcome.to} (DB plane; query cache purged with it).`];
+ case 'disabled':
+ return [' [migrate] reranking disabled (search.reranker.enabled false).'];
+ case 'switch_failed':
+ return [
+ ` [migrate] reranker NOT switched — the live probe failed; the previous config was kept:`,
+ ` ${outcome.reason ?? 'unknown reason'}`,
+ ` Fix the key/model and re-run, or: gbrain config set search.reranker.model ${outcome.to}`,
+ ];
+ case 'suggested':
+ return [
+ ' [migrate] ACTION: the exposed reranker was NOT changed (target ships none). Switch or disable it:',
+ ...(outcome.suggestion ? [` gbrain config set search.reranker.model ${outcome.suggestion}`] : []),
+ ' gbrain config set search.reranker.enabled false',
+ ];
+ default:
+ return [];
+ }
+}
+
/** Single-keypress y/N confirm on stdin. Injectable for tests. */
async function defaultConfirm(question: string): Promise<boolean> {
process.stderr.write(`${question} [y/N] `);
@@ -177,6 +344,36 @@ export async function probeTargetProvider(
}
}
+/**
+ * One tiny rerank call against the TARGET reranker BEFORE the config write
+ * (round-2 #11-adjacent C11): an embedding migration must not enable a
+ * reranker that can't answer — that would leave every search paying the
+ * fail-open timeout. Probe failure keeps the old config and is REPORTED,
+ * never silent.
+ */
+export async function probeTargetReranker(
+ model: string,
+): Promise<{ ok: true } | { ok: false; message: string }> {
+ try {
+ const { rerank } = await import('../core/ai/gateway.ts');
+ const results = await rerank({
+ query: 'gbrain reranker migration probe',
+ documents: ['gbrain reranker migration probe document a', 'gbrain reranker migration probe document b'],
+ model,
+ timeoutMs: 8000,
+ });
+ if (!Array.isArray(results) || results.length === 0) {
+ return { ok: false, message: `Reranker probe against ${model} returned no results.` };
+ }
+ return { ok: true };
+ } catch (e) {
+ return {
+ ok: false,
+ message: `Reranker probe against ${model} failed: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
/**
* Persist the target model+dims to the FILE plane and reconfigure the
* in-process gateway. The gateway reads file/env config, not the DB plane —
@@ -187,11 +384,29 @@ export async function persistEmbeddingFileConfig(
toModel: string,
toDims: number,
): Promise<void> {
- const { loadConfig, saveConfig } = await import('../core/config.ts');
+ const { loadConfig, loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
const { configureGateway } = await import('../core/ai/gateway.ts');
const { buildGatewayConfig } = await import('../core/ai/build-gateway-config.ts');
- const cfg = loadConfig();
- if (!cfg) {
+ // Round-2 #2: read the FILE plane, not env-merged loadConfig(). Persisting
+ // the merged view wrote env-sourced API keys/DB URLs into
+ // ~/.gbrain/config.json as a side effect of every migration.
+ const fileCfg = loadConfigFileOnly();
+ if (!fileCfg) {
+ // No file plane. Env-canonical deployments (containers/CI where
+ // GBRAIN_EMBEDDING_* IS the durable config, possibly with a read-only
+ // HOME) are legitimate: when env already pins the exact target, there is
+ // nothing to persist — proceed on env alone. The DB plane still gets the
+ // target (apply step 4) so doctor agrees.
+ // Full pinning required: a dims-only env var must not count (the model
+ // would be unpinned and the next process falls back to the legacy
+ // default — the #1421 class). envFullyPinsTarget requires the MODEL var.
+ const envPinsTarget = envFullyPinsTarget(toModel, toDims);
+ if (envPinsTarget) {
+ serr(' [migrate] no ~/.gbrain/config.json — env-canonical mode: GBRAIN_EMBEDDING_* pins the target; keep it set for every gbrain process.');
+ const merged = loadConfig();
+ if (merged) configureGateway(buildGatewayConfig(merged));
+ return;
+ }
// REFUSE rather than warn-and-proceed. Without a file plane to write, the
// switch would not survive this process: the next `gbrain` invocation
// reads file/env config, sees the OLD provider, and re-embeds the brain
@@ -207,10 +422,353 @@ export async function persistEmbeddingFileConfig(
' in the environment of every gbrain process) and re-run.',
);
}
- cfg.embedding_model = toModel;
- cfg.embedding_dimensions = toDims;
- saveConfig(cfg);
- configureGateway(buildGatewayConfig(cfg));
+ fileCfg.embedding_model = toModel;
+ fileCfg.embedding_dimensions = toDims;
+ saveConfig(fileCfg);
+ // Reconfigure the in-process gateway from the MERGED view (env still wins
+ // at runtime; when env is set it matches the target — the ≠ case was
+ // refused before apply).
+ const merged = loadConfig();
+ configureGateway(buildGatewayConfig(merged ?? fileCfg));
+}
+
+// ============================================================================
+// Shared orchestrator (round-2 #11): ONE flow consumed by BOTH the CLI
+// command and the `migrate_embeddings` op handler, so hardening (locks,
+// retarget, verified skip, heartbeat, completion bookkeeping) can never
+// exist on one surface and not the other.
+// ============================================================================
+
+export interface MigrationFlowOpts {
+ to: string;
+ dim?: number;
+ ignoreEnvOverride?: boolean;
+ forceSunsetTarget?: boolean;
+ retarget?: boolean;
+ /** auto (default) | off | keep | <provider:model> — see resolveRerankerPlan. */
+ reranker?: string;
+ noEmbed?: boolean;
+ batchSize?: number;
+ pace?: ReturnType<typeof parsePaceArgs>;
+ quiet?: boolean;
+ onProgress?: (done: number, total: number, embedded: number) => void;
+}
+
+/** Outcome of the reranker companion step, reported never silent. */
+export interface RerankerOutcome {
+ action: 'switched' | 'disabled' | 'switch_failed' | 'suggested' | 'none';
+ to?: string;
+ reason?: string;
+ suggestion?: string | null;
+}
+
+export interface MigrationPlanContext {
+ plan: EmbeddingMigrationPlan;
+ verify: MigrationVerify;
+ envPresence: ReturnType<typeof detectEnvPresence>;
+ /** env is set AND exactly pins the target (the notice-and-proceed case). */
+ envMatchesTarget: boolean;
+ /** A live marker for a DIFFERENT target (the --retarget decision), if any. */
+ inflightOther: MigrationState | null;
+ /** The reranker companion decision (D8). */
+ rerankerPlan: RerankerPlan;
+ /** Which brain/DB this run is actually pointed at (wrong-brain visibility). */
+ identity: { engine: string; target: string };
+ /** Quiesce-lite: live embed writers that are NOT under the migration locks. */
+ concurrentWriters: { workers: number; embedJobs: number };
+ /** Non-default search_embedding_column, if configured (read-path caveat). */
+ customSearchColumn: string | null;
+}
+
+export type MigrationFlowResult =
+ | { status: 'locked'; holder: 'migration' | 'embed_backfill'; detail: string }
+ | { status: 'refused_retarget'; inflight: MigrationState }
+ | { status: 'refused_env'; warning: EnvOverrideWarning }
+ | { status: 'probe_failed'; message: string }
+ | { status: 'apply_failed'; reason: string }
+ | {
+ status: 'applied_no_embed';
+ invalidated: number; cache_cleared: number;
+ schema_transitioned: boolean; pinned_repaired: string[];
+ reranker: RerankerOutcome;
+ }
+ | {
+ status: 'completed';
+ embedded: number; remaining: 0; signatures_reconciled: number;
+ invalidated: number; cache_cleared: number;
+ schema_transitioned: boolean; pinned_repaired: string[];
+ reranker: RerankerOutcome;
+ verify_search: VerifySearchOutcome;
+ }
+ | {
+ status: 'incomplete';
+ embedded: number; remaining: number; signatures_reconciled: number;
+ invalidated: number; cache_cleared: number;
+ schema_transitioned: boolean; pinned_repaired: string[];
+ reranker: RerankerOutcome;
+ lock_skipped?: boolean; lock_lost?: boolean;
+ };
+
+/**
+ * Read-only planning context: the plan, the DB-reality convergence verdict,
+ * env/config-plane resolution, brain identity, and the concurrent-writer
+ * census. Never mutates anything.
+ */
+export async function planMigrationFlow(
+ engine: BrainEngine,
+ opts: Pick<MigrationFlowOpts, 'to' | 'dim' | 'forceSunsetTarget' | 'reranker'>,
+): Promise<MigrationPlanContext> {
+ // From-state as the gateway resolved it (file/env config + defaults) —
+ // display only; nothing load-bearing trusts it (D2).
+ let fromModel: string | undefined;
+ let fromDims: number | undefined;
+ try {
+ const { getEmbeddingModel, getEmbeddingDimensions } = await import('../core/ai/gateway.ts');
+ fromModel = getEmbeddingModel();
+ fromDims = getEmbeddingDimensions();
+ } catch { /* gateway unconfigured — plan falls back to shipped defaults */ }
+
+ const plan = await planEmbeddingMigration(engine, {
+ to: opts.to,
+ ...(opts.dim !== undefined && { dim: opts.dim }),
+ ...(fromModel !== undefined && { fromModel }),
+ ...(fromDims !== undefined && { fromDims }),
+ ...(opts.forceSunsetTarget && { allowSunsetTarget: true }),
+ });
+
+ const envPresence = detectEnvPresence();
+ // FULL pinning (model var required): feeds the env-canonical verify
+ // conjunct and the notice copy — a dims-only env var neither pins the
+ // target nor may fake convergence on a no-file-plane brain.
+ const envMatchesTarget = envFullyPinsTarget(plan.to_model, plan.to_dims);
+
+ // File plane read WITHOUT env merge — verify must not be poisonable.
+ let filePlane: { model?: string | null; dims?: number | null } | null = null;
+ try {
+ const { loadConfigFileOnly } = await import('../core/config.ts');
+ const fileCfg = loadConfigFileOnly();
+ filePlane = fileCfg
+ ? { model: fileCfg.embedding_model ?? null, dims: fileCfg.embedding_dimensions ?? null }
+ : null;
+ } catch { /* unreadable file plane = absent */ }
+
+ const verify = await verifyMigrationComplete(engine, {
+ toModel: plan.to_model,
+ toDims: plan.to_dims,
+ }, { filePlane, envMatchesTarget, envPresent: envPresence.present });
+
+ // Live marker for a DIFFERENT target: the caller's --retarget decision.
+ const marker = await readMigrationState(engine);
+ const inflightOther = marker.state
+ && (marker.state.to_model !== plan.to_model || marker.state.to_dims !== plan.to_dims)
+ ? marker.state
+ : null;
+
+ // Reranker companion decision (D8) — throws a paste-ready message on an
+ // invalid explicit --reranker value BEFORE anything destructive can run.
+ const rerankerPlan = await resolveRerankerPlan(engine, plan.from_model, plan.to_model, opts.reranker);
+
+ // Brain/DB identity (round-1 C1): make wrong-brain routing visible in every
+ // transcript. Redacted — never print a raw connection string.
+ let identity = { engine: 'unknown', target: 'unknown' };
+ try {
+ const { loadConfig } = await import('../core/config.ts');
+ const cfg = loadConfig();
+ if (cfg?.database_url) identity = { engine: 'postgres', target: redactPgUrl(cfg.database_url) };
+ else if (cfg?.database_path) identity = { engine: 'pglite', target: cfg.database_path };
+ else identity = { engine: cfg?.engine ?? 'pglite', target: 'default path' };
+ } catch { /* identity is informational */ }
+
+ // Quiesce-lite census (round-1 C2 / round-2 #3): embed writers outside the
+ // migration locks. Report, don't block — the completion census is the
+ // correctness backstop; this is the operator's "stop the worker first" cue.
+ let concurrentWriters = { workers: 0, embedJobs: 0 };
+ try {
+ const { readWorkers } = await import('../core/minions/worker-registry.ts');
+ const workers = readWorkers().length;
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM minion_jobs
+ WHERE status IN ('waiting', 'running')
+ AND name IN ('embed', 'embed-catch-up', 'embed-backfill')`,
+ );
+ concurrentWriters = { workers, embedJobs: Number(rows[0]?.n ?? 0) };
+ } catch { /* census is informational */ }
+
+ // Custom read column (v2-deferred write side): the migration rebuilds the
+ // default `embedding` column; a brain reading from another column needs to
+ // know its read path is NOT what this run re-embeds.
+ let customSearchColumn: string | null = null;
+ try {
+ const col = await engine.getConfig('search_embedding_column');
+ if (col && col !== 'embedding') customSearchColumn = col;
+ } catch { /* informational */ }
+
+ return { plan, verify, envPresence, envMatchesTarget, inflightOther, rerankerPlan, identity, concurrentWriters, customSearchColumn };
+}
+
+/**
+ * The consented, destructive half. Callers run planMigrationFlow first, get
+ * user consent (CLI confirm / op yes:true), then call this. Lock ordering:
+ * global migration lock → all-source embed locks (sorted, archived included)
+ * → probe → apply → drain (heldLocks + heartbeat) → reconcile → complete.
+ */
+export async function executeMigrationFlow(
+ engine: BrainEngine,
+ ctx: MigrationPlanContext,
+ opts: MigrationFlowOpts,
+): Promise<MigrationFlowResult> {
+ const { plan } = ctx;
+
+ // Global migration lock FIRST (round-2 #4): two migrations must serialize
+ // even on empty brains (zero source locks) and across retarget decisions.
+ let globalLock: DbLockHandle | null = null;
+ try {
+ globalLock = await tryAcquireDbLock(engine, GLOBAL_MIGRATION_LOCK_ID, EMBED_BACKFILL_LOCK_TTL_MIN);
+ } catch {
+ globalLock = null; // lock subsystem down — treated as held (fail closed for a destructive op)
+ }
+ if (!globalLock) {
+ return {
+ status: 'locked',
+ holder: 'migration',
+ detail: 'another embedding migration holds the brain-wide migration lock (or the lock subsystem is unavailable)',
+ };
+ }
+
+ const heldLocks: DbLockHandle[] = [globalLock];
+ try {
+ // Retarget gate UNDER the global lock (no read-then-write race).
+ const marker = await readMigrationState(engine);
+ if (
+ marker.state
+ && (marker.state.to_model !== plan.to_model || marker.state.to_dims !== plan.to_dims)
+ && !opts.retarget
+ ) {
+ return { status: 'refused_retarget', inflight: marker.state };
+ }
+
+ // All-source embed locks, sorted, ARCHIVED INCLUDED (round-2 #4: the
+ // drain walks archived sources' chunks too — lock set must match).
+ let sourceIds: string[] = [];
+ try {
+ const rows = await engine.listAllSources({ includeArchived: true });
+ sourceIds = rows.map((r) => r.id).sort();
+ } catch { /* zero sources (empty brain) — global lock alone covers it */ }
+ for (const sid of sourceIds) {
+ let lock: DbLockHandle | null = null;
+ try {
+ lock = await tryAcquireDbLock(engine, embedBackfillLockId(sid), EMBED_BACKFILL_LOCK_TTL_MIN);
+ } catch {
+ lock = null;
+ }
+ if (!lock) {
+ return {
+ status: 'locked',
+ holder: 'embed_backfill',
+ detail: `an embed backfill holds the lock for source "${sid}" (check \`gbrain jobs list\`; a hard-killed run's lock expires within ${EMBED_BACKFILL_LOCK_TTL_MIN} minutes)`,
+ };
+ }
+ heldLocks.push(lock);
+ }
+
+ // Live probe BEFORE any mutation.
+ const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
+ if (!probe.ok) return { status: 'probe_failed', message: probe.message };
+
+ const applied = await applyEmbeddingMigration(engine, plan, {
+ ignoreEnvOverride: opts.ignoreEnvOverride,
+ forceSunsetTarget: opts.forceSunsetTarget,
+ persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
+ });
+ if (applied.status === 'refused') return { status: 'refused_env', warning: applied.warning };
+ if (applied.status === 'failed') return { status: 'apply_failed', reason: applied.reason };
+
+ // Reranker companion step (D8/C11): probe live, then config write +
+ // cache purge in one transaction. Probe failure keeps the old config and
+ // is reported — never fails the whole migration, never silent.
+ let reranker: RerankerOutcome = { action: 'none' };
+ const rrAction = ctx.rerankerPlan.action;
+ if (rrAction.kind === 'switch') {
+ const rrProbe = await probeTargetReranker(rrAction.to);
+ if (rrProbe.ok) {
+ await applyRerankerAction(engine, rrAction);
+ reranker = { action: 'switched', to: rrAction.to };
+ } else {
+ reranker = { action: 'switch_failed', to: rrAction.to, reason: rrProbe.message };
+ }
+ } else if (rrAction.kind === 'disable') {
+ await applyRerankerAction(engine, rrAction);
+ reranker = { action: 'disabled' };
+ } else if (rrAction.suggestion !== null) {
+ // auto found exposure but the target ships no reranker: never silently
+ // enable a third provider's paid service — surface the exact command.
+ reranker = { action: 'suggested', suggestion: rrAction.suggestion };
+ }
+
+ if (opts.noEmbed) {
+ return {
+ status: 'applied_no_embed',
+ invalidated: applied.invalidated,
+ cache_cleared: applied.cache_cleared,
+ schema_transitioned: applied.schema_transitioned,
+ pinned_repaired: applied.pinned_repaired,
+ reranker,
+ };
+ }
+
+ // Re-embed drain. heldLocks: the drain must not re-acquire (and fail
+ // against) our own locks; it heartbeats them instead (lock-loss aborts).
+ const embedResult: EmbedResult = await runEmbedCore(engine, {
+ stale: true,
+ catchUp: true,
+ singleFlight: true,
+ includeNullSignature: true,
+ quiet: opts.quiet,
+ heldLocks,
+ ...(opts.batchSize !== undefined && { batchSize: opts.batchSize }),
+ ...(opts.pace && { pace: opts.pace }),
+ ...(opts.onProgress && { onProgress: opts.onProgress }),
+ });
+
+ const reconciled = await reconcilePageSignatures(engine, plan);
+ const remaining = await engine.countStaleChunks({
+ signature: migrationSignature(plan.to_model, plan.to_dims),
+ includeNullSignature: true,
+ });
+
+ const base = {
+ embedded: embedResult.embedded,
+ signatures_reconciled: reconciled,
+ invalidated: applied.invalidated,
+ cache_cleared: applied.cache_cleared,
+ schema_transitioned: applied.schema_transitioned,
+ pinned_repaired: applied.pinned_repaired,
+ reranker,
+ };
+ if (remaining === 0 && !embedResult.lock_lost) {
+ // Completion smoke check (D11): warn-don't-block self-retrieval. The
+ // outcome is stamped into the completion marker (content-free) so
+ // `--status` can READ it later without re-spending on live probes.
+ const verifySearch = await verifySearchRoundTrip(engine, { samples: 3 });
+ await completeEmbeddingMigration(engine, plan, {
+ verify_search: { status: verifySearch.status, samples: verifySearch.samples },
+ ...(reranker.action !== 'none' && { reranker }),
+ ...(plan.synopsis_tier_pages > 0 && { context_tier_downgraded_pages: plan.synopsis_tier_pages }),
+ });
+ return { status: 'completed', remaining: 0, verify_search: verifySearch, ...base };
+ }
+ return {
+ status: 'incomplete',
+ remaining,
+ ...base,
+ ...(embedResult.lock_skipped && { lock_skipped: true }),
+ ...(embedResult.lock_lost && { lock_lost: true }),
+ };
+ } finally {
+ for (const h of heldLocks.reverse()) {
+ try { await h.release(); } catch { /* best-effort; TTL is the backstop */ }
+ }
+ }
}
export interface RunMigrateEmbeddingsOpts {
@@ -233,54 +791,140 @@ export async function runMigrateEmbeddings(
exit(0);
}
const flags = parseMigrateEmbeddingsFlags(args);
+
+ // ── Read-only status surface (D6). No env refusal (it REPORTS env), no
+ // mutation, no spend — the mid-incident "where am I?" command.
+ if (args.includes('--status')) {
+ const report = await readMigrationStatus(engine);
+ const envPresence = detectEnvPresence();
+ // API-key PRESENCE only — never values (Section 3).
+ const keyPresence: Record<string, boolean> = {};
+ for (const k of ['VOYAGE_API_KEY', 'OPENAI_API_KEY', 'ZEROENTROPY_API_KEY', 'OPENROUTER_API_KEY']) {
+ keyPresence[k] = Boolean(process.env[k]);
+ }
+ let filePlane: { model?: string | null; dims?: number | null } | null = null;
+ let identity = { engine: 'unknown', target: 'unknown' };
+ try {
+ const { loadConfigFileOnly, loadConfig } = await import('../core/config.ts');
+ const fileCfg = loadConfigFileOnly();
+ filePlane = fileCfg
+ ? { model: fileCfg.embedding_model ?? null, dims: fileCfg.embedding_dimensions ?? null }
+ : null;
+ const cfg = loadConfig();
+ if (cfg?.database_url) identity = { engine: 'postgres', target: redactPgUrl(cfg.database_url) };
+ else if (cfg?.database_path) identity = { engine: 'pglite', target: cfg.database_path };
+ else identity = { engine: cfg?.engine ?? 'pglite', target: 'default path' };
+ } catch { /* informational */ }
+
+ const resumeCmd = report.marker.kind === 'live'
+ ? renderResumeCommand(report.marker.state)
+ : null;
+
+ if (flags.json) {
+ console.log(JSON.stringify({
+ status: 'status',
+ identity,
+ env: { present: envPresence.present, model: envPresence.model, dims: envPresence.dims },
+ keys: keyPresence,
+ file_plane: filePlane,
+ ...report,
+ resume_command: resumeCmd,
+ }, null, 2));
+ exit(0);
+ }
+
+ console.log('Embedding migration status');
+ console.log(` Brain: ${identity.engine} (${identity.target}); scope: brain-wide (all sources)`);
+ console.log(` Env plane: GBRAIN_EMBEDDING_MODEL=${envPresence.model ?? '(unset)'} GBRAIN_EMBEDDING_DIMENSIONS=${envPresence.dims ?? '(unset)'}`);
+ console.log(` Keys: ${Object.entries(keyPresence).map(([k, v]) => `${k}=${v ? 'set' : 'unset'}`).join(' ')}`);
+ console.log(` File plane: ${filePlane ? `${filePlane.model ?? '(none)'} @ ${filePlane.dims ?? '?'}d` : '(no ~/.gbrain/config.json)'}`);
+ console.log(` DB plane: ${report.db_plane.model ?? '(none)'} @ ${report.db_plane.dims ?? '?'}d`);
+ console.log(` Column: content_chunks.embedding ${report.column_dims === null ? 'absent/unreadable' : `${report.column_dims}d`}${report.pinned_widths.map((p) => `; ${p.table} ${p.dims === null ? '?' : `${p.dims}d`}`).join('')}`);
+ console.log(` Vectors: ${report.missing_embeddings ?? '?'} chunk(s) missing; ${report.chunkless_pages ?? '?'} contentful page(s) without chunks; facts pending: ${report.facts_pending ?? 'n/a'}`);
+ if (report.signature_census.length > 0) {
+ console.log(` Signatures: ${report.signature_census.map((c) => `${c.signature ?? '(none recorded)'}: ${c.pages}`).join(', ')}`);
+ }
+ if (report.synopsis_tier_pages !== null && report.synopsis_tier_pages > 0) {
+ console.log(` Context tier: ${report.synopsis_tier_pages} page(s) at per_chunk_synopsis (a migration re-embeds them at title tier)`);
+ }
+ if (report.stale_vs_target.target) {
+ console.log(` Target: ${report.stale_vs_target.target} — ${report.stale_vs_target.stale ?? '?'} chunk(s) not yet in that space`);
+ }
+ switch (report.marker.kind) {
+ case 'live': {
+ const s = report.marker.state;
+ console.log(` Migration: IN FLIGHT to ${s.to_model} (${s.to_dims}d), started ${s.started_at}${s.retargeted_at ? `, retargeted ${s.retargeted_at}` : ''}`);
+ if (s.superseded && s.superseded.length > 0) {
+ console.log(` abandoned targets: ${s.superseded.map((x) => `${x.to_model} (${x.to_dims}d, started ${x.started_at})`).join('; ')}`);
+ }
+ console.log(` Resume: ${resumeCmd}`);
+ break;
+ }
+ case 'corrupt':
+ console.log(` Migration: state marker is CORRUPT (raw: ${report.marker.raw_prefix}) — re-running a migration rewrites it`);
+ break;
+ default:
+ console.log(' Migration: none in flight');
+ }
+ if (report.completed) {
+ const c = report.completed;
+ console.log(` Last completed: to ${String(c.to_model)} (${String(c.to_dims)}d) at ${String(c.completed_at)}${c.verify_search ? `; smoke check: ${String((c.verify_search as { status?: unknown }).status)}` : ''}`);
+ }
+ exit(0);
+ }
+
if (!flags.to) {
serr('Missing --to <provider:model>. Example: gbrain migrate embeddings --to openai:text-embedding-3-small');
serr('Run with --help for all flags.');
exit(1);
}
- // From-state as the gateway resolved it (file/env config + defaults) —
- // the truth for what embeds run under TODAY.
- let fromModel: string | undefined;
- let fromDims: number | undefined;
- try {
- const { getEmbeddingModel, getEmbeddingDimensions } = await import('../core/ai/gateway.ts');
- fromModel = getEmbeddingModel();
- fromDims = getEmbeddingDimensions();
- } catch {
- // Gateway unconfigured — plan falls back to shipped defaults.
- }
-
- let plan: EmbeddingMigrationPlan;
+ let ctx: MigrationPlanContext;
try {
- plan = await planEmbeddingMigration(engine, {
+ ctx = await planMigrationFlow(engine, {
to: flags.to!,
...(flags.dim !== undefined && { dim: flags.dim }),
- ...(fromModel !== undefined && { fromModel }),
- ...(fromDims !== undefined && { fromDims }),
- ...(flags.forceSunsetTarget && { allowSunsetTarget: true }),
+ ...(flags.forceSunsetTarget && { forceSunsetTarget: true }),
+ ...(flags.reranker !== undefined && { reranker: flags.reranker }),
});
} catch (e) {
serr(e instanceof Error ? e.message : String(e));
exit(1);
return; // unreachable; keeps TS happy for injected exit seams
}
+ const plan = ctx.plan;
if (flags.json) {
// Human plan goes to stderr so stdout stays JSON-clean.
- serr(renderPlan(plan));
+ serr(renderPlan(ctx));
} else {
- console.log(renderPlan(plan));
+ console.log(renderPlan(ctx));
}
- if (plan.chunks_to_embed === 0 && !plan.dim_change && plan.from_model === plan.to_model) {
- if (flags.json) console.log(JSON.stringify({ status: 'skipped_no_work', plan }, null, 2));
- else console.log('Nothing to migrate — brain is already on the target model.');
+ // Different-target in-flight marker: the --retarget decision comes BEFORE
+ // any skip — a converged brain with a live foreign marker still needs the
+ // user to resume it or explicitly abandon it.
+ if (ctx.inflightOther && !flags.retarget && !flags.dryRun) {
+ const s = ctx.inflightOther;
+ if (flags.json) console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: s, plan }, null, 2));
+ printRetargetRefusal(s);
+ exit(1);
+ }
+
+ // DB-reality skip (D2): "nothing to migrate" ONLY when every convergence
+ // conjunct verifies against the database + the un-merged file plane, no
+ // foreign marker is pending a retarget decision, AND no reranker companion
+ // action is pending (a resolved switch/disable executes as a config-only
+ // completion even on a converged brain — round-2 #6). The old
+ // three-conjunct skip trusted `from_model`, which env vars poison.
+ if (ctx.verify.complete && !ctx.inflightOther && ctx.rerankerPlan.action.kind === 'none') {
+ if (flags.json) console.log(JSON.stringify({ status: 'skipped_no_work', plan, verified: ctx.verify }, null, 2));
+ else console.log('Nothing to migrate — brain is verified on the target model (schema, vectors, signatures, config).');
exit(0);
}
if (flags.dryRun) {
- if (flags.json) console.log(JSON.stringify({ status: 'planned', plan }, null, 2));
+ if (flags.json) console.log(JSON.stringify({ status: 'planned', plan, verified: ctx.verify }, null, 2));
exit(0);
}
@@ -311,52 +955,20 @@ export async function runMigrateEmbeddings(
}
}
- // ── Live probe BEFORE any mutation: one tiny embed against the TARGET
- // provider validates API key, model id, and dimension support in one call.
- const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
- if (!probe.ok) {
- serr(probe.message);
- exit(1);
- }
-
- // ── Apply: schema + config + invalidation + cache purge.
- const applied = await applyEmbeddingMigration(engine, plan, {
- ignoreEnvOverride: flags.ignoreEnvOverride,
- persistConfig: (toModel, toDims) => persistEmbeddingFileConfig(toModel, toDims),
- });
-
- if (applied.status === 'refused') {
- if (flags.json) console.log(JSON.stringify(applied, null, 2));
- else serr(formatEnvOverrideWarning(applied.warning));
- exit(1);
- }
- if (applied.status === 'failed') {
- if (flags.json) console.log(JSON.stringify(applied, null, 2));
- else serr(`Migration apply failed: ${applied.reason}`);
- exit(1);
- }
-
- serr(` [migrate] schema ${applied.schema_transitioned ? `rebuilt at ${plan.to_dims}d` : 'unchanged'}; ` +
- `${applied.invalidated} chunk(s) invalidated; query cache purged (${applied.cache_cleared} row(s)).`);
-
- if (flags.noEmbed) {
- const msg = 'Config + schema migrated. Re-embed deferred — run: gbrain embed --stale --catch-up --include-null-signature';
- if (flags.json) console.log(JSON.stringify({ ...applied, status: 'applied_no_embed', plan }, null, 2));
- else console.log(msg);
- exit(0);
- }
-
- // ── Re-embed. All the machinery (locks, pacing, backoff, progress,
- // signature stamping) is the standard embed pipeline.
+ // ── Execute: locks → probe → apply → drain → reconcile → complete, all in
+ // the shared orchestrator (identical semantics on the op path).
const { createProgress } = await import('../core/progress.ts');
const { getCliOptions, cliOptsToProgressOptions } = await import('../core/cli-options.ts');
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
let progressStarted = false;
- const embedResult = await runEmbedCore(engine, {
- stale: true,
- catchUp: true,
- singleFlight: true,
- includeNullSignature: true,
+ const result = await executeMigrationFlow(engine, ctx, {
+ to: flags.to!,
+ ...(flags.dim !== undefined && { dim: flags.dim }),
+ ignoreEnvOverride: flags.ignoreEnvOverride,
+ forceSunsetTarget: flags.forceSunsetTarget,
+ retarget: flags.retarget,
+ ...(flags.reranker !== undefined && { reranker: flags.reranker }),
+ noEmbed: flags.noEmbed,
quiet: flags.json,
...(flags.batchSize !== undefined && { batchSize: flags.batchSize }),
...(flags.pace && { pace: flags.pace }),
@@ -370,50 +982,106 @@ export async function runMigrateEmbeddings(
});
if (progressStarted) progress.finish();
- // Reconcile signatures BEFORE the completion probe: pages straddling a
- // stale-batch boundary are embedded correctly but left unstamped by the
- // embed loop's all-or-nothing stamp rule. Without this the probe would call
- // a fully-migrated brain "incomplete" and the re-run would pay again.
- const reconciled = await reconcilePageSignatures(engine, plan);
- if (reconciled > 0) {
- serr(` [migrate] reconciled the embedding signature on ${reconciled} fully-embedded page(s) (batch-boundary pages).`);
+ // Refusals normalize to the op-envelope shape ({status:'refused', reason})
+ // in their own cases below; everything else gets the generic envelope.
+ if (flags.json && result.status !== 'refused_env' && result.status !== 'refused_retarget') {
+ console.log(JSON.stringify({ ...result, plan }, null, 2));
}
- const remaining = await engine.countStaleChunks({
- signature: `${plan.to_model}:${plan.to_dims}`,
- includeNullSignature: true,
- });
-
- if (remaining === 0) {
- await completeEmbeddingMigration(engine, plan);
- if (flags.json) {
- console.log(JSON.stringify({ status: 'completed', plan, embedded: embedResult.embedded, remaining: 0 }, null, 2));
- } else {
- slog(`Migration complete: ${embedResult.embedded} chunk(s) embedded on ${plan.to_model} (${plan.to_dims}d).`);
- if (plan.reranker_warning) serr(` [migrate] reminder: ${plan.reranker_warning}`);
+ switch (result.status) {
+ case 'locked': {
+ if (result.holder === 'migration') {
+ serr(`Migration refused: ${result.detail}.`);
+ serr(`If a previous migration was killed hard, its lock expires within ${EMBED_BACKFILL_LOCK_TTL_MIN} minutes — re-run then.`);
+ } else {
+ serr(`Migration paused before any change: ${result.detail}.`);
+ serr('Let the backfill finish (or stop the worker), then re-run the same command.');
+ }
+ exit(1);
+ break;
}
- exit(0);
- } else {
- if (flags.json) {
- console.log(JSON.stringify({
- status: 'incomplete', plan, embedded: embedResult.embedded, remaining,
- ...(embedResult.lock_skipped && { lock_skipped: true }),
- }, null, 2));
- } else if (embedResult.lock_skipped) {
- // E2E-observed failure mode: a hard-killed (SIGKILL/crash) migration
- // leaves its single-flight embed lock behind, and every immediate
- // re-run "resumes" without embedding anything. Say so — "re-run to
- // resume" would be a lie until the lock expires.
- const { EMBED_BACKFILL_LOCK_TTL_MIN } = await import('../core/embed-backfill-lock.ts');
- serr(`Migration paused: ${remaining} chunk(s) still stale, and the re-embed was SKIPPED because`);
- serr('another embed backfill holds the per-source lock. If that is a live run (check');
- serr('`gbrain jobs list`), let it finish. If a previous migration was killed hard, its lock');
- serr(`expires after at most ${EMBED_BACKFILL_LOCK_TTL_MIN} minutes — re-run the same command then.`);
- } else {
- serr(`Migration incomplete: ${remaining} chunk(s) still stale (embed failures or an interrupted run).`);
- serr('Re-run the same command to resume — completed chunks are never re-embedded.');
+ case 'refused_retarget': {
+ if (flags.json) {
+ console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: result.inflight, plan }, null, 2));
+ } else {
+ printRetargetRefusal(result.inflight);
+ }
+ exit(1);
+ break;
+ }
+ case 'refused_env': {
+ if (flags.json) {
+ console.log(JSON.stringify({ status: 'refused', reason: 'env_override', warning: result.warning, plan }, null, 2));
+ } else {
+ serr(formatEnvOverrideWarning(result.warning));
+ }
+ exit(1);
+ break;
+ }
+ case 'probe_failed': {
+ serr(result.message);
+ exit(1);
+ break;
+ }
+ case 'apply_failed': {
+ serr(`Migration apply failed: ${result.reason}`);
+ exit(1);
+ break;
+ }
+ case 'applied_no_embed': {
+ serr(renderApplySummary(result, plan));
+ for (const line of renderRerankerOutcome(result.reranker)) serr(line);
+ if (!flags.json) console.log('Config + schema migrated. Re-embed deferred — run: gbrain embed --stale --catch-up --include-null-signature');
+ exit(0);
+ break;
+ }
+ case 'completed': {
+ serr(renderApplySummary(result, plan));
+ if (result.signatures_reconciled > 0) {
+ serr(` [migrate] reconciled the embedding signature on ${result.signatures_reconciled} fully-embedded page(s) (batch-boundary pages).`);
+ }
+ for (const line of renderRerankerOutcome(result.reranker)) serr(line);
+ // Honestly labeled: a smoke check (self-retrieval), not a recall eval —
+ // BrainBench owns retrieval quality.
+ if (result.verify_search.status === 'pass') {
+ serr(` [migrate] smoke check (self-retrieval, not a recall eval): pass (${result.verify_search.samples.length} sample(s)).`);
+ } else if (result.verify_search.status === 'warn') {
+ const bad = result.verify_search.samples.filter((s) => s.status !== 'hit');
+ serr(` [migrate] smoke check: WARN (${result.verify_search.reason_code ?? 'miss'}) — ${bad.map((s) => `page ${s.page_id}: ${s.status}${s.reason_code ? ` (${s.reason_code})` : ''}`).join('; ') || 'no samples'}.`);
+ serr(' Search still completed the migration; investigate with `gbrain search` / doctor if quality looks off.');
+ } else {
+ serr(` [migrate] smoke check: skipped (${result.verify_search.reason_code ?? 'n/a'}).`);
+ }
+ if (plan.synopsis_tier_pages > 0) {
+ serr(` [migrate] context tier: ${plan.synopsis_tier_pages} page(s) re-embedded at the title tier (was per_chunk_synopsis).`);
+ }
+ if (!flags.json) {
+ slog(`Migration complete: ${result.embedded} chunk(s) embedded on ${plan.to_model} (${plan.to_dims}d).`);
+ }
+ exit(0);
+ break;
+ }
+ case 'incomplete': {
+ for (const line of renderRerankerOutcome(result.reranker)) serr(line);
+ if (result.lock_lost) {
+ serr(`Migration aborted: the single-flight lock was lost mid-drain (stolen or the heartbeat kept failing).`);
+ serr(`${result.remaining} chunk(s) still stale; partial progress is banked. Re-run the same command once the other holder finishes.`);
+ } else if (result.lock_skipped) {
+ // E2E-observed failure mode: a hard-killed (SIGKILL/crash) migration
+ // leaves its single-flight embed lock behind, and every immediate
+ // re-run "resumes" without embedding anything. Say so — "re-run to
+ // resume" would be a lie until the lock expires.
+ serr(`Migration paused: ${result.remaining} chunk(s) still stale, and the re-embed was SKIPPED because`);
+ serr('another embed backfill holds the per-source lock. If that is a live run (check');
+ serr('`gbrain jobs list`), let it finish. If a previous migration was killed hard, its lock');
+ serr(`expires after at most ${EMBED_BACKFILL_LOCK_TTL_MIN} minutes — re-run the same command then.`);
+ } else {
+ serr(`Migration incomplete: ${result.remaining} chunk(s) still stale (embed failures or an interrupted run).`);
+ serr('Re-run the same command to resume — completed chunks are never re-embedded.');
+ }
+ exit(1);
+ break;
}
- exit(1);
}
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 06227d8f33..7ae63ee6ac 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -496,8 +496,9 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
try {
const { readContentChunksEmbeddingDim } = await import('../core/embedding-dim-check.ts');
colDims = (await readContentChunksEmbeddingDim(engine)).dims;
- } catch { /* fresh brain — omit --dim */ }
- const dimFlag = colDims ? ` --dim ${colDims}` : '';
+ } catch { /* fresh brain — canonical command carries its own --dim */ }
+ const { renderCanonicalMigrationCommands } = await import('../core/ai/defaults.ts');
+ const cmds = renderCanonicalMigrationCommands({ colDims });
console.log('');
console.log('═══════════════════════════════════════════════════════════════');
console.log(`[gbrain] ACTION REQUIRED: ZeroEntropy hosted API sunsets ${ZEROENTROPY_SUNSET_DATE}.`);
@@ -522,11 +523,11 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
console.log(' vector; NO re-embed. See docs/guides/embedding-migration.md.');
console.log('');
console.log('[2] Migrate to another provider (resumable; preview cost first):');
- console.log(` gbrain migrate embeddings --to <provider:model>${dimFlag} --dry-run`);
- console.log(` gbrain migrate embeddings --to <provider:model>${dimFlag}`);
- if (colDims) {
- console.log(` (--dim ${colDims} is this brain's current index width — keep it to`);
- console.log(' avoid a needless schema rebuild when the target supports it.)');
+ console.log(` ${cmds.recommendedDryRun}`);
+ console.log(` ${cmds.recommended}`);
+ if (cmds.note) console.log(` ${cmds.note}`);
+ if (cmds.openaiAlternative) {
+ console.log(` Keep-width alternative: ${cmds.openaiAlternative}`);
}
if (onZeReranker) {
console.log('');
diff --git a/src/commands/ze-switch.ts b/src/commands/ze-switch.ts
index a201a1f40a..9bcb9033cb 100644
--- a/src/commands/ze-switch.ts
+++ b/src/commands/ze-switch.ts
@@ -117,13 +117,12 @@ export async function runZeSwitch(args: string[], engine: BrainEngine): Promise<
if (!flags.undo && !flags.dryRun) {
const {
ZEROENTROPY_SUNSET_DATE,
- NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
- NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
+ 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: gbrain migrate embeddings --to ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} --dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS} --dry-run\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 }));
diff --git a/src/core/advisor/collect-setup-smells.ts b/src/core/advisor/collect-setup-smells.ts
index 5100f5fb96..15c6e7a89d 100644
--- a/src/core/advisor/collect-setup-smells.ts
+++ b/src/core/advisor/collect-setup-smells.ts
@@ -59,10 +59,15 @@ export const collectSetupSmells: AdvisorCollector = {
};
const keyMissing = !!keyName && !process.env[keyName] && !fileKeys[keyName];
if (keyMissing) {
+ const { NEW_INSTALL_DEFAULT_EMBEDDING_MODEL, renderCanonicalMigrationCommands } =
+ await import('../ai/defaults.ts');
+ const rep = recipe?.sunset?.replacement?.embedding;
+ const migrateCmd = !rep || rep === NEW_INSTALL_DEFAULT_EMBEDDING_MODEL
+ ? renderCanonicalMigrationCommands().recommendedDryRun
+ : `gbrain migrate embeddings --to ${rep} --dry-run`;
const sunsetNote = recipe?.sunset
? ` NOTE: ${recipe.name} shuts down ${recipe.sunset.date} — migrate instead of ` +
- `setting its key: \`gbrain migrate embeddings --to ` +
- `${recipe.sunset.replacement?.embedding ?? 'voyage:voyage-4'} --dry-run\`.`
+ `setting its key: \`${migrateCmd}\`.`
: '';
findings.push({
id: 'embedding_key_missing',
diff --git a/src/core/ai/defaults.ts b/src/core/ai/defaults.ts
index 78a69d5312..2a405df943 100644
--- a/src/core/ai/defaults.ts
+++ b/src/core/ai/defaults.ts
@@ -69,3 +69,45 @@ export const NEW_INSTALL_DEFAULT_RERANKER_MODEL = 'voyage:rerank-2.5';
* doctor check. Self-hosting the Apache-2.0 zembed-1 weights is unaffected.
*/
export const ZEROENTROPY_SUNSET_DATE = '2026-09-04';
+
+/**
+ * ONE canonical rendering of the sunset-migration command for every surface
+ * that tells a user/agent how to leave a dying provider (gateway deprecation
+ * line, init warnings, upgrade banners, doctor provider_sunset, ze-switch
+ * refusal, advisor). Before this, five surfaces printed five different
+ * commands — including one with an unsubstituted placeholder and this
+ * brain's current width as `--dim`, which is INVALID on Voyage (valid
+ * widths: 256/512/1024/2048). Rules:
+ * - the Voyage command ALWAYS carries `--dim 1024` (never the brain's
+ * current width);
+ * - the keep-width OpenAI alternative renders only when the current
+ * column width is known and <= 1536 (text-embedding-3-small's cap);
+ * - the note explains the rebuild whenever the width changes.
+ * Lives here (zero-dep constants module) so every consumer can import it
+ * without cycles; drift-guarded by test against the doc/skill copies.
+ */
+export function renderCanonicalMigrationCommands(opts: { colDims?: number | null } = {}): {
+ /** Live run (agents append --yes themselves after consent). */
+ recommended: string;
+ /** Cost preview — what every warning surface should print first. */
+ recommendedDryRun: string;
+ /** Keep-width alternative (no schema rebuild), when the width allows it. */
+ openaiAlternative: string | null;
+ /** Rebuild explanation when the recommended target changes the width. */
+ note: string | null;
+} {
+ const base = `gbrain migrate embeddings --to ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} --dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS}`;
+ const colDims = opts.colDims ?? null;
+ const openaiAlternative = colDims !== null && colDims <= 1536
+ ? `gbrain migrate embeddings --to openai:text-embedding-3-small --dim ${colDims} --dry-run`
+ : null;
+ const note = colDims !== null && colDims !== NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS
+ ? `(--dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS} rebuilds the ${colDims}d index — Voyage's valid widths are 256/512/1024/2048${openaiAlternative ? `; the OpenAI alternative keeps this brain's ${colDims}d width` : ''}.)`
+ : null;
+ return {
+ recommended: base,
+ recommendedDryRun: `${base} --dry-run`,
+ openaiAlternative,
+ note,
+ };
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 3fbd0bc543..4dc872ef59 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -107,7 +107,12 @@ const MAX_CHARS = 8000;
// Re-exported from the leaf `defaults.ts` so heavy schema/registry modules
// don't transitively load every provider SDK just to read the defaults.
export { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './defaults.ts';
-import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './defaults.ts';
+import {
+ DEFAULT_EMBEDDING_MODEL,
+ DEFAULT_EMBEDDING_DIMENSIONS,
+ NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
+ renderCanonicalMigrationCommands,
+} from './defaults.ts';
const DEFAULT_EXPANSION_MODEL = 'anthropic:claude-haiku-4-5-20251001';
const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';
// v0.35.0.0+: reranker default. Used only when search.reranker.enabled is set
@@ -1443,10 +1448,16 @@ function warnSunsetOnce(recipe: Recipe, touchpoint: 'embedding' | 'reranker'): v
_sunsetWarned.add(key);
const replacement =
touchpoint === 'embedding' ? sunset.replacement?.embedding : sunset.replacement?.reranker;
+ // Canonical command (defaults.ts renderer) when the replacement IS the
+ // recommended default — always carries the valid --dim; a bespoke
+ // replacement falls back to the target's own declared width via --dim
+ // omission (the recipe default applies).
const fix =
touchpoint === 'embedding'
? replacement
- ? ` Migrate: \`gbrain migrate embeddings --to ${replacement} --dry-run\``
+ ? replacement === NEW_INSTALL_DEFAULT_EMBEDDING_MODEL
+ ? ` Migrate: \`${renderCanonicalMigrationCommands().recommendedDryRun}\``
+ : ` Migrate: \`gbrain migrate embeddings --to ${replacement} --dry-run\``
: ''
: replacement
? ` Switch: \`gbrain config set search.reranker.model ${replacement}\``
diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.ts
index bcc65a7576..9f73da603a 100644
--- a/src/core/brain-score-recommendations.ts
+++ b/src/core/brain-score-recommendations.ts
@@ -158,6 +158,14 @@ export interface RecommendationContext {
chatModel?: string;
/** Whether the chat provider has a usable API key. */
hasChatApiKey?: boolean;
+ /**
+ * D12: embedded chunks on pages with NO recorded embedding signature
+ * (unknown provenance — possibly a previous model's space). Probed by the
+ * engine-holding caller (loadRecommendationContext); this module is sync.
+ * When > 0, the embed.stale step widens with includeNullSignature so the
+ * cohort is re-embedded instead of grandfathered forever.
+ */
+ nullSignatureCohort?: number;
}
/** Triage result for one check. */
@@ -223,14 +231,26 @@ export function computeRecommendations(
}
// ---------------------------------------------------------------------
- // embed.stale — missing embeddings. Critical: invisible to vector search
+ // embed.stale — missing embeddings AND/OR the NULL-signature cohort
+ // (unknown-provenance vectors that the grandfather clause would otherwise
+ // keep in a previous model's space forever). Critical: invisible to (or
+ // wrong in) vector search.
// ---------------------------------------------------------------------
- if (health.missing_embeddings > 0 && ctx.embeddingProviderConfigured !== false) {
- const params = { stale: true, sourceId: ctx.sourceId };
+ const nullSigCohort = ctx.nullSignatureCohort ?? 0;
+ if ((health.missing_embeddings > 0 || nullSigCohort > 0) && ctx.embeddingProviderConfigured !== false) {
+ const params = {
+ stale: true,
+ sourceId: ctx.sourceId,
+ // D12: widen only when the cohort exists — the params feed the
+ // idempotency key, so a cohort appearing/clearing is semantically
+ // different work (one-time dedupe miss on transition, accepted).
+ ...(nullSigCohort > 0 && { includeNullSignature: true }),
+ };
const embedModel = ctx.embeddingModel ?? 'openai:text-embedding-3-large';
const embedDims = ctx.embeddingDimensions ?? 3072;
- // Rough char estimate per chunk ~ 1.5k chars (chunker target).
- const estChars = health.missing_embeddings * 1500;
+ // Rough char estimate per chunk ~ 1.5k chars (chunker target). The
+ // cohort is real re-embed spend too — count it (round-2 #12).
+ const estChars = (health.missing_embeddings + nullSigCohort) * 1500;
let est_usd_cost = 0;
try {
const priceLookup = lookupEmbeddingPrice(embedModel);
@@ -240,17 +260,24 @@ export function computeRecommendations(
} catch {
/* unknown model — leave at 0, surface as warning elsewhere */
}
+ const rationaleParts: string[] = [];
+ if (health.missing_embeddings > 0) {
+ rationaleParts.push(`${health.missing_embeddings} chunk${health.missing_embeddings === 1 ? '' : 's'} invisible to vector search`);
+ }
+ if (nullSigCohort > 0) {
+ rationaleParts.push(`${nullSigCohort} chunk${nullSigCohort === 1 ? '' : 's'} with no recorded embedding signature (unknown provenance)`);
+ }
out.push({
id: 'embed.stale',
job: 'embed',
params,
idempotency_key: idemKey(source, 'embed', { ...params, embedModel, embedDims }),
severity: 'critical',
- est_seconds: Math.min(3600, 5 + health.missing_embeddings * 0.05),
+ est_seconds: Math.min(3600, 5 + (health.missing_embeddings + nullSigCohort) * 0.05),
est_usd_cost,
// sync should run first so embed sees fresh pages.
depends_on: ctx.repoPath && health.stale_pages > 0 ? ['sync.repo'] : [],
- rationale: `${health.missing_embeddings} chunk${health.missing_embeddings === 1 ? '' : 's'} invisible to vector search`,
+ rationale: rationaleParts.join('; '),
status: 'remediable',
});
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d70029948e..858e1f763c 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -31,7 +31,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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'],
- 'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--to', '--version', '--yes'],
+ 'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
'claw-test': ['--ab', '--agent', '--all', '--auto', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--output-format', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
'code-callees': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],
'code-callers': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],
@@ -40,15 +40,15 @@ 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', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--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', '--reset', '--resolve', '--restore-only', '--resume', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-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', '--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', '--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'],
'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', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--version'],
- 'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],
+ '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'],
+ 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dim', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],
'export': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--explain', '--federated', '--fix', '--follow', '--help', '--include-null-signature', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type'],
'extract': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--multimodal', '--name-status', '--near-symbol', '--ner', '--no-extract', '--no-federated', '--older-than', '--pack', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--run-id', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type', '--verbose', '--workers', '--yes'],
- 'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--to', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--to', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],
'features': ['--aliases', '--all', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--no-extract', '--pace', '--pace-max-concurrency', '--pack', '--path', '--pattern', '--pending', '--priority', '--progress-json', '--quiet', '--repo', '--reset', '--resolve', '--run-id', '--since', '--slugs', '--source', '--source-id', '--stale', '--supersessions', '--thin', '--type', '--verbose', '--workers'],
'files': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--no-pointer', '--page', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--retry-failed', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--yes'],
'forget': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
@@ -58,43 +58,43 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--aliases', '--all', '--brain', '--depth', '--direction', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--include-null-signature', '--json', '--lang', '--markdown', '--mcp-only', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--type'],
'hook': ['--aliases', '--all', '--allow-unverified-remote', '--auto', '--batch-limit', '--brain', '--budget-ms', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--include-null-signature', '--jq', '--json', '--name-only', '--no-embedding', '--no-extract', '--once', '--others', '--path', '--pattern', '--pending', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--reset', '--resolve', '--show-current', '--show-toplevel', '--source', '--stale', '--stats', '--status', '--supersessions', '--surface', '--thin', '--timeout', '--token', '--token-ttl'],
'import': ['--aliases', '--all', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--code', '--compile', '--concurrency', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--older-than', '--others', '--path', '--pattern', '--pending', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--url', '--workers'],
- 'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version'],
+ 'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],
'integrity': ['--aliases', '--all', '--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--limit', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--url'],
'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--supersessions', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],
'lint': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--aliases', '--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--column', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--help', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--json', '--kind', '--lang', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--near-symbol', '--ner', '--nice', '--no-extract', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resolve', '--restore-only', '--resume', '--run-id', '--safe', '--scope', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--supersessions', '--symbol-kind', '--target', '--target-score', '--thin', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--yes'],
- 'migrate': ['--ab', '--aliases', '--all', '--auto-update', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--build-index', '--by-mention', '--catch-up', '--compile', '--days', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclusive', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--lang', '--locks', '--markdown', '--max-age', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--phase', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--refresh-unqualified', '--remediate', '--reranking', '--reset', '--resolve', '--restore-only', '--resume', '--rollback', '--skip-verify', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
- 'models': ['--aliases', '--all', '--brain', '--ctx-size', '--detail', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--include-null-signature', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--pattern', '--pending', '--reranking', '--reset', '--resolve', '--skip', '--source', '--stale', '--supersessions', '--thin', '--to', '--undo', '--version'],
+ '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'],
'mounts': ['--alias', '--brain', '--cache', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--explain', '--help', '--id', '--json', '--lang', '--lock', '--markdown', '--mcp-url', '--multimodal', '--near-symbol', '--path', '--restore-only', '--skills-dir', '--source', '--stale', '--symbol-kind', '--thin', '--verbose'],
- 'notability-eval': ['--aliases', '--all', '--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--include-null-signature', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--out', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--skip-llm', '--source', '--stale', '--supersessions', '--target-high', '--target-low', '--target-medium', '--thin', '--to', '--version'],
+ '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'],
'orphans': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--count', '--explain', '--follow', '--help', '--include-null-signature', '--include-pseudo', '--json', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout'],
'pages': ['--aliases', '--all', '--brain', '--dry-run', '--help', '--include-null-signature', '--json', '--no-extract', '--older-than', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin'],
'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'],
'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--path', '--pglite', '--quiet', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
'protocol': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-embedding', '--offset', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
- 'providers': ['--brain', '--ctx-size', '--embedding-dimensions', '--embedding-model', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--source', '--surface', '--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'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--aliases', '--all', '--apply', '--brain', '--code', '--compile', '--explain', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--no-embed', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl'],
'recall': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
'reconcile-links': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--include-null-signature', '--json', '--name-status', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--strategy', '--supersessions', '--thin', '--timeout', '--type'],
- 'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--code', '--compile', '--concurrency', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--version', '--workers', '--yes'],
- 'reindex-code': ['--abi', '--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--older-than', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--serial', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--version', '--workers', '--yes'],
+ 'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--version', '--workers', '--yes'],
+ 'reindex-code': ['--abi', '--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--older-than', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--serial', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--version', '--workers', '--yes'],
'reindex-frontmatter': ['--aliases', '--all', '--brain', '--concurrency', '--dry-run', '--force', '--help', '--include-null-signature', '--json', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--slug-prefix', '--source', '--stale', '--supersessions', '--thin', '--workers', '--yes'],
'reindex-search-vector': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-null-signature', '--json', '--migrate-only', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--yes'],
- 'remote': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--column', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-pages', '--full', '--help', '--http', '--include-flagged', '--index-audit', '--json', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--multimodal', '--nice', '--no-embedding', '--older-than', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--scope', '--scopes', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--top-k', '--url', '--window', '--workers', '--yes'],
+ 'remote': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-pages', '--full', '--help', '--http', '--include-flagged', '--index-audit', '--json', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--multimodal', '--nice', '--no-embedding', '--older-than', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--scope', '--scopes', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--top-k', '--url', '--window', '--workers', '--yes'],
'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restore-only', '--source', '--stale', '--supabase', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--url'],
'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', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--follow', '--force', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranking', '--reset', '--resolve', '--resume', '--slugs', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--undo', '--version', '--yes'],
+ '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'],
'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'],
- 'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--to', '--version', '--yes'],
+ 'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
'serve': ['--aliases', '--all', '--bind', '--bound-slug-prefixes', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--log-full-params', '--name', '--no-embedding', '--no-extract', '--once', '--parallel', '--pattern', '--pending', '--port', '--prefix', '--print-admin-token', '--public-url', '--reset', '--resolve', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--supersessions', '--suppress', '--suppress-bootstrap-token', '--surface', '--thin', '--token-ttl', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--verbose', '--writes-pages', '--writes-to'],
'skillopt': ['--aliases', '--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--include-null-signature', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--model', '--no-extract', '--no-mutate', '--optimizer-model', '--patch', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--stale', '--supersessions', '--target-model', '--target-models', '--thin', '--verbose', '--yes'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index f7ff8d1210..a99647bda5 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -74,6 +74,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'embed_staleness',
'embedding_column_registry',
'embedding_env_override',
+ 'embedding_migration_state',
'embedding_provider',
'embedding_width_consistency',
'embeddings',
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 4fb5eca291..1873f89ff1 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -6,34 +6,332 @@
* `ze-switch` (ZE-only target) and `ze-switch --undo` (needs a snapshot fresh
* installs don't have) cannot cover.
*
- * Deliberately thin: everything heavy is reused —
- * - runSchemaTransition (retrieval-upgrade-planner.ts) for dimension changes
- * - invalidateStaleSignatureEmbeddings + the NULL-embedding cursor for
- * staleness + resume (the NULL column IS the checkpoint: a killed run
- * re-runs the same command and continues where it stopped)
- * - the embed pipeline (src/commands/embed.ts) for the actual re-embed,
- * with pacing, backfill locks, rate-limit backoff, and progress
- * - lookupEmbeddingPrice / estimateCostFromChars for the preflight estimate
- * - detectEnvOverride (the #1421 damage-class gate) before any mutation
+ * This module is the v0.47 SURVIVOR: the migration primitives live HERE
+ * (runSchemaTransition, transitionDimPinnedColumn, detectEnvOverride and the
+ * env gates, marker read/write, verifyMigrationComplete, readMigrationStatus,
+ * verifySearchRoundTrip, reranker plan/apply, the canonical resume-command
+ * renderer); retrieval-upgrade-planner.ts re-imports them for back-compat and
+ * is deleted in the ZE removal wave.
*
- * #3391 companion fix: the migration widens staleness with
- * `includeNullSignature: true` so pages that predate the v108 signature stamp
- * are re-embedded too, instead of silently staying in the old embedding space.
+ * What it owns:
+ * - schema transition per dim-pinned column (content_chunks / facts /
+ * query_cache repaired independently), HNSW policy via vector-index.ts
+ * - staleness + resume: invalidateStaleSignatureEmbeddings widened with
+ * `includeNullSignature: true` (#3391) + the NULL-embedding cursor (the
+ * NULL column IS the checkpoint: a killed run re-runs the same command)
+ * - migration marker v2 (started_at preserved on same-target resume,
+ * retarget history, force_sunset_target) + transactional completion
+ * bookkeeping; markers stay content-free (privacy)
+ * - DB-reality convergence (verifyMigrationComplete) — never trusts config
+ * - the env gates: refuse on env≠target, notice-and-proceed on env==target,
+ * env-canonical persistence when no file plane exists (the #1421
+ * damage-class, where env silently kept the old model active at embed
+ * time while the schema had already moved)
+ * - reranker companion switch (DB plane, one tx with the cache purge) +
+ * the post-drain self-retrieval smoke check (warn-only)
*
* The command layer (src/commands/migrate-embeddings.ts) owns everything
- * process-shaped: confirm prompts, file-plane config persistence (the gateway
- * reads file/env, not the DB plane), gateway reconfiguration, and the embed
- * catch-up run. This module is engine-pure so both engines and the op handler
- * share one implementation.
+ * process-shaped: confirm prompts, locks + heartbeat, gateway
+ * reconfiguration, and the embed drain. This module is engine-pure so both
+ * engines, the op handler, doctor, and `--status` share one implementation.
*/
import type { BrainEngine } from './engine.ts';
import { resolveRecipe, embeddingDimsForModel } from './ai/model-resolver.ts';
import { lookupEmbeddingPrice, estimateCostFromChars } from './embedding-pricing.ts';
-import { detectEnvOverride, type EnvOverrideWarning } from './retrieval-upgrade-planner.ts';
-import { runSchemaTransition } from './retrieval-upgrade-planner.ts';
import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
+import { hnswIndexExpected } from './vector-index.ts';
+import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
+
+// ============================================================================
+// Env-override safety gate (moved from retrieval-upgrade-planner.ts — this
+// module is the v0.47 survivor; the planner re-exports for back-compat and
+// is deleted in the ZE removal wave)
+// ============================================================================
+
+/**
+ * v0.41.2.1 — env-override safety gate.
+ *
+ * `process.env.GBRAIN_EMBEDDING_MODEL` and `GBRAIN_EMBEDDING_DIMENSIONS`
+ * win over DB+file config in `loadConfig()`. The 716K-chunk damage
+ * incident (PR #1421) shipped because ze-switch wrote DB config but
+ * the env override silently kept the old model active at embed time —
+ * schema migrated to 2560d while embeds still produced 1536d vectors.
+ *
+ * detectEnvOverride is a pure read of process.env (or an injected env
+ * for tests). triggered:true means refusal is required unless the
+ * caller passes ignoreEnvOverride:true (mirrors --ignore-missing-key).
+ */
+export interface EnvOverrideWarning {
+ triggered: boolean;
+ vars: Array<{ name: string; current: string; target: string }>;
+}
+
+export function detectEnvOverride(
+ targetModel: string,
+ targetDim: number,
+ env: NodeJS.ProcessEnv = process.env,
+): EnvOverrideWarning {
+ const vars: EnvOverrideWarning['vars'] = [];
+ const envModel = env.GBRAIN_EMBEDDING_MODEL?.trim();
+ if (envModel && envModel !== targetModel) {
+ vars.push({ name: 'GBRAIN_EMBEDDING_MODEL', current: envModel, target: targetModel });
+ }
+ const envDimRaw = env.GBRAIN_EMBEDDING_DIMENSIONS?.trim();
+ if (envDimRaw) {
+ const envDim = Number(envDimRaw);
+ if (!Number.isFinite(envDim) || envDim !== targetDim) {
+ vars.push({
+ name: 'GBRAIN_EMBEDDING_DIMENSIONS',
+ current: envDimRaw,
+ target: String(targetDim),
+ });
+ }
+ }
+ return { triggered: vars.length > 0, vars };
+}
+
+/**
+ * ASCII box rendering (repo convention D10 v0.22.11 — no Unicode box
+ * drawing). Pure function; CLI calls this and writes to stderr.
+ * Line width <= 78 cols for safe rendering in any terminal or log
+ * aggregator.
+ */
+export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {
+ const lines: string[] = [];
+ lines.push('+----------------------------------------------------------------------------+');
+ lines.push('| ENV OVERRIDE DETECTED - ACTION REQUIRED |');
+ lines.push('+----------------------------------------------------------------------------+');
+ for (const v of w.vars) {
+ lines.push(`| ${v.name} is set in your environment:`.padEnd(77) + '|');
+ lines.push(`| Current env: ${v.current}`.padEnd(77) + '|');
+ lines.push(`| Switch target: ${v.target}`.padEnd(77) + '|');
+ lines.push('| |');
+ }
+ lines.push('| The env var takes HIGHEST PRECEDENCE and will override this switch. |');
+ lines.push('| Update your .env file or shell environment before retrying: |');
+ lines.push('| |');
+ const unsetCmd = ` unset ${w.vars.map(v => v.name).join(' ')}`;
+ // Match the other content-line pattern: `|` + 76 chars + `|` = 78 total.
+ lines.push(`|${unsetCmd.padEnd(76)}|`);
+ lines.push('| |');
+ lines.push('| Without this change, the switch has NO EFFECT at runtime. |');
+ lines.push('| Pass --ignore-env-override to apply anyway (advanced; you know why). |');
+ lines.push('+----------------------------------------------------------------------------+');
+ return lines.join('\n');
+}
+
+// ============================================================================
+// Schema transition (D18; moved from retrieval-upgrade-planner.ts)
+// ============================================================================
+
+/**
+ * The atomic DROP + ALTER + CREATE INDEX sequence for content_chunks.
+ * Both engines accept identical SQL (PGLite uses pgvector via WASM, same
+ * grammar). Wrapped in engine.transaction so a partial failure rolls back.
+ *
+ * Index names verified against:
+ * src/schema.sql:163 -> idx_chunks_embedding
+ * src/core/pglite-schema.ts:127 -> idx_chunks_embedding
+ * src/schema.sql:169 -> idx_chunks_embedding_image
+ * src/core/pglite-schema.ts:130 -> idx_chunks_embedding_image
+ *
+ * IF NOT EXISTS on CREATE INDEX makes the operation safe to re-run during
+ * `--resume`.
+ */
+export async function runSchemaTransition(engine: BrainEngine, targetDim: number): Promise<void> {
+ // Sink-side guard: targetDim is interpolated into DDL below. Every current
+ // caller validates upstream, but a future programmatic caller passing an
+ // unvalidated value must fail HERE, not become SQL in an admin DDL path
+ // (NaN passes `<= 0` checks; strings pass truthiness).
+ if (!Number.isInteger(targetDim) || targetDim <= 0 || targetDim > 100_000) {
+ throw new Error(`runSchemaTransition: targetDim must be a positive integer, got ${String(targetDim)}`);
+ }
+ // v0.41 fix: only transition the primary text embedding column.
+ // The embedding_image (v0.27.1) and embedding_multimodal (v0.36 / migration
+ // v78) columns use SEPARATE multimodal models (e.g. voyage-multimodal-3 at
+ // 1024d) whose dimensions are independent of the text embedding model.
+ // Dropping and recreating either at targetDim silently breaks multimodal
+ // search by creating a dimension mismatch between the column and the
+ // multimodal provider's output.
+ //
+ // Before this fix, switching text embeddings from OpenAI (1536d) to
+ // ZeroEntropy (1280d) would also change embedding_image from 1024d to
+ // 1280d, making voyage-multimodal-3 unable to write to it. The same
+ // class of bug applies to embedding_multimodal — leave both untouched.
+ await engine.transaction(async (tx) => {
+ // Text embedding column — transition to target dim.
+ await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);
+ await tx.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
+ await tx.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(${targetDim})`);
+ // HNSW cap policy lives in vector-index.ts (single home): pgvector caps
+ // `vector` HNSW at 2000 dims, so a valid 2048d target must skip the index
+ // (exact scans stay correct) instead of failing the whole DDL.
+ if (hnswIndexExpected('vector', targetDim)) {
+ await tx.executeRaw(
+ `CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)`,
+ );
+ }
+
+ // Image/multimodal embedding column — rebuild index but preserve
+ // existing dimension. Only create it if it doesn't already exist
+ // (fresh brains may not have it yet). Partial WHERE clause matches
+ // schema.sql:258-260 and pglite-schema.ts:198-200: HNSW footprint
+ // scales with image-chunk count, not table size.
+ const hasImageCol = await tx.executeRaw<{ exists: boolean }>(
+ `SELECT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'content_chunks'
+ AND column_name = 'embedding_image'
+ ) AS exists`,
+ );
+ if (hasImageCol[0]?.exists) {
+ await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding_image`);
+ await tx.executeRaw(
+ `CREATE INDEX IF NOT EXISTS idx_chunks_embedding_image
+ ON content_chunks USING hnsw (embedding_image vector_cosine_ops)
+ WHERE embedding_image IS NOT NULL`,
+ );
+ }
+
+ // #3390: the OTHER two dim-pinned columns that carry TEXT-embedding-space
+ // vectors. Both are created at brain-birth width (migrate.ts v55 for
+ // query_cache, v42 for facts) and NO migration ever ALTERs them, so before
+ // this fix a dimension change left them at the old width:
+ // - query_cache.embedding stayed narrow → every store() AND lookup()
+ // silently swallowed the width error (by design, so the cache can
+ // never break search), i.e. a PERMANENT 0% hit rate.
+ // - facts.embedding stayed narrow → every per-fact embed write failed
+ // ($N::vector into the old width), and the doctor check that would
+ // warn is skipped on PGLite (the DEFAULT engine).
+ // Both are text-embedding-space columns, so they MUST move with
+ // content_chunks.embedding. The image/multimodal columns above are the
+ // deliberate exception (separate models, independent dims).
+ for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
+ await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, targetDim);
+ }
+ });
+
+ // Post-tx data hygiene: the column rebuild NULLed every vector but left
+ // embedded_at stamped — stale data that used to make coverage surfaces lie.
+ // All READ paths now key on the vector itself (getStats/getHealth/getChunks
+ // embedding_is_null), so this clear is belt-and-braces, DELIBERATELY outside
+ // the DDL transaction: a ~1M-row UPDATE inside the ACCESS EXCLUSIVE window
+ // would hold the exclusive lock through row churn (the pooler-contention
+ // class pace-mode exists for), and a crash mid-batch leaves only
+ // redundant-lie rows that nothing reads. Batched with an event-loop yield
+ // between batches (setTimeout(0), NOT setImmediate — Bun starves the timers
+ // phase under a tight setImmediate loop) so lock heartbeats keep firing.
+ try {
+ // Keyset cursor: a bare `WHERE embedded_at IS NOT NULL LIMIT 50000` loop
+ // re-scans past every already-cleared row each batch (O(N²/batch) page
+ // visits on big brains); advancing on id visits each heap page once. The
+ // cursor also caps the loop naturally (id is monotonic) — no livelock
+ // against concurrent stampers outside the migration locks.
+ let cursor = 0;
+ for (;;) {
+ const res = await engine.executeRaw<{ n: number; max_id: number | null }>(
+ `WITH b AS (
+ SELECT id FROM content_chunks
+ WHERE id > $1 AND embedded_at IS NOT NULL
+ ORDER BY id LIMIT 50000
+ ),
+ u AS (UPDATE content_chunks c SET embedded_at = NULL FROM b WHERE c.id = b.id RETURNING b.id)
+ SELECT count(*)::int AS n, max(id)::int AS max_id FROM u`,
+ [cursor],
+ );
+ const n = Number(res[0]?.n ?? 0);
+ if (n === 0) break;
+ cursor = Number(res[0]?.max_id ?? cursor);
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ } catch {
+ // Best-effort: the vector column is the source of truth; a failed clear
+ // must never fail the migration.
+ }
+}
+
+/**
+ * The dim-pinned TEXT-embedding-space columns outside content_chunks.
+ * `indexSql` is a factory because each table's index carries its own partial
+ * WHERE clause + opclass, and the opclass must match the column TYPE
+ * (vector_cosine_ops vs halfvec_cosine_ops).
+ *
+ * Deliberately OMITTED: `takes.embedding` — the live takes search path
+ * (`searchTakes`, both engines) is trigram-based, not vector, so that column
+ * has no read path this migration could break; its own stale lane
+ * (`active AND embedding IS NULL`) covers regeneration if a vector consumer
+ * lands later.
+ */
+export const TEXT_EMBEDDING_DIM_PINNED_TABLES: ReadonlyArray<{
+ table: string;
+ index: string;
+ indexSql: (opclass: string) => string;
+}> = [
+ {
+ table: 'query_cache',
+ index: 'idx_query_cache_embedding_hnsw',
+ indexSql: (opclass) =>
+ `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
+ ON query_cache USING hnsw (embedding ${opclass})
+ WHERE embedding IS NOT NULL`,
+ },
+ {
+ table: 'facts',
+ index: 'idx_facts_embedding_hnsw',
+ indexSql: (opclass) =>
+ `CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
+ ON facts USING hnsw (embedding ${opclass})
+ WHERE embedding IS NOT NULL AND expired_at IS NULL`,
+ },
+];
+
+/**
+ * Rebuild one dim-pinned embedding column at `targetDim`, PRESERVING its
+ * existing column type (`vector` vs `halfvec` — migrate.ts picks halfvec when
+ * the server supports it, and the HNSW opclass must match). No-op when the
+ * table or column doesn't exist (fresh/older brains).
+ *
+ * Dropping the column discards the stored vectors, which is correct: they are
+ * in the OLD embedding space and unusable after the swap. query_cache is a
+ * cache (refills on the next query); facts re-embed on their next write /
+ * `gbrain extract` pass.
+ */
+async function transitionDimPinnedColumn(
+ tx: { executeRaw: <T = unknown>(sql: string, params?: unknown[]) => Promise<T[]> },
+ table: string,
+ indexName: string,
+ indexSql: (opclass: string) => string,
+ targetDim: number,
+): Promise<void> {
+ // Same sink-side guard as runSchemaTransition (this runs standalone on the
+ // independent-repair path, not only under the guarded full transition).
+ if (!Number.isInteger(targetDim) || targetDim <= 0 || targetDim > 100_000) {
+ throw new Error(`transitionDimPinnedColumn: targetDim must be a positive integer, got ${String(targetDim)}`);
+ }
+ const probe = await tx.executeRaw<{ udt_name: string | null }>(
+ `SELECT udt_name FROM information_schema.columns
+ WHERE table_schema = 'public' AND table_name = $1 AND column_name = 'embedding'`,
+ [table],
+ );
+ const udt = probe[0]?.udt_name;
+ if (!udt) return; // table or column absent — nothing to transition
+ // Preserve the column type; anything unexpected falls back to `vector`.
+ const columnType: 'vector' | 'halfvec' = udt.toLowerCase() === 'halfvec' ? 'halfvec' : 'vector';
+ const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
+
+ await tx.executeRaw(`DROP INDEX IF EXISTS ${indexName}`);
+ await tx.executeRaw(`ALTER TABLE ${table} DROP COLUMN IF EXISTS embedding`);
+ await tx.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding ${columnType}(${targetDim})`);
+ // HNSW has a per-type dimension ceiling; above it pgvector refuses the
+ // index and exact scans remain the (correct, slower) path. Mirrors the
+ // same guard in migrate.ts's original DDL.
+ if (hnswIndexExpected(columnType, targetDim)) {
+ await tx.executeRaw(indexSql(opclass));
+ }
+}
/**
* Resume/state marker (DB plane). Present while a migration is in flight so
@@ -44,11 +342,67 @@ export const MIGRATION_STATE_KEY = 'embedding_migration.state';
export const MIGRATION_COMPLETED_KEY = 'embedding_migration.completed';
export interface MigrationState {
+ /** Marker schema version. Absent = v1 (pre-hardening). */
+ version?: 2;
to_model: string;
to_dims: number;
from_model: string;
from_dims: number;
+ /**
+ * Preserved across same-target re-applies (set-if-absent) so `--status` and
+ * doctor report the TRUE age of the migration, not the latest retry.
+ */
started_at: string;
+ /** Set when the run used --force-sunset-target (resume command must too). */
+ force_sunset_target?: boolean;
+ /** Set when this marker replaced a live different-target marker. */
+ retargeted_at?: string;
+ /** History of abandoned targets (newest last) for --status forensics. */
+ superseded?: Array<{ to_model: string; to_dims: number; started_at: string }>;
+}
+
+/**
+ * ONE resume-command template for every surface that prints it (doctor,
+ * --status, both retarget refusals) — a flag that must survive resume has one
+ * home to gain, not four to miss.
+ */
+export function renderResumeCommand(state: MigrationState): string {
+ return `gbrain migrate embeddings --to ${state.to_model} --dim ${state.to_dims}${state.force_sunset_target ? ' --force-sunset-target' : ''} --yes`;
+}
+
+/**
+ * Read + parse the live migration marker. Corrupt JSON returns
+ * `{ corrupt: true, raw }` instead of throwing — every consumer of this is a
+ * read-only/reporting surface that must never crash on a bad row.
+ */
+export async function readMigrationState(
+ engine: BrainEngine,
+): Promise<{ state: MigrationState | null; corrupt: boolean; raw: string | null }> {
+ let raw: string | null = null;
+ try {
+ raw = await engine.getConfig(MIGRATION_STATE_KEY);
+ } catch {
+ return { state: null, corrupt: false, raw: null };
+ }
+ if (!raw) return { state: null, corrupt: false, raw: null };
+ try {
+ const state = JSON.parse(raw) as MigrationState;
+ // Shape validation: marker fields are interpolated into paste-ready
+ // resume commands on doctor/--status/refusal surfaces, and anything with
+ // config-table write access can plant this row. A model id outside the
+ // provider:model charset or a non-integer dims is CORRUPT, not a command.
+ if (
+ typeof state.to_model !== 'string'
+ || !/^[A-Za-z0-9._/:-]+$/.test(state.to_model)
+ || !Number.isInteger(state.to_dims)
+ || state.to_dims <= 0
+ ) {
+ return { state: null, corrupt: true, raw };
+ }
+ return { state, corrupt: false, raw };
+ } catch {
+ return { state: null, corrupt: true, raw };
+ }
}
export interface EmbeddingMigrationPlan {
@@ -76,13 +430,112 @@ export interface EmbeddingMigrationPlan {
resuming: boolean;
/** Set when the brain's reranker is also on the outgoing provider. */
reranker_warning: string | null;
+ /**
+ * DB-reality corroboration of the From line: top signatures actually
+ * stamped on pages (env vars can lie about From; the census cannot).
+ * `signature: null` bucket = pages with no recorded signature.
+ */
+ signature_census: Array<{ signature: string | null; pages: number }>;
+ /**
+ * Pages currently embedded at the per_chunk_synopsis context tier. A plain
+ * stale re-embed lands them at the TITLE tier (embedding-context.ts) — a
+ * quality downgrade the user consents to via the plan (tier-preserving
+ * re-embed is a filed follow-up, not built).
+ */
+ synopsis_tier_pages: number;
}
export type MigrationApplyResult =
- | { status: 'applied'; invalidated: number; cache_cleared: number; schema_transitioned: boolean }
+ | {
+ status: 'applied';
+ invalidated: number;
+ cache_cleared: number;
+ schema_transitioned: boolean;
+ /** Dim-pinned columns repaired independently of a full rebuild. */
+ pinned_repaired: string[];
+ }
| { status: 'refused'; reason: 'env_override'; warning: EnvOverrideWarning }
| { status: 'failed'; reason: string };
+/**
+ * Env-presence probe (distinct from detectEnvOverride, which fires only on a
+ * MISMATCH): true when GBRAIN_EMBEDDING_* is set at all. env == target is not
+ * refused — it proceeds with a loud notice (env-first deployments are
+ * legitimate) — but every surface that reports config planes needs to know.
+ */
+export function detectEnvPresence(
+ env: NodeJS.ProcessEnv = process.env,
+): { present: boolean; model: string | null; dims: string | null } {
+ const model = env.GBRAIN_EMBEDDING_MODEL?.trim() || null;
+ const dims = env.GBRAIN_EMBEDDING_DIMENSIONS?.trim() || null;
+ return { present: Boolean(model || dims), model, dims };
+}
+
+/**
+ * Does the env FULLY pin the target? Requires GBRAIN_EMBEDDING_MODEL set and
+ * equal to the target (dims, when set, must match too — detectEnvOverride
+ * covers that). A dims-ONLY env var must NOT count: `present` would be true
+ * and no mismatch "triggers", but the MODEL is unpinned — an env-canonical
+ * migration would then persist the target nowhere the gateway reads, and the
+ * next process falls back to the legacy configless default (the #1421
+ * config-says-new/runtime-embeds-old damage class).
+ */
+export function envFullyPinsTarget(
+ targetModel: string,
+ targetDim: number,
+ env: NodeJS.ProcessEnv = process.env,
+): boolean {
+ const model = env.GBRAIN_EMBEDDING_MODEL?.trim();
+ if (!model || model !== targetModel) return false;
+ return !detectEnvOverride(targetModel, targetDim, env).triggered;
+}
+
+/**
+ * ONE computation for "does the schema need a (re)build?" shared by plan
+ * (display) and apply (trigger) so they can never disagree. An absent or
+ * unparsable column (dims === null) NEEDS a build — the old plan-side
+ * `dims !== null && dims !== to` spelling showed no DESTRUCTIVE warning while
+ * apply ran the DDL anyway.
+ */
+export function schemaRebuildNeeded(colDims: number | null, toDims: number): boolean {
+ return colDims !== toDims;
+}
+
+/**
+ * Widths of the dim-pinned TEXT-embedding-space columns outside
+ * content_chunks. `null` dims = column exists but width unreadable; absent
+ * tables/columns are omitted entirely (nothing to repair).
+ */
+export async function readDimPinnedWidths(
+ engine: BrainEngine,
+): Promise<Array<{ table: string; dims: number | null }>> {
+ const out: Array<{ table: string; dims: number | null }> = [];
+ for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
+ try {
+ // Schema-qualified (public) + relkind='r', matching the sibling probes
+ // (readContentChunksEmbeddingDim pins nspname; transitionDimPinnedColumn
+ // pins table_schema) — a same-named table in another schema on a shared
+ // database must not feed a wrong width into the repair DDL or verify.
+ const rows = await engine.executeRaw<{ dim: number | null }>(
+ `SELECT a.atttypmod AS dim
+ FROM pg_attribute a
+ JOIN pg_class c ON c.oid = a.attrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind = 'r'
+ AND c.relname = $1 AND a.attname = 'embedding'
+ AND a.attnum > 0 AND NOT a.attisdropped`,
+ [t.table],
+ );
+ if (rows.length === 0) continue; // table/column absent
+ const dim = rows[0]?.dim;
+ out.push({ table: t.table, dims: typeof dim === 'number' && dim > 0 ? dim : null });
+ } catch {
+ // Probe failure = unknown, not broken; skip (transition no-ops there too).
+ }
+ }
+ return out;
+}
+
/** `<provider:model>:<dims>` — must match currentEmbeddingSignature()'s shape. */
export function migrationSignature(toModel: string, toDims: number): string {
return `${toModel}:${toDims}`;
@@ -152,38 +605,78 @@ export async function planEmbeddingMigration(
const col = await readContentChunksEmbeddingDim(engine);
const sig = migrationSignature(toModel, toDims);
- const wide = await engine.countStaleChunks({ signature: sig, includeNullSignature: true });
- const narrow = await engine.countStaleChunks({ signature: sig });
- const totalChars = await engine.sumStaleChunkChars({ signature: sig, includeNullSignature: true });
+ let wide: number;
+ let narrow: number;
+ let totalChars: number;
+ if (col.exists) {
+ wide = await engine.countStaleChunks({ signature: sig, includeNullSignature: true });
+ narrow = await engine.countStaleChunks({ signature: sig });
+ totalChars = await engine.sumStaleChunkChars({ signature: sig, includeNullSignature: true });
+ } else {
+ // Column ABSENT: the stale predicates reference cc.embedding and would
+ // throw. Every chunk needs embedding once the column is (re)built.
+ const rows = await engine.executeRaw<{ n: number; chars: number }>(
+ `SELECT count(*)::int AS n, COALESCE(sum(length(chunk_text)), 0)::bigint AS chars FROM content_chunks`,
+ );
+ wide = Number(rows[0]?.n ?? 0);
+ narrow = wide;
+ totalChars = Number(rows[0]?.chars ?? 0);
+ }
const price = lookupEmbeddingPrice(toModel);
const estCostUsd = price.kind === 'known'
? estimateCostFromChars(totalChars, price.pricePerMTok)
: 0;
- let resuming = false;
+ const marker = await readMigrationState(engine);
+ const resuming = marker.state !== null
+ && marker.state.to_model === toModel
+ && marker.state.to_dims === toDims;
+
+ // DB-reality census: what the pages themselves say they were embedded with.
+ // Top 5 buckets; NULL = no recorded signature (pre-v108 or never stamped).
+ let signatureCensus: Array<{ signature: string | null; pages: number }> = [];
try {
- const stateStr = await engine.getConfig(MIGRATION_STATE_KEY);
- if (stateStr) {
- const state = JSON.parse(stateStr) as MigrationState;
- resuming = state.to_model === toModel && state.to_dims === toDims;
- }
+ const rows = await engine.executeRaw<{ signature: string | null; pages: number }>(
+ `SELECT embedding_signature AS signature, count(*)::int AS pages
+ FROM pages
+ WHERE deleted_at IS NULL
+ GROUP BY embedding_signature
+ ORDER BY count(*) DESC
+ LIMIT 5`,
+ );
+ signatureCensus = rows.map((r) => ({ signature: r.signature, pages: Number(r.pages) }));
+ } catch {
+ // Census is informational; a probe failure never blocks planning.
+ }
+
+ // Context-tier downgrade consent (outside-voice C6): a stale re-embed
+ // replaces per_chunk_synopsis vectors with title-tier ones.
+ let synopsisTierPages = 0;
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages
+ WHERE deleted_at IS NULL AND contextual_retrieval_mode = 'per_chunk_synopsis'`,
+ );
+ synopsisTierPages = Number(rows[0]?.n ?? 0);
} catch {
- // Corrupt state marker — treat as fresh.
+ // Column may not exist on older brains — informational only.
}
// Sunset companion warning: migrating embeddings off a provider whose
- // reranker is still configured leaves rerank on the outgoing provider.
+ // reranker is still ACTIVE leaves rerank on the outgoing provider. Resolved
+ // THROUGH the mode bundles (not the bare DB key) — the common ZE case is an
+ // unset key riding the bundle default, which the old key-only read missed.
let rerankerWarning: string | null = null;
try {
- const rr = await engine.getConfig('search.reranker.model');
- const outgoingProvider = fromModel.split(':')[0];
- const targetProvider = toModel.split(':')[0];
- if (rr && outgoingProvider !== targetProvider && rr.startsWith(`${outgoingProvider}:`)) {
+ const exposure = await resolveRerankerExposure(engine, fromModel, toModel);
+ if (exposure) {
rerankerWarning =
- `search.reranker.model is still ${rr} (the outgoing provider). ` +
- `If that provider is sunsetting, also update or disable the reranker: ` +
- `gbrain config set search.reranker.enabled false`;
+ `the resolved reranker is ${exposure.model}` +
+ (exposure.sunset_date
+ ? ` and its provider shuts down ${exposure.sunset_date}`
+ : ' (the outgoing provider)') +
+ ` — pass --reranker to switch or disable it in the same run`;
}
} catch {
// Reranker warning is cosmetic.
@@ -195,7 +688,8 @@ export async function planEmbeddingMigration(
column_dims: col.dims,
to_model: toModel,
to_dims: toDims,
- dim_change: col.dims !== null && col.dims !== toDims,
+ // ONE computation shared with apply's trigger (absent column ⇒ build).
+ dim_change: schemaRebuildNeeded(col.dims, toDims),
chunks_to_embed: wide,
total_chars: totalChars,
null_signature_chunks: wide - narrow,
@@ -203,6 +697,348 @@ export async function planEmbeddingMigration(
price_known: price.kind === 'known',
resuming,
reranker_warning: rerankerWarning,
+ signature_census: signatureCensus,
+ synopsis_tier_pages: synopsisTierPages,
+ };
+}
+
+// ============================================================================
+// Read-only status + completion smoke check (D6 + D11)
+// ============================================================================
+
+export interface MigrationStatusReport {
+ marker:
+ | { kind: 'none' }
+ | { kind: 'live'; state: MigrationState }
+ | { kind: 'corrupt'; raw_prefix: string };
+ completed: Record<string, unknown> | null;
+ db_plane: { model: string | null; dims: string | null };
+ column_dims: number | null;
+ pinned_widths: Array<{ table: string; dims: number | null }>;
+ missing_embeddings: number | null;
+ chunkless_pages: number | null;
+ signature_census: Array<{ signature: string | null; pages: number }>;
+ /** facts rows whose text-space vector is NULL (regenerate on next extract/write). */
+ facts_pending: number | null;
+ synopsis_tier_pages: number | null;
+ /** Stale count vs the live marker's target (else null — no target known). */
+ stale_vs_target: { target: string | null; stale: number | null };
+}
+
+/**
+ * Read-only migration status. Never throws, never mutates, never spends —
+ * `--status` is the surface a stranded agent reads mid-incident, so every
+ * probe degrades to null instead of erroring.
+ */
+export async function readMigrationStatus(engine: BrainEngine): Promise<MigrationStatusReport> {
+ const marker = await readMigrationState(engine);
+ const markerReport: MigrationStatusReport['marker'] = marker.corrupt
+ ? { kind: 'corrupt', raw_prefix: (marker.raw ?? '').slice(0, 120) }
+ : marker.state
+ ? { kind: 'live', state: marker.state }
+ : { kind: 'none' };
+
+ let completed: Record<string, unknown> | null = null;
+ try {
+ const raw = await engine.getConfig(MIGRATION_COMPLETED_KEY);
+ if (raw) completed = JSON.parse(raw) as Record<string, unknown>;
+ } catch { /* corrupt/absent completion record — report null */ }
+
+ let dbModel: string | null = null;
+ let dbDims: string | null = null;
+ try {
+ dbModel = await engine.getConfig('embedding_model');
+ dbDims = await engine.getConfig('embedding_dimensions');
+ } catch { /* report null */ }
+
+ let columnDims: number | null = null;
+ try {
+ columnDims = (await readContentChunksEmbeddingDim(engine)).dims;
+ } catch { /* report null */ }
+
+ let pinned: Array<{ table: string; dims: number | null }> = [];
+ try {
+ pinned = await readDimPinnedWidths(engine);
+ } catch { /* report empty */ }
+
+ let missing: number | null = null;
+ try {
+ missing = (await engine.getHealth()).missing_embeddings;
+ } catch { /* report null */ }
+
+ let chunkless: number | null = null;
+ try {
+ chunkless = await engine.countChunklessPagesWithContent();
+ } catch { /* report null */ }
+
+ let census: Array<{ signature: string | null; pages: number }> = [];
+ try {
+ const rows = await engine.executeRaw<{ signature: string | null; pages: number }>(
+ `SELECT embedding_signature AS signature, count(*)::int AS pages
+ FROM pages WHERE deleted_at IS NULL
+ GROUP BY embedding_signature ORDER BY count(*) DESC LIMIT 5`,
+ );
+ census = rows.map((r) => ({ signature: r.signature, pages: Number(r.pages) }));
+ } catch { /* report empty */ }
+
+ let factsPending: number | null = null;
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM facts WHERE embedding IS NULL AND expired_at IS NULL`,
+ );
+ factsPending = Number(rows[0]?.n ?? 0);
+ } catch { /* facts table absent — report null */ }
+
+ let synopsisTier: number | null = null;
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages
+ WHERE deleted_at IS NULL AND contextual_retrieval_mode = 'per_chunk_synopsis'`,
+ );
+ synopsisTier = Number(rows[0]?.n ?? 0);
+ } catch { /* report null */ }
+
+ let staleVsTarget: MigrationStatusReport['stale_vs_target'] = { target: null, stale: null };
+ const target = marker.state
+ ? { model: marker.state.to_model, dims: marker.state.to_dims }
+ : dbModel && dbDims && Number.isFinite(Number(dbDims))
+ ? { model: dbModel, dims: Number(dbDims) }
+ : null;
+ if (target) {
+ try {
+ const stale = await engine.countStaleChunks({
+ signature: migrationSignature(target.model, target.dims),
+ includeNullSignature: true,
+ });
+ staleVsTarget = { target: `${target.model} (${target.dims}d)`, stale };
+ } catch {
+ staleVsTarget = { target: `${target.model} (${target.dims}d)`, stale: null };
+ }
+ }
+
+ return {
+ marker: markerReport,
+ completed,
+ db_plane: { model: dbModel, dims: dbDims },
+ column_dims: columnDims,
+ pinned_widths: pinned,
+ missing_embeddings: missing,
+ chunkless_pages: chunkless,
+ signature_census: census,
+ facts_pending: factsPending,
+ synopsis_tier_pages: synopsisTier,
+ stale_vs_target: staleVsTarget,
+ };
+}
+
+export interface VerifySearchOutcome {
+ status: 'pass' | 'warn' | 'skipped';
+ /** Content-free per-sample record — safe to stamp into the completion marker. */
+ samples: Array<{ page_id: number; status: 'hit' | 'miss' | 'error'; reason_code?: string }>;
+ reason_code?: string;
+}
+
+/**
+ * Completion smoke check (D11): self-retrieval on up to N recently-embedded
+ * pages via query-side embedQuery + vector search. Honestly labeled: a SMOKE
+ * CHECK, not a recall eval (BrainBench owns retrieval quality). NEVER throws;
+ * warn-don't-block; hit identity by (page_id, source_id), never slug. The
+ * persisted record carries only page ids + reason codes — no query snippets
+ * or page content (markers land in config dumps and logs).
+ */
+export async function verifySearchRoundTrip(
+ engine: BrainEngine,
+ opts: { samples?: number } = {},
+): Promise<VerifySearchOutcome> {
+ try {
+ const { currentEmbeddingSignature, embedQuery } = await import('./embedding.ts');
+ if (currentEmbeddingSignature() === null) {
+ return { status: 'skipped', samples: [], reason_code: 'gateway_unconfigured' };
+ }
+ const n = Math.max(1, Math.min(10, opts.samples ?? 3));
+ const rows = await engine.executeRaw<{ page_id: number; source_id: string; chunk_text: string }>(
+ `SELECT cc.page_id, p.source_id, cc.chunk_text
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ WHERE cc.embedding IS NOT NULL AND p.deleted_at IS NULL
+ AND (cc.modality IS NULL OR cc.modality = 'text')
+ ORDER BY cc.id DESC
+ LIMIT $1`,
+ [n],
+ );
+ if (rows.length === 0) {
+ return { status: 'skipped', samples: [], reason_code: 'no_embedded_chunks' };
+ }
+ const samples: VerifySearchOutcome['samples'] = [];
+ for (const row of rows) {
+ try {
+ const query = row.chunk_text.slice(0, 160);
+ const vec = await embedQuery(query);
+ const results = await engine.searchVector(vec, {
+ limit: 10,
+ sourceId: row.source_id,
+ } as never);
+ const hit = Array.isArray(results)
+ && results.some((r) => Number((r as { page_id?: unknown }).page_id) === Number(row.page_id));
+ samples.push({ page_id: Number(row.page_id), status: hit ? 'hit' : 'miss' });
+ } catch (e) {
+ // The persisted record must stay content-free: raw provider error
+ // bodies can echo the query (page content) back — classify into a
+ // fixed enum for the marker; the free-text detail goes to stderr via
+ // the CLI's warn line, never into a config-table row.
+ const msg = e instanceof Error ? e.message : '';
+ const code = /timeout|timed out/i.test(msg)
+ ? 'timeout'
+ : /embed/i.test(msg)
+ ? 'embed_failed'
+ : 'search_failed';
+ samples.push({ page_id: Number(row.page_id), status: 'error', reason_code: code });
+ }
+ }
+ const misses = samples.filter((s) => s.status !== 'hit');
+ return misses.length === 0
+ ? { status: 'pass', samples }
+ : { status: 'warn', samples, reason_code: 'self_retrieval_miss' };
+ } catch (e) {
+ return {
+ status: 'warn',
+ samples: [],
+ reason_code: e instanceof Error ? e.message.slice(0, 80) : 'unknown',
+ };
+ }
+}
+
+/**
+ * DB-reality convergence check — the ONLY basis on which the command may say
+ * "nothing to migrate". Never trusts `from_model` (env vars poison it); every
+ * conjunct is probed from the database or the file plane the caller read
+ * WITHOUT env merge.
+ */
+export interface MigrationVerify {
+ complete: boolean;
+ blockers: string[];
+ details: {
+ column_dims: number | null;
+ pinned_widths: Array<{ table: string; dims: number | null }>;
+ stale_wide: number;
+ missing_embeddings: number;
+ chunkless_pages: number;
+ marker: 'none' | 'same_target' | 'different_target' | 'corrupt';
+ file_plane_ok: boolean;
+ };
+}
+
+export async function verifyMigrationComplete(
+ engine: BrainEngine,
+ target: { toModel: string; toDims: number },
+ opts: {
+ /** File-plane config read WITHOUT env merge (loadConfigFileOnly). */
+ filePlane?: { model?: string | null; dims?: number | null } | null;
+ /** True when GBRAIN_EMBEDDING_* env exactly matches the target. */
+ envMatchesTarget?: boolean;
+ /** True when GBRAIN_EMBEDDING_* env is set at all. */
+ envPresent?: boolean;
+ } = {},
+): Promise<MigrationVerify> {
+ const blockers: string[] = [];
+
+ // env≠target: the runtime would embed at a DIFFERENT model than the target
+ // no matter what the DB says — a converged-looking brain is one process
+ // restart away from re-poisoning. Never claim "nothing to migrate" here.
+ if (opts.envPresent === true && opts.envMatchesTarget !== true) {
+ blockers.push('GBRAIN_EMBEDDING_* env vars override the runtime AWAY from the target — unset them (or pass --ignore-env-override)');
+ }
+
+ const col = await readContentChunksEmbeddingDim(engine);
+ if (schemaRebuildNeeded(col.dims, target.toDims)) {
+ blockers.push(
+ col.dims === null
+ ? `embedding column is absent/unreadable — will be (re)built at ${target.toDims}d`
+ : `embedding column is ${col.dims}d, target is ${target.toDims}d`,
+ );
+ }
+
+ const pinned = await readDimPinnedWidths(engine);
+ for (const p of pinned) {
+ if (schemaRebuildNeeded(p.dims, target.toDims)) {
+ blockers.push(`${p.table}.embedding is ${p.dims === null ? 'unreadable' : `${p.dims}d`}, target is ${target.toDims}d`);
+ }
+ }
+
+ const sig = migrationSignature(target.toModel, target.toDims);
+ let staleWide = 0;
+ if (col.exists) {
+ staleWide = await engine.countStaleChunks({ signature: sig, includeNullSignature: true });
+ } else {
+ // Absent column: the stale predicate would throw; every chunk is pending.
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks`,
+ );
+ staleWide = Number(rows[0]?.n ?? 0);
+ }
+ if (staleWide > 0) {
+ blockers.push(`${staleWide} chunk(s) not in the target embedding space`);
+ }
+
+ // Belt-and-braces raw NULL residue via the (post-truth-fix) health count —
+ // no pages JOIN divergence, embed_skip already excluded on both engines.
+ let missing = 0;
+ try {
+ missing = (await engine.getHealth()).missing_embeddings;
+ } catch {
+ // Health probe failure: report-only conjunct, don't block on it.
+ }
+ if (missing > 0 && staleWide === 0) {
+ blockers.push(`${missing} chunk(s) have NULL vectors outside the stale predicate`);
+ }
+
+ // Contentful pages with zero chunk rows: the embed drain heals these, so a
+ // brain with any is NOT converged (round-2 #6; same census the drain uses).
+ let chunkless = 0;
+ try {
+ chunkless = await engine.countChunklessPagesWithContent();
+ } catch {
+ // Optional census; older engines without the method just skip it.
+ }
+ if (chunkless > 0) {
+ blockers.push(`${chunkless} contentful page(s) have no chunks yet (the re-embed pass heals these)`);
+ }
+
+ const marker = await readMigrationState(engine);
+ let markerState: MigrationVerify['details']['marker'] = 'none';
+ if (marker.corrupt) {
+ markerState = 'corrupt';
+ blockers.push('migration state marker is corrupt (treated as in-flight; completing the run rewrites it)');
+ } else if (marker.state) {
+ const same = marker.state.to_model === target.toModel && marker.state.to_dims === target.toDims;
+ markerState = same ? 'same_target' : 'different_target';
+ if (same) {
+ blockers.push(`a migration to this target started ${marker.state.started_at} is still in flight — resuming it`);
+ }
+ // different_target is the caller's --retarget decision, not a convergence
+ // blocker for THIS target; readMigrationStatus surfaces it.
+ }
+
+ const fp = opts.filePlane;
+ const filePlaneOk = fp
+ ? fp.model === target.toModel && Number(fp.dims) === target.toDims
+ : opts.envMatchesTarget === true; // env-canonical mode: no file plane, env pins the target
+ if (!filePlaneOk) {
+ blockers.push('runtime config (file plane) does not point at the target yet');
+ }
+
+ return {
+ complete: blockers.length === 0,
+ blockers,
+ details: {
+ column_dims: col.dims,
+ pinned_widths: pinned,
+ stale_wide: staleWide,
+ missing_embeddings: missing,
+ chunkless_pages: chunkless,
+ marker: markerState,
+ file_plane_ok: filePlaneOk,
+ },
};
}
@@ -226,6 +1062,8 @@ export async function applyEmbeddingMigration(
ignoreEnvOverride?: boolean;
/** Persist target model+dims to the file plane + reconfigure the gateway. */
persistConfig?: (toModel: string, toDims: number) => void | Promise<void>;
+ /** Stamped into the marker so the printed resume command is complete. */
+ forceSunsetTarget?: boolean;
} = {},
): Promise<MigrationApplyResult> {
const envWarning = detectEnvOverride(plan.to_model, plan.to_dims);
@@ -235,22 +1073,65 @@ export async function applyEmbeddingMigration(
try {
// 1. State marker FIRST — a crash after any later step is resumable.
+ // Same-target re-apply PRESERVES the original started_at (set-if-
+ // absent) so status/doctor report the migration's true age; a
+ // different-target live marker is pushed into `superseded` (the caller
+ // already gated the retarget decision).
+ const prior = await readMigrationState(engine);
+ const now = new Date().toISOString();
+ const sameTarget = prior.state !== null
+ && prior.state.to_model === plan.to_model
+ && prior.state.to_dims === plan.to_dims;
+
const state: MigrationState = {
+ version: 2,
to_model: plan.to_model,
to_dims: plan.to_dims,
from_model: plan.from_model,
from_dims: plan.from_dims,
- started_at: new Date().toISOString(),
+ started_at: now,
};
+ if (opts.forceSunsetTarget) state.force_sunset_target = true;
+ if (sameTarget && prior.state) {
+ // Resume: keep the original run's identity.
+ state.from_model = prior.state.from_model;
+ state.from_dims = prior.state.from_dims;
+ state.started_at = prior.state.started_at;
+ if (prior.state.retargeted_at) state.retargeted_at = prior.state.retargeted_at;
+ if (prior.state.superseded) state.superseded = prior.state.superseded;
+ } else if (prior.state) {
+ // Retarget: record the abandoned target's identity.
+ state.retargeted_at = now;
+ state.superseded = [
+ ...(prior.state.superseded ?? []),
+ { to_model: prior.state.to_model, to_dims: prior.state.to_dims, started_at: prior.state.started_at },
+ ];
+ }
await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
- // 2. Schema transition when the ACTUAL column width differs from the
- // target (probe again — the plan may be stale after a resume).
+ // 2. Schema work — probe again (the plan may be stale after a resume) and
+ // repair each dim-pinned column INDEPENDENTLY (round-2 #9): a brain
+ // whose chunks column is already at target but whose facts/query_cache
+ // stayed narrow gets those repaired without a full destructive rebuild.
let schemaTransitioned = false;
+ const pinnedRepaired: string[] = [];
const col = await readContentChunksEmbeddingDim(engine);
- if (col.dims !== plan.to_dims) {
+ if (schemaRebuildNeeded(col.dims, plan.to_dims)) {
await runSchemaTransition(engine, plan.to_dims);
schemaTransitioned = true;
+ } else {
+ const pinned = await readDimPinnedWidths(engine);
+ const stalePinned = pinned.filter((p) => schemaRebuildNeeded(p.dims, plan.to_dims));
+ if (stalePinned.length > 0) {
+ await engine.transaction(async (tx) => {
+ for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
+ if (stalePinned.some((p) => p.table === t.table)) {
+ await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, plan.to_dims);
+ pinnedRepaired.push(t.table);
+ }
+ }
+ });
+ }
}
// 3. #3391: mark EVERYTHING not in the target space as stale, including
@@ -289,12 +1170,165 @@ export async function applyEmbeddingMigration(
// Table may not exist on old brains; a miss here is harmless.
}
- return { status: 'applied', invalidated, cache_cleared: cacheCleared, schema_transitioned: schemaTransitioned };
+ return {
+ status: 'applied',
+ invalidated,
+ cache_cleared: cacheCleared,
+ schema_transitioned: schemaTransitioned,
+ pinned_repaired: pinnedRepaired,
+ };
} catch (err) {
return { status: 'failed', reason: err instanceof Error ? err.message : String(err) };
}
}
+// ============================================================================
+// Reranker companion switch (D8): embeddings + reranker are ONE flow.
+// ============================================================================
+
+/**
+ * Is the brain's ACTIVE reranker (resolved through mode bundles, not just the
+ * explicit DB key) exposed by this migration? Exposed = reranking is enabled
+ * AND the resolved model's provider is sunsetting OR is the outgoing
+ * embedding provider while the target is a different one.
+ */
+export async function resolveRerankerExposure(
+ engine: BrainEngine,
+ fromModel: string,
+ toModel: string,
+): Promise<{ model: string; sunset_date: string | null; replacement: string | null } | null> {
+ const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
+ if (!knobs.reranker_enabled) return null;
+ const current = knobs.reranker_model;
+ const currentProvider = current.split(':')[0];
+ const outgoingProvider = fromModel.split(':')[0];
+ const targetProvider = toModel.split(':')[0];
+ let sunsetDate: string | null = null;
+ let replacement: string | null = null;
+ try {
+ const { recipe } = resolveRecipe(current);
+ sunsetDate = recipe.sunset?.date ?? null;
+ replacement = recipe.sunset?.replacement?.reranker ?? null;
+ } catch {
+ // Unknown reranker recipe: not classifiable as exposed — rerank already
+ // fails open at search time and doctor's provider checks own that case.
+ }
+ const exposed = sunsetDate !== null
+ || (currentProvider === outgoingProvider && currentProvider !== targetProvider);
+ return exposed ? { model: current, sunset_date: sunsetDate, replacement } : null;
+}
+
+export type RerankerAction =
+ | { kind: 'switch'; to: string }
+ | { kind: 'disable' }
+ | { kind: 'none'; suggestion: string | null };
+
+export interface RerankerPlan {
+ exposed: { model: string; sunset_date: string | null } | null;
+ action: RerankerAction;
+}
+
+/**
+ * Decide the reranker companion action for this migration.
+ *
+ * flag semantics (`--reranker`):
+ * auto (default) — when the resolved reranker is exposed: switch to the
+ * TARGET provider's default reranker when it ships one; otherwise NEVER
+ * silently enable a third provider's paid service — return a suggestion
+ * the caller prints as an ACTION line (and doctor keeps nagging).
+ * keep — leave reranker config untouched (warning still shows).
+ * off — disable reranking (`search.reranker.enabled false`).
+ * <provider:model> — switch to that model (validated: the recipe must
+ * declare a reranker touchpoint; throws a paste-ready message otherwise).
+ */
+export async function resolveRerankerPlan(
+ engine: BrainEngine,
+ fromModel: string,
+ toModel: string,
+ flag: string | undefined,
+): Promise<RerankerPlan> {
+ const exposedFull = await resolveRerankerExposure(engine, fromModel, toModel);
+ const exposed = exposedFull
+ ? { model: exposedFull.model, sunset_date: exposedFull.sunset_date }
+ : null;
+ const mode = flag ?? 'auto';
+
+ if (mode === 'keep') return { exposed, action: { kind: 'none', suggestion: null } };
+ if (mode === 'off') return { exposed, action: { kind: 'disable' } };
+ if (mode !== 'auto') {
+ // Explicit provider:model — validate BEFORE anything destructive runs.
+ if (!mode.includes(':')) {
+ throw new Error(
+ `--reranker must be auto|off|keep|<provider:model>. Got: ${mode}. ` +
+ `Example: --reranker voyage:rerank-2.5`,
+ );
+ }
+ const { recipe } = resolveRecipe(mode); // throws with provider list on unknown
+ if (!recipe.touchpoints.reranker) {
+ throw new Error(
+ `Provider ${recipe.id} declares no reranker. Pick a reranker-capable model ` +
+ `(e.g. voyage:rerank-2.5) or pass --reranker off.`,
+ );
+ }
+ return { exposed, action: { kind: 'switch', to: mode } };
+ }
+
+ // auto
+ if (!exposedFull) return { exposed, action: { kind: 'none', suggestion: null } };
+ try {
+ const { recipe } = resolveRecipe(toModel);
+ const tp = recipe.touchpoints.reranker as { default_model?: string; models?: string[] } | undefined;
+ const defaultModel = tp?.default_model ?? tp?.models?.[0];
+ if (defaultModel) {
+ return { exposed, action: { kind: 'switch', to: `${recipe.id}:${defaultModel}` } };
+ }
+ } catch { /* fall through to suggestion */ }
+ // Target provider has no reranker: suggest, never silently enable a THIRD
+ // provider's paid service.
+ return { exposed, action: { kind: 'none', suggestion: exposedFull.replacement } };
+}
+
+/**
+ * Apply the reranker companion action: config write + query-cache purge in
+ * ONE transaction (a crash can't leave old-reranker cache rows serving a
+ * new-reranker config, in either order). DB plane deliberately — reranker
+ * config lives in the DB (resolveSearchMode), unlike embedding config
+ * (file/env planes).
+ */
+export async function applyRerankerAction(
+ engine: BrainEngine,
+ action: RerankerAction,
+): Promise<void> {
+ if (action.kind === 'none') return;
+ await engine.transaction(async (tx) => {
+ const upsert = async (key: string, value: string) => {
+ await tx.executeRaw(
+ `INSERT INTO config (key, value) VALUES ($1, $2)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
+ [key, value],
+ );
+ };
+ if (action.kind === 'switch') {
+ await upsert('search.reranker.model', action.to);
+ await upsert('search.reranker.enabled', 'true');
+ } else {
+ await upsert('search.reranker.enabled', 'false');
+ }
+ // Rank order changes with the reranker; cached result sets must not
+ // survive the flip. Table may be absent on very old brains — the tx
+ // would abort, so probe first.
+ const has = await tx.executeRaw<{ exists: boolean }>(
+ `SELECT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name = 'query_cache'
+ ) AS exists`,
+ );
+ if (has[0]?.exists) {
+ await tx.executeRaw(`DELETE FROM query_cache`);
+ }
+ });
+}
+
/**
* Stamp the target signature on every page that is fully embedded but not yet
* stamped. Call after the re-embed drain, BEFORE the completion probe.
@@ -333,8 +1367,17 @@ export async function reconcilePageSignatures(
SELECT 1 FROM content_chunks c
WHERE c.page_id = p.id AND c.embedding IS NULL
)
+ AND NOT EXISTS (
+ -- Model-truth conjunct: chunks carry the gateway-resolved
+ -- provider:model at write time. A page whose vectors were written by
+ -- a concurrent OUT-OF-LOCK embed worker still running the OLD model
+ -- must NOT be relabeled as target-space — the final census relies on
+ -- the old signature/model evidence this stamp would erase.
+ SELECT 1 FROM content_chunks c
+ WHERE c.page_id = p.id AND c.model IS DISTINCT FROM $2
+ )
RETURNING p.slug`,
- [sig],
+ [sig, plan.to_model],
);
return (rows as unknown[]).length;
}
@@ -342,19 +1385,34 @@ export async function reconcilePageSignatures(
/**
* Finish bookkeeping after the re-embed drains: clear the in-flight marker,
* stamp the completion record. Call ONLY when countStaleChunks() === 0.
+ *
+ * ONE transaction (round-2 #10): delete + insert as separate writes had a
+ * crash window that lost BOTH the resume state and the completion receipt —
+ * and the verified skip would then read the brain as trivially converged
+ * with no record of what happened.
+ *
+ * `extra` is merged into the completion record (e.g. verify_search from the
+ * completion smoke check). Keep it small and content-free — this row lands
+ * in config-table dumps and logs.
*/
export async function completeEmbeddingMigration(
engine: BrainEngine,
plan: EmbeddingMigrationPlan,
+ extra: Record<string, unknown> = {},
): Promise<void> {
- await engine.unsetConfig(MIGRATION_STATE_KEY);
- await engine.setConfig(
- MIGRATION_COMPLETED_KEY,
- JSON.stringify({
- to_model: plan.to_model,
- to_dims: plan.to_dims,
- from_model: plan.from_model,
- completed_at: new Date().toISOString(),
- }),
- );
+ const completed = JSON.stringify({
+ to_model: plan.to_model,
+ to_dims: plan.to_dims,
+ from_model: plan.from_model,
+ completed_at: new Date().toISOString(),
+ ...extra,
+ });
+ await engine.transaction(async (tx) => {
+ await tx.executeRaw(`DELETE FROM config WHERE key = $1`, [MIGRATION_STATE_KEY]);
+ await tx.executeRaw(
+ `INSERT INTO config (key, value) VALUES ($1, $2)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
+ [MIGRATION_COMPLETED_KEY, completed],
+ );
+ });
}
diff --git a/src/core/embedding.ts b/src/core/embedding.ts
index 108b854f8d..f1b2701d45 100644
--- a/src/core/embedding.ts
+++ b/src/core/embedding.ts
@@ -123,10 +123,6 @@ export function getEmbeddingDimensions(): number {
return gatewayGetDims();
}
-// Back-compat exports for tests that imported these from v0.13.
-export const EMBEDDING_MODEL = 'text-embedding-3-large';
-export const EMBEDDING_DIMENSIONS = 1536;
-
/**
* USD cost per 1k tokens for text-embedding-3-large. Retained for back-compat
* with callers/tests that import it directly; new cost math resolves the
@@ -172,14 +168,17 @@ export function estimateEmbeddingCostUsd(tokens: number): number {
* already tracked per-page via `pages.chunker_version` (used by sync +
* doctor). This signature is strictly about the EMBEDDING space.
*
- * Falls back to the OpenAI default signature when the gateway is
- * unconfigured (unit-test context), matching the other estimator fallbacks.
+ * Returns null when the gateway is unconfigured. The old fallback silently
+ * claimed the OpenAI default signature, which STAMPED A LIE onto pages
+ * embedded in a gateway-less context — a wrong signature is worse than none
+ * (NULL = "unknown provenance", which the includeNullSignature machinery
+ * already handles honestly). Callers skip stamping/signature-widening on null.
*/
-export function currentEmbeddingSignature(): string {
+export function currentEmbeddingSignature(): string | null {
try {
return `${gatewayGetModel()}:${gatewayGetDims()}`;
} catch {
- return `${EMBEDDING_MODEL}:${EMBEDDING_DIMENSIONS}`;
+ return null;
}
}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 8c1ac1b3f6..df85fb4f85 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -911,7 +911,12 @@ export async function importFromContent(
// as stale via embed --stale. The deferred/backfill + per-slug embed
// paths stamp too; this covers the inline import/sync path.
if (!opts.noEmbed) {
- await tx.setPageEmbeddingSignature(slug, { sourceId, signature: currentEmbeddingSignature() });
+ // D9: signature is null when the gateway is unconfigured — skip the
+ // stamp (a wrong signature is worse than none).
+ const importSig = currentEmbeddingSignature();
+ if (importSig) {
+ await tx.setPageEmbeddingSignature(slug, { sourceId, signature: importSig });
+ }
}
} else {
// Content is empty — delete stale chunks so they don't ghost in search results
@@ -1372,7 +1377,11 @@ export async function importCodeFile(
// falsely marked current; `reindex --code --force` / `embed --stale`
// handle the swap for those.
if (!opts.noEmbed && needsEmbedIndexes.length === chunks.length) {
- await tx.setPageEmbeddingSignature(slug, { sourceId, signature: currentEmbeddingSignature() });
+ // D9: no stamp without a gateway (wrong signature is worse than none).
+ const codeSig = currentEmbeddingSignature();
+ if (codeSig) {
+ await tx.setPageEmbeddingSignature(slug, { sourceId, signature: codeSig });
+ }
}
} else {
await tx.deleteChunks(slug, txOpts);
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 30ffd6ed57..75ea8a9269 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -172,8 +172,10 @@ export function makeEmbedBackfillHandler(engine: BrainEngine) {
pacer,
...(concurrency !== undefined && { concurrency }),
// v0.41.31: re-embed pages whose model signature drifted + stamp
- // provenance as chunks land.
- embeddingSignature: currentEmbeddingSignature(),
+ // provenance as chunks land. D9: omitted when the gateway is
+ // unconfigured (null) — the drain falls back to NULL-embedding-only
+ // staleness instead of stamping a wrong signature.
+ ...(currentEmbeddingSignature() !== null && { embeddingSignature: currentEmbeddingSignature()! }),
onProgress: ({ embedded, chunksProcessed, cursor }) => {
// Fire-and-forget; updateProgress returns a Promise but the
// handler is sync inside the loop.
diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.ts
index d33408a639..293b19fa6d 100644
--- a/src/core/ops/embedding-migration.ts
+++ b/src/core/ops/embedding-migration.ts
@@ -1,10 +1,13 @@
/**
- * Embedding-migration operation cluster — pure move from operations.ts
+ * Embedding-migration operation cluster — peeled from operations.ts
* (v0.46.x tranche 3): the #3390 provider-agnostic migrate_embeddings
- * local-only admin op. Op const stays module-private;
- * `embeddingMigrationOperations` below is spliced into the canonical
- * `operations` array in ../operations.ts at the cluster's original position.
- * Never import from '../operations.ts' here (cycle).
+ * local-only admin op, consuming the SAME orchestrator as the CLI
+ * (planMigrationFlow/executeMigrationFlow — locks, retarget gate,
+ * DB-verified skip, reranker companion, heartbeat, completion bookkeeping
+ * are identical on both surfaces by construction). Op const stays
+ * module-private; `embeddingMigrationOperations` below is spliced into the
+ * canonical `operations` array in ../operations.ts at the cluster's
+ * original position. Never import from '../operations.ts' here (cycle).
*/
import type { Operation } from './contract.ts';
@@ -19,6 +22,9 @@ const migrate_embeddings: Operation = {
dim: { type: 'number', description: "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none." },
dry_run: { type: 'boolean', description: 'Plan + cost estimate only; change nothing.' },
yes: { type: 'boolean', description: 'Confirm the re-embed spend + destructive schema change. Required for a live run.' },
+ force_sunset_target: { type: 'boolean', description: 'Allow migrating ONTO a provider with an announced shutdown (self-hosted wire-compatible endpoints).' },
+ retarget: { type: 'boolean', description: 'Abandon a DIFFERENT in-flight migration target and start this one (the abandoned target is recorded in the marker history).' },
+ reranker: { type: 'string', description: 'Reranker companion action: auto (default), off, keep, or an explicit provider:model (e.g. voyage:rerank-2.5). Reranker config lives on the DB plane.' },
},
mutating: true,
scope: 'admin',
@@ -31,64 +37,65 @@ const migrate_embeddings: Operation = {
if (ctx.remote !== false) {
throw new Error('migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.');
}
- const {
- planEmbeddingMigration, applyEmbeddingMigration, completeEmbeddingMigration,
- reconcilePageSignatures, migrationSignature,
- } = await import('../embedding-migration.ts');
+ // ONE shared orchestrator with the CLI (round-2 #11): locks, retarget
+ // gate, DB-verified skip, heartbeat, and completion bookkeeping are
+ // identical on both surfaces by construction.
+ const { planMigrationFlow, executeMigrationFlow } = await import('../../commands/migrate-embeddings.ts');
const to = p.to as string;
const dim = p.dim as number | undefined;
- let fromModel: string | undefined;
- let fromDims: number | undefined;
- try {
- const { getEmbeddingModel, getEmbeddingDimensions } = await import('../ai/gateway.ts');
- fromModel = getEmbeddingModel();
- fromDims = getEmbeddingDimensions();
- } catch { /* gateway unconfigured — plan falls back to defaults */ }
- const plan = await planEmbeddingMigration(ctx.engine, {
+ const planCtx = await planMigrationFlow(ctx.engine, {
to,
...(dim !== undefined && { dim }),
- ...(fromModel !== undefined && { fromModel }),
- ...(fromDims !== undefined && { fromDims }),
+ ...(p.force_sunset_target === true && { forceSunsetTarget: true }),
+ ...(typeof p.reranker === 'string' && { reranker: p.reranker }),
});
+ const plan = planCtx.plan;
+ // Different-target in-flight marker: the retarget decision precedes any
+ // skip (mirrors the CLI ordering exactly — shared-orchestrator parity).
+ if (planCtx.inflightOther && p.retarget !== true && p.dry_run !== true && !ctx.dryRun) {
+ return { status: 'refused', reason: 'retarget_required', inflight: planCtx.inflightOther, plan };
+ }
+ if (planCtx.verify.complete && !planCtx.inflightOther && planCtx.rerankerPlan.action.kind === 'none') {
+ return { status: 'skipped_no_work', plan, verified: planCtx.verify };
+ }
if (ctx.dryRun || p.dry_run === true || p.yes !== true) {
- return { status: p.yes === true || p.dry_run === true ? 'planned' : 'needs_confirmation', plan };
+ return {
+ status: p.yes === true || p.dry_run === true ? 'planned' : 'needs_confirmation',
+ plan,
+ verified: planCtx.verify,
+ };
}
- const { persistEmbeddingFileConfig, probeTargetProvider } = await import('../../commands/migrate-embeddings.ts');
- // Safety parity with the CLI path: probe the target provider BEFORE any
- // mutation. Without this, `yes:true` would drop the embedding column and
- // only then discover the key/model/dim is wrong.
- const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
- if (!probe.ok) return { status: 'failed', reason: probe.message, plan };
- const applied = await applyEmbeddingMigration(ctx.engine, plan, {
- persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
- });
- if (applied.status !== 'applied') return { ...applied, plan };
- const { runEmbedCore } = await import('../../commands/embed.ts');
- // singleFlight parity with the CLI path: takes the same per-source
- // embed-backfill lock so this can't race a queued embed-backfill job on
- // the NULL→non-NULL upsert (the TODOS:2299 class).
- const embedResult = await runEmbedCore(ctx.engine, {
- stale: true, catchUp: true, singleFlight: true, includeNullSignature: true, quiet: true,
- });
- // Stamp batch-boundary pages before probing for completion (see
- // reconcilePageSignatures — the embed loop's all-or-nothing stamp rule
- // skips any page split across two stale batches).
- const reconciled = await reconcilePageSignatures(ctx.engine, plan);
- const remaining = await ctx.engine.countStaleChunks({
- signature: migrationSignature(plan.to_model, plan.to_dims),
- includeNullSignature: true,
+ const result = await executeMigrationFlow(ctx.engine, planCtx, {
+ to,
+ ...(dim !== undefined && { dim }),
+ ...(p.force_sunset_target === true && { forceSunsetTarget: true }),
+ ...(p.retarget === true && { retarget: true }),
+ ...(typeof p.reranker === 'string' && { reranker: p.reranker }),
+ quiet: true,
});
- if (remaining === 0) await completeEmbeddingMigration(ctx.engine, plan);
- return {
- status: remaining === 0 ? 'completed' : 'incomplete',
- plan,
- embedded: embedResult.embedded,
- remaining,
- signatures_reconciled: reconciled,
- invalidated: applied.invalidated,
- schema_transitioned: applied.schema_transitioned,
- cache_cleared: applied.cache_cleared,
- };
+ // Flatten the orchestrator's tagged union into the op's historical shape:
+ // failures carry a `reason`, refusals carry `status:'refused'` + a reason
+ // discriminator (the env refusal keeps its pre-orchestrator spelling so
+ // existing consumers keying on reason:'env_override' still match).
+ if (result.status === 'probe_failed') return { status: 'failed', reason: result.message, plan };
+ if (result.status === 'apply_failed') return { status: 'failed', reason: result.reason, plan };
+ // A held lock keeps its discriminator (holder: migration vs embed_backfill)
+ // — remote callers need it to pick the right remediation, same as the CLI.
+ if (result.status === 'locked') {
+ return { status: 'locked', holder: result.holder, detail: result.detail, plan };
+ }
+ if (result.status === 'refused_env') {
+ return { status: 'refused', reason: 'env_override', warning: result.warning, plan };
+ }
+ if (result.status === 'refused_retarget') {
+ return {
+ status: 'refused',
+ reason: 'retarget_required',
+ inflight: result.inflight,
+ plan,
+ };
+ }
+ return { ...result, plan };
},
cliHints: { name: 'migrate-embeddings', hidden: true },
};
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 9d04385f51..c645c8ded9 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2936,11 +2936,14 @@ export class PGLiteEngine implements BrainEngine {
const source = sourceIds ?? opts?.sourceId ?? 'default';
// #2544: explicit non-vector column list — rowToChunk discards embeddings
// at this call site, so `cc.*` shipped every vector only to be thrown away.
+ // embedding_is_null: boolean truth of the stored vector (a schema rebuild
+ // NULLs vectors without touching embedded_at).
const { rows } = await this.db.query(
`SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
cc.model, cc.token_count, cc.embedded_at, cc.language,
cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,
- cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality
+ cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,
+ (cc.embedding IS NULL) AS embedding_is_null
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
WHERE p.slug = $1 AND ${sourceIds ? 'p.source_id = ANY($2::text[])' : 'p.source_id = $2'}
@@ -5068,7 +5071,10 @@ export class PGLiteEngine implements BrainEngine {
-- v0.26.5: exclude soft-deleted from page_count (mirrors postgres-engine).
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
(SELECT count(*) FROM content_chunks) as chunk_count,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL) as embedded_count,
+ -- Keyed on the stored VECTOR, not embedded_at (parity with
+ -- postgres-engine): a schema rebuild NULLs every vector without
+ -- touching embedded_at.
+ (SELECT count(*) FROM content_chunks WHERE embedding IS NOT NULL) as embedded_count,
(SELECT count(*) FROM links) as link_count,
(SELECT count(DISTINCT tag) FROM tags) as tag_count,
(SELECT count(*) FROM timeline_entries) as timeline_entry_count
@@ -5109,8 +5115,18 @@ export class PGLiteEngine implements BrainEngine {
)
SELECT
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
- GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
+ -- Parity with postgres-engine: stored-VECTOR truth over ELIGIBLE
+ -- chunks (embedding, not embedded_at; embed_skip excluded from BOTH
+ -- sides; zero eligible = vacuous 100%).
+ (SELECT CASE
+ WHEN count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')) = 0
+ THEN 1.0
+ ELSE count(*) FILTER (WHERE cc.embedding IS NOT NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ / count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ END
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id) as embed_coverage,
0 as stale_pages,
-- Bug 11 — orphan = islanded (no inbound AND no outbound). The raw
-- list is filtered in TS using the shared orphan-reporting policy.
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2086cd9f23..5f0893b1e7 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2789,11 +2789,14 @@ export class PostgresEngine implements BrainEngine {
// #2544: explicit non-vector column list — rowToChunk discards
// embeddings at this call site (includeEmbedding defaults false), so
// `cc.*` shipped every vector over the wire only to be thrown away.
+ // embedding_is_null: boolean truth of the stored vector (a schema
+ // rebuild NULLs vectors without touching embedded_at).
const rows = await tx`
SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
cc.model, cc.token_count, cc.embedded_at, cc.language,
cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,
- cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality
+ cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,
+ (cc.embedding IS NULL) AS embedding_is_null
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
WHERE p.slug = ${slug} AND ${scope}
@@ -4973,7 +4976,10 @@ export class PostgresEngine implements BrainEngine {
-- storage until the autopilot purge phase runs.
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
(SELECT count(*) FROM content_chunks) as chunk_count,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL) as embedded_count,
+ -- Keyed on the stored VECTOR, not embedded_at: a schema rebuild NULLs
+ -- every vector without touching embedded_at, and this count must not
+ -- report a dark column as embedded.
+ (SELECT count(*) FROM content_chunks WHERE embedding IS NOT NULL) as embedded_count,
(SELECT count(*) FROM links) as link_count,
(SELECT count(DISTINCT tag) FROM tags) as tag_count,
(SELECT count(*) FROM timeline_entries) as timeline_entry_count
@@ -5014,8 +5020,20 @@ export class PostgresEngine implements BrainEngine {
)
SELECT
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
- GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
+ -- Coverage is the stored-VECTOR truth over ELIGIBLE chunks: keyed on
+ -- embedding (not embedded_at, which a schema rebuild leaves stale) and
+ -- excluding embed_skip pages from BOTH sides so a brain with zero
+ -- remediable work can't read as under-covered. Zero eligible chunks =
+ -- vacuous 100%, matching missing_embeddings' exclusion below.
+ (SELECT CASE
+ WHEN count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')) = 0
+ THEN 1.0
+ ELSE count(*) FILTER (WHERE cc.embedding IS NOT NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ / count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ END
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id) as embed_coverage,
0 as stale_pages,
0 as orphan_pages,
(SELECT count(*) FROM links l
diff --git a/src/core/remediation/context.ts b/src/core/remediation/context.ts
index 1fe8ae651a..59f93fc5ee 100644
--- a/src/core/remediation/context.ts
+++ b/src/core/remediation/context.ts
@@ -62,11 +62,29 @@ export async function loadRecommendationContext(
const fromCfg = cfgField ? (fileCfg as Record<string, unknown> | null)?.[cfgField] : undefined;
return !!(process.env[envVar] || fromCfg);
});
+ // D12: NULL-signature cohort (embedded chunks on pages with no recorded
+ // embedding signature — pre-v108 or never stamped). computeRecommendations
+ // is sync/engine-less, so the ENGINE-holding upstream probes it and threads
+ // it through the context. Fail OPEN to 0: a probe bug must never kill
+ // remediation (it just falls back to the plain stale run).
+ let nullSignatureCohort = 0;
+ try {
+ const { currentEmbeddingSignature } = await import('../embedding.ts');
+ const sig = currentEmbeddingSignature();
+ if (sig) {
+ const wide = await engine.countStaleChunks({ signature: sig, includeNullSignature: true });
+ const narrow = await engine.countStaleChunks({ signature: sig });
+ nullSignatureCohort = Math.max(0, wide - narrow);
+ }
+ } catch {
+ nullSignatureCohort = 0;
+ }
return {
repoPath: repoPath ?? undefined,
embeddingModel,
embeddingDimensions,
embeddingProviderConfigured: embeddingConfigured,
hasChatApiKey: !!(process.env.ANTHROPIC_API_KEY || fileCfg?.anthropic_api_key),
+ nullSignatureCohort,
};
}
diff --git a/src/core/retrieval-upgrade-planner.ts b/src/core/retrieval-upgrade-planner.ts
index 1edce6522b..670bc14ba0 100644
--- a/src/core/retrieval-upgrade-planner.ts
+++ b/src/core/retrieval-upgrade-planner.ts
@@ -63,7 +63,19 @@ import type { BrainEngine } from './engine.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import { lookupEmbeddingPrice, estimateCostFromChars } from './embedding-pricing.ts';
import { computeReembedEstimate } from './post-upgrade-reembed.ts';
-import { hnswIndexExpected } from './vector-index.ts';
+import {
+ detectEnvOverride,
+ formatEnvOverrideWarning,
+ runSchemaTransition,
+ type EnvOverrideWarning,
+} from './embedding-migration.ts';
+import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';
+
+// Back-compat re-exports: these primitives moved to embedding-migration.ts
+// (the v0.47 survivor module) so the ZE removal wave can delete this file
+// wholesale. Existing importers (ze-switch, tests) keep working until then.
+export { detectEnvOverride, formatEnvOverrideWarning, runSchemaTransition };
+export type { EnvOverrideWarning };
// ============================================================================
// Constants
@@ -147,78 +159,6 @@ export type ApplyResult =
| { status: 'refused'; plan: RetrievalUpgradeState; reason: 'env_override'; warning: EnvOverrideWarning }
| { status: 'failed'; plan: RetrievalUpgradeState; reason: string };
-/**
- * v0.41.2.1 — env-override safety gate.
- *
- * `process.env.GBRAIN_EMBEDDING_MODEL` and `GBRAIN_EMBEDDING_DIMENSIONS`
- * win over DB+file config in `loadConfig()`. The 716K-chunk damage
- * incident (PR #1421) shipped because ze-switch wrote DB config but
- * the env override silently kept the old model active at embed time —
- * schema migrated to 2560d while embeds still produced 1536d vectors.
- *
- * detectEnvOverride is a pure read of process.env (or an injected env
- * for tests). triggered:true means refusal is required unless the
- * caller passes ignoreEnvOverride:true (mirrors --ignore-missing-key).
- */
-export interface EnvOverrideWarning {
- triggered: boolean;
- vars: Array<{ name: string; current: string; target: string }>;
-}
-
-export function detectEnvOverride(
- targetModel: string,
- targetDim: number,
- env: NodeJS.ProcessEnv = process.env,
-): EnvOverrideWarning {
- const vars: EnvOverrideWarning['vars'] = [];
- const envModel = env.GBRAIN_EMBEDDING_MODEL?.trim();
- if (envModel && envModel !== targetModel) {
- vars.push({ name: 'GBRAIN_EMBEDDING_MODEL', current: envModel, target: targetModel });
- }
- const envDimRaw = env.GBRAIN_EMBEDDING_DIMENSIONS?.trim();
- if (envDimRaw) {
- const envDim = Number(envDimRaw);
- if (!Number.isFinite(envDim) || envDim !== targetDim) {
- vars.push({
- name: 'GBRAIN_EMBEDDING_DIMENSIONS',
- current: envDimRaw,
- target: String(targetDim),
- });
- }
- }
- return { triggered: vars.length > 0, vars };
-}
-
-/**
- * ASCII box rendering (repo convention D10 v0.22.11 — no Unicode box
- * drawing). Pure function; CLI calls this and writes to stderr.
- * Line width <= 78 cols for safe rendering in any terminal or log
- * aggregator.
- */
-export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {
- const lines: string[] = [];
- lines.push('+----------------------------------------------------------------------------+');
- lines.push('| ENV OVERRIDE DETECTED - ACTION REQUIRED |');
- lines.push('+----------------------------------------------------------------------------+');
- for (const v of w.vars) {
- lines.push(`| ${v.name} is set in your environment:`.padEnd(77) + '|');
- lines.push(`| Current env: ${v.current}`.padEnd(77) + '|');
- lines.push(`| Switch target: ${v.target}`.padEnd(77) + '|');
- lines.push('| |');
- }
- lines.push('| The env var takes HIGHEST PRECEDENCE and will override this switch. |');
- lines.push('| Update your .env file or shell environment before retrying: |');
- lines.push('| |');
- const unsetCmd = ` unset ${w.vars.map(v => v.name).join(' ')}`;
- // Match the other content-line pattern: `|` + 76 chars + `|` = 78 total.
- lines.push(`|${unsetCmd.padEnd(76)}|`);
- lines.push('| |');
- lines.push('| Without this change, the switch has NO EFFECT at runtime. |');
- lines.push('| Pass --ignore-env-override to apply anyway (advanced; you know why). |');
- lines.push('+----------------------------------------------------------------------------+');
- return lines.join('\n');
-}
-
/**
* v0.41.2.1 — Apply/resume opts. ignoreEnvOverride mirrors the existing
* --ignore-missing-key precedent in the same command surface.
@@ -468,10 +408,15 @@ export async function resumeRetrievalUpgrade(
// requested=true, applied=false. Either schema is at target and config
// still says source, or schema crashed mid-DDL. Re-run schema transition
- // (idempotent via CREATE INDEX IF NOT EXISTS + ALTER COLUMN no-op semantics)
// then write config + mark applied.
try {
- await runSchemaTransition(engine, targetDim);
+ // Width guard: the transition is DROP COLUMN + ADD COLUMN — a same-width
+ // re-run still DELETES every stored vector. Resume must only rebuild when
+ // the column genuinely isn't at the target width yet.
+ const col = await readContentChunksEmbeddingDim(engine);
+ if (col.dims !== targetDim) {
+ await runSchemaTransition(engine, targetDim);
+ }
await engine.setConfig('embedding_model', ZE_TARGET_EMBEDDING_MODEL);
await engine.setConfig('embedding_dimensions', String(targetDim));
await engine.setConfig('search.reranker.enabled', 'true');
@@ -514,7 +459,12 @@ export async function undoRetrievalUpgrade(engine: BrainEngine): Promise<
}
try {
- await runSchemaTransition(engine, snapshot.embedding_dimensions);
+ // Width guard (mirrors resume): a same-width DROP+ADD still deletes every
+ // vector — only rebuild when the column isn't at the snapshot width.
+ const col = await readContentChunksEmbeddingDim(engine);
+ if (col.dims !== snapshot.embedding_dimensions) {
+ await runSchemaTransition(engine, snapshot.embedding_dimensions);
+ }
await engine.setConfig('embedding_model', snapshot.embedding_model);
await engine.setConfig('embedding_dimensions', String(snapshot.embedding_dimensions));
await engine.setConfig('search.reranker.enabled', snapshot.search_reranker_enabled ? 'true' : 'false');
@@ -536,159 +486,11 @@ export async function undoRetrievalUpgrade(engine: BrainEngine): Promise<
}
// ============================================================================
-// Schema transition (D18)
+// Schema transition — MOVED to embedding-migration.ts (re-exported above).
+// This file is deleted wholesale in the v0.47 ZE removal wave; the survivor
+// module owns the DDL now.
// ============================================================================
-/**
- * The atomic DROP + ALTER + CREATE INDEX sequence for content_chunks.
- * Both engines accept identical SQL (PGLite uses pgvector via WASM, same
- * grammar). Wrapped in engine.transaction so a partial failure rolls back.
- *
- * Index names verified against:
- * src/schema.sql:163 -> idx_chunks_embedding
- * src/core/pglite-schema.ts:127 -> idx_chunks_embedding
- * src/schema.sql:169 -> idx_chunks_embedding_image
- * src/core/pglite-schema.ts:130 -> idx_chunks_embedding_image
- *
- * IF NOT EXISTS on CREATE INDEX makes the operation safe to re-run during
- * `--resume`.
- *
- * Exported (#3390) so the provider-agnostic embedding migration
- * (src/core/embedding-migration.ts) reuses the SAME dimension-transition
- * path instead of duplicating the DDL sequence.
- */
-export async function runSchemaTransition(engine: BrainEngine, targetDim: number): Promise<void> {
- // v0.41 fix: only transition the primary text embedding column.
- // The embedding_image (v0.27.1) and embedding_multimodal (v0.36 / migration
- // v78) columns use SEPARATE multimodal models (e.g. voyage-multimodal-3 at
- // 1024d) whose dimensions are independent of the text embedding model.
- // Dropping and recreating either at targetDim silently breaks multimodal
- // search by creating a dimension mismatch between the column and the
- // multimodal provider's output.
- //
- // Before this fix, switching text embeddings from OpenAI (1536d) to
- // ZeroEntropy (1280d) would also change embedding_image from 1024d to
- // 1280d, making voyage-multimodal-3 unable to write to it. The same
- // class of bug applies to embedding_multimodal — leave both untouched.
- await engine.transaction(async (tx) => {
- // Text embedding column — transition to target dim.
- await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);
- await tx.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
- await tx.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(${targetDim})`);
- await tx.executeRaw(
- `CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)`,
- );
-
- // Image/multimodal embedding column — rebuild index but preserve
- // existing dimension. Only create it if it doesn't already exist
- // (fresh brains may not have it yet). Partial WHERE clause matches
- // schema.sql:258-260 and pglite-schema.ts:198-200: HNSW footprint
- // scales with image-chunk count, not table size.
- const hasImageCol = await tx.executeRaw<{ exists: boolean }>(
- `SELECT EXISTS (
- SELECT 1 FROM information_schema.columns
- WHERE table_schema = 'public'
- AND table_name = 'content_chunks'
- AND column_name = 'embedding_image'
- ) AS exists`,
- );
- if (hasImageCol[0]?.exists) {
- await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding_image`);
- await tx.executeRaw(
- `CREATE INDEX IF NOT EXISTS idx_chunks_embedding_image
- ON content_chunks USING hnsw (embedding_image vector_cosine_ops)
- WHERE embedding_image IS NOT NULL`,
- );
- }
-
- // #3390: the OTHER two dim-pinned columns that carry TEXT-embedding-space
- // vectors. Both are created at brain-birth width (migrate.ts v55 for
- // query_cache, v42 for facts) and NO migration ever ALTERs them, so before
- // this fix a dimension change left them at the old width:
- // - query_cache.embedding stayed narrow → every store() AND lookup()
- // silently swallowed the width error (by design, so the cache can
- // never break search), i.e. a PERMANENT 0% hit rate.
- // - facts.embedding stayed narrow → every per-fact embed write failed
- // ($N::vector into the old width), and the doctor check that would
- // warn is skipped on PGLite (the DEFAULT engine).
- // Both are text-embedding-space columns, so they MUST move with
- // content_chunks.embedding. The image/multimodal columns above are the
- // deliberate exception (separate models, independent dims).
- for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
- await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, targetDim);
- }
- });
-}
-
-/**
- * The dim-pinned TEXT-embedding-space columns outside content_chunks.
- * `indexSql` is a factory because each table's index carries its own partial
- * WHERE clause + opclass, and the opclass must match the column TYPE
- * (vector_cosine_ops vs halfvec_cosine_ops).
- */
-const TEXT_EMBEDDING_DIM_PINNED_TABLES: ReadonlyArray<{
- table: string;
- index: string;
- indexSql: (opclass: string) => string;
-}> = [
- {
- table: 'query_cache',
- index: 'idx_query_cache_embedding_hnsw',
- indexSql: (opclass) =>
- `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
- ON query_cache USING hnsw (embedding ${opclass})
- WHERE embedding IS NOT NULL`,
- },
- {
- table: 'facts',
- index: 'idx_facts_embedding_hnsw',
- indexSql: (opclass) =>
- `CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
- ON facts USING hnsw (embedding ${opclass})
- WHERE embedding IS NOT NULL AND expired_at IS NULL`,
- },
-];
-
-/**
- * Rebuild one dim-pinned embedding column at `targetDim`, PRESERVING its
- * existing column type (`vector` vs `halfvec` — migrate.ts picks halfvec when
- * the server supports it, and the HNSW opclass must match). No-op when the
- * table or column doesn't exist (fresh/older brains).
- *
- * Dropping the column discards the stored vectors, which is correct: they are
- * in the OLD embedding space and unusable after the swap. query_cache is a
- * cache (refills on the next query); facts re-embed on their next write /
- * `gbrain extract` pass.
- */
-async function transitionDimPinnedColumn(
- tx: { executeRaw: <T = unknown>(sql: string, params?: unknown[]) => Promise<T[]> },
- table: string,
- indexName: string,
- indexSql: (opclass: string) => string,
- targetDim: number,
-): Promise<void> {
- const probe = await tx.executeRaw<{ udt_name: string | null }>(
- `SELECT udt_name FROM information_schema.columns
- WHERE table_schema = 'public' AND table_name = $1 AND column_name = 'embedding'`,
- [table],
- );
- const udt = probe[0]?.udt_name;
- if (!udt) return; // table or column absent — nothing to transition
- // Preserve the column type; anything unexpected falls back to `vector`.
- const columnType: 'vector' | 'halfvec' = udt.toLowerCase() === 'halfvec' ? 'halfvec' : 'vector';
- const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
-
- await tx.executeRaw(`DROP INDEX IF EXISTS ${indexName}`);
- await tx.executeRaw(`ALTER TABLE ${table} DROP COLUMN IF EXISTS embedding`);
- await tx.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding ${columnType}(${targetDim})`);
- // HNSW has a per-type dimension ceiling; above it pgvector refuses the
- // index and exact scans remain the (correct, slower) path. Mirrors the
- // same guard in migrate.ts's original DDL.
- if (hnswIndexExpected(columnType, targetDim)) {
- await tx.executeRaw(indexSql(opclass));
- }
-}
-
// ============================================================================
// Helpers
// ============================================================================
diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.ts
index 1a3c3e0c9b..246a7661d0 100644
--- a/src/core/sync-cost-gate.ts
+++ b/src/core/sync-cost-gate.ts
@@ -400,7 +400,10 @@ export async function runInlineCostGate(
// never blocks the sync. Signature-aware (model/dims swap surfaces here).
let staleChars = 0;
try {
- staleChars = await engine.sumStaleChunkChars({ signature: currentEmbeddingSignature() });
+ // D9: signature is null when the gateway is unconfigured — fall back to
+ // NULL-embedding-only staleness rather than filtering on a bogus stamp.
+ const staleSig = currentEmbeddingSignature();
+ staleChars = await engine.sumStaleChunkChars(staleSig ? { signature: staleSig } : {});
} catch {
staleChars = 0;
}
diff --git a/src/core/types.ts b/src/core/types.ts
index 40ec978a53..2a59afae0c 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -602,6 +602,13 @@ export interface Chunk {
* image search arm.
*/
modality?: 'text' | 'image';
+ /**
+ * True when the stored vector is NULL. Cheap boolean (no vector egress) so
+ * non-embedding readers can tell "vector missing" apart from `embedded_at`,
+ * which a schema rebuild leaves stale. Present only on paths that select it
+ * (getChunks).
+ */
+ embedding_is_null?: boolean;
}
/**
diff --git a/src/core/utils.ts b/src/core/utils.ts
index 09d4eb6324..a51e0a014a 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -337,6 +337,9 @@ export function rowToChunk(row: Record<string, unknown>, includeEmbedding = fals
doc_comment: (row.doc_comment as string | null | undefined) ?? null,
symbol_name_qualified: (row.symbol_name_qualified as string | null | undefined) ?? null,
modality: (row.modality as 'text' | 'image' | undefined) ?? undefined,
+ // Only present when the SELECT included it (getChunks); undefined elsewhere
+ // so callers can tell "not selected" from "vector present".
+ ...(row.embedding_is_null !== undefined && { embedding_is_null: Boolean(row.embedding_is_null) }),
};
}
diff --git a/src/core/ze-exposure.ts b/src/core/ze-exposure.ts
index 144533370c..1e800d3738 100644
--- a/src/core/ze-exposure.ts
+++ b/src/core/ze-exposure.ts
@@ -37,6 +37,7 @@ import {
NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
NEW_INSTALL_DEFAULT_RERANKER_MODEL,
+ renderCanonicalMigrationCommands,
} from './ai/defaults.ts';
import { lookupEmbeddingPrice } from './embedding-pricing.ts';
@@ -282,10 +283,7 @@ export function renderZeActionRequired(exposure: ZeExposure): string {
? ` (${exposure.blastRadius.embeddedChunksCapped ? 'at least ' : ''}~$${exposure.blastRadius.estReembedUsd.toFixed(2)} to re-embed with ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL})`
: ''),
);
- lines.push(
- `Fix: gbrain migrate embeddings --to ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL} ` +
- `--dim ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS} --dry-run`,
- );
+ lines.push(`Fix: ${renderCanonicalMigrationCommands().recommendedDryRun}`);
lines.push(
` (Voyage's valid widths are 256/512/1024/2048 — legacy default brains are ` +
`1280d and get a one-time rebuild to ${NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS}.`,
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 4ed9120b79..a44ca760f4 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.9.1 -->
+<!-- gbrain-template-stamp: 0.46.10.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/brain-score-recommendations.test.ts b/test/brain-score-recommendations.test.ts
index 97891928fa..d4687e6595 100644
--- a/test/brain-score-recommendations.test.ts
+++ b/test/brain-score-recommendations.test.ts
@@ -344,3 +344,37 @@ describe('estimateAnthropicCost', () => {
expect(cost).toBeGreaterThan(0);
});
});
+
+describe('D12 — NULL-signature cohort widens embed.stale', () => {
+ const makeHealth = (over: Partial<import('../src/core/types.ts').BrainHealth> = {}) => ({
+ page_count: 100, embed_coverage: 1, stale_pages: 0, orphan_pages: 0,
+ dead_links: 0, missing_embeddings: 0, link_count: 50, link_coverage: 1,
+ timeline_coverage: 1, most_connected: [], brain_score: 90,
+ ...over,
+ }) as import('../src/core/types.ts').BrainHealth;
+
+ test('cohort > 0 with zero missing embeddings still fires embed.stale, widened + costed', () => {
+ const recs = computeRecommendations(makeHealth(), {
+ embeddingModel: 'openai:text-embedding-3-small',
+ embeddingDimensions: 1536,
+ embeddingProviderConfigured: true,
+ nullSignatureCohort: 563,
+ });
+ const rec = recs.find((r) => r.id === 'embed.stale');
+ expect(rec).toBeDefined();
+ expect((rec!.params as { includeNullSignature?: boolean }).includeNullSignature).toBe(true);
+ expect(rec!.est_usd_cost).toBeGreaterThan(0); // the cohort is real spend
+ expect(rec!.rationale).toContain('563');
+ expect(rec!.rationale).toContain('no recorded embedding signature');
+ });
+
+ test('no cohort ⇒ params unchanged (no includeNullSignature key, idempotency stable)', () => {
+ const recs = computeRecommendations(makeHealth({ missing_embeddings: 10 }), {
+ embeddingModel: 'openai:text-embedding-3-small',
+ embeddingDimensions: 1536,
+ embeddingProviderConfigured: true,
+ });
+ const rec = recs.find((r) => r.id === 'embed.stale')!;
+ expect('includeNullSignature' in (rec.params as Record<string, unknown>)).toBe(false);
+ });
+});
diff --git a/test/canonical-migration-command.test.ts b/test/canonical-migration-command.test.ts
new file mode 100644
index 0000000000..16177a6ec3
--- /dev/null
+++ b/test/canonical-migration-command.test.ts
@@ -0,0 +1,165 @@
+/**
+ * ONE canonical migration command everywhere (D5). Before this, five warning
+ * surfaces printed five different commands — including an unsubstituted
+ * `<provider:model>` placeholder and a `--dim 1280` that Voyage rejects
+ * (valid widths: 256/512/1024/2048).
+ *
+ * 1. Renderer contract: always `--dim 1024` on the Voyage line; keep-width
+ * OpenAI alternative only when the current width allows it (<= 1536);
+ * rebuild note only when the width actually changes.
+ * 2. Source sweep: every `--to voyage:voyage-4` literal in src/ carries
+ * `--dim 1024` on the same line; no `<provider:model>` placeholder
+ * command survives anywhere in src/.
+ * 3. Every sunset-warning surface consumes the renderer.
+ *
+ * The docs/skills sweep (same pairing rule over *.md) lives with the docs
+ * wave commit — see the docs assertions appended there.
+ */
+import { describe, test, expect } from 'bun:test';
+import { readFileSync, readdirSync, statSync } from 'fs';
+import { join } from 'path';
+import { renderCanonicalMigrationCommands } from '../src/core/ai/defaults.ts';
+
+function walk(dir: string, out: string[] = []): string[] {
+ for (const name of readdirSync(dir)) {
+ const p = join(dir, name);
+ const st = statSync(p);
+ if (st.isDirectory()) walk(p, out);
+ else if (p.endsWith('.ts') && !p.endsWith('.generated.ts')) out.push(p);
+ }
+ return out;
+}
+
+const SRC = join(import.meta.dir, '..', 'src');
+
+describe('canonical migration command (single home: ai/defaults.ts)', () => {
+ test('renderer contract', () => {
+ const bare = renderCanonicalMigrationCommands();
+ expect(bare.recommended).toBe('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
+ expect(bare.recommendedDryRun).toBe('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run');
+ expect(bare.openaiAlternative).toBeNull();
+ expect(bare.note).toBeNull();
+
+ const legacy = renderCanonicalMigrationCommands({ colDims: 1280 });
+ expect(legacy.recommendedDryRun).toContain('--dim 1024');
+ expect(legacy.note).toContain('256/512/1024/2048');
+ expect(legacy.openaiAlternative).toBe('gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --dry-run');
+
+ const already = renderCanonicalMigrationCommands({ colDims: 1024 });
+ expect(already.note).toBeNull();
+
+ const wide = renderCanonicalMigrationCommands({ colDims: 3072 });
+ expect(wide.openaiAlternative).toBeNull(); // 3-small caps at 1536
+ expect(wide.note).toContain('3072');
+ });
+
+ test('src sweep: every voyage migrate command carries --dim 1024; no placeholder commands', () => {
+ const offenders: string[] = [];
+ const placeholders: string[] = [];
+ for (const file of walk(SRC)) {
+ const text = readFileSync(file, 'utf-8');
+ const lines = text.split('\n');
+ lines.forEach((line, i) => {
+ if (line.includes('--to voyage:voyage-4') && !line.includes('--dim 1024')) {
+ // Allow pure prose ABOUT the flag pairing; command strings must pair.
+ if (line.includes('migrate embeddings')) offenders.push(`${file}:${i + 1}`);
+ }
+ // The stage-1 booby-trap shape: an unsubstituted placeholder RECOMMENDED
+ // with a concrete width (`--to <provider:model> --dim 1280`). Generic
+ // usage/help syntax (`--to <provider:model> [--dim N]`) is legitimate.
+ if (/migrate embeddings --to <provider:model>.*--dim \d/.test(line)) {
+ placeholders.push(`${file}:${i + 1}`);
+ }
+ });
+ }
+ expect(offenders).toEqual([]);
+ expect(placeholders).toEqual([]);
+ });
+
+ test('docs/skills sweep: every voyage migrate command in md files carries --dim 1024; no phantom flags', () => {
+ const roots = ['docs', 'skills', '.'];
+ const offenders: string[] = [];
+ const phantoms: string[] = [];
+ const seen = new Set<string>();
+ const mdWalk = (dir: string, out: string[] = []): string[] => {
+ for (const name of readdirSync(dir)) {
+ if (name === 'node_modules' || name === '.git' || name.startsWith('.gbrain')) continue;
+ const p = join(dir, name);
+ const st = statSync(p);
+ if (st.isDirectory()) {
+ if (dir === join(import.meta.dir, '..')) {
+ if (name !== 'docs' && name !== 'skills') continue; // repo root: only top-level md + docs/skills trees
+ }
+ mdWalk(p, out);
+ } else if (p.endsWith('.md')) out.push(p);
+ }
+ return out;
+ };
+ const files: string[] = [];
+ for (const r of roots) {
+ const abs = join(import.meta.dir, '..', r);
+ for (const f of r === '.' ? readdirSync(abs).filter((n) => n.endsWith('.md')).map((n) => join(abs, n)) : mdWalk(abs)) {
+ if (!seen.has(f)) { seen.add(f); files.push(f); }
+ }
+ }
+ for (const file of files) {
+ // CHANGELOG is an append-only historical record (entries also wrap
+ // mid-command); guidance docs are the lint target.
+ if (file.endsWith('CHANGELOG.md')) continue;
+ const lines = readFileSync(file, 'utf-8').split('\n');
+ lines.forEach((line, i) => {
+ if (line.includes('migrate embeddings') && line.includes('--to voyage:voyage-4') && !line.includes('--dim 1024')) {
+ offenders.push(`${file}:${i + 1}`);
+ }
+ // The phantom flag a doc used to prescribe.
+ if (line.includes('retrieval-upgrade') && line.includes('--reindex')) {
+ phantoms.push(`${file}:${i + 1}`);
+ }
+ });
+ }
+ expect(offenders).toEqual([]);
+ expect(phantoms).toEqual([]);
+ });
+
+ test('the ZE-sunset playbook carries the guess-killers', () => {
+ const playbook = readFileSync(join(import.meta.dir, '..', 'skills', 'migrations', 'v0.46.3.0.md'), 'utf-8');
+ // Env preflight (the incident class): named vars + unset instruction.
+ expect(playbook).toContain('GBRAIN_EMBEDDING_MODEL');
+ expect(playbook).toContain('unset GBRAIN_EMBEDDING_MODEL GBRAIN_EMBEDDING_DIMENSIONS');
+ // Status surface + recovery + exit codes.
+ expect(playbook).toContain('gbrain migrate embeddings --status');
+ expect(playbook).toContain('## Recovery');
+ expect(playbook).toContain('Exit codes');
+ // Reranker handled in the same run + the plane asymmetry explained.
+ expect(playbook).toContain('--reranker');
+ expect(playbook).toContain('plane asymmetry');
+ // The canonical command, correctly paired.
+ expect(playbook).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
+
+ // Stale playbooks carry the do-not-follow banner.
+ for (const rel of ['skills/migrations/v0.35.0.0.md', 'skills/migrations/v0.36.2.0.md']) {
+ const text = readFileSync(join(import.meta.dir, '..', rel), 'utf-8');
+ expect(text).toContain('HISTORICAL — DO NOT FOLLOW');
+ expect(text).toContain('v0.46.3.0.md');
+ }
+ });
+
+ test('every sunset-warning surface consumes the renderer', () => {
+ const consumers = [
+ 'src/core/ai/gateway.ts',
+ 'src/commands/init.ts',
+ 'src/core/advisor/collect-setup-smells.ts',
+ 'src/commands/upgrade.ts',
+ 'src/core/ze-exposure.ts',
+ 'src/commands/ze-switch.ts',
+ ];
+ for (const rel of consumers) {
+ const text = readFileSync(join(import.meta.dir, '..', rel), 'utf-8');
+ expect(text.includes('renderCanonicalMigrationCommands')).toBe(true);
+ }
+ // Doctor's consumer (checkProviderSunset) lives in the peeled checks tree;
+ // the containment convention reads the concatenated doctor surface.
+ const { doctorSource } = require('./helpers/doctor-source.ts');
+ expect(doctorSource().includes('renderCanonicalMigrationCommands')).toBe(true);
+ });
+});
diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.ts
index 86ff3accb8..745df726a7 100644
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@ -373,6 +373,21 @@ describe('applyEmbeddingMigration', () => {
{ chunk_index: 0, chunk_text: 'fghij', chunk_source: 'compiled_truth', token_count: 4 },
{ chunk_index: 1, chunk_text: 'not embedded', chunk_source: 'compiled_truth', token_count: 4 },
]);
+ // The drain stamps chunk.model with the model that actually embedded each
+ // chunk; reconcile only stamps pages whose chunks ALL carry the target
+ // model (a foreign-model chunk means the page is NOT in the new space).
+ // Mirror the post-drain state the batch-boundary shape actually leaves.
+ await engine.executeRaw(
+ `UPDATE content_chunks SET model = 'openai:text-embedding-3-small'
+ WHERE page_id IN (SELECT id FROM pages WHERE slug IN ('done','partial') AND source_id = 'default')`,
+ );
+ // 'foreign' — every chunk embedded, but by a DIFFERENT model (a non-locked
+ // writer raced the drain): must NOT get the new stamp.
+ await seedEmbedded('foreign', 'klmno', 'old:model:1');
+ await engine.executeRaw(
+ `UPDATE content_chunks SET model = 'other:writer-model'
+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'foreign' AND source_id = 'default')`,
+ );
const plan = await planEmbeddingMigration(engine, {
to: 'openai:text-embedding-3-small', dim: colDim,
@@ -382,10 +397,11 @@ describe('applyEmbeddingMigration', () => {
const sig = `openai:text-embedding-3-small:${colDim}`;
const rows = await engine.executeRaw<{ slug: string; embedding_signature: string | null }>(
- `SELECT slug, embedding_signature FROM pages WHERE slug IN ('done','partial') ORDER BY slug`,
+ `SELECT slug, embedding_signature FROM pages WHERE slug IN ('done','partial','foreign') ORDER BY slug`,
);
expect(rows.find(r => r.slug === 'done')?.embedding_signature).toBe(sig);
expect(rows.find(r => r.slug === 'partial')?.embedding_signature).toBe('old:model:1');
+ expect(rows.find(r => r.slug === 'foreign')?.embedding_signature).toBe('old:model:1');
});
test('completeEmbeddingMigration clears the state marker and stamps completion', async () => {
diff --git a/test/embedding-truth-predicates.serial.test.ts b/test/embedding-truth-predicates.serial.test.ts
new file mode 100644
index 0000000000..2ad887ebf6
--- /dev/null
+++ b/test/embedding-truth-predicates.serial.test.ts
@@ -0,0 +1,251 @@
+/**
+ * Truth-predicate pins (split-brain fix): after a schema rebuild NULLs every
+ * vector, every status surface must tell the truth even though `embedded_at`
+ * used to stay stamped.
+ *
+ * 1. Post-rebuild: getStats().embedded_count === 0,
+ * getHealth().embed_coverage === 0, missing_embeddings === all chunks,
+ * and embedded_at is cleared (post-tx hygiene batches).
+ * 2. Per-slug embed re-embeds rebuild-darkened chunks instead of the
+ * "all chunks already embedded" silent no-op (embedding_is_null).
+ * 3. getChunks exposes embedding_is_null truthfully on both engines'
+ * shared row shape (PGLite here; SQL text is parity-pinned).
+ * 4. embed_skip chunks are excluded from BOTH sides of coverage; a brain
+ * whose only chunks are embed_skip reads vacuous 100%, not 0%.
+ * 5. Nullable signature (D9 honesty): currentEmbeddingSignature() is
+ * `provider:model:dims` when the gateway resolves (same shape as
+ * migrationSignature) and null when it can't; a chunk embedded while
+ * the signature is null gets NO embedding_signature stamp, and only
+ * the includeNullSignature widening counts it stale.
+ *
+ * Named `.serial.test.ts`: installs a fake embed transport + temp
+ * GBRAIN_HOME for its whole lifecycle.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __setEmbedTransportForTests,
+ __unconfigureGatewayForTests,
+} from '../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { runSchemaTransition, migrationSignature } from '../src/core/embedding-migration.ts';
+import { currentEmbeddingSignature } from '../src/core/embedding.ts';
+import { embedStaleForSource } from '../src/core/embed-stale.ts';
+
+const DIMS = 1280;
+const PAGES = ['truth-1', 'truth-2', 'truth-3'];
+
+let engine: PGLiteEngine;
+let tmpHome: string;
+const savedEnv: Record<string, string | undefined> = {};
+let embedCalls = 0;
+
+/** File-baseline gateway config. Re-applied by the nullable-signature test
+ * after it deliberately unconfigures the gateway. */
+function configureBaselineGateway(): void {
+ configureGateway({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: DIMS,
+ env: { ZEROENTROPY_API_KEY: 'ze-test-fake' },
+ });
+}
+
+/** CRITICAL: must be re-installed after every resetGateway /
+ * __unconfigureGatewayForTests (both wipe transports) or tests hit the
+ * real embedding API. */
+function installTransport(): void {
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ embedCalls += values.length;
+ return {
+ embeddings: values.map(() => new Array(DIMS).fill(0).map((_, i) => Math.cos(i) * 0.01 + 0.002)),
+ usage: { tokens: values.length * 4 },
+ } as never;
+ });
+}
+
+beforeAll(async () => {
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'DATABASE_URL']) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-truth-pred-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: DIMS,
+ zeroentropy_api_key: 'ze-test-fake',
+ }, null, 2));
+
+ resetGateway();
+ configureBaselineGateway();
+ installTransport();
+
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: DIMS } as never);
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+describe('truth predicates survive a schema rebuild', () => {
+ test('seed: pages embedded through the real pipeline read as covered', async () => {
+ for (const slug of PAGES) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nbody of ${slug}` });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: `chunk for ${slug}`, chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+ }
+ const seeded = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(seeded.embedded).toBe(PAGES.length);
+
+ const stats = await engine.getStats();
+ expect(stats.embedded_count).toBe(PAGES.length);
+ const health = await engine.getHealth();
+ expect(health.embed_coverage).toBe(1);
+ expect(health.missing_embeddings).toBe(0);
+
+ const chunks = await engine.getChunks(PAGES[0]!);
+ expect(chunks.length).toBe(1);
+ expect(chunks[0]!.embedding_is_null).toBe(false);
+ }, 30000);
+
+ test('post-rebuild: every surface reports the dark column truthfully', async () => {
+ // Same-width rebuild — the destructive path with no dim change, the
+ // hardest case for embedded_at-keyed surfaces.
+ await runSchemaTransition(engine, DIMS);
+
+ const stats = await engine.getStats();
+ expect(stats.embedded_count).toBe(0);
+
+ const health = await engine.getHealth();
+ expect(health.embed_coverage).toBe(0);
+ expect(health.missing_embeddings).toBe(PAGES.length);
+
+ // Post-tx hygiene: embedded_at cleared in batches after the DDL commit.
+ const stale = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedded_at IS NOT NULL`,
+ );
+ expect(Number(stale[0]?.n)).toBe(0);
+
+ const chunks = await engine.getChunks(PAGES[0]!);
+ expect(chunks[0]!.embedding_is_null).toBe(true);
+ }, 30000);
+
+ test('per-slug embed re-embeds rebuild-darkened chunks (no silent no-op)', async () => {
+ // Re-stamp embedded_at WITHOUT restoring vectors — the exact residue an
+ // interrupted hygiene pass (or a pre-fix rebuild) leaves behind. The old
+ // `!c.embedded_at` filter no-ops here; embedding_is_null must not.
+ await engine.executeRaw(`UPDATE content_chunks SET embedded_at = now()`);
+ embedCalls = 0;
+
+ const result = await runEmbedCore(engine, { slugs: [PAGES[0]!], quiet: true });
+ expect(result.embedded).toBe(1);
+ expect(embedCalls).toBeGreaterThan(0);
+
+ const chunks = await engine.getChunks(PAGES[0]!);
+ expect(chunks[0]!.embedding_is_null).toBe(false);
+ }, 30000);
+
+ test('embed_skip is excluded from both sides; all-skip brain reads vacuous 100%', async () => {
+ // Mark every page embed_skip: eligible set becomes empty.
+ await engine.executeRaw(
+ `UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"embed_skip": true}'::jsonb`,
+ );
+ // Darken the vectors again so the old predicate would have read 0%.
+ await runSchemaTransition(engine, DIMS);
+
+ const health = await engine.getHealth();
+ expect(health.embed_coverage).toBe(1); // vacuous: zero eligible chunks
+ expect(health.missing_embeddings).toBe(0); // nothing remediable
+
+ // Cleanup for any later suites in this file.
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter - 'embed_skip'`);
+ }, 30000);
+});
+
+describe('nullable embedding signature (D9 honesty)', () => {
+ test('currentEmbeddingSignature: provider:model:dims when configured, null when the gateway cannot resolve', () => {
+ // Configured path: exact canonical shape, and shape-parity with
+ // migrationSignature (embedding-migration.ts documents "must match
+ // currentEmbeddingSignature()'s shape").
+ expect(currentEmbeddingSignature()).toBe('zeroentropyai:zembed-1:1280');
+ expect(currentEmbeddingSignature()).toBe(migrationSignature('zeroentropyai:zembed-1', DIMS));
+
+ // Null path: plain resetGateway() restores a CONFIGURED test baseline
+ // (the #3554 preload), so a truly-unconfigured gateway is only reachable
+ // through the sanctioned __unconfigureGatewayForTests seam. The old
+ // fallback silently claimed the OpenAI default signature here — a lie.
+ try {
+ __unconfigureGatewayForTests();
+ expect(currentEmbeddingSignature()).toBeNull();
+ } finally {
+ // __unconfigureGatewayForTests wipes transports too — restore BOTH.
+ configureBaselineGateway();
+ installTransport();
+ }
+ expect(currentEmbeddingSignature()).toBe('zeroentropyai:zembed-1:1280');
+ });
+
+ test('null-signature embed: no embedding_signature stamp; only includeNullSignature widening counts it stale', async () => {
+ // Quarantine the earlier suites' pages (currently dark from the last
+ // rebuild) so this test's stale set is exactly one page.
+ await engine.executeRaw(
+ `UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"embed_skip": true}'::jsonb`,
+ );
+ try {
+ await engine.putPage('truth-nullsig', {
+ type: 'note', title: 'truth-nullsig', compiled_truth: '# truth-nullsig\n\nnull provenance body',
+ });
+ await engine.upsertChunks('truth-nullsig', [
+ { chunk_index: 0, chunk_text: 'chunk for truth-nullsig', chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+
+ // The exact caller-level null contract: embed-backfill.ts spreads
+ // `embeddingSignature` ONLY when currentEmbeddingSignature() !== null
+ // (and embed.ts's bulk path passes `?? undefined`) — so a null
+ // signature reaches embedStaleForSource as an ABSENT option. Drive the
+ // real pipeline (gateway + fake transport) through that shape.
+ embedCalls = 0;
+ const res = await embedStaleForSource(engine, 'default', {});
+ expect(res.done).toBe(true);
+ expect(res.embedded).toBe(1);
+ expect(embedCalls).toBeGreaterThan(0);
+
+ // The vector landed...
+ const chunks = await engine.getChunks('truth-nullsig');
+ expect(chunks[0]!.embedding_is_null).toBe(false);
+ // ...but provenance stays honestly NULL (no signature, no stamp).
+ const sig = await engine.executeRaw<{ embedding_signature: string | null }>(
+ `SELECT embedding_signature FROM pages WHERE slug = 'truth-nullsig' AND source_id = 'default'`,
+ );
+ expect(sig[0]?.embedding_signature).toBeNull();
+
+ // Staleness accounting: unknown provenance is grandfathered by the
+ // narrow predicate and surfaced only by the includeNullSignature
+ // widening (the migrate-embeddings drain uses the widened form).
+ const probeSig = 'probe-provider:probe-model:999';
+ expect(await engine.countStaleChunks({ signature: probeSig, includeNullSignature: true })).toBe(1);
+ expect(await engine.countStaleChunks({ signature: probeSig })).toBe(0);
+ } finally {
+ await engine.executeRaw(
+ `UPDATE pages SET frontmatter = frontmatter - 'embed_skip' WHERE slug <> 'truth-nullsig'`,
+ );
+ }
+ }, 30000);
+});
diff --git a/test/get-page-federated-scope.test.ts b/test/get-page-federated-scope.test.ts
index dd3eae1a0a..dfbc42c3b0 100644
--- a/test/get-page-federated-scope.test.ts
+++ b/test/get-page-federated-scope.test.ts
@@ -453,8 +453,14 @@ describe('#2555 get_chunks federated scope', () => {
'parent_symbol_path', 'doc_comment', 'symbol_name_qualified', 'modality']) {
expect(body, `${enginePath} getChunks must select cc.${col}`).toContain(`cc.${col}`);
}
- // The vector columns stay unselected.
- expect(body).not.toMatch(/cc\.embedding\b/);
+ // The vector columns stay unselected. The ONE allowed reference is the
+ // cheap `(cc.embedding IS NULL) AS embedding_is_null` boolean (no vector
+ // egress — a schema rebuild NULLs vectors without touching embedded_at,
+ // and the per-slug embed filter needs the stored-vector truth). Strip
+ // that exact shape, then keep forbidding any other cc.embedding use.
+ const withoutNullBoolean = body.replace(/\(cc\.embedding IS NULL\) AS embedding_is_null/g, '');
+ expect(withoutNullBoolean).not.toMatch(/cc\.embedding\b/);
+ expect(body).toContain('(cc.embedding IS NULL) AS embedding_is_null');
}
});
});
diff --git a/test/jobs-embed-background-parity.serial.test.ts b/test/jobs-embed-background-parity.serial.test.ts
new file mode 100644
index 0000000000..1ac678c88b
--- /dev/null
+++ b/test/jobs-embed-background-parity.serial.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Background payload parity (D7): `gbrain embed --stale --catch-up
+ * --include-null-signature --batch-size N --background` used to silently
+ * DEGRADE — the CLI payload builder dropped all four flags and the `embed`
+ * handler read none of them, so the documented migration-recovery command ran
+ * as a plain 30-minute-budget stale pass with the NULL-signature grandfather
+ * clause intact. Same class as the dryRun wiring bug this file's sibling
+ * (jobs-embed-background-dryrun) pinned.
+ *
+ * 1. Behavioral: the `embed` handler honors includeNullSignature — an
+ * embedded page with NO recorded signature is re-embedded when the job
+ * data widens, and stays grandfathered when it doesn't.
+ * 2. Source pins: the payload builder serializes all four flags and the
+ * handler reads them back (the wiring the dryRun bug taught us to pin).
+ */
+import { describe, it, expect, beforeAll, afterAll, mock } from 'bun:test';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+let embedCalls = 0;
+mock.module('../src/core/embedding.ts', () => ({
+ embedBatch: async (texts: string[]) => {
+ embedCalls++;
+ return texts.map(() => new Float32Array(1536));
+ },
+ currentEmbeddingSignature: () => 'test:model:1536',
+ embedQuery: async () => new Float32Array(1536),
+}));
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+const savedKey = process.env.OPENAI_API_KEY;
+
+beforeAll(async () => {
+ // The live (non-dryRun) handler path runs the embed-creds preflight —
+ // configure a fake-keyed gateway (embedBatch itself is mocked above).
+ process.env.OPENAI_API_KEY = 'sk-parity-test-fake';
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-parity-test-fake' },
+ });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ resetGateway();
+ if (savedKey === undefined) delete process.env.OPENAI_API_KEY;
+ else process.env.OPENAI_API_KEY = savedKey;
+});
+
+async function embedHandler() {
+ const worker = new MinionWorker(engine, { concurrency: 1 });
+ await registerBuiltinHandlers(worker, engine);
+ const handler = (worker as unknown as {
+ handlers: Map<string, (j: unknown) => Promise<unknown>>;
+ }).handlers.get('embed');
+ if (!handler) throw new Error('embed handler not registered');
+ return handler;
+}
+
+function fakeJob(data: Record<string, unknown>) {
+ return {
+ id: 'job-parity-test',
+ data,
+ signal: new AbortController().signal,
+ updateProgress: async () => {},
+ };
+}
+
+describe('embed job background parity (D7)', () => {
+ it('includeNullSignature in job data widens the stale pass; absent keeps the grandfather clause', async () => {
+ // A page embedded (vectors present) with NO recorded signature — the
+ // pre-v108 cohort the grandfather clause protects.
+ await engine.putPage('parity-page', { type: 'note', title: 'parity', compiled_truth: '# p\n\nbody' });
+ await engine.upsertChunks('parity-page', [
+ { chunk_index: 0, chunk_text: 'parity chunk text', chunk_source: 'compiled_truth', token_count: 4, embedding: new Float32Array(1536) },
+ ]);
+ await engine.executeRaw(`UPDATE content_chunks SET embedded_at = now()`);
+ await engine.executeRaw(`UPDATE pages SET embedding_signature = NULL WHERE slug = 'parity-page'`);
+
+ const handler = await embedHandler();
+
+ // Without widening: grandfathered — nothing embeds.
+ embedCalls = 0;
+ await handler(fakeJob({ stale: true }));
+ expect(embedCalls).toBe(0);
+
+ // With widening: the cohort is invalidated + re-embedded.
+ embedCalls = 0;
+ await handler(fakeJob({ stale: true, includeNullSignature: true }));
+ expect(embedCalls).toBeGreaterThan(0);
+ }, 30000);
+
+ it('payload builder serializes catchUp/includeNullSignature/batchSize/priority; handler reads them', () => {
+ const embedSrc = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'embed.ts'), 'utf-8');
+ // The builder must carry all four (the dryRun bug: serialized but unread;
+ // this class: not even serialized).
+ expect(embedSrc).toContain("catchUp: cleanArgs.includes('--catch-up')");
+ expect(embedSrc).toContain("includeNullSignature: cleanArgs.includes('--include-null-signature')");
+ expect(embedSrc).toMatch(/paramBuilder[\s\S]{0,2500}batchSize/);
+ expect(embedSrc).toMatch(/paramBuilder[\s\S]{0,2500}priority/);
+
+ const jobsSrc = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'), 'utf-8');
+ expect(jobsSrc).toContain('catchUp: !!job.data.catchUp');
+ expect(jobsSrc).toContain('includeNullSignature: !!job.data.includeNullSignature');
+ expect(jobsSrc).toMatch(/'embed-catch-up'[\s\S]{0,900}includeNullSignature/);
+ });
+});
diff --git a/test/migrate-embeddings-boundary.serial.test.ts b/test/migrate-embeddings-boundary.serial.test.ts
index b24308c2b3..2d95bba634 100644
--- a/test/migrate-embeddings-boundary.serial.test.ts
+++ b/test/migrate-embeddings-boundary.serial.test.ts
@@ -137,7 +137,9 @@ describe('migration across a stale-batch boundary', () => {
// were correctly embedded — the boundary page was never stamped.
expect(code).toBe(0);
- expect(embeddedTexts.length).toBe(6); // all six chunks re-embedded once
+ // 6 chunk re-embeds + 3 completion smoke-check QUERY embeds (the smoke
+ // check runs only on the completed path).
+ expect(embeddedTexts.length).toBe(9);
expect(await engine.countStaleChunks()).toBe(0);
// Every page carries the TARGET signature, including the boundary page.
diff --git a/test/migrate-embeddings-flow.serial.test.ts b/test/migrate-embeddings-flow.serial.test.ts
index 6356ff9977..e09a0ef410 100644
--- a/test/migrate-embeddings-flow.serial.test.ts
+++ b/test/migrate-embeddings-flow.serial.test.ts
@@ -225,8 +225,10 @@ describe('migrate embeddings — full flow on PGLite', () => {
const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes']);
expect(code).toBe(0);
- // Only the two previously-failed pages were embedded this pass.
- expect(embeddedTexts.length).toBe(2);
+ // Only the two previously-failed pages were embedded this pass, plus the
+ // 3 completion smoke-check QUERY embeds (self-retrieval runs only on the
+ // completed path — the interrupted run above had none).
+ expect(embeddedTexts.length).toBe(5);
expect(embeddedTexts.join(' ')).toContain('page-4');
expect(embeddedTexts.join(' ')).toContain('page-5');
diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.ts
new file mode 100644
index 0000000000..f80348c52a
--- /dev/null
+++ b/test/migrate-embeddings-hardening.serial.test.ts
@@ -0,0 +1,1096 @@
+/**
+ * Migration-hardening pins (the poisonable-skip class + its guardrails):
+ *
+ * 1. From==To WITH work outstanding: config already points at the target
+ * but NULL vectors remain ⇒ the run FALLS THROUGH and resumes (the old
+ * three-conjunct skip exited 0 here — the zero-coverage path).
+ * 2. env==target PROCEEDS with a notice; env≠target refused (env gate).
+ * 3. Absent embedding column ⇒ plan says "will be (re)built", NOT the
+ * DESTRUCTIVE deletion warning; empty brain migrates cleanly.
+ * 4. --retarget: a live different-target marker refuses (naming both
+ * commands) without --retarget, proceeds with it, and records history.
+ * 5. Lock passthrough + heartbeat: a heldLocks drain whose refresh()
+ * returns false ABORTS with lock_lost (no silent mutual-exclusion loss).
+ * 6. 2048d transition: DDL succeeds with NO HNSW index (pgvector caps
+ * `vector` HNSW at 2000 dims); exact-scan search still works.
+ * 7. Same-width ze-switch resume does NOT drop stored vectors (width guard).
+ *
+ * Added hardening pins (second wave):
+ * 8. Locked branches refuse pre-mutation: global migration lock ⇒
+ * locked/migration; per-source embed-backfill lock ⇒ locked/embed_backfill.
+ * 9. persistEmbeddingFileConfig never persists env-sourced secrets
+ * (API keys / database_url) into ~/.gbrain/config.json (round-2 #2).
+ * 10. A dims-only GBRAIN_EMBEDDING_DIMENSIONS never fully pins the target;
+ * a no-file-plane run refuses at apply instead of going env-canonical.
+ * 11. Wrong-width dim-pinned companion columns (facts/query_cache) are
+ * repaired independently — pinned_repaired[], no content_chunks rebuild.
+ * 12. Same-width resume/undo width guard keeps stored vectors (both the
+ * ze-switch resume path and the snapshot undo path).
+ * 13. Corrupt AND wrong-shape markers report corrupt on readMigrationState +
+ * --status without throwing; a fresh run rewrites the marker clean (v2).
+ * 14. Retarget history: superseded[] chain + retargeted_at + the
+ * --force-sunset-target resume-command rendering.
+ * 15. verifySearchRoundTrip miss branch: warn/self_retrieval_miss with
+ * content-free samples (page ids + codes, never query text).
+ * 16. Heartbeat transient-error policy: 3 consecutive refresh() throws abort
+ * with lock_lost; a mid-run success resets the counter (no abort).
+ * 17. Empty-brain run-to-completion: full migrate exits 0 with no destructive
+ * warning, stamps the completed marker, then verified-skips on re-run.
+ *
+ * Serial: temp GBRAIN_HOME + fake embed transport for the file's lifecycle.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, renameSync, existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __setEmbedTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import {
+ runMigrateEmbeddings,
+ GLOBAL_MIGRATION_LOCK_ID,
+ persistEmbeddingFileConfig,
+ planMigrationFlow,
+} from '../src/commands/migrate-embeddings.ts';
+import {
+ MIGRATION_STATE_KEY,
+ MIGRATION_COMPLETED_KEY,
+ runSchemaTransition,
+ readMigrationState,
+ resolveRerankerPlan,
+ applyRerankerAction,
+ envFullyPinsTarget,
+ planEmbeddingMigration,
+ applyEmbeddingMigration,
+ readDimPinnedWidths,
+ renderResumeCommand,
+ verifySearchRoundTrip,
+ type MigrationState,
+} from '../src/core/embedding-migration.ts';
+import { tryAcquireDbLock, type DbLockHandle } from '../src/core/db-lock.ts';
+import { embedBackfillLockId } from '../src/core/embed-backfill-lock.ts';
+import {
+ resumeRetrievalUpgrade,
+ undoRetrievalUpgrade,
+ KEY_REQUESTED,
+ KEY_PREVIOUS_SNAPSHOT,
+ ZE_TARGET_EMBEDDING_DIM,
+} from '../src/core/retrieval-upgrade-planner.ts';
+
+const FROM_DIMS = 1280;
+const TO_DIMS = 1536;
+
+let engine: PGLiteEngine;
+let tmpHome: string;
+const savedEnv: Record<string, string | undefined> = {};
+let currentDims = FROM_DIMS;
+let embeddedTexts: string[] = [];
+let slowEmbedMs = 0;
+
+function installTransport(): void {
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ if (slowEmbedMs > 0) await new Promise((r) => setTimeout(r, slowEmbedMs));
+ for (const v of values) {
+ if (!v.includes('probe')) embeddedTexts.push(v);
+ }
+ return {
+ embeddings: values.map(() => new Array(currentDims).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001)),
+ usage: { tokens: values.length * 4 },
+ } as never;
+ });
+}
+
+class ExitError extends Error {
+ constructor(public code: number) { super(`exit ${code}`); }
+}
+const exitSeam = (code: number): never => { throw new ExitError(code); };
+
+async function runMigrate(args: string[]): Promise<number> {
+ try {
+ await runMigrateEmbeddings(engine, args, { exit: exitSeam });
+ throw new Error('runMigrateEmbeddings returned without exiting');
+ } catch (e) {
+ if (e instanceof ExitError) return e.code;
+ throw e;
+ }
+}
+
+/** Same as runMigrate but against an explicit engine (empty-brain suite). */
+async function runMigrateOn(target: PGLiteEngine, args: string[]): Promise<number> {
+ try {
+ await runMigrateEmbeddings(target, args, { exit: exitSeam });
+ throw new Error('runMigrateEmbeddings returned without exiting');
+ } catch (e) {
+ if (e instanceof ExitError) return e.code;
+ throw e;
+ }
+}
+
+/** Capture console.log lines (the --json stdout envelope / plan render). */
+function captureStdout(): { lines: string[]; restore: () => void } {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };
+ return { lines, restore: () => { console.log = orig; } };
+}
+
+function writeFileConfig(model: string, dims: number): void {
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ embedding_model: model,
+ embedding_dimensions: dims,
+ zeroentropy_api_key: 'ze-test-fake',
+ openai_api_key: 'sk-test-fake',
+ }, null, 2));
+}
+
+beforeAll(async () => {
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'GBRAIN_EMBED_LOCK_HEARTBEAT_MS', 'OPENAI_API_KEY', 'ZEROENTROPY_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL']) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-migrate-hardening-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileConfig('zeroentropyai:zembed-1', FROM_DIMS);
+
+ resetGateway();
+ configureGateway({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: FROM_DIMS,
+ env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ installTransport();
+
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: FROM_DIMS } as never);
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+describe('poisonable skip is dead', () => {
+ test('From==To with NULL vectors outstanding resumes instead of exiting 0', async () => {
+ // Seed two pages embedded at the FROM provider.
+ for (const slug of ['skip-1', 'skip-2']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nbody` });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: `chunk of ${slug}`, chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+ }
+ await runEmbedCore(engine, { stale: true, quiet: true });
+
+ // The incident state: config (file plane + gateway) ALREADY points at the
+ // target, the column is already at target width, but the vectors are
+ // NULL. The old skip conjunct (from==to && !dim_change && stale-count)
+ // exited 0 on variants of this; the verified skip must fall through.
+ currentDims = TO_DIMS;
+ writeFileConfig('openai:text-embedding-3-small', TO_DIMS);
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ installTransport();
+ await runSchemaTransition(engine, TO_DIMS); // NULLs every vector at target width
+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-small');
+ await engine.setConfig('embedding_dimensions', String(TO_DIMS));
+
+ embeddedTexts = [];
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(code).toBe(0); // completed — by DOING the work, not by skipping it
+ // 2 drain re-embeds + 2 completion smoke-check query embeds (the smoke
+ // check is part of the completed path). Vectors restored either way:
+ const vecs = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(vecs[0]?.n)).toBe(2);
+ expect(embeddedTexts.length).toBe(4);
+
+ // And now that the brain is GENUINELY converged, the verified skip fires.
+ embeddedTexts = [];
+ const again = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(again).toBe(0);
+ expect(embeddedTexts.length).toBe(0); // no work, no spend
+ }, 60000);
+
+ test('env==target proceeds (dry-run works); env!=target refuses the live run', async () => {
+ // env == target: the notice-and-proceed case (env-first deployments).
+ process.env.GBRAIN_EMBEDDING_MODEL = 'openai:text-embedding-3-small';
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(TO_DIMS);
+ try {
+ const dryCode = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--dry-run']);
+ expect(dryCode).toBe(0); // dry-run renders the plan — not refused
+
+ // env != target: the #1421 refusal, unchanged.
+ process.env.GBRAIN_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(FROM_DIMS);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(code).toBe(1); // refused_env
+ } finally {
+ delete process.env.GBRAIN_EMBEDDING_MODEL;
+ delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
+ }
+ }, 30000);
+
+ test('retarget gate: different-target marker refuses without --retarget, proceeds with it', async () => {
+ // Plant a live marker for a DIFFERENT target.
+ await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify({
+ version: 2,
+ to_model: 'voyage:voyage-4',
+ to_dims: 1024,
+ from_model: 'zeroentropyai:zembed-1',
+ from_dims: FROM_DIMS,
+ started_at: '2026-08-01T00:00:00.000Z',
+ } satisfies MigrationState));
+ try {
+ const refused = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(refused).toBe(1);
+ // Marker untouched by the refusal.
+ const marker = await readMigrationState(engine);
+ expect(marker.state?.to_model).toBe('voyage:voyage-4');
+
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--retarget']);
+ expect(code).toBe(0);
+ // Completed: marker cleared; the abandoned target is in the completion
+ // path's history via the superseded chain (marker was rewritten then
+ // cleared — verify the brain converged and no marker remains).
+ const after = await readMigrationState(engine);
+ expect(after.state).toBeNull();
+ } finally {
+ await engine.unsetConfig(MIGRATION_STATE_KEY);
+ }
+ }, 60000);
+});
+
+describe('locks + schema honesty', () => {
+ test('heldLocks heartbeat: refresh()===false aborts the drain with lock_lost', async () => {
+ // Darken one page so the drain has work, then hand runEmbedCore a fake
+ // held lock whose refresh reports "stolen".
+ await engine.executeRaw(`UPDATE content_chunks SET embedding = NULL`);
+ const fakeLock: DbLockHandle = {
+ id: 'fake-held-lock',
+ acquiredAt: '0',
+ release: async () => {},
+ refresh: async () => false,
+ };
+ process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS = '40';
+ slowEmbedMs = 400; // hold the drain open long enough for a heartbeat tick
+ try {
+ const result = await runEmbedCore(engine, {
+ stale: true,
+ catchUp: true,
+ singleFlight: true,
+ includeNullSignature: true,
+ quiet: true,
+ heldLocks: [fakeLock],
+ });
+ expect(result.lock_lost).toBe(true);
+ } finally {
+ delete process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS;
+ slowEmbedMs = 0;
+ // Recover the brain for later tests.
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ }
+ }, 60000);
+
+ test('2048d transition: no HNSW index (pgvector cap), exact-scan search works', async () => {
+ currentDims = 2048;
+ await runSchemaTransition(engine, 2048);
+ const idx = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pg_indexes WHERE indexname = 'idx_chunks_embedding'`,
+ );
+ expect(Number(idx[0]?.n)).toBe(0); // above the 2000-dim vector HNSW cap
+
+ // Exact-scan path still works end to end. 3-large: its recipe allows
+ // flexible dims up to 3072, so 2048 passes the client-side dim check
+ // (3-small caps at 1536 and would refuse before the transport).
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 2048,
+ env: { OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ installTransport();
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(rows[0]?.n)).toBeGreaterThan(0);
+
+ // Restore the 1536d state for anything that runs after.
+ currentDims = TO_DIMS;
+ await runSchemaTransition(engine, TO_DIMS);
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ installTransport();
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ }, 60000);
+
+ test('empty/absent column: plan shows the (re)build line, not the deletion warning', async () => {
+ // Drop the column outright — the absent/unparsable case (dims === null).
+ await engine.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);
+ await engine.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
+ try {
+ // Capture the --json stdout envelope (console.log) — it carries the
+ // plan + the verify blockers, which is where the honesty lives.
+ const outLines: string[] = [];
+ const origLog = console.log;
+ console.log = (...a: unknown[]) => { outLines.push(a.map(String).join(' ')); };
+ let code: number;
+ try {
+ code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--dry-run', '--json']);
+ } finally {
+ console.log = origLog;
+ }
+ expect(code).toBe(0); // dry-run against an absent column plans, never throws
+ const envelope = JSON.parse(outLines.join('\n')) as {
+ status: string;
+ plan: { column_dims: number | null; dim_change: boolean; chunks_to_embed: number };
+ verified: { complete: boolean; blockers: string[] };
+ };
+ expect(envelope.status).toBe('planned');
+ // Absent column: rebuild flagged honestly (dim_change true even though
+ // dims === null — the old spelling hid the DDL), copy says (re)built.
+ expect(envelope.plan.column_dims).toBeNull();
+ expect(envelope.plan.dim_change).toBe(true);
+ expect(envelope.plan.chunks_to_embed).toBeGreaterThan(0);
+ expect(envelope.verified.complete).toBe(false);
+ expect(envelope.verified.blockers.join('\n')).toContain('will be (re)built');
+ } finally {
+ // Restore the column + vectors for subsequent files.
+ await runSchemaTransition(engine, TO_DIMS);
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ }
+ }, 60000);
+});
+
+describe('reranker companion (D8)', () => {
+ test('bundle-default ZE reranker is exposed; auto switches to the target provider reranker', async () => {
+ // No explicit search.reranker.model row — the exposure must resolve
+ // THROUGH the mode-bundle default (zeroentropyai:zerank-2), the common
+ // ZE case the old explicit-key-only warning missed.
+ const plan = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', undefined);
+ expect(plan.exposed).not.toBeNull();
+ expect(plan.exposed!.model).toBe('zeroentropyai:zerank-2');
+ expect(plan.exposed!.sunset_date).toBeTruthy();
+ expect(plan.action).toEqual({ kind: 'switch', to: 'voyage:rerank-2.5' });
+ });
+
+ test('auto with a reranker-less target suggests, never silently enables a third provider', async () => {
+ const plan = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'openai:text-embedding-3-small', undefined);
+ expect(plan.exposed).not.toBeNull();
+ expect(plan.action.kind).toBe('none');
+ expect((plan.action as { suggestion: string | null }).suggestion).toBe('voyage:rerank-2.5');
+ });
+
+ test('off disables, keep leaves alone, invalid explicit values refuse with paste-ready messages', async () => {
+ const off = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', 'off');
+ expect(off.action).toEqual({ kind: 'disable' });
+
+ const keep = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', 'keep');
+ expect(keep.action).toEqual({ kind: 'none', suggestion: null });
+
+ // Provider exists but declares no reranker touchpoint.
+ await expect(
+ resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', 'openai:text-embedding-3-small'),
+ ).rejects.toThrow(/declares no reranker/);
+
+ // Not provider:model shaped at all.
+ await expect(
+ resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', 'garbage'),
+ ).rejects.toThrow(/--reranker must be/);
+ });
+
+ test('config-only completion: converged brain + --reranker off still flips the DB key (no skip swallow)', async () => {
+ // Brain is converged on openai 3-small @1536 from the suites above — the
+ // verified skip would fire, but a pending reranker action must execute
+ // as a config-only completion instead.
+ await engine.executeRaw(
+ `INSERT INTO query_cache (id, query_text, source_id) VALUES ('qc-rr', 'stale rank order', 'default')
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'off']);
+ expect(code).toBe(0);
+ expect(await engine.getConfig('search.reranker.enabled')).toBe('false');
+ // Rank order changed ⇒ cache purged in the same transaction.
+ const qc = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM query_cache`);
+ expect(Number(qc[0]?.n)).toBe(0);
+ }, 60000);
+
+ test('explicit switch: live probe passes (stubbed wire) and the write lands model + enabled together', async () => {
+ // Gateway needs a voyage key for the rerank call; the wire is stubbed.
+ // The key must ALSO live in process.env: the flow's mid-run
+ // persistEmbeddingFileConfig reconfigures the gateway from file+env, and
+ // the file plane deliberately carries no voyage key — without this the
+ // probe dies on the key check before ever reaching the stubbed wire
+ // (green-locally/red-on-CI when a real key sits in the dev env).
+ process.env.VOYAGE_API_KEY = 'pa-test-fake';
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake', VOYAGE_API_KEY: 'pa-test-fake' },
+ });
+ installTransport();
+ const origFetch = globalThis.fetch;
+ (globalThis as { fetch: typeof fetch }).fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ const u = String(url);
+ if (u.includes('/rerank')) {
+ // Voyage REST returns data[] (not results[]) — the shape the gateway
+ // must parse (live-key e2e pins the real wire; this pins the parse).
+ return new Response(JSON.stringify({
+ data: [{ index: 0, relevance_score: 0.9 }, { index: 1, relevance_score: 0.2 }],
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }
+ return origFetch(url as never, init);
+ }) as typeof fetch;
+ try {
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'voyage:rerank-2.5']);
+ expect(code).toBe(0);
+ expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
+ expect(await engine.getConfig('search.reranker.enabled')).toBe('true');
+ } finally {
+ (globalThis as { fetch: typeof fetch }).fetch = origFetch;
+ delete process.env.VOYAGE_API_KEY;
+ }
+ }, 60000);
+
+ test('probe failure keeps the previous reranker config and reports switch_failed', async () => {
+ // Wire stub throws: the probe must fail on the WIRE (not on a missing
+ // key — hence the fake env key), the migration still completes, and the
+ // config stays where the previous test put it.
+ process.env.VOYAGE_API_KEY = 'pa-test-fake';
+ const origFetch = globalThis.fetch;
+ (globalThis as { fetch: typeof fetch }).fetch = (async (url: string | URL | Request) => {
+ if (String(url).includes('/rerank')) throw new Error('stub: reranker endpoint down');
+ return origFetch(url as never);
+ }) as typeof fetch;
+ try {
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'voyage:rerank-2.5-lite']);
+ expect(code).toBe(0); // embeddings converged; reranker failure is reported, not fatal
+ // Old config kept — NOT flipped to the unreachable model.
+ expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
+ } finally {
+ (globalThis as { fetch: typeof fetch }).fetch = origFetch;
+ delete process.env.VOYAGE_API_KEY;
+ }
+ }, 60000);
+
+ test('applyRerankerAction is transactional: model + enabled + cache purge land together', async () => {
+ await engine.executeRaw(
+ `INSERT INTO query_cache (id, query_text, source_id) VALUES ('qc-rr2', 'stale again', 'default')
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ await applyRerankerAction(engine, { kind: 'switch', to: 'voyage:rerank-2.5-lite' });
+ expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5-lite');
+ expect(await engine.getConfig('search.reranker.enabled')).toBe('true');
+ const qc = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM query_cache`);
+ expect(Number(qc[0]?.n)).toBe(0);
+ });
+});
+
+describe('status surface + completion smoke check (D6/D11)', () => {
+ test('--status --json reports planes, censuses, markers — and never mutates', async () => {
+ const outLines: string[] = [];
+ const origLog = console.log;
+ console.log = (...a: unknown[]) => { outLines.push(a.map(String).join(' ')); };
+ let code: number;
+ try {
+ code = await runMigrate(['--status', '--json']);
+ } finally {
+ console.log = origLog;
+ }
+ expect(code).toBe(0);
+ const report = JSON.parse(outLines.join('\n')) as Record<string, never> & {
+ status: string;
+ identity: { engine: string };
+ env: { present: boolean };
+ keys: Record<string, boolean>;
+ file_plane: { model: string | null } | null;
+ db_plane: { model: string | null };
+ column_dims: number | null;
+ missing_embeddings: number | null;
+ signature_census: Array<{ signature: string | null; pages: number }>;
+ marker: { kind: string };
+ completed: { verify_search?: { status: string } } | null;
+ resume_command: string | null;
+ };
+ expect(report.status).toBe('status');
+ expect(report.identity.engine).toBe('pglite');
+ expect(report.env.present).toBe(false);
+ // Key PRESENCE booleans only — never values.
+ expect(typeof report.keys.VOYAGE_API_KEY).toBe('boolean');
+ expect(JSON.stringify(report)).not.toContain('sk-test-fake');
+ expect(report.file_plane?.model).toBe('openai:text-embedding-3-small');
+ expect(report.db_plane.model).toBe('openai:text-embedding-3-small');
+ expect(report.column_dims).toBe(TO_DIMS);
+ expect(report.missing_embeddings).toBe(0);
+ expect(report.signature_census.length).toBeGreaterThan(0);
+ expect(report.marker.kind).toBe('none');
+ expect(report.resume_command).toBeNull();
+ // The last completed migration stamped a content-free smoke-check record.
+ expect(report.completed?.verify_search?.status).toBe('pass');
+ expect(JSON.stringify(report.completed)).not.toContain('chunk of');
+ }, 30000);
+
+ test('doctor embedding_migration_state: warns with resume command on a live marker, ok when clear', async () => {
+ const { checkEmbeddingMigrationState } = await import('../src/commands/doctor.ts');
+ const clear = await checkEmbeddingMigrationState(engine);
+ expect(clear.status).toBe('ok');
+
+ await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify({
+ version: 2,
+ to_model: 'voyage:voyage-4',
+ to_dims: 1024,
+ from_model: 'openai:text-embedding-3-small',
+ from_dims: TO_DIMS,
+ started_at: '2026-08-10T00:00:00.000Z',
+ } satisfies MigrationState));
+ try {
+ const live = await checkEmbeddingMigrationState(engine);
+ expect(live.status).toBe('warn');
+ expect(live.message).toContain('voyage:voyage-4');
+ expect(live.message).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
+ expect(live.message).toContain('--status');
+ } finally {
+ await engine.unsetConfig(MIGRATION_STATE_KEY);
+ }
+ }, 30000);
+
+ test('verifySearchRoundTrip: pass on a healthy brain; error samples warn; unconfigured gateway skips — never throws', async () => {
+ const { verifySearchRoundTrip } = await import('../src/core/embedding-migration.ts');
+
+ const pass = await verifySearchRoundTrip(engine, { samples: 2 });
+ expect(pass.status).toBe('pass');
+ expect(pass.samples.every((s) => s.status === 'hit')).toBe(true);
+
+ // Transport throws ⇒ per-sample error ⇒ warn (exit semantics untouched).
+ __setEmbedTransportForTests(async () => { throw new Error('probe transport down'); });
+ try {
+ const warn = await verifySearchRoundTrip(engine, { samples: 2 });
+ expect(warn.status).toBe('warn');
+ expect(warn.samples.every((s) => s.status === 'error')).toBe(true);
+ } finally {
+ installTransport();
+ }
+
+ // (The gateway_unconfigured ⇒ skipped branch is unreachable under the
+ // test harness — resetGateway() restores a configured baseline. The
+ // branch is three lines guarded by the same currentEmbeddingSignature()
+ // null-contract pinned elsewhere in this wave.)
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake', VOYAGE_API_KEY: 'pa-test-fake' },
+ });
+ installTransport();
+ }, 30000);
+});
+
+describe('locked branches refuse before any mutation', () => {
+ test('held global migration lock ⇒ locked/migration; held per-source embed lock ⇒ locked/embed_backfill', async () => {
+ // Work outstanding so the verified skip can't fire and the flow actually
+ // reaches the lock acquisition step.
+ await engine.executeRaw(
+ `UPDATE content_chunks SET embedding = NULL WHERE id = (SELECT MIN(id) FROM content_chunks)`,
+ );
+ let globalLock: DbLockHandle | null = null;
+ const sourceLocks: DbLockHandle[] = [];
+ try {
+ globalLock = await tryAcquireDbLock(engine, GLOBAL_MIGRATION_LOCK_ID, 60);
+ if (!globalLock) throw new Error('test setup: failed to acquire the global migration lock');
+
+ const cap1 = captureStdout();
+ let code1: number;
+ try {
+ code1 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ } finally {
+ cap1.restore();
+ }
+ expect(code1).toBe(1);
+ const env1 = JSON.parse(cap1.lines.join('\n')) as { status: string; holder: string };
+ expect(env1.status).toBe('locked');
+ expect(env1.holder).toBe('migration');
+
+ // Release the global lock; hold the per-source embed-backfill locks
+ // instead — the second refusal class, with its own holder label.
+ await globalLock.release();
+ globalLock = null;
+ const sources = await engine.listAllSources({ includeArchived: true });
+ for (const sid of sources.map((r) => r.id).sort()) {
+ const l = await tryAcquireDbLock(engine, embedBackfillLockId(sid), 60);
+ expect(l).not.toBeNull();
+ sourceLocks.push(l!);
+ }
+ expect(sourceLocks.length).toBeGreaterThan(0);
+
+ const cap2 = captureStdout();
+ let code2: number;
+ try {
+ code2 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ } finally {
+ cap2.restore();
+ }
+ expect(code2).toBe(1);
+ const env2 = JSON.parse(cap2.lines.join('\n')) as { status: string; holder: string; detail: string };
+ expect(env2.status).toBe('locked');
+ expect(env2.holder).toBe('embed_backfill');
+ expect(env2.detail).toContain('embed backfill');
+
+ // Neither refusal mutated anything: no state marker was written.
+ const marker = await readMigrationState(engine);
+ expect(marker.state).toBeNull();
+ expect(marker.corrupt).toBe(false);
+ } finally {
+ if (globalLock) { try { await globalLock.release(); } catch { /* best-effort */ } }
+ for (const l of sourceLocks) { try { await l.release(); } catch { /* best-effort */ } }
+ // Recover the darkened chunk for later suites.
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ }
+ }, 60000);
+});
+
+describe('config-plane hygiene (env leak + env-canonical gates)', () => {
+ test('persistEmbeddingFileConfig writes the target to the file plane, never env-sourced secrets', async () => {
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ const prevVoyage = process.env.VOYAGE_API_KEY;
+ process.env.GBRAIN_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(FROM_DIMS);
+ process.env.VOYAGE_API_KEY = 'pa-env-secret-canary';
+ // Password-less on purpose: the assertion is that the database_url KEY
+ // never lands in the file at all, and a userinfo-bearing URL literal
+ // would (rightly) trip the pre-push credential scanner.
+ process.env.DATABASE_URL = 'postgres://env-host-canary:5432/leakdb';
+ try {
+ await persistEmbeddingFileConfig('voyage:voyage-4', 1024);
+ const raw = readFileSync(cfgPath, 'utf-8');
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ // The TARGET landed on the file plane — not the env model.
+ expect(parsed.embedding_model).toBe('voyage:voyage-4');
+ expect(parsed.embedding_dimensions).toBe(1024);
+ // Round-2 #2 regression: the file-only loader path must never persist
+ // env-sourced secret material as a side effect of a migration.
+ expect(raw).not.toContain('pa-env-secret-canary');
+ expect(raw).not.toContain('env-host-canary');
+ expect(parsed.voyage_api_key).toBeUndefined();
+ expect(parsed.database_url).toBeUndefined();
+ // File-sourced keys stay exactly as the file had them.
+ expect(parsed.openai_api_key).toBe('sk-test-fake');
+ expect(parsed.zeroentropy_api_key).toBe('ze-test-fake');
+ } finally {
+ delete process.env.GBRAIN_EMBEDDING_MODEL;
+ delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
+ delete process.env.DATABASE_URL;
+ if (prevVoyage === undefined) delete process.env.VOYAGE_API_KEY;
+ else process.env.VOYAGE_API_KEY = prevVoyage;
+ // persistEmbeddingFileConfig reconfigured the in-process gateway from
+ // the env-merged view — restore the baseline file plane + gateway.
+ writeFileConfig('openai:text-embedding-3-small', TO_DIMS);
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake', VOYAGE_API_KEY: 'pa-test-fake' },
+ });
+ installTransport();
+ }
+ }, 30000);
+
+ test('dims-only env never fully pins the target; a no-file-plane run refuses at apply', async () => {
+ // Unit: the MODEL var is required — dims alone must not pin (#1421 class).
+ expect(envFullyPinsTarget('openai:text-embedding-3-small', TO_DIMS, {
+ GBRAIN_EMBEDDING_DIMENSIONS: String(TO_DIMS),
+ } as NodeJS.ProcessEnv)).toBe(false);
+ expect(envFullyPinsTarget('openai:text-embedding-3-small', TO_DIMS, {
+ GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-small',
+ GBRAIN_EMBEDDING_DIMENSIONS: String(TO_DIMS),
+ } as NodeJS.ProcessEnv)).toBe(true);
+
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ renameSync(cfgPath, `${cfgPath}.hidden`);
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(TO_DIMS);
+ try {
+ // Flow-level: env is NOT treated as canonical — verify stays incomplete
+ // on the file-plane conjunct even though the dims env var matches.
+ const ctx = await planMigrationFlow(engine, { to: 'openai:text-embedding-3-small', dim: TO_DIMS });
+ expect(ctx.envMatchesTarget).toBe(false);
+ expect(ctx.verify.complete).toBe(false);
+ expect(ctx.verify.details.file_plane_ok).toBe(false);
+
+ const cap = captureStdout();
+ let code: number;
+ try {
+ code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ } finally {
+ cap.restore();
+ }
+ expect(code).toBe(1);
+ const envl = JSON.parse(cap.lines.join('\n')) as { status: string; reason: string };
+ expect(envl.status).toBe('apply_failed');
+ expect(envl.reason).toContain('No ~/.gbrain/config.json');
+ // Nothing pretended env was the durable plane: no config file appeared.
+ expect(existsSync(cfgPath)).toBe(false);
+ } finally {
+ delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
+ renameSync(`${cfgPath}.hidden`, cfgPath);
+ // apply step 1 wrote the resume marker before the persist refusal.
+ await engine.unsetConfig(MIGRATION_STATE_KEY);
+ }
+ }, 60000);
+});
+
+describe('independent dim-pinned repair + same-width guards', () => {
+ test('wrong-width facts column is repaired alone — content_chunks is NOT rebuilt', async () => {
+ const before = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(before[0]?.n)).toBeGreaterThan(0);
+ // Break ONE dim-pinned companion column (facts is in
+ // TEXT_EMBEDDING_DIM_PINNED_TABLES) while chunks stay at target width.
+ await engine.executeRaw(`DROP INDEX IF EXISTS idx_facts_embedding_hnsw`);
+ await engine.executeRaw(`ALTER TABLE facts DROP COLUMN IF EXISTS embedding`);
+ await engine.executeRaw(`ALTER TABLE facts ADD COLUMN embedding vector(999)`);
+ try {
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: TO_DIMS });
+ expect(plan.dim_change).toBe(false); // chunks column already at target
+ const result = await applyEmbeddingMigration(engine, plan, {});
+ expect(result.status).toBe('applied');
+ if (result.status !== 'applied') throw new Error('unreachable');
+ expect(result.schema_transitioned).toBe(false);
+ expect(result.pinned_repaired).toContain('facts');
+ // The stored chunk vectors survived (no full destructive rebuild).
+ const after = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(after[0]?.n)).toBe(Number(before[0]?.n));
+ const widths = await readDimPinnedWidths(engine);
+ expect(widths.find((w) => w.table === 'facts')?.dims).toBe(TO_DIMS);
+ } finally {
+ // apply writes the resume marker; this test never completes the run.
+ await engine.unsetConfig(MIGRATION_STATE_KEY);
+ }
+ }, 60000);
+
+ test('same-width resume + undo keep stored vectors (width guard, no silent drop+re-add)', async () => {
+ // resume path: throwaway brain already AT the ZE target width with one
+ // live vector — resume must not run the DROP+ADD transition.
+ const e3 = new PGLiteEngine();
+ await e3.connect({ embedding_dimensions: ZE_TARGET_EMBEDDING_DIM } as never);
+ await e3.initSchema();
+ try {
+ // initSchema resolves the column width from the gateway/file plane (both
+ // at 1536 here) — pin the throwaway brain AT the ZE resume target width
+ // explicitly so the same-width guard is what's under test.
+ await runSchemaTransition(e3, ZE_TARGET_EMBEDDING_DIM);
+ await e3.putPage('rw-1', { type: 'note', title: 'rw-1', compiled_truth: '# rw\n\nbody' });
+ await e3.upsertChunks('rw-1', [
+ { chunk_index: 0, chunk_text: 'resume width guard chunk', chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+ const vec = '[' + new Array(ZE_TARGET_EMBEDDING_DIM).fill(0.002).join(',') + ']';
+ await e3.executeRaw(`UPDATE content_chunks SET embedding = $1::vector`, [vec]);
+ await e3.setConfig(KEY_REQUESTED, 'true');
+ const resumed = await resumeRetrievalUpgrade(e3);
+ expect(resumed.status).toBe('applied');
+ const n = await e3.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(n[0]?.n)).toBe(1); // vector survived: column was not rebuilt
+ } finally {
+ await e3.disconnect();
+ }
+
+ // undo path: snapshot at the CURRENT width on the main brain — the guard
+ // must skip the transition and keep every stored vector.
+ const before = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(before[0]?.n)).toBeGreaterThan(0);
+ const snapshot = {
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ search_reranker_enabled: (await engine.getConfig('search.reranker.enabled')) === 'true',
+ search_reranker_model: await engine.getConfig('search.reranker.model'),
+ };
+ await engine.setConfig(KEY_PREVIOUS_SNAPSHOT, JSON.stringify(snapshot));
+ try {
+ const undone = await undoRetrievalUpgrade(engine);
+ expect(undone.status).toBe('undone');
+ const after = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM content_chunks WHERE embedding IS NOT NULL`,
+ );
+ expect(Number(after[0]?.n)).toBe(Number(before[0]?.n));
+ } finally {
+ await engine.unsetConfig(KEY_PREVIOUS_SNAPSHOT);
+ }
+ }, 120000);
+});
+
+describe('marker integrity across surfaces', () => {
+ test('corrupt + wrong-shape markers report corrupt everywhere; a fresh run rewrites clean', async () => {
+ await engine.setConfig(MIGRATION_STATE_KEY, 'not json {{{');
+ const garbage = await readMigrationState(engine);
+ expect(garbage.corrupt).toBe(true);
+ expect(garbage.state).toBeNull();
+
+ // --status renders the corrupt marker without throwing.
+ const cap = captureStdout();
+ let code: number;
+ try {
+ code = await runMigrate(['--status', '--json']);
+ } finally {
+ cap.restore();
+ }
+ expect(code).toBe(0);
+ const report = JSON.parse(cap.lines.join('\n')) as {
+ marker: { kind: string; raw_prefix?: string };
+ resume_command: string | null;
+ };
+ expect(report.marker.kind).toBe('corrupt');
+ expect(report.marker.raw_prefix).toContain('not json');
+ expect(report.resume_command).toBeNull();
+
+ // Syntactically-valid but wrong-shape marker is ALSO corrupt (shape
+ // validation: to_model must be a provider:model string, dims an integer).
+ await engine.setConfig(MIGRATION_STATE_KEY, '{"to_model": 123}');
+ const wrongShape = await readMigrationState(engine);
+ expect(wrongShape.corrupt).toBe(true);
+ expect(wrongShape.state).toBeNull();
+
+ // A fresh migration rewrites the marker clean (v2) instead of crashing.
+ const applied = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--no-embed']);
+ expect(applied).toBe(0);
+ const clean = await readMigrationState(engine);
+ expect(clean.corrupt).toBe(false);
+ expect(clean.state?.version).toBe(2);
+ expect(clean.state?.to_model).toBe('openai:text-embedding-3-small');
+
+ // Complete the run: marker cleared, brain left converged for later suites.
+ const completed = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(completed).toBe(0);
+ const after = await readMigrationState(engine);
+ expect(after.state).toBeNull();
+ expect(after.corrupt).toBe(false);
+ }, 60000);
+
+ test('retarget history: superseded chain + retargeted_at + resume-command flag rendering', async () => {
+ // Target A at the SAME width (no schema churn), applied but not drained —
+ // leaves a live marker for A.
+ const a = await runMigrate(['--to', 'openai:text-embedding-3-large', '--dim', String(TO_DIMS), '--yes', '--no-embed']);
+ expect(a).toBe(0);
+ // Retarget to B: the marker must record A in the superseded history.
+ const b = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--no-embed', '--retarget']);
+ expect(b).toBe(0);
+ const marker = await readMigrationState(engine);
+ expect(marker.corrupt).toBe(false);
+ expect(marker.state?.version).toBe(2);
+ expect(marker.state?.to_model).toBe('openai:text-embedding-3-small');
+ expect(marker.state?.retargeted_at).toBeTruthy();
+ expect(marker.state?.superseded?.length).toBe(1);
+ expect(marker.state?.superseded?.[0]?.to_model).toBe('openai:text-embedding-3-large');
+
+ // ONE resume-command template: the force flag renders iff the state has it.
+ const state = marker.state as MigrationState;
+ expect(renderResumeCommand({ ...state, force_sunset_target: true })).toContain('--force-sunset-target');
+ expect(renderResumeCommand(state)).not.toContain('--force-sunset-target');
+
+ // Converge again: resume B for real (drains the invalidated chunks).
+ embeddedTexts = [];
+ const done = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ expect(done).toBe(0);
+ expect((await readMigrationState(engine)).state).toBeNull();
+ }, 60000);
+});
+
+describe('smoke-check miss + heartbeat resilience', () => {
+ test('verifySearchRoundTrip reports warn/self_retrieval_miss with content-free samples', async () => {
+ const canary = 'sealed-privacy-canary-text';
+ try {
+ // 11 decoy pages whose stored vectors EQUAL the fake transport's query
+ // vector, then the victim LAST (highest chunk id ⇒ it is the sampled
+ // page) with a far-away vector: query-embed succeeds, but the source
+ // page cannot land in the top-10.
+ for (let i = 0; i < 11; i++) {
+ const slug = `srm-decoy-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\ndecoy body` });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: `decoy chunk ${i}`, chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+ }
+ await engine.putPage('srm-victim', { type: 'note', title: 'srm-victim', compiled_truth: '# victim\n\nbody' });
+ await engine.upsertChunks('srm-victim', [
+ { chunk_index: 0, chunk_text: canary, chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+
+ // The fake transport's vector for ANY input (installTransport pattern).
+ const q = new Array(TO_DIMS).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001);
+ const far = new Array(TO_DIMS).fill(0);
+ far[0] = 1; // near-orthogonal to q (q[0] = 0.001)
+ await engine.executeRaw(
+ `UPDATE content_chunks SET embedding = $1::vector
+ WHERE page_id IN (SELECT id FROM pages WHERE slug LIKE 'srm-decoy-%')`,
+ ['[' + q.join(',') + ']'],
+ );
+ await engine.executeRaw(
+ `UPDATE content_chunks SET embedding = $1::vector
+ WHERE page_id IN (SELECT id FROM pages WHERE slug = 'srm-victim')`,
+ ['[' + far.join(',') + ']'],
+ );
+
+ const outcome = await verifySearchRoundTrip(engine, { samples: 1 });
+ expect(outcome.status).toBe('warn');
+ expect(outcome.reason_code).toBe('self_retrieval_miss');
+ expect(outcome.samples.length).toBe(1);
+ expect(typeof outcome.samples[0]?.page_id).toBe('number');
+ expect(outcome.samples[0]?.status).toBe('miss');
+ // Privacy pin: samples carry ids + codes, never the raw query text.
+ expect(JSON.stringify(outcome)).not.toContain(canary);
+ } finally {
+ await engine.executeRaw(
+ `DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE slug LIKE 'srm-%')`,
+ );
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'srm-%'`);
+ embeddedTexts = [];
+ }
+ }, 60000);
+
+ test('heartbeat: 3 consecutive refresh throws abort the drain; a mid-run success resets the counter', async () => {
+ process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS = '20';
+ try {
+ // Case 1: refresh THROWS every tick ⇒ 3 consecutive errors ⇒ lock_lost
+ // (the transient-error sibling of the refresh()===false test above).
+ await engine.executeRaw(`UPDATE content_chunks SET embedding = NULL`);
+ let throwCalls = 0;
+ const alwaysThrows: DbLockHandle = {
+ id: 'fake-throwing-lock',
+ acquiredAt: '0',
+ release: async () => {},
+ refresh: async () => {
+ throwCalls += 1;
+ throw new Error('heartbeat transport down');
+ },
+ };
+ slowEmbedMs = 500; // hold the drain open across ≥3 heartbeat ticks
+ const aborted = await runEmbedCore(engine, {
+ stale: true,
+ catchUp: true,
+ singleFlight: true,
+ includeNullSignature: true,
+ quiet: true,
+ heldLocks: [alwaysThrows],
+ });
+ expect(aborted.lock_lost).toBe(true);
+ expect(throwCalls).toBeGreaterThanOrEqual(3);
+
+ // Case 2: throw, throw, SUCCESS, throw, throw, success… — never 3 in a
+ // row, so the consecutive counter resets and the drain completes.
+ await engine.executeRaw(`UPDATE content_chunks SET embedding = NULL`);
+ let flakyCalls = 0;
+ const flaky: DbLockHandle = {
+ id: 'fake-flaky-lock',
+ acquiredAt: '0',
+ release: async () => {},
+ refresh: async () => {
+ flakyCalls += 1;
+ if (flakyCalls === 1 || flakyCalls === 2 || flakyCalls === 4 || flakyCalls === 5) {
+ throw new Error('transient heartbeat blip');
+ }
+ return true;
+ },
+ };
+ slowEmbedMs = 600; // ≥6 ticks at 20ms — covers the full throw/reset sequence
+ const survived = await runEmbedCore(engine, {
+ stale: true,
+ catchUp: true,
+ singleFlight: true,
+ includeNullSignature: true,
+ quiet: true,
+ heldLocks: [flaky],
+ });
+ expect(survived.lock_lost).toBeFalsy();
+ expect(survived.embedded).toBeGreaterThan(0);
+ expect(flakyCalls).toBeGreaterThanOrEqual(5); // the reset sequence actually ran
+ } finally {
+ delete process.env.GBRAIN_EMBED_LOCK_HEARTBEAT_MS;
+ slowEmbedMs = 0;
+ // Recover the brain (case 1 aborts mid-drain).
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ }
+ }, 60000);
+});
+
+describe('empty-brain migration (plan pin 15)', () => {
+ test('zero-page brain runs to completion, then verified-skips on the second run', async () => {
+ currentDims = TO_DIMS;
+ const e2 = new PGLiteEngine();
+ await e2.connect({ embedding_dimensions: TO_DIMS } as never);
+ await e2.initSchema();
+ try {
+ // File plane points elsewhere so the FIRST run has real work (config
+ // convergence) instead of instantly skipping. Same width as the fresh
+ // column ⇒ the plan must NOT show the destructive-deletion warning.
+ writeFileConfig('zeroentropyai:zembed-1', FROM_DIMS);
+
+ const cap1 = captureStdout();
+ let code1: number;
+ try {
+ code1 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ } finally {
+ cap1.restore();
+ }
+ expect(code1).toBe(0);
+ const rendered = cap1.lines.join('\n');
+ expect(rendered).toContain('Embedding migration plan');
+ expect(rendered).not.toContain('DESTRUCTIVE'); // nothing stored, nothing deleted
+ expect(rendered).toContain('Migration complete');
+
+ // Completion bookkeeping: live marker cleared, completed record stamped.
+ const marker = await readMigrationState(e2);
+ expect(marker.state).toBeNull();
+ expect(marker.corrupt).toBe(false);
+ const completedRaw = await e2.getConfig(MIGRATION_COMPLETED_KEY);
+ expect(completedRaw).toBeTruthy();
+ const completed = JSON.parse(completedRaw!) as {
+ to_model: string;
+ verify_search?: { status: string };
+ };
+ expect(completed.to_model).toBe('openai:text-embedding-3-small');
+ // Zero chunks: the smoke check records a content-free skip, not a crash.
+ expect(completed.verify_search?.status).toBe('skipped');
+
+ // Second run: verified skip — no work, no spend.
+ embeddedTexts = [];
+ const cap2 = captureStdout();
+ let code2: number;
+ try {
+ code2 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ } finally {
+ cap2.restore();
+ }
+ expect(code2).toBe(0);
+ const envl = JSON.parse(cap2.lines.join('\n')) as { status: string };
+ expect(envl.status).toBe('skipped_no_work');
+ expect(embeddedTexts.length).toBe(0);
+ } finally {
+ await e2.disconnect();
+ writeFileConfig('openai:text-embedding-3-small', TO_DIMS);
+ }
+ }, 120000);
+});
diff --git a/test/migrate-embeddings-op-contract.serial.test.ts b/test/migrate-embeddings-op-contract.serial.test.ts
new file mode 100644
index 0000000000..41a5d77f26
--- /dev/null
+++ b/test/migrate-embeddings-op-contract.serial.test.ts
@@ -0,0 +1,289 @@
+/**
+ * `migrate_embeddings` OP-path contract pins (the flatten seam).
+ *
+ * The op handler (src/core/operations.ts) consumes the SAME orchestrator as
+ * the CLI (planMigrationFlow/executeMigrationFlow in
+ * src/commands/migrate-embeddings.ts) and flattens MigrationFlowResult's
+ * tagged union into the op's historical envelope. These tests pin that
+ * flatten so a refactor of either surface can't silently change the shapes
+ * MCP/op consumers key on:
+ *
+ * 1. Remote guard: ctx.remote !== false throws (belt-and-braces on top of
+ * localOnly) — admin scope + localOnly pinned too.
+ * 2. refused_env: GBRAIN_EMBEDDING_* pointing at a DIFFERENT model than the
+ * target flattens to {status:'refused', reason:'env_override', warning,
+ * plan} and leaves NO migration marker behind.
+ * 3. retarget flatten: a live different-target marker refuses a live run as
+ * {status:'refused', reason:'retarget_required', inflight, plan}
+ * (same reason string as the CLI's --json envelope); dry_run bypasses
+ * the plan-stage refusal and returns 'planned'.
+ * 4. locked flatten: a held GLOBAL_MIGRATION_LOCK_ID surfaces as
+ * {status:'locked', holder, detail, plan} — the SAME shape as the CLI
+ * --json envelope, so remote callers keep the holder discriminator
+ * (migration vs embed_backfill) and can pick the right remediation.
+ * 5. verified skip: a converged brain returns {status:'skipped_no_work',
+ * plan, verified:{complete:true}} on the second call, with ZERO embed
+ * spend.
+ *
+ * Every envelope must also survive JSON.stringify round-trip (op results
+ * travel over MCP as JSON — a non-serializable payload is a contract bug).
+ *
+ * Serial: temp GBRAIN_HOME + fake embedding transport for the file's
+ * lifecycle. CRITICAL harness rule: after EVERY configureGateway/resetGateway
+ * the fake transport must be re-installed or tests hit the real API
+ * (configureGateway itself preserves transports; resetGateway wipes them).
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __setEmbedTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { GLOBAL_MIGRATION_LOCK_ID } from '../src/commands/migrate-embeddings.ts';
+import {
+ MIGRATION_STATE_KEY,
+ readMigrationState,
+ type MigrationState,
+ type EnvOverrideWarning,
+} from '../src/core/embedding-migration.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+
+const FROM_MODEL = 'zeroentropyai:zembed-1';
+const FROM_DIMS = 1280;
+const TO_MODEL = 'openai:text-embedding-3-small';
+const TO_DIMS = 1536;
+
+const op = operationsByName['migrate_embeddings']!;
+
+let engine: PGLiteEngine;
+let tmpHome: string;
+const savedEnv: Record<string, string | undefined> = {};
+let currentDims = FROM_DIMS;
+let embeddedTexts: string[] = [];
+
+function installTransport(): void {
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ for (const v of values) {
+ if (!v.includes('probe')) embeddedTexts.push(v);
+ }
+ return {
+ embeddings: values.map(() => new Array(currentDims).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001)),
+ usage: { tokens: values.length * 4 },
+ } as never;
+ });
+}
+
+function ctx(over: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine,
+ config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: false,
+ ...over,
+ } as OperationContext;
+}
+
+/** Op results travel over MCP as JSON — pin serializability cheaply. */
+function expectJsonRoundTrip(res: unknown): void {
+ const s = JSON.stringify(res);
+ expect(typeof s).toBe('string');
+ const parsed = JSON.parse(s) as { status?: string };
+ expect(parsed.status).toBe((res as { status: string }).status);
+}
+
+interface OpEnvelope {
+ status: string;
+ reason?: string;
+ holder?: string;
+ detail?: string;
+ warning?: EnvOverrideWarning;
+ inflight?: MigrationState;
+ plan?: { to_model: string; to_dims: number };
+ verified?: { complete: boolean; blockers: string[] };
+ embedded?: number;
+ remaining?: number;
+ verify_search?: { status: string };
+}
+
+async function runOp(params: Record<string, unknown>): Promise<OpEnvelope> {
+ return (await op.handler(ctx(), params)) as OpEnvelope;
+}
+
+beforeAll(async () => {
+ for (const k of [
+ 'GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS',
+ 'OPENAI_API_KEY', 'ZEROENTROPY_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL',
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-migrate-op-contract-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ embedding_model: FROM_MODEL,
+ embedding_dimensions: FROM_DIMS,
+ zeroentropy_api_key: 'ze-test-fake',
+ openai_api_key: 'sk-test-fake',
+ }, null, 2));
+
+ resetGateway();
+ configureGateway({
+ embedding_model: FROM_MODEL,
+ embedding_dimensions: FROM_DIMS,
+ env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ installTransport();
+
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: FROM_DIMS } as never);
+ await engine.initSchema();
+
+ // Seed a small brain embedded at the FROM provider so the live run has
+ // real invalidation + drain work.
+ for (const slug of ['op-a', 'op-b']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nbody of ${slug}` });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: `chunk of ${slug}`, chunk_source: 'compiled_truth', token_count: 4 },
+ ]);
+ }
+ await runEmbedCore(engine, { stale: true, quiet: true });
+}, 60000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+describe('migrate_embeddings op envelope contract', () => {
+ test('admin scope + localOnly + remote belt-and-braces guard', async () => {
+ expect(op.scope).toBe('admin');
+ expect(op.localOnly).toBe(true);
+ // Belt-and-braces on top of localOnly: anything not strictly
+ // remote:false throws before the orchestrator is even imported.
+ await expect(
+ op.handler(ctx({ remote: true }), { to: TO_MODEL, dim: TO_DIMS }),
+ ).rejects.toThrow(/local-only/);
+ }, 30000);
+
+ test('refused_env: env pointing at a different model flattens to refused/env_override with warning + plan', async () => {
+ process.env.GBRAIN_EMBEDDING_MODEL = FROM_MODEL; // != TO_MODEL
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(FROM_DIMS); // != TO_DIMS
+ currentDims = TO_DIMS; // the pre-apply live probe embeds at TARGET width
+ try {
+ const res = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ expect(res.status).toBe('refused');
+ expect(res.reason).toBe('env_override');
+ expect(res.warning?.triggered).toBe(true);
+ const varNames = (res.warning?.vars ?? []).map((v) => v.name);
+ expect(varNames).toContain('GBRAIN_EMBEDDING_MODEL');
+ expect(varNames).toContain('GBRAIN_EMBEDDING_DIMENSIONS');
+ expect(res.plan?.to_model).toBe(TO_MODEL);
+ expect(res.plan?.to_dims).toBe(TO_DIMS);
+ expectJsonRoundTrip(res);
+ // The env refusal fires BEFORE the marker write — a refused run must
+ // not leave a resumable migration marker behind.
+ const marker = await readMigrationState(engine);
+ expect(marker.state).toBeNull();
+ } finally {
+ delete process.env.GBRAIN_EMBEDDING_MODEL;
+ delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
+ currentDims = FROM_DIMS;
+ }
+ }, 30000);
+
+ test('retarget flatten: live different-target marker refuses as refused/retarget_required; dry_run bypasses to planned', async () => {
+ await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify({
+ version: 2,
+ to_model: 'voyage:voyage-4',
+ to_dims: 1024,
+ from_model: FROM_MODEL,
+ from_dims: FROM_DIMS,
+ started_at: '2026-08-01T00:00:00.000Z',
+ } satisfies MigrationState));
+ try {
+ // Live-run intent WITHOUT retarget: refused at the plan stage (mirrors
+ // the CLI ordering — retarget decision precedes any skip/execute).
+ const refused = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ expect(refused.status).toBe('refused');
+ expect(refused.reason).toBe('retarget_required');
+ expect(refused.inflight?.to_model).toBe('voyage:voyage-4');
+ expect(refused.inflight?.to_dims).toBe(1024);
+ expect(refused.plan?.to_model).toBe(TO_MODEL);
+ expectJsonRoundTrip(refused);
+
+ // Marker untouched by the refusal.
+ const marker = await readMigrationState(engine);
+ expect(marker.state?.to_model).toBe('voyage:voyage-4');
+
+ // dry_run explicitly bypasses the plan-stage retarget refusal
+ // (`p.dry_run !== true` in the guard) and renders the plan instead.
+ const dry = await runOp({ to: TO_MODEL, dim: TO_DIMS, dry_run: true });
+ expect(dry.status).toBe('planned');
+ expect(dry.plan?.to_model).toBe(TO_MODEL);
+ expectJsonRoundTrip(dry);
+ } finally {
+ await engine.unsetConfig(MIGRATION_STATE_KEY);
+ }
+ }, 30000);
+
+ test("locked flatten: held global migration lock reports status:'locked' with the holder discriminator", async () => {
+ // Hold the brain-wide migration lock as a live foreign holder. The op's
+ // executeMigrationFlow tryAcquire sees a live row and yields 'locked',
+ // which the op surfaces with the SAME shape as the CLI --json envelope —
+ // the holder discriminator is what tells a remote caller whether to wait
+ // out another migration or an embed backfill.
+ const held = await tryAcquireDbLock(engine, GLOBAL_MIGRATION_LOCK_ID, 60);
+ expect(held).not.toBeNull();
+ try {
+ const res = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ expect(res.status).toBe('locked');
+ expect(res.holder).toBe('migration');
+ expect(res.detail).toContain('migration lock');
+ expect(res.plan?.to_model).toBe(TO_MODEL);
+ expectJsonRoundTrip(res);
+ } finally {
+ await held!.release();
+ }
+ }, 30000);
+
+ test('live run completes; second call returns skipped_no_work with the verify payload and zero embed spend', async () => {
+ currentDims = TO_DIMS;
+ embeddedTexts = [];
+ const completed = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ expect(completed.status).toBe('completed');
+ expect(completed.remaining).toBe(0);
+ expect(Number(completed.embedded)).toBeGreaterThan(0);
+ expect(completed.verify_search?.status).toBeDefined();
+ expect(completed.plan?.to_model).toBe(TO_MODEL);
+ expectJsonRoundTrip(completed);
+ expect(embeddedTexts.length).toBeGreaterThan(0); // real drain work happened
+ // Completion clears the marker.
+ const marker = await readMigrationState(engine);
+ expect(marker.state).toBeNull();
+
+ // Converged brain: the DB-verified skip fires on the second call — no
+ // work, no spend, verify payload attached.
+ embeddedTexts = [];
+ const skipped = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ expect(skipped.status).toBe('skipped_no_work');
+ expect(skipped.verified?.complete).toBe(true);
+ expect(skipped.plan?.to_model).toBe(TO_MODEL);
+ expectJsonRoundTrip(skipped);
+ expect(embeddedTexts.length).toBe(0);
+ }, 60000);
+});