Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.36.2.0 feat: ZeroEntropy as default + zero-based README rewrite (#1136)

Garry Tancdba533a0442
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4bf05a81e0..96387dabfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,108 @@
All notable changes to GBrain will be documented in this file.
+## [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.**
+
+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`).
+
+### 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 |
+|---|---|---|---|
+| Top-1 wins (of 20 queries) | 6 | 4 | **11** |
+| Avg latency | 973ms | 559ms | **442ms** |
+| Cost per 1M tokens | $0.13 | $0.06 | **$0.05 (regular) / $0.025 (sale)** |
+| 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).
+
+### 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.
+
+**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
+- Splits the cost into schema-change time vs re-embed time (two-line cost UX so the long-running step is honest)
+- 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 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.
+
+### 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).
+
+**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).
+
+**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.
+
+**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.
+
+### Itemized changes
+
+#### Track A — ZeroEntropy 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/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`).
+- `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`).
+- 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.
+
+#### 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.
+
+#### 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/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/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.
+
+### To take advantage of v0.36.2.0
+
+`gbrain upgrade` runs the consolidated retrieval-upgrade prompt automatically.
+
+1. **Run the upgrade:**
+ ```bash
+ gbrain upgrade
+ ```
+2. **Read the comparison numbers in the prompt.** Press `s` to switch, Enter to stay (default), `l` to ask later, `n` to never ask.
+3. **If you switched: refill embeddings.** The schema is rebuilt at 1280d but embeddings are NULL until you re-embed:
+ ```bash
+ gbrain embed --stale # serial; ~$X estimate from the upgrade prompt
+ ```
+ The autopilot cycle's embed phase also walks through this on its own cadence.
+4. **Verify:**
+ ```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.
+
+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 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.
## [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.
diff --git a/README.md b/README.md
index ecad88b2b1..fcf7865d36 100644
--- a/README.md
+++ b/README.md
@@ -1,707 +1,141 @@
# GBrain
-**Your AI agent is smart but forgetful. GBrain gives it a brain.**
-
-Ask your agent about a meeting from six weeks ago, a paper you skimmed in
-March, an idea you jotted down late one night. GBrain finds it. And it knows
-the connections — who attended that meeting, who that paper's author has
-invested in, what other ideas in your brain it overlaps with.
-
-On [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval),
-the public benchmark for AI memory systems, the right answer lands in
-gbrain's top 5 results **97.6% of the time**. Better than every comparable
-system that doesn't pay for a language-model call on every retrieval, at
-$0.50 per thousand queries.
-
-For relational questions ("who works at this company?", "what did this
-founder invest in this quarter?"), gbrain's self-wiring knowledge graph
-makes the answer roughly **4× more relevant** than plain vector RAG. The
-graph isn't hand-curated. Every page write extracts entity references and
-creates typed edges (`works_at`, `attended`, `invested_in`, `founded`,
-`advises`) with zero language-model calls.
-
-[Receipts on the evals →](#receipts-on-the-evals)
-
-I'm the President and CEO of Y Combinator, and I use this 16 hours a day.
-The production brain powering my OpenClaw and Hermes deployments has grown
-into the largest documented personal-AI knowledge graph in active use:
-
-| | |
-|---|---|
-| **~100K** | total items in the brain |
-| **~16,000** | people pages, auto-enriched |
-| **~5,000** | companies |
-| **~8,000** | concepts |
-| **~4,000** | original essays + ideas + drafts |
-| **~3,500** | daily notes |
-| **~31,000** | media items (tweets, books, papers, interviews, films, articles, calls) |
-| **~2,200** | LLM-conversation transcripts (ChatGPT, Claude, Perplexity, agent forks) |
-| **108** | cron jobs running autonomously |
-| **273** | skills in the live agent fork (35 from gbrain bundle + 238 user-built on top) |
-
-The agent ingests meetings, emails, tweets, voice calls, books, papers, and
-original ideas while you sleep. It enriches every person and company it
-encounters. It fixes its own citations, consolidates memory overnight,
-detects contradictions in your typed claims about people and companies, and
-flags trajectory regressions. You wake up and the brain is smarter than when
-you went to bed.
-
-GBrain is those patterns, generalized. As my personal agent gets smarter,
-so does yours.
-
-### What it is, technically
-
-- **Open-source** (MIT) TypeScript CLI + MCP server. One binary, no service
- to host. Mac and Linux. Requires [Bun](https://bun.sh) 1.3+.
-- **Local-first.** Your brain lives in `~/.gbrain` on your machine. Embedded
- Postgres (PGLite via WASM) so there's no database to install — ready in
- ~2 seconds. Or point at your own Postgres / Supabase for big brains.
-- **Your data stays on disk.** Embedding calls hit OpenAI / Voyage / Anthropic
- only if you configure those keys. Sync, search, and graph extraction all
- run locally with zero outbound traffic.
-- **Speaks MCP.** Plugs into Claude Code, Cursor, Windsurf, ChatGPT desktop,
- and any agent that consumes the Model Context Protocol — stdio for local,
- HTTP + OAuth 2.1 for multi-user.
-
-> **LLMs:** fetch [`llms.txt`](llms.txt) for the doc map, or
-> [`llms-full.txt`](llms-full.txt) for the map with core docs inlined.
-> **Agents:** start with [`AGENTS.md`](AGENTS.md) (or
-> [`CLAUDE.md`](CLAUDE.md) for Claude Code).
-
----
+Your AI agent is smart but forgetful. GBrain gives it a brain.
-## Install
+Built by the President and CEO of Y Combinator to run his actual AI agents. The production brain behind his OpenClaw and Hermes deployments: **17,888 pages, 4,383 people, 723 companies**, 21 cron jobs running autonomously, built in 12 days. The agent ingests meetings, emails, tweets, voice calls, and original ideas while you sleep. It enriches every person and company it encounters. It fixes its own citations and consolidates memory overnight. You wake up smarter than when you went to bed.
-Three paths, ordered by how much you're committing.
+The brain wires itself. Every page write extracts entity references and creates typed links (`attended`, `works_at`, `invested_in`, `founded`, `advises`) with zero LLM calls. Hybrid search. Self-wiring knowledge graph. Structured timeline. Backlink-boosted ranking. Ask "who works at Acme AI?" or "what did Bob invest in this quarter?" and get answers vector search alone can't reach. Benchmarked side-by-side: gbrain lands **P@5 49.1%, R@5 97.9%** on a 240-page Opus-generated rich-prose corpus, beating its graph-disabled variant by **+31.4 points P@5** and ripgrep-BM25 + vector-only RAG by a similar margin. Full BrainBench scorecards live in the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo.
-### Path 1 — 60 seconds, just try it (standalone CLI)
+**New default in v0.36.2.0: ZeroEntropy** for both embedding (`zembed-1` at 1280d via Matryoshka) and reranker (`zerank-2`). On a real-corpus benchmark vs OpenAI and Voyage: **2.2× faster** (442ms vs OpenAI 973ms), **2.6× cheaper at regular pricing** ($0.05/M vs OpenAI $0.13), wins 11 of 20 queries head-to-head, reshuffles 60% of top-1 results when used as a second-pass reranker. Bring your own key from [zeroentropy.dev](https://dashboard.zeroentropy.dev), or stay on OpenAI/Voyage via `gbrain config set embedding_model <provider:model>` — your choice is sticky.
-```bash
-git clone https://github.com/garrytan/gbrain.git
-cd gbrain && bun install && bun link
-gbrain init # brain ready in ~2 seconds (PGLite)
-gbrain import ~/notes/ # index any directory of markdown
-gbrain query "what themes show up across my notes?"
-```
+GBrain is those patterns, generalized. Install in 30 minutes. Your agent does the work. As Garry's personal agent gets smarter, so does yours.
-What you'll see — gbrain finds the relevant pages, ranks them by hybrid
-search, and prints the top hits with snippets:
+**New in v0.35.7 — Temporal trajectory + founder scorecard.** Author typed metric assertions in the `## Facts` fence (`mrr=50000`, `arr=2000000`, `team_size=12`) and gbrain stores them as first-class typed columns. `gbrain eval trajectory companies/acme-example` prints the chronological history with regressions auto-flagged inline. `gbrain founder scorecard companies/acme-example` rolls up claim accuracy, consistency, growth direction, and red flags into a stable `schema_version: 1` JSON contract. New MCP op `find_trajectory` exposes the same data to agents (read scope, visibility-filtered for remote callers). The `consolidate` cycle phase now writes `valid_until` on chronologically-superseded facts AND uses semantic upsert on `(page_id, claim, since_date)` — re-running the dream cycle on stable input is now a true no-op (fixed a pre-existing duplicate-takes bug from prior versions).
-```
-$ gbrain query "what themes show up across my notes?"
-Found 8 results in 124ms (hybrid: vector + keyword + RRF)
-
-1. concepts/durable-systems.md (score 0.91)
- "Software that survives its maintainers has three properties: ..."
-2. essays/2025-thinking-out-loud.md (score 0.87)
- "I keep coming back to the idea that the best companies ..."
-3. meetings/2026-02-12-alice-call.md (score 0.83)
- "Discussed how Alice's framework for ..."
-...
-```
+> **~30 minutes to a fully working brain.** Database ready in 2 seconds (PGLite, no server). You just answer questions about API keys.
-Add `gbrain extract all` after import to build the knowledge graph
-(entity links + timeline edges). `gbrain dream` runs the full 9-phase
-maintenance cycle.
+> **LLMs:** fetch [`llms.txt`](llms.txt) for the documentation map, or [`llms-full.txt`](llms-full.txt) for the same map with core docs inlined in one fetch. **Agents:** start with [`AGENTS.md`](AGENTS.md) (or [`CLAUDE.md`](CLAUDE.md) if you're Claude Code).
-### Path 2 — Plug it into Claude Code / Cursor (MCP)
+## Install
-```bash
-# Local single-user via stdio MCP
-claude mcp add gbrain "$(which gbrain) serve"
+GBrain runs in three shapes. Pick the one that matches how you use AI agents today.
-# Multi-user via HTTP MCP with OAuth 2.1 + admin dashboard
-gbrain serve --http # prints admin bootstrap token
-gbrain serve --http --bind 0.0.0.0 --public-url https://brain.example.com
-```
+### Run with your agent platform
-Now ask Claude / Cursor "what did Alice and I discuss last quarter?"
-and it queries your brain. The HTTP server supports OAuth 2.1
-(`client_credentials`, `authorization_code` with PKCE, refresh rotation,
-revocation, RFC 7591 DCR). Source-scoped clients (`--source dept-x`) tie
-write authority to one source; `--federated-read S1,S2,S3` adds orthogonal
-read scopes. Loopback bind by default — pass `--bind 0.0.0.0` to publish.
+Already using [OpenClaw](https://github.com/garrytan/openclaw) or [Hermes](https://github.com/garrytan/hermes)? GBrain installs as a skillpack into your agent's workspace.
-### Path 3 — Full agentic install (~30 min)
+```bash
+gbrain init --pglite
+gbrain skillpack install
+```
-If you want the nightly auto-enrichment, cron jobs, and overnight
-synthesis I described above, the brain needs an agent to drive it.
+That's it. Your agent picks up 43 skills (signal detection, brain-ops, ingest, enrich, citation-fixer, daily-task-manager, cron-scheduler, eval framework, and 35 more). Routing lives in `skills/RESOLVER.md` — the agent reads it once per request, picks the right skill, executes.
-- **[OpenClaw](https://openclaw.ai)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
-- **[Hermes Agent](https://github.com/NousResearch/hermes-agent)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
+### CLI standalone
-Then paste this into your agent:
+Use gbrain from any shell, no agent platform required.
-```
-Retrieve and follow the instructions at:
-https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md
+```bash
+bun install -g github:garrytan/gbrain
+gbrain init --pglite # 2 seconds; no server, no Docker
+gbrain doctor # verify health
```
-It clones the repo, installs GBrain, sets up the brain, scaffolds 35
-skills, configures recurring jobs, and asks you for the API keys it
-needs. Budget ~30 minutes for the conversation.
-
----
-
-## Receipts on the evals
-
-The lead's numbers come from published, reproducible eval runs. Sibling
-repo [gbrain-evals](https://github.com/garrytan/gbrain-evals) has the full
-reports, corpora, and cross-system tables. Glossary so the metric jargon
-below doesn't get in the way:
-
-- **R@5** — did the right answer land in gbrain's top 5? Higher is better.
-- **P@5** — what fraction of the top 5 are actually correct? Higher is better.
-- **No LLM in the loop** — retrieval uses embeddings + keyword search +
- ranking, with no language model called per query. Cheaper, deterministic,
- reproducible.
-
-### LongMemEval — the standard public memory benchmark
-
-500 questions across 6 question types, each against a haystack of ~50
-conversation sessions. Built by [Wu et al.](https://huggingface.co/datasets/xiaowu0162/longmemeval),
-the published yardstick for memory systems.
-
-| System | R@5 | LLM in retrieval? | Notes |
-|---|---|---|---|
-| **gbrain-hybrid** | **97.60%** | no | this run, 2026-05-07 |
-| MemPalace hybrid+rerank (held-out) | 98.4% | yes | 0.8pt ahead because they pay for an LLM call per query |
-| MemPalace raw | 96.6% | no | gbrain wins this head-to-head by 1pt |
-| Hindsight | 91.4% | yes | per their release |
-| Stella (academic) | ~85% | no | dense retriever |
-| Contriever (academic) | ~78% | no | dense retriever |
-| BM25 (sparse) | ~70% | no | keyword baseline |
-
-Mastra (94.87%) and Supermemory (~99%) publish on this dataset but measure
-end-to-end QA accuracy with an LLM judge, which is a different thing than
-"did retrieval find the right session." Not directly comparable; flagged
-honestly in the [cross-system table](https://github.com/garrytan/gbrain-evals/blob/main/docs/comparison-systems.md).
-Reports + reproduction:
-[2026-05-07 LongMemEval](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-05-07-longmemeval-s.md).
-
-### BrainBench — relational queries (in-house corpus)
-
-LongMemEval is conversation-style. The other half of the proof is relational
-questions over a structured knowledge base. We built a 240-page rich-prose
-corpus (80 people, 80 companies, 50 meetings, 30 concepts) and wrote 145
-relational gold queries — "who attended this meeting?", "what's this person
-invested in?" — against it. Reproducible, deterministic.
-
-| Retrieval system | P@5 | Δ vs gbrain |
-|---|---|---|
-| **gbrain** (hybrid + knowledge graph) | **49.1%** | — |
-| Vector + keyword RRF (graph turned off) | 17.8% | −31.4 |
-| Keyword search only (BM25) | 17.1% | −32.0 |
-| Vector-only RAG | 10.8% | −38.4 |
-
-The knowledge graph layer is worth **31 points P@5** on these queries.
-Separable, measured, load-bearing. Flat across seven releases (v0.16 → v0.20)
-— zero retrieval regression while ops + infra changed underneath.
-[Full report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-04-23-brainbench-v0.20.0.md)
-
-### Curated content vs bulk swamp
-
-Personal brains accumulate bulk content (tweet dumps, daily chat
-transcripts, archived articles). When a query phrase appears in both a
-short curated essay AND a long chat dump, which wins? Source-aware ranking
-keeps the essay on top. **93.3% top-1 hit** (vs 80% on grep-only). [Report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-04-25-brainbench-cat13b-source-swamp.md)
-
-### Calibration loop — the brain that knows how you've been wrong
-
-v0.36.1.0's calibration wave extracts gradeable claims from your prose,
-grades them against reality over time, and applies the resulting bias
-profile when the AI gives you advice. **First published benchmark for AI
-memory systems that reason about user track records.**
-
-| Eval | Result | Cost |
-|---|---|---|
-| **cat14 — advice quality A/B** | **75% calibrated wins / 0% baseline wins / 25% tie** | ~$0.05 per run |
-| **cat15 — propose_takes F1** | **0.952 training / 0.922 holdout** (gap 0.03, no overfitting) | ~$0.10 per run |
-
-Voice gate 100%, force-fit prevention 100%. Hindsight introduced the
-concept as a skill demo without quantified evaluation; cat14 + cat15
-stake out the category. The iteration log at `cat14-calibration/`
-captures three same-day prompt variants where the eval caught two
-regressions before either could ship.
-[Full report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-05-18-brainbench-cat14-cat15-calibration.md)
-
-### Prompt compression
-
-Routing rule: the `functional-area-resolver` skill compresses a fat
-`AGENTS.md` into a two-layer dispatch table. A real-world 25KB resolver
-compressed to **13KB (48% the size) and gained 13–17 percentage points of
-routing accuracy** across Opus 4.7, Sonnet 4.6, and Haiku 4.5. The
-`(dispatcher for: ...)` clause is load-bearing — strip it (same
-compression, no dispatcher signal) and Sonnet's accuracy collapses to
-41.7%. [Cross-model receipts in this repo.](evals/functional-area-resolver/)
-
-### Run your own evals
+Then point any MCP-aware client (Claude Code, Cursor, Windsurf) at it, or use it from your shell:
```bash
-# Public benchmark, in-process, ~30s warm
-gbrain eval longmemeval ~/Downloads/longmemeval_s.jsonl
-
-# Multi-model output quality gate (3 frontier models score the same output)
-gbrain eval cross-modal --task "..." --output report.md
-
-# Capture real query/search traffic as regression-eval data
-GBRAIN_CONTRIBUTOR_MODE=1 gbrain eval export > snapshot.ndjson
-gbrain eval replay --against snapshot.ndjson
-
-# In-house BrainBench corpus + multi-adapter runner
-cd ~/git/gbrain-evals && bun eval/runner/multi-adapter.ts
+gbrain search "who works at acme AI?"
+gbrain query "what did bob invest in this quarter?"
+gbrain graph-query people/garry-tan --depth 2
```
-Full BrainBench corpus + per-category scorecards (Cats 1–13) in the sibling
-[gbrain-evals](https://github.com/garrytan/gbrain-evals) repo.
+Detailed setup paths (Postgres at scale, Supabase, thin-client mode) live in [`docs/INSTALL.md`](docs/INSTALL.md).
----
+### MCP server (any MCP client)
-## What it does
+```bash
+gbrain serve # stdio MCP (Claude Desktop / Code / Cursor)
+gbrain serve --http # HTTP MCP with OAuth 2.1 + admin dashboard
+ # at /admin, SSE activity feed at /admin/events
+```
-### 1. Ingests everything, enriches automatically
+Per-client guides (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork) live under [`docs/mcp/`](docs/mcp/). HTTP server supports DCR-style client registration, scope-gated access (`read`/`write`/`admin`), and built-in rate limiting.
-Markdown sync from a git brain. Meeting transcripts (Whisper / Groq Whisper).
-EPUB / PDF books (`book-mirror` produces personalized chapter-by-chapter
-analysis). PDFs of academic papers with citation extraction. Articles via
-Reader / Perplexity / archive.is. Tweets (timeline + bookmarks). Voice notes.
-ChatGPT / Claude / Perplexity / agent-fork conversation exports. Email
-threads. Calendar events. Foursquare exports. Slack channel archives.
+## What it does (the loop)
-Every page write extracts entity references → typed links (`attended`,
-`works_at`, `invested_in`, `founded`, `advises`, `mentions`) with zero LLM
-calls. The graph wires itself.
+```
+ signal → search → respond → write → auto-link → sync
+ (every (brain-first (informed (page + (typed edges (cron
+ message) retrieval) by context) timeline) + backlinks) keeps fresh)
+```
-### 2. Hybrid search that beats vector-only RAG
+- **Signal detector** runs on every message your agent receives. Captures ideas, entity mentions, time-sensitive todos, names, links.
+- **Brain-first lookup** before any external API call. The cheapest, fastest, most personal information source you have.
+- **Auto-link** fires on every page write. No LLM calls; pure pattern matching on `[[wiki/people/bob]]` style references. New entity → new page stub → graph grows.
+- **Cron-driven enrichment** runs while you sleep: dedup people pages, fix citations, score salience, find contradictions, prep tomorrow's tasks.
-Per-query: vector + keyword + RRF fusion + multi-query expansion (Haiku) +
-source-aware ranking + reranking (ZeroEntropy, optional). Two-stage CTE so
-the HNSW index stays usable when source-boost re-ranks the top-K. Hard
-exclude prefixes (`test/`, `archive/`, etc.) at retrieval. Intent classifier
-auto-selects detail level by query type (entity / temporal / event /
-general). **P@5 49.1%, R@5 97.9%** on the BrainBench corpus.
+The whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.
-### 3. Self-maintaining via the dream cycle
+## Capabilities
-A 9-phase nightly cycle: `lint → backlinks → sync → synthesize → extract →
-patterns → recompute_emotional_weight → embed → orphans` (+ a `purge` phase
-for the destructive-guard lifecycle). Each phase is independently runnable
-via `gbrain dream --phase <name>`. Subagents fan out under a rate-leased
-Anthropic client; protected job names gate trust; per-job + per-cycle
-timeouts; auto-replay on stalled jobs. Conversation transcripts become brain
-pages with content-hash dedup so re-runs are no-ops.
+**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). Default: `balanced` with ZeroEntropy reranker on.
-### 4. Multi-source brains + temporal trajectory
+**Self-wiring knowledge graph.** Every `put_page` extracts entity refs from markdown/wikilinks/typed-link syntax and writes edges with zero LLM calls. Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. The graph is what produces the +31.4 P@5 lift over vector-only RAG.
-`gbrain sources add <id> --local-path <path>` mounts additional brains
-alongside your `host` brain (team-published, CEO-class, departmental). Each
-source has its own RLS-isolated DB rows. OAuth clients can write to one
-source and read federated.
+**Job queue (Minions).** BullMQ-shaped, Postgres-native job queue. Durable subagents (LLM tool loops that survive crashes via two-phase pending→done persistence), shell jobs with audit, child jobs with cascading timeouts, rate leases for outbound providers, attachments via S3/Supabase storage. Replaces "spawn subagent as fire-and-forget Promise" with something that recovers from anything.
-Author typed claims in the `## Facts` fence: `mrr=50000`, `arr=2000000`,
-`team_size=12`, `valuation_usd=15000000`. `gbrain eval trajectory
-companies/<slug>` prints the chronological history with regressions
-auto-flagged. `gbrain founder scorecard <entity>` rolls up claim accuracy,
-consistency, growth direction, and red flags into a stable JSON contract.
+**43 curated skills.** Routing lives in [`skills/RESOLVER.md`](skills/RESOLVER.md). Covers signal capture, ingest (idea / media / meeting), enrichment, querying, brain ops, citation fixing, daily task management, cron scheduling, reports, voice, soul audit, skill creation, eval framework, and migrations. Skills are markdown files (tool-agnostic), packaged as a single skillpack the installer drops into your agent workspace.
-### 5. Durable background work
+**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. `gbrain eval export` + `gbrain eval replay` capture real queries and replay them against code changes (set `GBRAIN_CONTRIBUTOR_MODE=1`). `gbrain eval cross-modal` cross-checks an output against the task using three different-provider frontier models. Full methodology in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md).
-`gbrain agent run <prompt>` submits LLM-loop subagents. `gbrain jobs submit
-shell --params '{"cmd":"..."}'` (operator-only) submits shell jobs.
-`gbrain jobs supervisor start` runs a self-restarting worker daemon with
-crash-cause classification, OOM detection, RSS watchdog, and per-cause
-metrics surfaced in `gbrain doctor`. `gbrain autopilot --install` registers
-the dream cycle as a launchd / systemd job.
+**Brain consistency.** `gbrain eval suspected-contradictions` samples retrieval pairs, layered date pre-filter, query-conditioned LLM judge, persistent cache. Surfaces conflicts between takes + facts the agent has written. Wired into the daily dream cycle.
-Children + aggregator parents, `child_done` inbox for fan-in, per-job
-timeouts, idempotency keys, cascade-kill. Supervisor classifies exit codes
-into `runtime_error / oom_or_external_kill / graceful_shutdown / clean_exit`
-so `120 crashes/24h` reads correctly instead of false-alarming on clean
-worker drains.
+## Integrations
----
+Data flowing into the brain. Each integration is a recipe — markdown + setup hints — that ships in `recipes/` and is discoverable via `gbrain integrations list`.
-## Multi-player and company brains
+- **Voice**: Whisper or Groq voice-to-brain capture. Setup in [`docs/integrations/voice.md`](docs/integrations/voice.md).
+- **Email + calendar**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
+- **Embedding providers**: 14 recipes covering OpenAI (default fallback), Voyage, ZeroEntropy (default), Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
+- **Credential gateway**: vault-aware secret distribution. [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
+- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
-Three ways to share a brain across multiple agents, machines, or teammates.
-Most setups want pattern 1 (single server, multiple MCP clients). The other
-two patterns exist for specific reasons.
+## Architecture
-### Pattern 1 — One GBrain server, many MCP clients (recommended)
+**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines ~47 operations both engines implement; CLI and MCP server are generated from one source.
-The GBrain server runs on the same machine or container as your primary
-agent (OpenClaw, Hermes, AlphaClaw). It publishes an MCP endpoint over
-HTTP with OAuth 2.1. Other agents — on other machines, in other apps,
-across teammates' laptops — connect as thin MCP clients.
+**Brain repo is the system of record.** Your knowledge lives in a regular git repo (your "brain repo") as markdown files. GBrain syncs the repo into Postgres for retrieval; deletes in git become soft-deletes in DB. You can publish public subsets, share team mounts, run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
-```bash
-# On the box that hosts your brain + primary agent:
-gbrain serve --http --bind 0.0.0.0 --public-url https://brain.example.com
-# Prints a one-time admin bootstrap token; paste it into the admin UI
-# at /admin to register OAuth clients.
-
-# On any other machine, set up a thin client:
-gbrain init --mcp-only
-# Walks you through pointing at the server URL + OAuth credentials.
-# No local database, no scaffolded skills — just a routing shim.
-```
+**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
-**Network: use Tailscale.** Run the server on a Tailscale-private address
-so the brain is reachable from your other machines without exposing
-anything to the public internet. Public-internet exposure works fine
-(OAuth + loopback-bind-by-default + admin dashboard handle it), it's just
-a larger blast radius. For teams, Tailscale + OAuth is the cheap path to
-"my engineering team's agents all read from one shared brain."
-
-**What thin clients CAN do** (subject to OAuth scope: `read` / `write` / `admin`):
-
-- `search`, `query`, `think` — full retrieval pipeline, including the
- knowledge graph + reranking
-- `get_page`, `list_pages`, `put_page`, `delete_page`, `restore_page` —
- page CRUD (`put_page`/`delete_page` require `write` scope)
-- `find_experts` (whoknows), `find_trajectory`, `find_orphans`,
- `find_anomalies`, `find_contradictions` — the analytical surfaces
-- `get_recent_salience`, `get_brain_identity` — observability
-- `apply-migrations`, `restore_page` — admin scope, OAuth-gated
-- Anything else marked `localOnly: false` in `src/core/operations.ts`
-
-**What thin clients CANNOT do** (server-side only, by design):
-
-- `sync_brain` — needs filesystem access to the git brain repo
-- `file_upload`, `file_list`, `file_url` — server-side S3 / Supabase
- Storage credentials don't cross the trust boundary
-- `get_recent_transcripts` — raw `.txt` transcripts; privacy gate keeps
- these local
-- `purge_deleted_pages` — destructive, admin-only, local-only
-- `code_traversal_cache_clear` — local maintenance
-
-If a thin client tries one of these, the server returns a clear
-"local-only" error pointing at the local CLI.
-
-**Source-scoped clients (v0.34+).** A teammate's OAuth client can be tied
-to a single source with `--source dept-x`; its writes are isolated to
-that source's RLS-protected rows. `--federated-read S1,S2,S3` adds
-orthogonal read scopes so the client can read across departments while
-writing to one canon. Useful when a team has a shared brain AND
-contributes back to a CEO-class brain.
-
-### Pattern 2 — Local PGLite for code search (GStack)
-
-For an engineering agent that wants symbol-aware code search on the
-repo it's currently working in, run a local PGLite instance instead of
-hitting a central GBrain server. [GStack](https://github.com/garrytan/gstack)
-supports this directly: one PGLite per worktree, indexed against that
-worktree's source tree.
+**Why the graph matters.** Vector search returns chunks that are semantically close. The graph returns chunks that are factually connected. Hybrid search pulls from both; auto-linking on every write keeps the graph fresh. Deep dive: [`docs/architecture/RETRIEVAL.md`](docs/architecture/RETRIEVAL.md).
-```bash
-# In the worktree you want to index:
-gbrain init --pglite # ~2 seconds, no server, no creds
-gbrain import . # indexes the worktree's code
-echo "$(pwd)" > .gbrain-source # pins this PGLite to this worktree
-```
-
-`/sync-gbrain` (a GStack skill) keeps the PGLite current as you work.
-Code-aware queries (`gbrain code-def`, `gbrain code-refs`,
-`gbrain code-callers`) walk tree-sitter call-graph edges across 29
-languages. Symbol-aware retrieval works better than `grep` for "where
-is X defined" / "what calls Y" queries.
-
-Don't use this pattern for shared knowledge. PGLite is single-process,
-worktree-scoped, no concurrent writers. The right tool for "my agent
-needs the brain my team uses" is pattern 1.
-
-### Pattern 3 — Federated repos (advanced)
-
-Multiple GBrain servers, each indexing the same brain repo from its
-own git clone. Each server has its own DB; they sync to the same
-markdown source of truth via `gbrain sync`.
-
-Use this when:
-- You want a personal brain AND a team brain that share some content
- (the team's knowledge wiki) but diverge on private notes.
-- You're crossing a hard trust boundary (your personal brain is
- read-write to you; the team brain is read-only to most teammates,
- write-gated to a few).
-- The shared content is genuinely repo-shaped (markdown files in git),
- not "we both query each other's brains via MCP."
-
-The mechanics: clone the same brain repo on each server, run
-`gbrain init` against each, configure both to sync from the same git
-remote. Pages land in both databases; the knowledge graph wires
-independently on each side from the same source markdown.
-
-**Most teams should NOT pick this.** The MCP-client path (pattern 1)
-gives you one source of truth, one set of skills, one knowledge graph,
-and OAuth-gated multi-user access. Federated repos make sense when the
-shared content is the source of truth (a published team wiki) and the
-agents are operating against their own private overlays.
-
-My personal setup runs both: a personal brain on my laptop and a team
-brain on a separate box, indexing two different git repos. The team
-brain is what teammates' thin MCP clients connect to; the personal
-brain stays local.
-
----
-
-## Skills
-
-35 curated skills ship in the bundle. The agent installs them via
-`gbrain skillpack scaffold <name>` (one-time additive copy — you own the
-files after). See [docs/guides/skillpacks-as-scaffolding.md](docs/guides/skillpacks-as-scaffolding.md)
-for the model.
-
-### Always-on
-| Skill | What it does |
-|---|---|
-| `signal-detector` | Catches ideas, entities, and TODOs on every message — the always-on capture surface. |
-| `brain-ops` | Brain-first lookup before web search. Enforces the read-enrich-write loop. |
-| `repo-architecture` | File-placement decisions follow the primary subject, not the format. |
-
-### Content ingestion
-| Skill | What it does |
-|---|---|
-| `idea-ingest` | Links / articles / tweets. Mandatory people page for the author. |
-| `media-ingest` | Video / audio / PDF / book with entity extraction. |
-| `meeting-ingestion` | Transcripts → attendee enrichment chaining. |
-| `voice-note-ingest` | Whisper → brain page with entity refs. |
-| `book-mirror` | EPUB / PDF → personalized chapter-by-chapter two-column analysis. |
-| `book-mirror-extreme` | Synthesis pass: lift the book's principles into your own framework. |
-| `brain-pdf` | Render any brain page as a publication-quality PDF. |
-
-### Research + synthesis
-| Skill | What it does |
-|---|---|
-| `perplexity-research` | Bounded Perplexity calls with brain-side dedup. |
-| `academic-verify` | Citation verification + DOI resolution + claim cross-check. |
-| `strategic-reading` | Reading-list curation tuned to active concept clusters. |
-| `archive-crawler` | Crawl + extract from `archive.is` / archive-org bookmarks. |
-| `article-enrichment` | Article → people / companies / concepts links. |
-| `concept-synthesis` | Cross-source synthesis: 3+ pages on one concept → unified writeup. |
-| `data-research` | Email-to-tracker pipeline with parameterized YAML recipes. |
-
-### Brain operations
-| Skill | What it does |
-|---|---|
-| `query` | The default query path. Walks intent classifier + hybrid search. |
-| `enrich` | Tier-escalating enrichment for people / companies / deals. |
-| `maintain` | Background brain hygiene: backlinks, citations, orphans. |
-| `citation-fixer` | Audit and fix citation format issues across the brain. |
-| `frontmatter-guard` | Validate every page's frontmatter against the contract. |
-
-### Operational
-| Skill | What it does |
-|---|---|
-| `daily-task-manager` | Task lifecycle with priority levels (P0–P4). |
-| `daily-task-prep` | Morning prep with calendar context + agenda generation. |
-| `cron-scheduler` | Schedule staggering, quiet hours, idempotency keys. |
-| `reports` | Timestamped reports with keyword routing. |
-| `cross-modal-review` | Quality gate via second model. |
-| `webhook-transforms` | External events → brain signals. |
-| `minion-orchestrator` | Background work: shell jobs + LLM subagents. |
-
-### Identity + meta
-| Skill | What it does |
-|---|---|
-| `soul-audit` | 6-phase interview → SOUL.md / USER.md / ACCESS_POLICY.md / HEARTBEAT.md. |
-| `testing` | Skill validation framework. |
-| `skillify` | The meta-skill: turn any feature into a properly-skilled, tested unit. |
-| `skill-creator` | Create conforming skills with MECE check. |
-| `skillpack-check` | Agent-readable bundle health report. |
-| `skillpack-harvest` | Lift a proven skill from your fork back into gbrain (privacy-linted). |
-| `functional-area-resolver` | Two-layer dispatch for compressing AGENTS.md / RESOLVER.md. |
-
-### Conventions (shared deps, installed alongside every skill)
-- `_AGENT_README.md` — agent operating contract: how to discover skills via frontmatter
-- `_brain-filing-rules.md` — file-placement rules (primary subject wins)
-- `_output-rules.md` — output quality standards (no LLM slop)
-- `_friction-protocol.md` — log user friction to `~/.gstack/friction/`
-- `conventions/` — cross-cutting rules (quality, brain-first, model-routing, test-before-bulk, cross-modal)
-
----
-
-## How it works
-
-### Architecture
-
-Contract-first: `src/core/operations.ts` defines ~47 shared operations. CLI
-and MCP server are both generated from that one source. Engine factory
-dynamically imports the configured engine (`pglite` for zero-config local,
-`postgres` for Supabase / self-hosted).
-
-**Trust boundary:** `OperationContext.remote` distinguishes trusted local
-CLI (`remote: false`) from untrusted agent-facing callers (`remote: true`).
-Security-sensitive operations tighten when `remote: true` is set.
-
-### Knowledge model
-
-Every brain page is markdown with YAML frontmatter:
-- **Frontmatter:** `name`, `type` (person / company / deal / concept / ...),
- `tags`, optional `sources:`, `triggers:` (for skills), `## Facts` fenced
- block with typed claims (`mrr=50000`, `arr=2000000`).
-- **Compiled truth:** stable section the agent updates with consensus
- knowledge.
-- **Timeline:** append-only event log, sentinel-separated (`<!-- timeline -->`).
-
-Pages are chunked by recursive markdown structure (default) or LLM-guided
-(opt-in). 29 programming languages get tree-sitter semantic chunking with
-embedded WASM grammars and tiktoken token budgeting.
-
-### Knowledge graph
-
-Every page write fires `extract.ts`:
-- Matches `[Name](people/slug)` markdown links AND `[[people/slug|Name]]`
- Obsidian wikilinks.
-- Heuristics infer link type: `attended`, `works_at`, `invested_in`,
- `founded`, `advises`, `source`, `mentions`.
-- Bulk-insert via `unnest()` arrays — 4-5 params regardless of batch size,
- sidesteps the 65535-param cap.
-
-Query: `gbrain graph-query alice --depth 2 --direction in` returns who
-attended what with Alice, transitively.
-
-### Search
-
-Per-query pipeline:
-1. Query intent classifier (entity / temporal / event / general) selects
- detail level.
-2. Multi-query expansion via Haiku (deterministic, off by default in
- `conservative` mode).
-3. Hybrid: keyword (`ts_rank` × source-factor) + vector (HNSW + source-boost
- re-rank) + RRF fusion.
-4. Optional reranker (ZeroEntropy `zerank-2` flagship or `zerank-1`).
-5. Source-aware ranking: curated content (`originals/`, `concepts/`,
- `writing/`) outranks bulk content (chat transcripts, `daily/`,
- `media/x/`). Hard-exclude `test/`, `archive/`, `attachments/` by default.
-6. Dedup + token budget enforcement per mode.
-
-### Engines
-
-- **PGLite** — embedded Postgres 17.5 via WASM. Zero-config default. Single-
- file backup. Forward-reference bootstrap walks schema migrations cleanly
- across the v0.13–v0.35 wave.
-- **Postgres + pgvector** — Supabase / self-hosted. `pg_trgm` + HNSW indexes.
- Migrations include 60+ schema bumps with `sqlFor.postgres` / `sqlFor.pglite`
- branches for engine-specific DDL.
-
-`gbrain migrate --to supabase` / `--to pglite` does the round-trip.
-
-### Storage tiering
-
-For brains crossing 100K files where bulk machine-generated content
-dominates the size: declare which directories are `db_tracked` (committed)
-vs `db_only` (DB-only, gitignored). `gbrain sync` manages `.gitignore`
-automatically; `gbrain export --restore-only` repopulates missing DB-only
-files from the database.
-
-See [docs/guides/storage-tiering.md](docs/guides/storage-tiering.md) for the
-config shape and per-tier defaults.
-
----
-
-## Commands
+## Docs
-```
-SETUP
- gbrain init [--pglite | --supabase] Set up a brain. Picks search mode.
- gbrain migrate --to {supabase,pglite} Round-trip between engines.
- gbrain doctor [--fast] [--fix] Health check + auto-repair.
-
-CONTENT
- gbrain sync [--workers N] Pull from the git brain.
- gbrain import <path> Index any directory of markdown.
- gbrain embed [--stale] Compute / refresh embeddings.
- gbrain extract {links,timeline,all} Build the knowledge graph.
-
-SEARCH + QUERY
- gbrain query "<question>" Hybrid search + RRF + reranking.
- gbrain search "<text>" Lower-level: vector | keyword | hybrid.
- gbrain whoknows <topic> Expertise routing across the graph.
- gbrain graph-query <slug> Typed-edge traversal.
- gbrain orphans Pages with zero inbound links.
- gbrain salience [--days N] Pages ranked by emotional + activity.
- gbrain anomalies [--lookback-days N] Cohort-level outlier detection.
-
-AGENTS + JOBS
- gbrain agent run "<prompt>" Submit a subagent run.
- gbrain agent logs <id> Tail the run's heartbeat + transcript.
- gbrain jobs submit shell --params ... Submit a shell job (operator-only).
- gbrain jobs supervisor start Self-restarting worker daemon.
-
-CYCLE + AUTOPILOT
- gbrain dream [--phase NAME] Run the 9-phase brain cycle.
- gbrain autopilot --install Register cycle as launchd / systemd job.
-
-SKILLPACK
- gbrain skillpack list What's in the bundle.
- gbrain skillpack scaffold <name> Copy a skill into your agent repo.
- gbrain skillpack reference <name> Diff vs bundle. Or --all --since <ver>.
- gbrain skillpack migrate-fence One-shot upgrade from pre-v0.36 model.
- gbrain skillpack harvest <slug> --from <host>
- Lift a proven fork skill into gbrain.
-
-SERVE
- gbrain serve Stdio MCP (single-user, Claude Code).
- gbrain serve --http [--bind HOST] HTTP MCP + OAuth 2.1 + admin dashboard.
-
-EVAL + TRAJECTORY
- gbrain eval longmemeval <dataset> LongMemEval benchmark, in-memory PGLite.
- gbrain eval cross-modal --task "..." 3 frontier models score the same output.
- gbrain eval whoknows <fixture> Two-layer gate for whoknows accuracy.
- gbrain eval suspected-contradictions Cached contradiction probe.
- gbrain eval trajectory <entity> Typed-claim history + regression flags.
- gbrain founder scorecard <entity> Claim accuracy / consistency / growth.
-
-INTEGRATIONS + SOURCES
- gbrain integrations list Recipe catalog (Reader, Perplexity, etc).
- gbrain sources {list,add,remove,...} Multi-source brain management.
- gbrain auth register-client <name> Mint an OAuth client for the HTTP MCP.
-```
+- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end
+- [`docs/architecture/`](docs/architecture/) — system design, topologies, retrieval theory
+- [`docs/guides/`](docs/guides/) — how-to runbooks (sub-agent routing, minion deployment, skill development, brain-first lookup, idea capture, diligence ingestion)
+- [`docs/integrations/`](docs/integrations/) — connecting external data sources (voice, email, calendar, embedding providers)
+- [`docs/mcp/`](docs/mcp/) — per-client MCP setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)
+- [`docs/eval/`](docs/eval/) — eval framework, metric glossary, methodology
+- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)
+- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents
+- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)
+- [`CONTRIBUTING.md`](CONTRIBUTING.md) — contributor guide, test discipline, eval-capture mode
+- [`SECURITY.md`](SECURITY.md) — OAuth threat model, hardening defaults
-Run `gbrain <command> --help` for per-command options.
+## Contributing
----
+Run `bun run test` for the fast loop, `bun run verify` for the pre-push gate, `bun run ci:local` to run the full Docker-backed CI stack locally. Detailed test discipline in [`CONTRIBUTING.md`](CONTRIBUTING.md).
-## Docs
+Community PRs are batched into release waves rather than merged one-by-one — see the "PR wave workflow" section in [`CLAUDE.md`](CLAUDE.md). Contributor attribution stays attached via `Co-Authored-By:` trailers. We credit every accepted contribution in [`CHANGELOG.md`](CHANGELOG.md).
-- **Architecture:** [`docs/architecture/`](docs/architecture/)
-- **Skills as scaffolding (v0.36):** [`docs/guides/skillpacks-as-scaffolding.md`](docs/guides/skillpacks-as-scaffolding.md)
-- **Search modes + cost matrix:** [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md)
-- **Storage tiering:** [`docs/guides/storage-tiering.md`](docs/guides/storage-tiering.md)
-- **Embedding providers (14 recipes):** [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md)
-- **Eval capture (BrainBench-Real):** [`docs/eval-bench.md`](docs/eval-bench.md)
-- **MCP per-client setup:** [`docs/mcp/`](docs/mcp/)
-- **Two-repo pattern (agent vs brain):** [`docs/guides/repo-architecture.md`](docs/guides/repo-architecture.md)
-- **Skill development cycle:** [`docs/guides/skill-development.md`](docs/guides/skill-development.md)
-- **Per-agent install guide:** [`AGENTS.md`](AGENTS.md), [`CLAUDE.md`](CLAUDE.md), [`INSTALL_FOR_AGENTS.md`](INSTALL_FOR_AGENTS.md)
-- **Full changelog:** [`CHANGELOG.md`](CHANGELOG.md)
-
----
-
-## Origin story
-
-I needed a brain that could remember every meeting, every founder
-encounter, every essay I'd ever drafted, every idea I wanted to chase
-later. Off-the-shelf knowledge tools (Roam, Obsidian, Notion) handle
-storage. None of them ingest a meeting, enrich the attendees, build the
-graph, fix the citations, and surface the connection three weeks later
-when it matters. So I built one. The first 12 days produced a working
-brain. The next 12 months produced 100,000 pages, a self-wiring knowledge
-graph, 108 cron jobs, and the multi-engine architecture that ships here.
-
-GBrain is the generalized version of that work. You scaffold the skills.
-You bring your data. Your agent runs the patterns. The brain compounds
-nightly.
-
----
+If you find a bug or want a feature: open an issue first. Quick fixes (typo, doc bug, obvious regression) can go straight to a PR. Anything touching schema, retrieval ranking, MCP protocol, or the security boundary needs a design discussion in the issue first.
-## Contributing
+## License + credit
-PRs welcome. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the dev loop,
-test taxonomy, and how to ship. Privacy rules in [`CLAUDE.md`](CLAUDE.md)
-are non-negotiable — no real names, fork names, or private references in
-public artifacts. The harvest CLI's privacy linter exists to catch
-accidental leaks before they merge.
+MIT. Built by Garry Tan to run his OpenClaw and Hermes deployments — the production brain behind his actual AI agents.
-## License
+Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-MIT.
+Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that became the v0.36.2.0 default. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
diff --git a/VERSION b/VERSION
index f53f4b31ea..df1e611ac0 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.36.1.1
\ No newline at end of file
+0.36.2.0
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
new file mode 100644
index 0000000000..70277db7be
--- /dev/null
+++ b/docs/INSTALL.md
@@ -0,0 +1,86 @@
+# Install
+
+Three install paths. Pick one. Mix later if needed.
+
+## 1. Run with an agent platform (recommended)
+
+Already running [OpenClaw](https://github.com/garrytan/openclaw) or [Hermes](https://github.com/garrytan/hermes)?
+
+```bash
+bun install -g github:garrytan/gbrain
+gbrain init --pglite # 2 seconds; no server
+gbrain skillpack install # 43 skills into your agent workspace
+gbrain doctor # green checks all the way down
+```
+
+Your agent now reads `skills/RESOLVER.md` once per request, routes intent to the right skill, executes. New entity mentions create new pages. Daily cron runs enrichment overnight.
+
+To upgrade later: `gbrain upgrade` runs schema migrations + post-upgrade prompts (chunker bumps, the v0.36.0.0 ZE switch). Always TTY-only; non-TTY upgrades skip prompts with informational stderr lines.
+
+## 2. CLI standalone
+
+No agent platform, just shell + MCP-aware editor.
+
+```bash
+bun install -g github:garrytan/gbrain
+gbrain init --pglite
+```
+
+The init flow detects your repo size and suggests Supabase for brains > 1000 markdown files. To switch later:
+
+```bash
+gbrain migrate --to supabase # PGLite → Postgres
+gbrain migrate --to pglite # Postgres → PGLite (rare)
+```
+
+API keys live in `~/.gbrain/config.json` (file plane) or env vars (`OPENAI_API_KEY`, `ZEROENTROPY_API_KEY`, `VOYAGE_API_KEY`, `ANTHROPIC_API_KEY`). Set via CLI:
+
+```bash
+gbrain config set zeroentropy_api_key sk-...
+gbrain config set anthropic_api_key sk-ant-...
+```
+
+Common follow-ups:
+
+```bash
+gbrain import ~/my-knowledge # bulk-import a markdown folder
+gbrain sync --watch # live-sync a git repo (autopilot mode)
+gbrain autopilot --install # background daemon for nightly enrichment
+```
+
+## 3. MCP server (any MCP client)
+
+```bash
+gbrain serve # stdio MCP (Claude Desktop / Code / Cursor)
+gbrain serve --http # HTTP MCP with OAuth 2.1 + admin dashboard
+```
+
+Per-client setup guides live in [`docs/mcp/`](mcp/):
+
+- [`docs/mcp/CLAUDE_CODE.md`](mcp/CLAUDE_CODE.md)
+- [`docs/mcp/CLAUDE_DESKTOP.md`](mcp/CLAUDE_DESKTOP.md)
+- [`docs/mcp/CHATGPT.md`](mcp/CHATGPT.md)
+- [`docs/mcp/PERPLEXITY.md`](mcp/PERPLEXITY.md)
+- [`docs/mcp/DEPLOY.md`](mcp/DEPLOY.md) — production deploy patterns
+
+The HTTP server ships with an admin SPA at `/admin`, an SSE activity feed at `/admin/events`, DCR-style client registration, scope-gated `read`/`write`/`admin` access, and rate limiting.
+
+## Thin-client mode
+
+Connect to someone else's brain without running a local engine:
+
+```bash
+gbrain init --mcp-only # configures remote MCP, skips local DB
+```
+
+Useful for: team mounts, brain-as-a-service deployments, dev machines without disk space. Most local commands refuse with a paste-ready hint. See [`docs/architecture/topologies.md`](architecture/topologies.md).
+
+## Verifying the install
+
+```bash
+gbrain doctor --json # full health check
+gbrain models # which AI models are configured for what
+gbrain models doctor # 1-token probe per configured model
+```
+
+If anything's yellow, `gbrain doctor` names the fix command in the message. Most issues are missing API keys or stale schema (`gbrain upgrade --force-schema`).
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
new file mode 100644
index 0000000000..ecd227c755
--- /dev/null
+++ b/docs/architecture/RETRIEVAL.md
@@ -0,0 +1,130 @@
+# Why the hybrid + graph stack works
+
+Vector search alone underdelivers on real personal-knowledge queries. This doc explains why gbrain layers four strategies together and how they compound.
+
+## The four strategies in concert
+
+1. **Vector (HNSW on pgvector)** — semantic similarity. Catches "who works on retrieval quality at YC?" → pages mentioning "Garry Tan + retrieval" even when the user never typed "YC".
+2. **BM25 keyword** — lexical match. Catches names, exact phrases, code identifiers, anything where the user remembers the literal token. Survives the cases where vector search drifts into thematic neighbors.
+3. **Reciprocal-rank fusion (RRF)** — merges vector + keyword rankings without weighting one over the other globally. Each strategy gets to vote.
+4. **Knowledge graph traversal** — follows typed edges. Catches "what did Bob invest in this quarter?" by walking `bob ── invested_in ──> company ── dated ──> Q1`. Vector search can't see causal chains; the graph can.
+
+## Why each one alone fails
+
+**Vector only.** Returns chunks semantically close to the query. Misses any factual relationship not directly encoded in the embedding. "Companies in Garry's portfolio" returns essays about portfolios, not company pages.
+
+**Keyword only (ripgrep-style).** Brittle to phrasing. "Who works on retrieval?" misses pages that say "search ranking" instead of "retrieval." Garbage on synonyms, near-misses, or paraphrases.
+
+**Graph only.** Excellent at "neighbors of Alice" but blind to anything not yet linked. Sparse on fresh pages until backlinks accumulate.
+
+**Hybrid (vector + keyword + RRF), no graph.** Decent at "what is X?" type queries. Fails on "what is Y's relationship to X?" — those are graph queries and no amount of embedding tuning recovers them.
+
+## The benchmark
+
+BrainBench (corpus + harness in the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo) measures retrieval P@5, R@5, MRR, nDCG@5 on a 240-page Opus-generated rich-prose corpus.
+
+| Strategy | P@5 | R@5 | Notes |
+|---|---|---|---|
+| ripgrep BM25 only | ~18 | ~75 | Lexical-only baseline |
+| vector-only RAG | ~18 | ~80 | Standard RAG implementation |
+| gbrain graph-disabled (hybrid + RRF, no graph traversal) | ~18 | ~85 | Hybrid alone |
+| **gbrain default (full stack)** | **49.1** | **97.9** | Graph + extract-quality lift |
+
+**+31 P@5 points** from the graph + extract quality work. The graph isn't a marginal feature; it's the load-bearing wall.
+
+## Auto-link: why zero-LLM-call edge extraction works
+
+Every `put_page` runs `extractEntityRefs` on the markdown body. It matches:
+
+- Standard markdown links: `[Garry Tan](wiki/people/garry-tan)`
+- Obsidian wikilinks: `[[wiki/people/garry-tan|Garry Tan]]`
+- Typed-link blockquotes: `> **Convention:** see [path](path).`
+
+Three regexes, zero LLM tokens, single SQL `addLinksBatch` call with `INSERT ... SELECT FROM unnest(...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1`. The graph grows on every write at near-zero cost. On a 17K-page brain, full graph extract completes in seconds.
+
+Heuristic link-type inference (`attended`, `works_at`, `invested_in`, `founded`, `advises`) fires from surrounding sentence context — also LLM-free. Power users who want richer types add them via the typed-link blockquote convention.
+
+## ZeroEntropy as reranker: 60% top-1 reshuffle
+
+v0.36.0.0 ships ZeroEntropy's `zerank-2` as the default reranker (on for the `balanced` mode bundle). On a real-corpus benchmark across 20 queries, zerank-2 reshuffles **60% of top-1 results** after the hybrid + RRF + graph stack. That's the headline number.
+
+The mechanical reason: hybrid ranking is locally optimal per strategy but globally suboptimal. A cross-encoder reranker reads the query + each candidate document jointly, with full attention. It catches the cases where the vector + keyword + graph signals all agreed on a document that's semantically related but topically wrong.
+
+The cost: +150ms p50 latency, ~$0.025/M tokens. Disabled with `gbrain config set search.reranker.enabled false`. For agent loops that do downstream LLM work after retrieval, the latency is invisible.
+
+## Source-aware ranking
+
+Hybrid search applies a source-factor CASE expression at the SQL layer (lives in `src/core/search/sql-ranking.ts`). Curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `your-openclaw/chat/`, `daily/`, `media/x/`. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/`) filter at retrieval, not post-rank.
+
+The boost map is configurable via `GBRAIN_SOURCE_BOOST` env var or per-call `SearchOpts.exclude_slug_prefixes`. Temporal queries (`detail: 'high'`) bypass the boost so chat pages re-surface for time-sensitive lookups.
+
+## Intent-aware query rewriting
+
+`src/core/search/intent.ts` classifies queries into `entity`, `temporal`, `event`, or `general`. Each routes through different ranking knobs:
+
+- **Entity** queries ("who works at X?") apply a higher graph-traversal weight.
+- **Temporal** queries ("what happened last week?") bypass source-boost so chat/daily pages surface.
+- **Event** queries ("Acme AI Series A") engage the timeline index.
+- **General** queries hit the standard hybrid stack.
+
+The classifier is deterministic (no LLM call). Wrong classification degrades gracefully — the hybrid stack still works without it.
+
+## Multi-query expansion
+
+For `detail: 'high'` searches, `src/core/search/expansion.ts` runs a Haiku-class LLM call to produce 2-3 query variants. Each variant runs through the full hybrid stack; results merge via RRF. Catches synonym misses without recall loss.
+
+Expansion is opt-in per mode bundle (`tokenmax` on by default; `balanced` + `conservative` off). Default off in the cheap tiers because the LLM call adds ~$0.001/query and ~200ms — real money at scale.
+
+## Putting it together
+
+The full pipeline for a `query` op:
+
+```
+intent classify
+ │
+ ▼
+expansion (if enabled)
+ │
+ ▼
+hybrid search:
+ ├── vector (HNSW on chunk embeddings)
+ ├── keyword (BM25 via tsvector)
+ ├── source-aware re-rank (CASE in SQL)
+ └── RRF fusion → top 30
+ │
+ ▼
+graph augment (typed-edge traversal from any seed)
+ │
+ ▼
+reranker (zerank-2 cross-encoder, top 30 → reordered)
+ │
+ ▼
+token-budget enforcement (per mode bundle)
+ │
+ ▼
+deduplication (same slug, different chunks → keep best)
+ │
+ ▼
+results
+```
+
+Each stage is testable in isolation. Each stage is replaceable. The whole pipeline is < 1ms of orchestration cost; the latency budget goes to the upstream HTTP calls (embedding, rerank) and the index scans.
+
+## How to verify on your own brain
+
+```bash
+# Run the public LongMemEval benchmark
+gbrain eval longmemeval datasets/longmemeval_s.jsonl
+
+# Capture your own queries and replay against retrieval changes
+export GBRAIN_CONTRIBUTOR_MODE=1
+# ... use gbrain normally ...
+gbrain eval export > before.ndjson
+# ... change something ...
+gbrain eval replay --against before.ndjson
+
+# A/B retrieval strategies on a labeled fixture
+gbrain eval --qrels labels.tsv --config balanced.json
+```
+
+Methodology + metric glossary in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md).
diff --git a/docs/ethos/ORIGIN.md b/docs/ethos/ORIGIN.md
new file mode 100644
index 0000000000..c067b1d9e5
--- /dev/null
+++ b/docs/ethos/ORIGIN.md
@@ -0,0 +1,27 @@
+# Origin story
+
+GBrain came out of building OpenClaw — Garry's personal AI agent fork. The first version had skills and a brain, but the brain was a flat directory of markdown files. Search was ripgrep. Memory was vibes.
+
+Two problems surfaced almost immediately.
+
+First, the agent forgot things between conversations. Every new session re-asked basic questions. Names of people Garry had introduced last week were gone. Decisions made on Tuesday didn't survive to Thursday. The brain existed but the agent couldn't actually use it.
+
+Second, the agent kept duplicating work. Two different signals about the same company became two different people pages. Three meetings with the same person became three uncorrelated timeline entries. The signal-to-noise ratio decayed in real time.
+
+GBrain is what you build when you decide both of those are unacceptable.
+
+The fix wasn't one big idea. It was many small ones layered together:
+
+- Brain-first lookup before any external API call.
+- Auto-linking on every page write so the graph grows for free.
+- Typed edges so "who works at Acme AI?" actually returns something.
+- Hybrid search because vector alone underdelivers.
+- Reranker on top because hybrid alone is locally optimal but globally suboptimal.
+- Nightly cron to dedup, enrich, fix citations, surface contradictions.
+- An agent that reads `skills/RESOLVER.md` once and knows what to do.
+
+None of those are novel ideas. The contribution is shipping all of them together, on Postgres + pgvector that runs in WASM (no server), with skills that are markdown (not code), routed by a small text file (not a router LLM).
+
+The production brain has been running for months now. 17,888 pages. 4,383 people. 723 companies. 21 cron jobs running autonomously. It wakes Garry up smarter than the day before.
+
+GBrain is what happens when you write the brain you actually wanted to have.
diff --git a/llms-full.txt b/llms-full.txt
index 6dc9d1c480..5fd78400c3 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2263,711 +2263,145 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/README.md
# GBrain
-**Your AI agent is smart but forgetful. GBrain gives it a brain.**
+Your AI agent is smart but forgetful. GBrain gives it a brain.
-Ask your agent about a meeting from six weeks ago, a paper you skimmed in
-March, an idea you jotted down late one night. GBrain finds it. And it knows
-the connections — who attended that meeting, who that paper's author has
-invested in, what other ideas in your brain it overlaps with.
+Built by the President and CEO of Y Combinator to run his actual AI agents. The production brain behind his OpenClaw and Hermes deployments: **17,888 pages, 4,383 people, 723 companies**, 21 cron jobs running autonomously, built in 12 days. The agent ingests meetings, emails, tweets, voice calls, and original ideas while you sleep. It enriches every person and company it encounters. It fixes its own citations and consolidates memory overnight. You wake up smarter than when you went to bed.
-On [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval),
-the public benchmark for AI memory systems, the right answer lands in
-gbrain's top 5 results **97.6% of the time**. Better than every comparable
-system that doesn't pay for a language-model call on every retrieval, at
-$0.50 per thousand queries.
+The brain wires itself. Every page write extracts entity references and creates typed links (`attended`, `works_at`, `invested_in`, `founded`, `advises`) with zero LLM calls. Hybrid search. Self-wiring knowledge graph. Structured timeline. Backlink-boosted ranking. Ask "who works at Acme AI?" or "what did Bob invest in this quarter?" and get answers vector search alone can't reach. Benchmarked side-by-side: gbrain lands **P@5 49.1%, R@5 97.9%** on a 240-page Opus-generated rich-prose corpus, beating its graph-disabled variant by **+31.4 points P@5** and ripgrep-BM25 + vector-only RAG by a similar margin. Full BrainBench scorecards live in the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo.
-For relational questions ("who works at this company?", "what did this
-founder invest in this quarter?"), gbrain's self-wiring knowledge graph
-makes the answer roughly **4× more relevant** than plain vector RAG. The
-graph isn't hand-curated. Every page write extracts entity references and
-creates typed edges (`works_at`, `attended`, `invested_in`, `founded`,
-`advises`) with zero language-model calls.
+**New default in v0.36.2.0: ZeroEntropy** for both embedding (`zembed-1` at 1280d via Matryoshka) and reranker (`zerank-2`). On a real-corpus benchmark vs OpenAI and Voyage: **2.2× faster** (442ms vs OpenAI 973ms), **2.6× cheaper at regular pricing** ($0.05/M vs OpenAI $0.13), wins 11 of 20 queries head-to-head, reshuffles 60% of top-1 results when used as a second-pass reranker. Bring your own key from [zeroentropy.dev](https://dashboard.zeroentropy.dev), or stay on OpenAI/Voyage via `gbrain config set embedding_model <provider:model>` — your choice is sticky.
-[Receipts on the evals →](#receipts-on-the-evals)
+GBrain is those patterns, generalized. Install in 30 minutes. Your agent does the work. As Garry's personal agent gets smarter, so does yours.
-I'm the President and CEO of Y Combinator, and I use this 16 hours a day.
-The production brain powering my OpenClaw and Hermes deployments has grown
-into the largest documented personal-AI knowledge graph in active use:
+**New in v0.35.7 — Temporal trajectory + founder scorecard.** Author typed metric assertions in the `## Facts` fence (`mrr=50000`, `arr=2000000`, `team_size=12`) and gbrain stores them as first-class typed columns. `gbrain eval trajectory companies/acme-example` prints the chronological history with regressions auto-flagged inline. `gbrain founder scorecard companies/acme-example` rolls up claim accuracy, consistency, growth direction, and red flags into a stable `schema_version: 1` JSON contract. New MCP op `find_trajectory` exposes the same data to agents (read scope, visibility-filtered for remote callers). The `consolidate` cycle phase now writes `valid_until` on chronologically-superseded facts AND uses semantic upsert on `(page_id, claim, since_date)` — re-running the dream cycle on stable input is now a true no-op (fixed a pre-existing duplicate-takes bug from prior versions).
-| | |
-|---|---|
-| **~100K** | total items in the brain |
-| **~16,000** | people pages, auto-enriched |
-| **~5,000** | companies |
-| **~8,000** | concepts |
-| **~4,000** | original essays + ideas + drafts |
-| **~3,500** | daily notes |
-| **~31,000** | media items (tweets, books, papers, interviews, films, articles, calls) |
-| **~2,200** | LLM-conversation transcripts (ChatGPT, Claude, Perplexity, agent forks) |
-| **108** | cron jobs running autonomously |
-| **273** | skills in the live agent fork (35 from gbrain bundle + 238 user-built on top) |
-
-The agent ingests meetings, emails, tweets, voice calls, books, papers, and
-original ideas while you sleep. It enriches every person and company it
-encounters. It fixes its own citations, consolidates memory overnight,
-detects contradictions in your typed claims about people and companies, and
-flags trajectory regressions. You wake up and the brain is smarter than when
-you went to bed.
-
-GBrain is those patterns, generalized. As my personal agent gets smarter,
-so does yours.
-
-### What it is, technically
-
-- **Open-source** (MIT) TypeScript CLI + MCP server. One binary, no service
- to host. Mac and Linux. Requires [Bun](https://bun.sh) 1.3+.
-- **Local-first.** Your brain lives in `~/.gbrain` on your machine. Embedded
- Postgres (PGLite via WASM) so there's no database to install — ready in
- ~2 seconds. Or point at your own Postgres / Supabase for big brains.
-- **Your data stays on disk.** Embedding calls hit OpenAI / Voyage / Anthropic
- only if you configure those keys. Sync, search, and graph extraction all
- run locally with zero outbound traffic.
-- **Speaks MCP.** Plugs into Claude Code, Cursor, Windsurf, ChatGPT desktop,
- and any agent that consumes the Model Context Protocol — stdio for local,
- HTTP + OAuth 2.1 for multi-user.
-
-> **LLMs:** fetch [`llms.txt`](llms.txt) for the doc map, or
-> [`llms-full.txt`](llms-full.txt) for the map with core docs inlined.
-> **Agents:** start with [`AGENTS.md`](AGENTS.md) (or
-> [`CLAUDE.md`](CLAUDE.md) for Claude Code).
+> **~30 minutes to a fully working brain.** Database ready in 2 seconds (PGLite, no server). You just answer questions about API keys.
----
+> **LLMs:** fetch [`llms.txt`](llms.txt) for the documentation map, or [`llms-full.txt`](llms-full.txt) for the same map with core docs inlined in one fetch. **Agents:** start with [`AGENTS.md`](AGENTS.md) (or [`CLAUDE.md`](CLAUDE.md) if you're Claude Code).
## Install
-Three paths, ordered by how much you're committing.
-
-### Path 1 — 60 seconds, just try it (standalone CLI)
-
-```bash
-git clone https://github.com/garrytan/gbrain.git
-cd gbrain && bun install && bun link
-gbrain init # brain ready in ~2 seconds (PGLite)
-gbrain import ~/notes/ # index any directory of markdown
-gbrain query "what themes show up across my notes?"
-```
-
-What you'll see — gbrain finds the relevant pages, ranks them by hybrid
-search, and prints the top hits with snippets:
-
-```
-$ gbrain query "what themes show up across my notes?"
-Found 8 results in 124ms (hybrid: vector + keyword + RRF)
-
-1. concepts/durable-systems.md (score 0.91)
- "Software that survives its maintainers has three properties: ..."
-2. essays/2025-thinking-out-loud.md (score 0.87)
- "I keep coming back to the idea that the best companies ..."
-3. meetings/2026-02-12-alice-call.md (score 0.83)
- "Discussed how Alice's framework for ..."
-...
-```
+GBrain runs in three shapes. Pick the one that matches how you use AI agents today.
-Add `gbrain extract all` after import to build the knowledge graph
-(entity links + timeline edges). `gbrain dream` runs the full 9-phase
-maintenance cycle.
+### Run with your agent platform
-### Path 2 — Plug it into Claude Code / Cursor (MCP)
+Already using [OpenClaw](https://github.com/garrytan/openclaw) or [Hermes](https://github.com/garrytan/hermes)? GBrain installs as a skillpack into your agent's workspace.
```bash
-# Local single-user via stdio MCP
-claude mcp add gbrain "$(which gbrain) serve"
-
-# Multi-user via HTTP MCP with OAuth 2.1 + admin dashboard
-gbrain serve --http # prints admin bootstrap token
-gbrain serve --http --bind 0.0.0.0 --public-url https://brain.example.com
+gbrain init --pglite
+gbrain skillpack install
```
-Now ask Claude / Cursor "what did Alice and I discuss last quarter?"
-and it queries your brain. The HTTP server supports OAuth 2.1
-(`client_credentials`, `authorization_code` with PKCE, refresh rotation,
-revocation, RFC 7591 DCR). Source-scoped clients (`--source dept-x`) tie
-write authority to one source; `--federated-read S1,S2,S3` adds orthogonal
-read scopes. Loopback bind by default — pass `--bind 0.0.0.0` to publish.
+That's it. Your agent picks up 43 skills (signal detection, brain-ops, ingest, enrich, citation-fixer, daily-task-manager, cron-scheduler, eval framework, and 35 more). Routing lives in `skills/RESOLVER.md` — the agent reads it once per request, picks the right skill, executes.
-### Path 3 — Full agentic install (~30 min)
+### CLI standalone
-If you want the nightly auto-enrichment, cron jobs, and overnight
-synthesis I described above, the brain needs an agent to drive it.
+Use gbrain from any shell, no agent platform required.
-- **[OpenClaw](https://openclaw.ai)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
-- **[Hermes Agent](https://github.com/NousResearch/hermes-agent)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
-
-Then paste this into your agent:
-
-```
-Retrieve and follow the instructions at:
-https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md
+```bash
+bun install -g github:garrytan/gbrain
+gbrain init --pglite # 2 seconds; no server, no Docker
+gbrain doctor # verify health
```
-It clones the repo, installs GBrain, sets up the brain, scaffolds 35
-skills, configures recurring jobs, and asks you for the API keys it
-needs. Budget ~30 minutes for the conversation.
-
----
-
-## Receipts on the evals
-
-The lead's numbers come from published, reproducible eval runs. Sibling
-repo [gbrain-evals](https://github.com/garrytan/gbrain-evals) has the full
-reports, corpora, and cross-system tables. Glossary so the metric jargon
-below doesn't get in the way:
-
-- **R@5** — did the right answer land in gbrain's top 5? Higher is better.
-- **P@5** — what fraction of the top 5 are actually correct? Higher is better.
-- **No LLM in the loop** — retrieval uses embeddings + keyword search +
- ranking, with no language model called per query. Cheaper, deterministic,
- reproducible.
-
-### LongMemEval — the standard public memory benchmark
-
-500 questions across 6 question types, each against a haystack of ~50
-conversation sessions. Built by [Wu et al.](https://huggingface.co/datasets/xiaowu0162/longmemeval),
-the published yardstick for memory systems.
-
-| System | R@5 | LLM in retrieval? | Notes |
-|---|---|---|---|
-| **gbrain-hybrid** | **97.60%** | no | this run, 2026-05-07 |
-| MemPalace hybrid+rerank (held-out) | 98.4% | yes | 0.8pt ahead because they pay for an LLM call per query |
-| MemPalace raw | 96.6% | no | gbrain wins this head-to-head by 1pt |
-| Hindsight | 91.4% | yes | per their release |
-| Stella (academic) | ~85% | no | dense retriever |
-| Contriever (academic) | ~78% | no | dense retriever |
-| BM25 (sparse) | ~70% | no | keyword baseline |
-
-Mastra (94.87%) and Supermemory (~99%) publish on this dataset but measure
-end-to-end QA accuracy with an LLM judge, which is a different thing than
-"did retrieval find the right session." Not directly comparable; flagged
-honestly in the [cross-system table](https://github.com/garrytan/gbrain-evals/blob/main/docs/comparison-systems.md).
-Reports + reproduction:
-[2026-05-07 LongMemEval](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-05-07-longmemeval-s.md).
-
-### BrainBench — relational queries (in-house corpus)
-
-LongMemEval is conversation-style. The other half of the proof is relational
-questions over a structured knowledge base. We built a 240-page rich-prose
-corpus (80 people, 80 companies, 50 meetings, 30 concepts) and wrote 145
-relational gold queries — "who attended this meeting?", "what's this person
-invested in?" — against it. Reproducible, deterministic.
-
-| Retrieval system | P@5 | Δ vs gbrain |
-|---|---|---|
-| **gbrain** (hybrid + knowledge graph) | **49.1%** | — |
-| Vector + keyword RRF (graph turned off) | 17.8% | −31.4 |
-| Keyword search only (BM25) | 17.1% | −32.0 |
-| Vector-only RAG | 10.8% | −38.4 |
-
-The knowledge graph layer is worth **31 points P@5** on these queries.
-Separable, measured, load-bearing. Flat across seven releases (v0.16 → v0.20)
-— zero retrieval regression while ops + infra changed underneath.
-[Full report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-04-23-brainbench-v0.20.0.md)
-
-### Curated content vs bulk swamp
-
-Personal brains accumulate bulk content (tweet dumps, daily chat
-transcripts, archived articles). When a query phrase appears in both a
-short curated essay AND a long chat dump, which wins? Source-aware ranking
-keeps the essay on top. **93.3% top-1 hit** (vs 80% on grep-only). [Report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-04-25-brainbench-cat13b-source-swamp.md)
-
-### Calibration loop — the brain that knows how you've been wrong
-
-v0.36.1.0's calibration wave extracts gradeable claims from your prose,
-grades them against reality over time, and applies the resulting bias
-profile when the AI gives you advice. **First published benchmark for AI
-memory systems that reason about user track records.**
-
-| Eval | Result | Cost |
-|---|---|---|
-| **cat14 — advice quality A/B** | **75% calibrated wins / 0% baseline wins / 25% tie** | ~$0.05 per run |
-| **cat15 — propose_takes F1** | **0.952 training / 0.922 holdout** (gap 0.03, no overfitting) | ~$0.10 per run |
-
-Voice gate 100%, force-fit prevention 100%. Hindsight introduced the
-concept as a skill demo without quantified evaluation; cat14 + cat15
-stake out the category. The iteration log at `cat14-calibration/`
-captures three same-day prompt variants where the eval caught two
-regressions before either could ship.
-[Full report.](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-05-18-brainbench-cat14-cat15-calibration.md)
-
-### Prompt compression
-
-Routing rule: the `functional-area-resolver` skill compresses a fat
-`AGENTS.md` into a two-layer dispatch table. A real-world 25KB resolver
-compressed to **13KB (48% the size) and gained 13–17 percentage points of
-routing accuracy** across Opus 4.7, Sonnet 4.6, and Haiku 4.5. The
-`(dispatcher for: ...)` clause is load-bearing — strip it (same
-compression, no dispatcher signal) and Sonnet's accuracy collapses to
-41.7%. [Cross-model receipts in this repo.](evals/functional-area-resolver/)
-
-### Run your own evals
+Then point any MCP-aware client (Claude Code, Cursor, Windsurf) at it, or use it from your shell:
```bash
-# Public benchmark, in-process, ~30s warm
-gbrain eval longmemeval ~/Downloads/longmemeval_s.jsonl
-
-# Multi-model output quality gate (3 frontier models score the same output)
-gbrain eval cross-modal --task "..." --output report.md
-
-# Capture real query/search traffic as regression-eval data
-GBRAIN_CONTRIBUTOR_MODE=1 gbrain eval export > snapshot.ndjson
-gbrain eval replay --against snapshot.ndjson
-
-# In-house BrainBench corpus + multi-adapter runner
-cd ~/git/gbrain-evals && bun eval/runner/multi-adapter.ts
+gbrain search "who works at acme AI?"
+gbrain query "what did bob invest in this quarter?"
+gbrain graph-query people/garry-tan --depth 2
```
-Full BrainBench corpus + per-category scorecards (Cats 1–13) in the sibling
-[gbrain-evals](https://github.com/garrytan/gbrain-evals) repo.
-
----
-
-## What it does
-
-### 1. Ingests everything, enriches automatically
-
-Markdown sync from a git brain. Meeting transcripts (Whisper / Groq Whisper).
-EPUB / PDF books (`book-mirror` produces personalized chapter-by-chapter
-analysis). PDFs of academic papers with citation extraction. Articles via
-Reader / Perplexity / archive.is. Tweets (timeline + bookmarks). Voice notes.
-ChatGPT / Claude / Perplexity / agent-fork conversation exports. Email
-threads. Calendar events. Foursquare exports. Slack channel archives.
-
-Every page write extracts entity references → typed links (`attended`,
-`works_at`, `invested_in`, `founded`, `advises`, `mentions`) with zero LLM
-calls. The graph wires itself.
-
-### 2. Hybrid search that beats vector-only RAG
+Detailed setup paths (Postgres at scale, Supabase, thin-client mode) live in [`docs/INSTALL.md`](docs/INSTALL.md).
-Per-query: vector + keyword + RRF fusion + multi-query expansion (Haiku) +
-source-aware ranking + reranking (ZeroEntropy, optional). Two-stage CTE so
-the HNSW index stays usable when source-boost re-ranks the top-K. Hard
-exclude prefixes (`test/`, `archive/`, etc.) at retrieval. Intent classifier
-auto-selects detail level by query type (entity / temporal / event /
-general). **P@5 49.1%, R@5 97.9%** on the BrainBench corpus.
-
-### 3. Self-maintaining via the dream cycle
-
-A 9-phase nightly cycle: `lint → backlinks → sync → synthesize → extract →
-patterns → recompute_emotional_weight → embed → orphans` (+ a `purge` phase
-for the destructive-guard lifecycle). Each phase is independently runnable
-via `gbrain dream --phase <name>`. Subagents fan out under a rate-leased
-Anthropic client; protected job names gate trust; per-job + per-cycle
-timeouts; auto-replay on stalled jobs. Conversation transcripts become brain
-pages with content-hash dedup so re-runs are no-ops.
-
-### 4. Multi-source brains + temporal trajectory
-
-`gbrain sources add <id> --local-path <path>` mounts additional brains
-alongside your `host` brain (team-published, CEO-class, departmental). Each
-source has its own RLS-isolated DB rows. OAuth clients can write to one
-source and read federated.
-
-Author typed claims in the `## Facts` fence: `mrr=50000`, `arr=2000000`,
-`team_size=12`, `valuation_usd=15000000`. `gbrain eval trajectory
-companies/<slug>` prints the chronological history with regressions
-auto-flagged. `gbrain founder scorecard <entity>` rolls up claim accuracy,
-consistency, growth direction, and red flags into a stable JSON contract.
-
-### 5. Durable background work
-
-`gbrain agent run <prompt>` submits LLM-loop subagents. `gbrain jobs submit
-shell --params '{"cmd":"..."}'` (operator-only) submits shell jobs.
-`gbrain jobs supervisor start` runs a self-restarting worker daemon with
-crash-cause classification, OOM detection, RSS watchdog, and per-cause
-metrics surfaced in `gbrain doctor`. `gbrain autopilot --install` registers
-the dream cycle as a launchd / systemd job.
-
-Children + aggregator parents, `child_done` inbox for fan-in, per-job
-timeouts, idempotency keys, cascade-kill. Supervisor classifies exit codes
-into `runtime_error / oom_or_external_kill / graceful_shutdown / clean_exit`
-so `120 crashes/24h` reads correctly instead of false-alarming on clean
-worker drains.
-
----
-
-## Multi-player and company brains
-
-Three ways to share a brain across multiple agents, machines, or teammates.
-Most setups want pattern 1 (single server, multiple MCP clients). The other
-two patterns exist for specific reasons.
-
-### Pattern 1 — One GBrain server, many MCP clients (recommended)
-
-The GBrain server runs on the same machine or container as your primary
-agent (OpenClaw, Hermes, AlphaClaw). It publishes an MCP endpoint over
-HTTP with OAuth 2.1. Other agents — on other machines, in other apps,
-across teammates' laptops — connect as thin MCP clients.
-
-```bash
-# On the box that hosts your brain + primary agent:
-gbrain serve --http --bind 0.0.0.0 --public-url https://brain.example.com
-# Prints a one-time admin bootstrap token; paste it into the admin UI
-# at /admin to register OAuth clients.
-
-# On any other machine, set up a thin client:
-gbrain init --mcp-only
-# Walks you through pointing at the server URL + OAuth credentials.
-# No local database, no scaffolded skills — just a routing shim.
-```
-
-**Network: use Tailscale.** Run the server on a Tailscale-private address
-so the brain is reachable from your other machines without exposing
-anything to the public internet. Public-internet exposure works fine
-(OAuth + loopback-bind-by-default + admin dashboard handle it), it's just
-a larger blast radius. For teams, Tailscale + OAuth is the cheap path to
-"my engineering team's agents all read from one shared brain."
-
-**What thin clients CAN do** (subject to OAuth scope: `read` / `write` / `admin`):
-
-- `search`, `query`, `think` — full retrieval pipeline, including the
- knowledge graph + reranking
-- `get_page`, `list_pages`, `put_page`, `delete_page`, `restore_page` —
- page CRUD (`put_page`/`delete_page` require `write` scope)
-- `find_experts` (whoknows), `find_trajectory`, `find_orphans`,
- `find_anomalies`, `find_contradictions` — the analytical surfaces
-- `get_recent_salience`, `get_brain_identity` — observability
-- `apply-migrations`, `restore_page` — admin scope, OAuth-gated
-- Anything else marked `localOnly: false` in `src/core/operations.ts`
-
-**What thin clients CANNOT do** (server-side only, by design):
-
-- `sync_brain` — needs filesystem access to the git brain repo
-- `file_upload`, `file_list`, `file_url` — server-side S3 / Supabase
- Storage credentials don't cross the trust boundary
-- `get_recent_transcripts` — raw `.txt` transcripts; privacy gate keeps
- these local
-- `purge_deleted_pages` — destructive, admin-only, local-only
-- `code_traversal_cache_clear` — local maintenance
-
-If a thin client tries one of these, the server returns a clear
-"local-only" error pointing at the local CLI.
-
-**Source-scoped clients (v0.34+).** A teammate's OAuth client can be tied
-to a single source with `--source dept-x`; its writes are isolated to
-that source's RLS-protected rows. `--federated-read S1,S2,S3` adds
-orthogonal read scopes so the client can read across departments while
-writing to one canon. Useful when a team has a shared brain AND
-contributes back to a CEO-class brain.
-
-### Pattern 2 — Local PGLite for code search (GStack)
-
-For an engineering agent that wants symbol-aware code search on the
-repo it's currently working in, run a local PGLite instance instead of
-hitting a central GBrain server. [GStack](https://github.com/garrytan/gstack)
-supports this directly: one PGLite per worktree, indexed against that
-worktree's source tree.
+### MCP server (any MCP client)
```bash
-# In the worktree you want to index:
-gbrain init --pglite # ~2 seconds, no server, no creds
-gbrain import . # indexes the worktree's code
-echo "$(pwd)" > .gbrain-source # pins this PGLite to this worktree
-```
-
-`/sync-gbrain` (a GStack skill) keeps the PGLite current as you work.
-Code-aware queries (`gbrain code-def`, `gbrain code-refs`,
-`gbrain code-callers`) walk tree-sitter call-graph edges across 29
-languages. Symbol-aware retrieval works better than `grep` for "where
-is X defined" / "what calls Y" queries.
-
-Don't use this pattern for shared knowledge. PGLite is single-process,
-worktree-scoped, no concurrent writers. The right tool for "my agent
-needs the brain my team uses" is pattern 1.
-
-### Pattern 3 — Federated repos (advanced)
-
-Multiple GBrain servers, each indexing the same brain repo from its
-own git clone. Each server has its own DB; they sync to the same
-markdown source of truth via `gbrain sync`.
-
-Use this when:
-- You want a personal brain AND a team brain that share some content
- (the team's knowledge wiki) but diverge on private notes.
-- You're crossing a hard trust boundary (your personal brain is
- read-write to you; the team brain is read-only to most teammates,
- write-gated to a few).
-- The shared content is genuinely repo-shaped (markdown files in git),
- not "we both query each other's brains via MCP."
-
-The mechanics: clone the same brain repo on each server, run
-`gbrain init` against each, configure both to sync from the same git
-remote. Pages land in both databases; the knowledge graph wires
-independently on each side from the same source markdown.
-
-**Most teams should NOT pick this.** The MCP-client path (pattern 1)
-gives you one source of truth, one set of skills, one knowledge graph,
-and OAuth-gated multi-user access. Federated repos make sense when the
-shared content is the source of truth (a published team wiki) and the
-agents are operating against their own private overlays.
-
-My personal setup runs both: a personal brain on my laptop and a team
-brain on a separate box, indexing two different git repos. The team
-brain is what teammates' thin MCP clients connect to; the personal
-brain stays local.
-
----
-
-## Skills
-
-35 curated skills ship in the bundle. The agent installs them via
-`gbrain skillpack scaffold <name>` (one-time additive copy — you own the
-files after). See [docs/guides/skillpacks-as-scaffolding.md](docs/guides/skillpacks-as-scaffolding.md)
-for the model.
-
-### Always-on
-| Skill | What it does |
-|---|---|
-| `signal-detector` | Catches ideas, entities, and TODOs on every message — the always-on capture surface. |
-| `brain-ops` | Brain-first lookup before web search. Enforces the read-enrich-write loop. |
-| `repo-architecture` | File-placement decisions follow the primary subject, not the format. |
-
-### Content ingestion
-| Skill | What it does |
-|---|---|
-| `idea-ingest` | Links / articles / tweets. Mandatory people page for the author. |
-| `media-ingest` | Video / audio / PDF / book with entity extraction. |
-| `meeting-ingestion` | Transcripts → attendee enrichment chaining. |
-| `voice-note-ingest` | Whisper → brain page with entity refs. |
-| `book-mirror` | EPUB / PDF → personalized chapter-by-chapter two-column analysis. |
-| `book-mirror-extreme` | Synthesis pass: lift the book's principles into your own framework. |
-| `brain-pdf` | Render any brain page as a publication-quality PDF. |
-
-### Research + synthesis
-| Skill | What it does |
-|---|---|
-| `perplexity-research` | Bounded Perplexity calls with brain-side dedup. |
-| `academic-verify` | Citation verification + DOI resolution + claim cross-check. |
-| `strategic-reading` | Reading-list curation tuned to active concept clusters. |
-| `archive-crawler` | Crawl + extract from `archive.is` / archive-org bookmarks. |
-| `article-enrichment` | Article → people / companies / concepts links. |
-| `concept-synthesis` | Cross-source synthesis: 3+ pages on one concept → unified writeup. |
-| `data-research` | Email-to-tracker pipeline with parameterized YAML recipes. |
-
-### Brain operations
-| Skill | What it does |
-|---|---|
-| `query` | The default query path. Walks intent classifier + hybrid search. |
-| `enrich` | Tier-escalating enrichment for people / companies / deals. |
-| `maintain` | Background brain hygiene: backlinks, citations, orphans. |
-| `citation-fixer` | Audit and fix citation format issues across the brain. |
-| `frontmatter-guard` | Validate every page's frontmatter against the contract. |
-
-### Operational
-| Skill | What it does |
-|---|---|
-| `daily-task-manager` | Task lifecycle with priority levels (P0–P4). |
-| `daily-task-prep` | Morning prep with calendar context + agenda generation. |
-| `cron-scheduler` | Schedule staggering, quiet hours, idempotency keys. |
-| `reports` | Timestamped reports with keyword routing. |
-| `cross-modal-review` | Quality gate via second model. |
-| `webhook-transforms` | External events → brain signals. |
-| `minion-orchestrator` | Background work: shell jobs + LLM subagents. |
-
-### Identity + meta
-| Skill | What it does |
-|---|---|
-| `soul-audit` | 6-phase interview → SOUL.md / USER.md / ACCESS_POLICY.md / HEARTBEAT.md. |
-| `testing` | Skill validation framework. |
-| `skillify` | The meta-skill: turn any feature into a properly-skilled, tested unit. |
-| `skill-creator` | Create conforming skills with MECE check. |
-| `skillpack-check` | Agent-readable bundle health report. |
-| `skillpack-harvest` | Lift a proven skill from your fork back into gbrain (privacy-linted). |
-| `functional-area-resolver` | Two-layer dispatch for compressing AGENTS.md / RESOLVER.md. |
-
-### Conventions (shared deps, installed alongside every skill)
-- `_AGENT_README.md` — agent operating contract: how to discover skills via frontmatter
-- `_brain-filing-rules.md` — file-placement rules (primary subject wins)
-- `_output-rules.md` — output quality standards (no LLM slop)
-- `_friction-protocol.md` — log user friction to `~/.gstack/friction/`
-- `conventions/` — cross-cutting rules (quality, brain-first, model-routing, test-before-bulk, cross-modal)
-
----
-
-## How it works
-
-### Architecture
+gbrain serve # stdio MCP (Claude Desktop / Code / Cursor)
+gbrain serve --http # HTTP MCP with OAuth 2.1 + admin dashboard
+ # at /admin, SSE activity feed at /admin/events
+```
-Contract-first: `src/core/operations.ts` defines ~47 shared operations. CLI
-and MCP server are both generated from that one source. Engine factory
-dynamically imports the configured engine (`pglite` for zero-config local,
-`postgres` for Supabase / self-hosted).
+Per-client guides (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork) live under [`docs/mcp/`](docs/mcp/). HTTP server supports DCR-style client registration, scope-gated access (`read`/`write`/`admin`), and built-in rate limiting.
-**Trust boundary:** `OperationContext.remote` distinguishes trusted local
-CLI (`remote: false`) from untrusted agent-facing callers (`remote: true`).
-Security-sensitive operations tighten when `remote: true` is set.
+## What it does (the loop)
-### Knowledge model
+```
+ signal → search → respond → write → auto-link → sync
+ (every (brain-first (informed (page + (typed edges (cron
+ message) retrieval) by context) timeline) + backlinks) keeps fresh)
+```
-Every brain page is markdown with YAML frontmatter:
-- **Frontmatter:** `name`, `type` (person / company / deal / concept / ...),
- `tags`, optional `sources:`, `triggers:` (for skills), `## Facts` fenced
- block with typed claims (`mrr=50000`, `arr=2000000`).
-- **Compiled truth:** stable section the agent updates with consensus
- knowledge.
-- **Timeline:** append-only event log, sentinel-separated (`<!-- timeline -->`).
+- **Signal detector** runs on every message your agent receives. Captures ideas, entity mentions, time-sensitive todos, names, links.
+- **Brain-first lookup** before any external API call. The cheapest, fastest, most personal information source you have.
+- **Auto-link** fires on every page write. No LLM calls; pure pattern matching on `[[wiki/people/bob]]` style references. New entity → new page stub → graph grows.
+- **Cron-driven enrichment** runs while you sleep: dedup people pages, fix citations, score salience, find contradictions, prep tomorrow's tasks.
-Pages are chunked by recursive markdown structure (default) or LLM-guided
-(opt-in). 29 programming languages get tree-sitter semantic chunking with
-embedded WASM grammars and tiktoken token budgeting.
+The whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.
-### Knowledge graph
+## Capabilities
-Every page write fires `extract.ts`:
-- Matches `[Name](people/slug)` markdown links AND `[[people/slug|Name]]`
- Obsidian wikilinks.
-- Heuristics infer link type: `attended`, `works_at`, `invested_in`,
- `founded`, `advises`, `source`, `mentions`.
-- Bulk-insert via `unnest()` arrays — 4-5 params regardless of batch size,
- sidesteps the 65535-param cap.
+**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md). Default: `balanced` with ZeroEntropy reranker on.
-Query: `gbrain graph-query alice --depth 2 --direction in` returns who
-attended what with Alice, transitively.
+**Self-wiring knowledge graph.** Every `put_page` extracts entity refs from markdown/wikilinks/typed-link syntax and writes edges with zero LLM calls. Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. The graph is what produces the +31.4 P@5 lift over vector-only RAG.
-### Search
+**Job queue (Minions).** BullMQ-shaped, Postgres-native job queue. Durable subagents (LLM tool loops that survive crashes via two-phase pending→done persistence), shell jobs with audit, child jobs with cascading timeouts, rate leases for outbound providers, attachments via S3/Supabase storage. Replaces "spawn subagent as fire-and-forget Promise" with something that recovers from anything.
-Per-query pipeline:
-1. Query intent classifier (entity / temporal / event / general) selects
- detail level.
-2. Multi-query expansion via Haiku (deterministic, off by default in
- `conservative` mode).
-3. Hybrid: keyword (`ts_rank` × source-factor) + vector (HNSW + source-boost
- re-rank) + RRF fusion.
-4. Optional reranker (ZeroEntropy `zerank-2` flagship or `zerank-1`).
-5. Source-aware ranking: curated content (`originals/`, `concepts/`,
- `writing/`) outranks bulk content (chat transcripts, `daily/`,
- `media/x/`). Hard-exclude `test/`, `archive/`, `attachments/` by default.
-6. Dedup + token budget enforcement per mode.
+**43 curated skills.** Routing lives in [`skills/RESOLVER.md`](skills/RESOLVER.md). Covers signal capture, ingest (idea / media / meeting), enrichment, querying, brain ops, citation fixing, daily task management, cron scheduling, reports, voice, soul audit, skill creation, eval framework, and migrations. Skills are markdown files (tool-agnostic), packaged as a single skillpack the installer drops into your agent workspace.
-### Engines
+**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. `gbrain eval export` + `gbrain eval replay` capture real queries and replay them against code changes (set `GBRAIN_CONTRIBUTOR_MODE=1`). `gbrain eval cross-modal` cross-checks an output against the task using three different-provider frontier models. Full methodology in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md).
-- **PGLite** — embedded Postgres 17.5 via WASM. Zero-config default. Single-
- file backup. Forward-reference bootstrap walks schema migrations cleanly
- across the v0.13–v0.35 wave.
-- **Postgres + pgvector** — Supabase / self-hosted. `pg_trgm` + HNSW indexes.
- Migrations include 60+ schema bumps with `sqlFor.postgres` / `sqlFor.pglite`
- branches for engine-specific DDL.
+**Brain consistency.** `gbrain eval suspected-contradictions` samples retrieval pairs, layered date pre-filter, query-conditioned LLM judge, persistent cache. Surfaces conflicts between takes + facts the agent has written. Wired into the daily dream cycle.
-`gbrain migrate --to supabase` / `--to pglite` does the round-trip.
+## Integrations
-### Storage tiering
+Data flowing into the brain. Each integration is a recipe — markdown + setup hints — that ships in `recipes/` and is discoverable via `gbrain integrations list`.
-For brains crossing 100K files where bulk machine-generated content
-dominates the size: declare which directories are `db_tracked` (committed)
-vs `db_only` (DB-only, gitignored). `gbrain sync` manages `.gitignore`
-automatically; `gbrain export --restore-only` repopulates missing DB-only
-files from the database.
+- **Voice**: Whisper or Groq voice-to-brain capture. Setup in [`docs/integrations/voice.md`](docs/integrations/voice.md).
+- **Email + calendar**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
+- **Embedding providers**: 14 recipes covering OpenAI (default fallback), Voyage, ZeroEntropy (default), Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy. Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
+- **Credential gateway**: vault-aware secret distribution. [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
+- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
-See [docs/guides/storage-tiering.md](docs/guides/storage-tiering.md) for the
-config shape and per-tier defaults.
+## Architecture
----
+**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines ~47 operations both engines implement; CLI and MCP server are generated from one source.
-## Commands
+**Brain repo is the system of record.** Your knowledge lives in a regular git repo (your "brain repo") as markdown files. GBrain syncs the repo into Postgres for retrieval; deletes in git become soft-deletes in DB. You can publish public subsets, share team mounts, run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
-```
-SETUP
- gbrain init [--pglite | --supabase] Set up a brain. Picks search mode.
- gbrain migrate --to {supabase,pglite} Round-trip between engines.
- gbrain doctor [--fast] [--fix] Health check + auto-repair.
-
-CONTENT
- gbrain sync [--workers N] Pull from the git brain.
- gbrain import <path> Index any directory of markdown.
- gbrain embed [--stale] Compute / refresh embeddings.
- gbrain extract {links,timeline,all} Build the knowledge graph.
-
-SEARCH + QUERY
- gbrain query "<question>" Hybrid search + RRF + reranking.
- gbrain search "<text>" Lower-level: vector | keyword | hybrid.
- gbrain whoknows <topic> Expertise routing across the graph.
- gbrain graph-query <slug> Typed-edge traversal.
- gbrain orphans Pages with zero inbound links.
- gbrain salience [--days N] Pages ranked by emotional + activity.
- gbrain anomalies [--lookback-days N] Cohort-level outlier detection.
-
-AGENTS + JOBS
- gbrain agent run "<prompt>" Submit a subagent run.
- gbrain agent logs <id> Tail the run's heartbeat + transcript.
- gbrain jobs submit shell --params ... Submit a shell job (operator-only).
- gbrain jobs supervisor start Self-restarting worker daemon.
-
-CYCLE + AUTOPILOT
- gbrain dream [--phase NAME] Run the 9-phase brain cycle.
- gbrain autopilot --install Register cycle as launchd / systemd job.
-
-SKILLPACK
- gbrain skillpack list What's in the bundle.
- gbrain skillpack scaffold <name> Copy a skill into your agent repo.
- gbrain skillpack reference <name> Diff vs bundle. Or --all --since <ver>.
- gbrain skillpack migrate-fence One-shot upgrade from pre-v0.36 model.
- gbrain skillpack harvest <slug> --from <host>
- Lift a proven fork skill into gbrain.
-
-SERVE
- gbrain serve Stdio MCP (single-user, Claude Code).
- gbrain serve --http [--bind HOST] HTTP MCP + OAuth 2.1 + admin dashboard.
-
-EVAL + TRAJECTORY
- gbrain eval longmemeval <dataset> LongMemEval benchmark, in-memory PGLite.
- gbrain eval cross-modal --task "..." 3 frontier models score the same output.
- gbrain eval whoknows <fixture> Two-layer gate for whoknows accuracy.
- gbrain eval suspected-contradictions Cached contradiction probe.
- gbrain eval trajectory <entity> Typed-claim history + regression flags.
- gbrain founder scorecard <entity> Claim accuracy / consistency / growth.
-
-INTEGRATIONS + SOURCES
- gbrain integrations list Recipe catalog (Reader, Perplexity, etc).
- gbrain sources {list,add,remove,...} Multi-source brain management.
- gbrain auth register-client <name> Mint an OAuth client for the HTTP MCP.
-```
-
-Run `gbrain <command> --help` for per-command options.
+**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
----
+**Why the graph matters.** Vector search returns chunks that are semantically close. The graph returns chunks that are factually connected. Hybrid search pulls from both; auto-linking on every write keeps the graph fresh. Deep dive: [`docs/architecture/RETRIEVAL.md`](docs/architecture/RETRIEVAL.md).
## Docs
-- **Architecture:** [`docs/architecture/`](docs/architecture/)
-- **Skills as scaffolding (v0.36):** [`docs/guides/skillpacks-as-scaffolding.md`](docs/guides/skillpacks-as-scaffolding.md)
-- **Search modes + cost matrix:** [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](docs/eval/SEARCH_MODE_METHODOLOGY.md)
-- **Storage tiering:** [`docs/guides/storage-tiering.md`](docs/guides/storage-tiering.md)
-- **Embedding providers (14 recipes):** [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md)
-- **Eval capture (BrainBench-Real):** [`docs/eval-bench.md`](docs/eval-bench.md)
-- **MCP per-client setup:** [`docs/mcp/`](docs/mcp/)
-- **Two-repo pattern (agent vs brain):** [`docs/guides/repo-architecture.md`](docs/guides/repo-architecture.md)
-- **Skill development cycle:** [`docs/guides/skill-development.md`](docs/guides/skill-development.md)
-- **Per-agent install guide:** [`AGENTS.md`](AGENTS.md), [`CLAUDE.md`](CLAUDE.md), [`INSTALL_FOR_AGENTS.md`](INSTALL_FOR_AGENTS.md)
-- **Full changelog:** [`CHANGELOG.md`](CHANGELOG.md)
+- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end
+- [`docs/architecture/`](docs/architecture/) — system design, topologies, retrieval theory
+- [`docs/guides/`](docs/guides/) — how-to runbooks (sub-agent routing, minion deployment, skill development, brain-first lookup, idea capture, diligence ingestion)
+- [`docs/integrations/`](docs/integrations/) — connecting external data sources (voice, email, calendar, embedding providers)
+- [`docs/mcp/`](docs/mcp/) — per-client MCP setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)
+- [`docs/eval/`](docs/eval/) — eval framework, metric glossary, methodology
+- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)
+- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents
+- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)
+- [`CONTRIBUTING.md`](CONTRIBUTING.md) — contributor guide, test discipline, eval-capture mode
+- [`SECURITY.md`](SECURITY.md) — OAuth threat model, hardening defaults
----
+## Contributing
-## Origin story
+Run `bun run test` for the fast loop, `bun run verify` for the pre-push gate, `bun run ci:local` to run the full Docker-backed CI stack locally. Detailed test discipline in [`CONTRIBUTING.md`](CONTRIBUTING.md).
-I needed a brain that could remember every meeting, every founder
-encounter, every essay I'd ever drafted, every idea I wanted to chase
-later. Off-the-shelf knowledge tools (Roam, Obsidian, Notion) handle
-storage. None of them ingest a meeting, enrich the attendees, build the
-graph, fix the citations, and surface the connection three weeks later
-when it matters. So I built one. The first 12 days produced a working
-brain. The next 12 months produced 100,000 pages, a self-wiring knowledge
-graph, 108 cron jobs, and the multi-engine architecture that ships here.
+Community PRs are batched into release waves rather than merged one-by-one — see the "PR wave workflow" section in [`CLAUDE.md`](CLAUDE.md). Contributor attribution stays attached via `Co-Authored-By:` trailers. We credit every accepted contribution in [`CHANGELOG.md`](CHANGELOG.md).
-GBrain is the generalized version of that work. You scaffold the skills.
-You bring your data. Your agent runs the patterns. The brain compounds
-nightly.
+If you find a bug or want a feature: open an issue first. Quick fixes (typo, doc bug, obvious regression) can go straight to a PR. Anything touching schema, retrieval ranking, MCP protocol, or the security boundary needs a design discussion in the issue first.
----
-
-## Contributing
+## License + credit
-PRs welcome. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the dev loop,
-test taxonomy, and how to ship. Privacy rules in [`CLAUDE.md`](CLAUDE.md)
-are non-negotiable — no real names, fork names, or private references in
-public artifacts. The harvest CLI's privacy linter exists to catch
-accidental leaks before they merge.
+MIT. Built by Garry Tan to run his OpenClaw and Hermes deployments — the production brain behind his actual AI agents.
-## License
+Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).
-MIT.
+Community PR contributors are credited in `CHANGELOG.md` per release. ZeroEntropy ([@zeroentropy](https://zeroentropy.dev)) for the embedding + reranker stack that became the v0.36.2.0 default. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.
---
diff --git a/package.json b/package.json
index 74777a8814..85630b8c44 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.36.1.1",
+ "version": "0.36.2.0",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
diff --git a/scripts/check-test-real-names.sh b/scripts/check-test-real-names.sh
index 4e8fa08009..fc3950e07e 100755
--- a/scripts/check-test-real-names.sh
+++ b/scripts/check-test-real-names.sh
@@ -59,6 +59,8 @@ ALLOWLIST=(
"test/scripts/check-proposal-pii.test.ts:WINTERMUTE" # case-insensitive sentinel literal for the same privacy-guard test
"test/serve-stdio-lifecycle.test.ts:Hermes" # comment naming a downstream-agent scenario — pre-existing, low signal
"test/extract.test.ts:Hermes" # markdown-link extraction test fixture — pre-existing, ambiguous (Greek god vs fork)
+ "test/readme-hero-anchors.test.ts:Hermes" # v0.36.0.0 D9 anchor test — asserts README mentions Hermes as a credit
+ "test/readme-hero-anchors.test.ts:OpenClaw" # v0.36.0.0 D9 anchor test — asserts README mentions OpenClaw as a credit
# v0.36.0.0: skillpack-harvest privacy linter tests structurally
# require the literal "Wintermute" to verify the linter catches it.
# Same meta-rule exception as integrations.test.ts and the proposal-pii
diff --git a/skills/migrations/v0.36.2.0.md b/skills/migrations/v0.36.2.0.md
new file mode 100644
index 0000000000..585a084a77
--- /dev/null
+++ b/skills/migrations/v0.36.2.0.md
@@ -0,0 +1,86 @@
+---
+name: v0.36.2.0
+version: 0.36.2.0
+headline: ZeroEntropy is the new default for embedding + reranker
+---
+
+# v0.36.2.0 Migration: ZeroEntropy as default
+
+**TL;DR:** v0.36.2.0 makes ZeroEntropy (`zembed-1` at 1280d via Matryoshka, `zerank-2` cross-encoder reranker) the default retrieval stack. Real-corpus benchmark says: 2.2× faster than OpenAI, 2.6× cheaper at regular pricing, wins 11/20 head-to-head queries, reranker reshuffles 60% of top-1 results. New installs land on it automatically. Existing brains see a one-shot upgrade prompt with a cost estimate; default-on-Enter is "stay on current provider" so the safe path is the no-action path.
+
+This migration is **opt-in for existing brains**. Running `gbrain upgrade` does not silently re-embed your data. The prompt is TTY-only; non-TTY upgrades (CI, cron, docker) print an informational stderr line and skip the switch.
+
+## What the agent should do post-upgrade
+
+When the user invokes any gbrain command immediately after `gbrain upgrade` to v0.36.2.0:
+
+1. **Check whether the prompt has been surfaced yet.** `gbrain ze-switch --dry-run --json` shows the planner state including `ze_switch_offered`, `ze_switch_prompt_shown`, and the comparison numbers. If `ze_switch_offered` is true and `ze_switch_prompt_shown` is false, the user hasn't seen the prompt yet.
+
+2. **Surface the comparison numbers.** Quote the benchmark from the prompt:
+ - Wins 11/20 queries head-to-head (OpenAI 6, Voyage 4)
+ - 442ms avg vs OpenAI 973ms (2.2× faster)
+ - $0.05/M tokens vs OpenAI $0.13 (2.6× cheaper at regular pricing)
+ - zerank-2 reshuffles 60% of top-1 results
+ - Only 10-18% overlap between providers — pairing primary + reranker compounds
+
+3. **Recommend switching** unless the user has stated a constraint that makes ZE unsuitable (no internet, regulatory concern with a specific provider, contractual commitment to another stack). When recommending, point them at:
+ ```bash
+ gbrain ze-switch # interactive prompt
+ gbrain ze-switch --dry-run # see the plan without applying
+ ```
+
+4. **If the user already declined** (`ze_switch_already_declined` true) and they ask about it later, mention `gbrain ze-switch --force` re-opens the prompt. The 90-day decline window auto-resets after that, so a year-later contributor "we have better benchmarks now" data gets surfaced naturally.
+
+5. **If the user switched and now regrets it**, mention `gbrain ze-switch --undo`. Restores their prior model + dim + reranker state with a symmetric cost-warning prompt (re-embedding back is also a real cost).
+
+## The CLI surface in full
+
+| Command | Effect |
+|---|---|
+| `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. |
+| `gbrain ze-switch --undo --non-interactive --confirm-reembed` | Scripted undo. The `--confirm-reembed` flag is required (un-doing also pays for re-embed). |
+
+## 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 (neither env nor `gbrain config set zeroentropy_api_key`). Fix hint points at the setup URL.
+- **`embedding_width_consistency`** — asserts the configured `embedding_dimensions` matches the actual `vector(N)` width on `content_chunks.embedding`. Warns on drift. Fix hint suggests `gbrain ze-switch --resume` if drift came from a half-applied switch, or `gbrain config set embedding_dimensions <schema-dim>` to match the existing schema.
+
+## 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
+
+- Don't run `gbrain ze-switch --non-interactive --ignore-missing-key` for a user without explaining the consequence — every embed call will fail until they set `ZEROENTROPY_API_KEY`. Surface that loudly.
+- Don't tell the user the sale price ($0.025/M) is the cost they'll pay long-term. It's a promotional rate. The CHANGELOG and prompt cite the regular $0.05/M as the cost anchor.
+- Don't assume the user wants the switch because the comparison numbers favor it. The user owns the decision. The prompt's default-on-Enter is "stay" for exactly this reason.
+
+## 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
+
+```bash
+gbrain doctor # both new checks should be green
+gbrain ze-switch --dry-run # status should be skipped_already_applied
+gbrain models # confirm embedding + reranker defaults
+gbrain search "test query" --limit 5 # confirm the reranker is firing
+```
diff --git a/src/cli.ts b/src/cli.ts
index 976d2920f0..f28e55257d 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -27,7 +27,7 @@ for (const op of operations) {
}
// CLI-only commands that bypass the operation layer
-const CLI_ONLY = new Set(['init', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'founder']);
+const CLI_ONLY = new Set(['init', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'founder']);
// CLI-only commands whose handlers print their own --help text. These are
// excluded from the generic short-circuit so detailed per-command and
// per-subcommand usage stays reachable.
@@ -917,6 +917,19 @@ async function handleCliOnly(command: string, args: string[]) {
return;
}
+ if (command === 'ze-switch') {
+ // v0.36.0.0 — manual ZE-default switch lever. Owns its own engine lifecycle
+ // to mirror the doctor pattern.
+ const { runZeSwitch } = await import('./commands/ze-switch.ts');
+ const eng = await connectEngine();
+ try {
+ await runZeSwitch(args, eng);
+ } finally {
+ await eng.disconnect();
+ }
+ return;
+ }
+
if (command === 'smoke-test') {
// Run smoke tests — no DB connection needed, the script handles its own checks
const { execSync } = await import('child_process');
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 1dac139bdf..fc51410d6a 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -816,6 +816,136 @@ export async function checkRerankerHealth(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 {
+ const model = await engine.getConfig('embedding_model') ?? '';
+ if (!model.startsWith('zeroentropyai:')) {
+ return {
+ name: 'ze_embedding_health',
+ status: 'ok',
+ message: `Configured embedding model "${model || 'default'}" is not ZeroEntropy — skip.`,
+ };
+ }
+ const envKey = process.env.ZEROENTROPY_API_KEY;
+ const configKey = await engine.getConfig('zeroentropy_api_key');
+ if (!envKey && !configKey) {
+ return {
+ name: 'ze_embedding_health',
+ status: 'warn',
+ message:
+ `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set. ` +
+ `Fix: get a key at https://dashboard.zeroentropy.dev and run ` +
+ `\`gbrain config set zeroentropy_api_key <YOUR_KEY>\` (or export ZEROENTROPY_API_KEY).`,
+ };
+ }
+ 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}`,
+ };
+ }
+}
+
+/**
+ * v0.36.0.0 (A5): embedding_width_consistency doctor check.
+ *
+ * Cross-checks that `config.embedding_dimensions` matches the actual
+ * `vector(N)` width on `content_chunks.embedding`. Drift here means the
+ * ze-switch was interrupted mid-flight (schema changed but config write
+ * crashed, or vice versa). Surfaces a paste-ready `gbrain ze-switch
+ * --resume` hint.
+ */
+export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
+ try {
+ const configDimStr = await engine.getConfig('embedding_dimensions');
+ if (!configDimStr) {
+ // Pre-v0.27 brain or never configured. Not our problem.
+ return {
+ name: 'embedding_width_consistency',
+ status: 'ok',
+ message: 'embedding_dimensions not configured — using defaults.',
+ };
+ }
+ const configDim = parseInt(configDimStr, 10);
+ if (!Number.isFinite(configDim) || configDim <= 0) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: `embedding_dimensions config value "${configDimStr}" is not a positive integer. Fix: \`gbrain config set embedding_dimensions <N>\`.`,
+ };
+ }
+
+ // Read the actual column width from pg_attribute / information_schema.
+ // Postgres + PGLite both expose vector typmod via atttypmod (vectors
+ // store dim as typmod). atttypmod==-1 means no constraint; >=0 is the
+ // dim+VARHDRSZ — we use format_type for portability.
+ 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`,
+ );
+ if (rows.length === 0) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: 'content_chunks.embedding column not found. Fix: run `gbrain init --migrate-only` or check schema.',
+ };
+ }
+ const formatType = rows[0].format_type;
+ // Parse 'vector(N)' shape.
+ const m = formatType.match(/vector\((\d+)\)/i);
+ if (!m) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: `Unexpected column type for content_chunks.embedding: "${formatType}".`,
+ };
+ }
+ const schemaDim = parseInt(m[1], 10);
+ if (schemaDim !== configDim) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message:
+ `Schema width mismatch: content_chunks.embedding is vector(${schemaDim}) but ` +
+ `embedding_dimensions config = ${configDim}. ` +
+ `Fix: \`gbrain ze-switch --resume\` if you were mid-switch, or ` +
+ `\`gbrain config set embedding_dimensions ${schemaDim}\` to match the schema.`,
+ };
+ }
+ return {
+ name: 'embedding_width_consistency',
+ status: 'ok',
+ message: `Schema width (${schemaDim}d) matches embedding_dimensions config`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: `Could not check embedding width: ${msg}`,
+ };
+ }
+}
+
/**
* v0.32.3 [CDX-20]: surface mode + per-key override drift.
*
@@ -2901,6 +3031,11 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSo
// v0.35.0.0+ reranker_health — read JSONL audit; warn on auth or volume.
progress.heartbeat('reranker_health');
checks.push(await checkRerankerHealth(engine));
+ // v0.36.0.0 (A5): ZE embedding key health + schema/config width consistency.
+ progress.heartbeat('ze_embedding_health');
+ checks.push(await checkZeEmbeddingHealth(engine));
+ progress.heartbeat('embedding_width_consistency');
+ checks.push(await checkEmbeddingWidthConsistency(engine));
}
progress.finish();
diff --git a/src/commands/ze-switch.ts b/src/commands/ze-switch.ts
new file mode 100644
index 0000000000..76f2e26f25
--- /dev/null
+++ b/src/commands/ze-switch.ts
@@ -0,0 +1,168 @@
+/**
+ * v0.36.0.0 — `gbrain ze-switch` CLI lever for the ZeroEntropy default switch.
+ *
+ * Subcommands / flags:
+ * gbrain ze-switch Run the interactive prompt
+ * gbrain ze-switch --dry-run Plan only; change nothing
+ * gbrain ze-switch --json Machine-readable envelope
+ * gbrain ze-switch --non-interactive Switch without prompting
+ * (errors if ZEROENTROPY_API_KEY missing
+ * unless --ignore-missing-key is also set)
+ * gbrain ze-switch --resume Finish a half-applied switch (recovery)
+ * gbrain ze-switch --force Bypass the `prompt_shown` gate
+ * (use after `n` / never-ask-again)
+ * gbrain ze-switch --undo Reverse: restore prior model + dim
+ * + reranker state. Cost-warning prompt
+ * appears before any change.
+ * gbrain ze-switch --undo --non-interactive --confirm-reembed
+ * Scripted undo path (also pays for re-embed)
+ */
+
+import type { BrainEngine } from '../core/engine.ts';
+import {
+ planRetrievalUpgrade,
+ applyRetrievalUpgrade,
+ resumeRetrievalUpgrade,
+ undoRetrievalUpgrade,
+} from '../core/retrieval-upgrade-planner.ts';
+import {
+ runRetrievalUpgradePrompt,
+ runUndoPrompt,
+} from '../core/retrieval-upgrade-prompt.ts';
+
+interface Flags {
+ dryRun: boolean;
+ json: boolean;
+ nonInteractive: boolean;
+ resume: boolean;
+ force: boolean;
+ undo: boolean;
+ confirmReembed: boolean;
+ ignoreMissingKey: boolean;
+}
+
+function parseFlags(args: string[]): Flags {
+ return {
+ dryRun: args.includes('--dry-run'),
+ json: args.includes('--json'),
+ nonInteractive: args.includes('--non-interactive') || args.includes('--yes'),
+ resume: args.includes('--resume'),
+ force: args.includes('--force'),
+ undo: args.includes('--undo'),
+ confirmReembed: args.includes('--confirm-reembed'),
+ ignoreMissingKey: args.includes('--ignore-missing-key'),
+ };
+}
+
+function printHelp() {
+ process.stdout.write(`Usage: gbrain ze-switch [flags]
+
+Switch the brain's embedding + reranker defaults to ZeroEntropy.
+
+Flags:
+ --dry-run Plan only; change nothing.
+ --json Machine-readable output.
+ --non-interactive Skip prompts; apply directly (CI / scripts).
+ --resume Finish a half-applied switch (crash recovery).
+ --force Bypass the prompt_shown gate (use after --undo or "never ask").
+ --undo Reverse the switch: restore prior model + dim + reranker.
+ --confirm-reembed Required with --undo --non-interactive (re-embed pays cost).
+ --ignore-missing-key Allow --non-interactive without ZEROENTROPY_API_KEY set.
+ --help Show this help.
+`);
+}
+
+export async function runZeSwitch(args: string[], engine: BrainEngine): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) {
+ printHelp();
+ process.exit(0);
+ }
+
+ const flags = parseFlags(args);
+
+ try {
+ // --dry-run: just plan, never apply.
+ if (flags.dryRun) {
+ const plan = await planRetrievalUpgrade(engine);
+ if (flags.json) {
+ console.log(JSON.stringify({ status: 'planned', plan }, null, 2));
+ } else {
+ console.log(`Current model: ${plan.current_embedding_model} (${plan.current_dim}d)`);
+ console.log(`Target model: ${plan.target_embedding_model ?? '(no change)'}`);
+ console.log(`Target dim: ${plan.target_dim ?? '(no change)'}`);
+ console.log(`Pages pending: chunker=${plan.pages_pending_chunker}, dim=${plan.pages_pending_dim}`);
+ console.log(`Est cost: $${plan.est_cost_usd.toFixed(2)}`);
+ console.log(`Est minutes: ${plan.est_minutes}`);
+ console.log(`Schema change: ~${plan.est_schema_change_seconds}s`);
+ console.log(`Offered: ${plan.ze_switch_offered}`);
+ }
+ return;
+ }
+
+ // --resume: complete a half-applied switch.
+ if (flags.resume) {
+ const result = await resumeRetrievalUpgrade(engine);
+ if (flags.json) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`Resume status: ${result.status}`);
+ }
+ process.exit(result.status === 'applied' || result.status === 'skipped_already_applied' ? 0 : 1);
+ }
+
+ // --undo: reverse switch.
+ if (flags.undo) {
+ if (flags.nonInteractive) {
+ if (!flags.confirmReembed) {
+ console.error('--undo --non-interactive requires --confirm-reembed (undo re-embeds at the prior width — costs real money).');
+ process.exit(1);
+ }
+ const result = await undoRetrievalUpgrade(engine);
+ if (flags.json) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`Undo status: ${result.status}`);
+ }
+ process.exit(result.status === 'undone' ? 0 : 1);
+ }
+ // Interactive undo: shows cost-warning prompt.
+ const result = await runUndoPrompt(engine);
+ if (flags.json) {
+ console.log(JSON.stringify(result, null, 2));
+ }
+ process.exit(result.status === 'undone' ? 0 : 1);
+ }
+
+ // --non-interactive: apply without prompting.
+ if (flags.nonInteractive) {
+ if (!process.env.ZEROENTROPY_API_KEY && !flags.ignoreMissingKey) {
+ const config = await engine.getConfig('zeroentropy_api_key');
+ if (!config) {
+ console.error('ZEROENTROPY_API_KEY not set. Pass --ignore-missing-key to switch anyway (embeddings will fail until you set a key).');
+ process.exit(1);
+ }
+ }
+ const plan = await planRetrievalUpgrade(engine);
+ const result = await applyRetrievalUpgrade(engine, plan);
+ if (flags.json) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`Switch status: ${result.status}`);
+ }
+ process.exit(
+ result.status === 'applied' || result.status === 'skipped_already_applied' || result.status === 'skipped_no_work'
+ ? 0
+ : 1,
+ );
+ }
+
+ // Interactive mode.
+ const result = await runRetrievalUpgradePrompt(engine, { force: flags.force });
+ if (flags.json) {
+ console.log(JSON.stringify(result, null, 2));
+ }
+ process.exit(result.status === 'applied' || result.status === 'declined_this_run' || result.status === 'declined_forever' || result.status === 'non_tty_skip' || result.status === 'not_offered' ? 0 : 1);
+ } finally {
+ // Engine lifecycle is owned by the dispatcher.
+ }
+}
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index 558f347ffb..4f170e8fc2 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -65,6 +65,31 @@ 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
+// returns HTTP 400 at first embed. We catch it locally with a paste-ready
+// fix so users don't see opaque "vector dimension mismatch" errors after
+// `gbrain ze-switch --undo` lands them on OpenAI at the wrong dim.
+const OPENAI_TEXT3_MAX_DIMS: Record<string, number> = {
+ 'text-embedding-3-small': 1536,
+ 'text-embedding-3-large': 3072,
+};
+
+export function isOpenAITextEmbedding3Model(modelId: string): boolean {
+ return modelId in OPENAI_TEXT3_MAX_DIMS;
+}
+
+export function maxOpenAITextEmbedding3Dim(modelId: string): number | undefined {
+ return OPENAI_TEXT3_MAX_DIMS[modelId];
+}
+
+export function isValidOpenAITextEmbedding3Dim(modelId: string, dims: number): boolean {
+ const max = OPENAI_TEXT3_MAX_DIMS[modelId];
+ if (max === undefined) return false;
+ return Number.isInteger(dims) && dims >= 1 && dims <= max;
+}
+
/**
* Build the providerOptions blob for embedMany() that pins output dimensions.
*
@@ -95,6 +120,17 @@ export function dimsProviderOptions(
// text-embedding-3-* supports dimensions; text-embedding-ada-002 does not.
// OpenAI embeddings are symmetric — inputType ignored.
if (modelId.startsWith('text-embedding-3')) {
+ // v0.36.0.0 (D13): fail-loud when configured dim is outside the
+ // model's Matryoshka range. OpenAI returns HTTP 400 otherwise with
+ // a generic message that misroutes as a network blip.
+ if (isOpenAITextEmbedding3Model(modelId) && !isValidOpenAITextEmbedding3Dim(modelId, dims)) {
+ const max = maxOpenAITextEmbedding3Dim(modelId)!;
+ throw new AIConfigError(
+ `OpenAI model "${modelId}" supports embedding_dimensions in 1..${max}, got ${dims}.`,
+ `Set \`embedding_dimensions\` to a value between 1 and ${max} ` +
+ `(\`gbrain config set embedding_dimensions ${Math.min(1024, max)}\` is a common default).`,
+ );
+ }
return { openai: { dimensions: dims } };
}
return undefined;
@@ -164,7 +200,16 @@ export function dimsProviderOptions(
// for `-large`, 1536 for `-small`); without `dimensions`, brains
// configured for a smaller width (e.g. 1536) hard-fail at first embed.
// Azure/OpenAI-compat embeddings are symmetric — inputType ignored.
+ // v0.36.0.0 (D13): same range validation as native-openai path.
if (modelId.startsWith('text-embedding-3')) {
+ if (isOpenAITextEmbedding3Model(modelId) && !isValidOpenAITextEmbedding3Dim(modelId, dims)) {
+ const max = maxOpenAITextEmbedding3Dim(modelId)!;
+ throw new AIConfigError(
+ `OpenAI model "${modelId}" supports embedding_dimensions in 1..${max}, got ${dims}.`,
+ `Set \`embedding_dimensions\` to a value between 1 and ${max} ` +
+ `(\`gbrain config set embedding_dimensions ${Math.min(1024, max)}\` is a common default).`,
+ );
+ }
return { openaiCompatible: { dimensions: dims } };
}
// DashScope text-embedding-v3 (Matryoshka 64-1024) and Zhipu
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index b1cc35299e..38d43a99ac 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -42,8 +42,20 @@ import { dimsProviderOptions } from './dims.ts';
import { AIConfigError, AITransientError, normalizeAIError } from './errors.ts';
const MAX_CHARS = 8000;
-const DEFAULT_EMBEDDING_MODEL = 'openai:text-embedding-3-large';
-const DEFAULT_EMBEDDING_DIMENSIONS = 1536;
+// v0.36.0.0 (D3 + D4): ZeroEntropy zembed-1 at 1280d via Matryoshka is the
+// new default for embedding. Real-corpus benchmark across 20 queries:
+// - ZE wins 11/20 (OpenAI 6, Voyage 4)
+// - 442ms avg vs OpenAI 973ms (2.2x faster)
+// - $0.05/M tokens vs OpenAI $0.13/M (2.6x cheaper at regular pricing)
+// ZE valid Matryoshka steps are {2560, 1280, 640, 320, 160, 80, 40}; 1280 is
+// the closest analog to current OpenAI 1536d (smaller -> smaller HNSW index
+// -> faster queries) while staying in the high-recall zone of the Matryoshka
+// curve. 1024 (Voyage's step) is NOT a valid ZE dim — see
+// src/core/ai/dims.ts:ZEROENTROPY_VALID_DIMS.
+// New installs without ZEROENTROPY_API_KEY size for 1280d anyway — the
+// AIConfigError surfaces at first embed with a paste-ready setup hint.
+const DEFAULT_EMBEDDING_MODEL = 'zeroentropyai:zembed-1';
+const DEFAULT_EMBEDDING_DIMENSIONS = 1280;
const DEFAULT_EXPANSION_MODEL = 'anthropic:claude-haiku-4-5-20251001';
const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';
// v0.35.0.0+: reranker default. Used only when search.reranker.enabled is set
diff --git a/src/core/retrieval-upgrade-planner.ts b/src/core/retrieval-upgrade-planner.ts
new file mode 100644
index 0000000000..6dbb0e9e08
--- /dev/null
+++ b/src/core/retrieval-upgrade-planner.ts
@@ -0,0 +1,468 @@
+/**
+ * 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)
+ *
+ * State diagram:
+ *
+ * [fresh brain]
+ * |
+ * | user picks "s" or runs `gbrain ze-switch`
+ * 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. Re-embed via `gbrain embed --stale` or autopilot.
+ *
+ * Crash between schema and config writes:
+ * requested=true, applied=false, schema is at target width.
+ * Doctor's `embedding_width_consistency` detects + suggests `--resume`.
+ *
+ * "Never ask again" path:
+ * prompt_shown=true, declined_at=<iso>. Re-asked after 90 days (C3).
+ *
+ * Undo path:
+ * ze_switch_previous_snapshot JSON drives reverse schema + config.
+ *
+ * The planner is intentionally NOT a migration in the MIGRATIONS array.
+ * Migrations are forward-only and run for every brain on every upgrade.
+ * The ZE switch is conditional (user-requested), idempotent (re-runnable),
+ * and reversible (--undo). Mixing it into MIGRATIONS would muddy the
+ * ledger semantics (see plan D12 for full rationale).
+ */
+
+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';
+
+// ============================================================================
+// Constants
+// ============================================================================
+
+/** v0.36.0.0 cutover target: ZeroEntropy zembed-1 at 1024d 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.
+ */
+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: 'failed'; plan: RetrievalUpgradeState; reason: string };
+
+// ============================================================================
+// 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 this
+ * and suggests `gbrain ze-switch --resume`.
+ */
+export async function applyRetrievalUpgrade(
+ engine: BrainEngine,
+ plan: RetrievalUpgradeState,
+): 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 };
+ }
+
+ 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): 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 };
+ }
+
+ // requested=true, applied=false. Either schema is at target and config
+ // still says source, or schema crashed mid-DDL. Re-run schema transition
+ // (idempotent via CREATE INDEX IF NOT EXISTS + ALTER COLUMN no-op semantics)
+ // then write config + mark applied.
+ try {
+ const targetDim = ZE_TARGET_EMBEDDING_DIM;
+ 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 {
+ 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 (D18)
+// ============================================================================
+
+/**
+ * The atomic DROP + ALTER + CREATE INDEX sequence for content_chunks.
+ * Both engines accept identical SQL (PGLite uses pgvector via WASM, same
+ * grammar). Wrapped in engine.transaction so a partial failure rolls back.
+ *
+ * Index names verified against:
+ * src/schema.sql:163 -> idx_chunks_embedding
+ * src/core/pglite-schema.ts:127 -> idx_chunks_embedding
+ * src/schema.sql:169 -> idx_chunks_embedding_image
+ * src/core/pglite-schema.ts:130 -> idx_chunks_embedding_image
+ *
+ * IF NOT EXISTS on CREATE INDEX makes the operation safe to re-run during
+ * `--resume`.
+ */
+async function runSchemaTransition(engine: BrainEngine, targetDim: number): Promise<void> {
+ await engine.transaction(async (tx) => {
+ await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);
+ await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding_image`);
+ await tx.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding`);
+ await tx.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding vector(${targetDim})`);
+ await tx.executeRaw(`ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_image`);
+ await tx.executeRaw(`ALTER TABLE content_chunks ADD COLUMN embedding_image vector(${targetDim})`);
+ await tx.executeRaw(
+ `CREATE INDEX IF NOT EXISTS idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)`,
+ );
+ await tx.executeRaw(
+ `CREATE INDEX IF NOT EXISTS idx_chunks_embedding_image ON content_chunks USING hnsw (embedding_image vector_cosine_ops)`,
+ );
+ });
+}
+
+// ============================================================================
+// 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/retrieval-upgrade-prompt.ts b/src/core/retrieval-upgrade-prompt.ts
new file mode 100644
index 0000000000..abf6ace33a
--- /dev/null
+++ b/src/core/retrieval-upgrade-prompt.ts
@@ -0,0 +1,273 @@
+/**
+ * v0.36.0.0 — Interactive prompt UI for the retrieval upgrade (D10 + D6 + C2).
+ *
+ * Wires the RetrievalUpgradePlanner to a TTY prompt that:
+ * - Shows the comparison numbers from the v0.36.0.0 wave
+ * - Presents a two-line cost split (D10): schema change + re-embed
+ * - Includes the privacy callout (C2) when balanced-mode reranker flips on
+ * - Honors TTY detection (non-TTY = skip, informational stderr line)
+ * - Default-on-Enter = STAY (safest); explicit 's' = switch, 'l' = later,
+ * 'n' = never ask again
+ *
+ * Used by:
+ * - src/commands/upgrade.ts:runPostUpgrade (post-migration call site)
+ * - src/commands/ze-switch.ts (manual CLI lever)
+ */
+
+import type { BrainEngine } from './engine.ts';
+import {
+ planRetrievalUpgrade,
+ applyRetrievalUpgrade,
+ recordDeclinedThisRun,
+ recordDeclinedForever,
+ resumeRetrievalUpgrade,
+ undoRetrievalUpgrade,
+ type RetrievalUpgradeState,
+ type ApplyResult,
+ type ZeSwitchSnapshot,
+ KEY_PROMPT_SHOWN,
+ KEY_APPLIED,
+ KEY_REQUESTED,
+ ZE_TARGET_EMBEDDING_MODEL,
+ ZE_TARGET_EMBEDDING_DIM,
+} from './retrieval-upgrade-planner.ts';
+
+// ============================================================================
+// Public API
+// ============================================================================
+
+export interface PromptOpts {
+ /** Override stdin TTY detection for tests. */
+ isTTY?: boolean;
+ /** Override the read function for tests (single keypress). */
+ readKey?: () => Promise<string>;
+ /** Where to write the prompt. Defaults to process.stderr. */
+ write?: (line: string) => void;
+ /** Bypass the `prompt_shown` gate (for `gbrain ze-switch --force`). */
+ force?: boolean;
+}
+
+export type PromptResult =
+ | { status: 'applied'; plan: RetrievalUpgradeState }
+ | { status: 'declined_this_run'; plan: RetrievalUpgradeState }
+ | { status: 'declined_forever'; plan: RetrievalUpgradeState }
+ | { status: 'not_offered'; plan: RetrievalUpgradeState; reason: string }
+ | { status: 'non_tty_skip'; plan: RetrievalUpgradeState }
+ | { status: 'failed'; plan: RetrievalUpgradeState; reason: string };
+
+/**
+ * Run the v0.36.0.0 retrieval-upgrade prompt. Returns a tagged-union outcome
+ * so callers can dispatch without parsing strings (mirrors D15).
+ */
+export async function runRetrievalUpgradePrompt(
+ engine: BrainEngine,
+ opts: PromptOpts = {},
+): Promise<PromptResult> {
+ const writeFn = opts.write ?? ((line: string) => process.stderr.write(line + '\n'));
+ const isTTY = typeof opts.isTTY === 'boolean'
+ ? opts.isTTY
+ : Boolean(process.stdin.isTTY);
+
+ // Don't re-ask within the same brain unless --force.
+ if (!opts.force) {
+ const shown = (await engine.getConfig(KEY_PROMPT_SHOWN)) === 'true';
+ const applied = (await engine.getConfig(KEY_APPLIED)) === 'true';
+ if (shown || applied) {
+ const plan = await planRetrievalUpgrade(engine);
+ return { status: 'not_offered', plan, reason: applied ? 'already_applied' : 'prompt_shown' };
+ }
+ }
+
+ const plan = await planRetrievalUpgrade(engine);
+
+ // Nothing to do.
+ if (!plan.ze_switch_offered) {
+ return {
+ status: 'not_offered',
+ plan,
+ reason: plan.ze_switch_already_declined ? 'declined' : 'not_eligible',
+ };
+ }
+
+ // Show banner regardless of TTY so non-TTY upgrades see what they skipped.
+ writeFn(formatBanner(plan));
+
+ if (!isTTY) {
+ writeFn('[ze-switch] non-TTY environment; skipping prompt. Run `gbrain ze-switch` manually when ready.');
+ return { status: 'non_tty_skip', plan };
+ }
+
+ // Single-keypress prompt. Enter = stay (safest default).
+ const key = await (opts.readKey ?? defaultReadKey)();
+ const normalized = key.toLowerCase().trim();
+
+ if (normalized === 's') {
+ const result = await applyRetrievalUpgrade(engine, plan);
+ if (result.status === 'applied') {
+ writeFn('[ze-switch] Schema rebuilt at 1024d. Run `gbrain embed --stale` to refill embeddings (or wait for autopilot).');
+ return { status: 'applied', plan };
+ }
+ if (result.status === 'failed') {
+ return { status: 'failed', plan, reason: result.reason };
+ }
+ // skipped_* shouldn't happen here (we just planned and saw offered=true).
+ return { status: 'failed', plan, reason: `unexpected apply status: ${result.status}` };
+ }
+ if (normalized === 'n') {
+ await recordDeclinedForever(engine);
+ writeFn('[ze-switch] Will not ask again. Re-enable with `gbrain ze-switch --force`.');
+ return { status: 'declined_forever', plan };
+ }
+ // Enter, 'l', or anything else = defer to next upgrade.
+ // Per C3 the planner re-asks on the next run; mark prompt_shown=false to
+ // re-enable. We DON'T touch the config here; absence of prompt_shown means
+ // re-ask. The 'l' case is identical.
+ return { status: 'declined_this_run', plan };
+}
+
+/** Mirror of runRetrievalUpgradePrompt for --undo (D16 cost-warning prompt). */
+export async function runUndoPrompt(
+ engine: BrainEngine,
+ opts: PromptOpts = {},
+): Promise<
+ | { status: 'undone'; snapshot: ZeSwitchSnapshot }
+ | { status: 'aborted' }
+ | { status: 'non_tty_skip' }
+ | { status: 'no_snapshot' }
+ | { status: 'failed'; reason: string }
+> {
+ const writeFn = opts.write ?? ((line: string) => process.stderr.write(line + '\n'));
+ const isTTY = typeof opts.isTTY === 'boolean'
+ ? opts.isTTY
+ : Boolean(process.stdin.isTTY);
+
+ // Read snapshot just to show the cost warning.
+ const snapshotStr = await engine.getConfig('ze_switch_previous_snapshot');
+ if (!snapshotStr) {
+ writeFn('[ze-switch --undo] No prior config snapshot found (brain was never switched). Nothing to undo.');
+ return { status: 'no_snapshot' };
+ }
+ let snapshot: ZeSwitchSnapshot;
+ try {
+ snapshot = JSON.parse(snapshotStr) as ZeSwitchSnapshot;
+ } catch (err) {
+ return { status: 'failed', reason: `corrupt snapshot: ${err instanceof Error ? err.message : String(err)}` };
+ }
+
+ const plan = await planRetrievalUpgrade(engine);
+ writeFn(formatUndoBanner(snapshot, plan.pages_pending_dim || 0));
+
+ if (!isTTY) {
+ writeFn('[ze-switch --undo] non-TTY environment; refusing without --confirm-reembed.');
+ return { status: 'non_tty_skip' };
+ }
+
+ const key = await (opts.readKey ?? defaultReadKey)();
+ if (key.toLowerCase().trim() !== 's') {
+ writeFn('[ze-switch --undo] aborted (you must press `s` to confirm).');
+ return { status: 'aborted' };
+ }
+
+ const result = await undoRetrievalUpgrade(engine);
+ if (result.status === 'undone') {
+ writeFn(`[ze-switch --undo] Restored ${snapshot.embedding_model} at ${snapshot.embedding_dimensions}d. Run \`gbrain embed --stale\` to refill embeddings.`);
+ return result;
+ }
+ return result;
+}
+
+/** Programmatic resume helper used by the CLI's --resume flag. */
+export async function runResume(engine: BrainEngine): Promise<ApplyResult> {
+ return resumeRetrievalUpgrade(engine);
+}
+
+// ============================================================================
+// Banner formatting (pure; testable)
+// ============================================================================
+
+/**
+ * Format the upgrade banner per D10 (two-line cost split) + C2 (privacy
+ * callout). Pure — returns a string; the caller emits to stderr.
+ */
+export function formatBanner(plan: RetrievalUpgradeState): string {
+ const lines: string[] = [];
+ lines.push('────────────────────────────────────────────────────────────');
+ lines.push('v0.36.0.0 ships a new default: ZeroEntropy');
+ lines.push('');
+ lines.push('Real-corpus benchmark across 20 queries on a 17K-page brain:');
+ lines.push(' • Wins 11/20 queries head-to-head (OpenAI 6, Voyage 4)');
+ lines.push(' • Fastest: 442ms vs OpenAI 973ms (2.2× faster)');
+ lines.push(' • Cheapest: $0.05/M tokens vs OpenAI $0.13/M (2.6× cheaper)');
+ lines.push(' (sale rate $0.025/M may be promotional, subject to change)');
+ lines.push(' • zerank-2 reshuffles 60% of top-1 results (real value)');
+ lines.push(' • Only 10–18% overlap between providers — they see different');
+ lines.push(' things, so a pair compounds');
+ lines.push('');
+ lines.push(`Your current setup: ${plan.current_embedding_model} (${plan.current_dim}d)`);
+ lines.push(`Target: ${ZE_TARGET_EMBEDDING_MODEL} (${ZE_TARGET_EMBEDDING_DIM}d via Matryoshka)`);
+ lines.push('');
+
+ // D10: two-line cost split — schema change vs re-embed.
+ const dollars = plan.est_cost_usd > 0 ? `~$${plan.est_cost_usd.toFixed(2)}` : 'estimate unavailable';
+ const pages = Math.max(plan.pages_pending_chunker, plan.pages_pending_dim);
+ lines.push(`Schema change: ~${plan.est_schema_change_seconds}s (drops + recreates embedding column with new index)`);
+ lines.push(`Re-embed: ~${plan.est_minutes}min and ${dollars} for ${pages.toLocaleString()} pages`);
+ lines.push(' (runs via `gbrain embed --stale` or autopilot — you can walk away)');
+
+ // C2: privacy callout for the balanced-mode reranker flip.
+ lines.push('');
+ lines.push('Heads-up: reranking on this default sends your query and top-30');
+ lines.push('search snippets to api.zeroentropy.dev. Disable any time with');
+ lines.push('`gbrain config set search.reranker.enabled false`.');
+
+ lines.push('');
+ lines.push('Options:');
+ lines.push(' [Enter] Stay on current provider for now (default — safe)');
+ lines.push(' s Switch to ZeroEntropy (RECOMMENDED)');
+ lines.push(' l Decide later (ask me again on next upgrade)');
+ lines.push(' n Never ask again');
+ lines.push('────────────────────────────────────────────────────────────');
+ return lines.join('\n');
+}
+
+/** Cost-warning prompt before --undo runs. D16 symmetric UX. */
+export function formatUndoBanner(snapshot: ZeSwitchSnapshot, pageCount: number): string {
+ const lines: string[] = [];
+ lines.push('────────────────────────────────────────────────────────────');
+ lines.push('Undo the v0.36.0.0 ZeroEntropy switch?');
+ lines.push('');
+ lines.push(`Will restore: ${snapshot.embedding_model} (${snapshot.embedding_dimensions}d)`);
+ lines.push(` reranker_enabled = ${snapshot.search_reranker_enabled}`);
+ if (snapshot.search_reranker_model) {
+ lines.push(` reranker_model = ${snapshot.search_reranker_model}`);
+ }
+ lines.push('');
+ lines.push(`This will re-embed ~${pageCount.toLocaleString()} pages at the prior width.`);
+ lines.push('Same re-embed bill as the forward switch (in reverse).');
+ lines.push('');
+ lines.push(' s Confirm undo');
+ lines.push(' [any] Abort');
+ lines.push('────────────────────────────────────────────────────────────');
+ return lines.join('\n');
+}
+
+// ============================================================================
+// Keypress reader (mockable for tests)
+// ============================================================================
+
+async function defaultReadKey(): Promise<string> {
+ return new Promise((resolve) => {
+ const stdin = process.stdin;
+ stdin.setRawMode?.(true);
+ stdin.resume();
+ stdin.setEncoding('utf8');
+ const onData = (chunk: string) => {
+ stdin.setRawMode?.(false);
+ stdin.pause();
+ stdin.removeListener('data', onData);
+ // Strip trailing newline; treat Enter as empty string.
+ resolve(chunk === '\r' || chunk === '\n' || chunk === '\r\n' ? '' : chunk.replace(/[\r\n]/g, ''));
+ };
+ stdin.on('data', onData);
+ });
+}
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 3d46949148..267fe144cc 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -148,10 +148,15 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
tokenBudget: 12000,
expansion: false,
searchLimit: 25,
- // Off in balanced too — operators opt in via
- // `gbrain config set search.reranker.enabled true` until eval data
- // backs a mode-bundle default change.
- reranker_enabled: false,
+ // 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. Missing ZEROENTROPY_API_KEY is handled via
+ // src/core/search/rerank.ts fail-open contract: log to audit JSONL,
+ // return input order unchanged. Opt out with
+ // `gbrain config set search.reranker.enabled false`.
+ reranker_enabled: true,
reranker_model: 'zeroentropyai:zerank-2',
reranker_top_n_in: 30,
reranker_top_n_out: null,
diff --git a/test/ai/dims-openai.test.ts b/test/ai/dims-openai.test.ts
new file mode 100644
index 0000000000..c1359fdfc4
--- /dev/null
+++ b/test/ai/dims-openai.test.ts
@@ -0,0 +1,136 @@
+/**
+ * v0.36.0.0 (D13): OpenAI Matryoshka dim validation tests.
+ *
+ * Pins:
+ * - OpenAI text-embedding-3-* accepts arbitrary truncation via Matryoshka,
+ * bounded by the model's native size (1536 for -small, 3072 for -large)
+ * - dimsProviderOptions throws AIConfigError for out-of-range dims
+ * - Error message includes a paste-ready `gbrain config set` fix
+ * - Plumbing reaches BOTH the native-openai path (line 97) AND the
+ * 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
+ * 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
+ * HTTP 400s at first embed instead of a config-time fail-loud.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ dimsProviderOptions,
+ isValidOpenAITextEmbedding3Dim,
+ isOpenAITextEmbedding3Model,
+ maxOpenAITextEmbedding3Dim,
+} from '../../src/core/ai/dims.ts';
+import { AIConfigError } from '../../src/core/ai/errors.ts';
+
+describe('OpenAI text-embedding-3 model recognition', () => {
+ test('isOpenAITextEmbedding3Model for known variants', () => {
+ expect(isOpenAITextEmbedding3Model('text-embedding-3-small')).toBe(true);
+ expect(isOpenAITextEmbedding3Model('text-embedding-3-large')).toBe(true);
+ });
+
+ test('isOpenAITextEmbedding3Model rejects ada-002 and unrelated', () => {
+ expect(isOpenAITextEmbedding3Model('text-embedding-ada-002')).toBe(false);
+ expect(isOpenAITextEmbedding3Model('zembed-1')).toBe(false);
+ expect(isOpenAITextEmbedding3Model('voyage-3-large')).toBe(false);
+ });
+
+ test('maxOpenAITextEmbedding3Dim returns 1536 / 3072', () => {
+ expect(maxOpenAITextEmbedding3Dim('text-embedding-3-small')).toBe(1536);
+ expect(maxOpenAITextEmbedding3Dim('text-embedding-3-large')).toBe(3072);
+ expect(maxOpenAITextEmbedding3Dim('text-embedding-ada-002')).toBeUndefined();
+ });
+});
+
+describe('isValidOpenAITextEmbedding3Dim — Matryoshka range', () => {
+ test('text-embedding-3-large: accepts 1..3072', () => {
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 1)).toBe(true);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 1024)).toBe(true);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 1536)).toBe(true);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 3072)).toBe(true);
+ });
+
+ test('text-embedding-3-large: rejects out-of-range', () => {
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 0)).toBe(false);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', -1)).toBe(false);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 3073)).toBe(false);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 5000)).toBe(false);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-large', 1.5)).toBe(false);
+ });
+
+ test('text-embedding-3-small: rejects > 1536 (smaller native size)', () => {
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-small', 1536)).toBe(true);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-small', 1537)).toBe(false);
+ expect(isValidOpenAITextEmbedding3Dim('text-embedding-3-small', 3072)).toBe(false);
+ });
+});
+
+describe('dimsProviderOptions — OpenAI native path', () => {
+ test('text-embedding-3-large at 1024d returns dimensions=1024 (D13 happy path)', () => {
+ const opts = dimsProviderOptions('native-openai', 'text-embedding-3-large', 1024);
+ expect(opts).toEqual({ openai: { dimensions: 1024 } });
+ });
+
+ test('text-embedding-3-small at 512d returns dimensions=512', () => {
+ const opts = dimsProviderOptions('native-openai', 'text-embedding-3-small', 512);
+ expect(opts).toEqual({ openai: { dimensions: 512 } });
+ });
+
+ test('text-embedding-3-large at 5000d throws AIConfigError', () => {
+ expect(() => dimsProviderOptions('native-openai', 'text-embedding-3-large', 5000))
+ .toThrow(AIConfigError);
+ });
+
+ test('text-embedding-3-small at 3072d throws (exceeds small native size)', () => {
+ expect(() => dimsProviderOptions('native-openai', 'text-embedding-3-small', 3072))
+ .toThrow(AIConfigError);
+ });
+
+ test('AIConfigError message includes paste-ready fix hint', () => {
+ try {
+ dimsProviderOptions('native-openai', 'text-embedding-3-large', 5000);
+ throw new Error('should have thrown');
+ } catch (err) {
+ expect(err).toBeInstanceOf(AIConfigError);
+ const msg = (err as Error).message;
+ expect(msg).toContain('text-embedding-3-large');
+ expect(msg).toContain('5000');
+ expect(msg).toContain('3072');
+ // Paste-ready fix appears in the `fix` property of AIConfigError.
+ const fix = (err as AIConfigError).fix ?? '';
+ expect(fix).toContain('gbrain config set embedding_dimensions');
+ }
+ });
+
+ test('ada-002 returns undefined (no dimensions support)', () => {
+ expect(dimsProviderOptions('native-openai', 'text-embedding-ada-002', 1536))
+ .toBeUndefined();
+ });
+
+ test('inputType ignored on OpenAI symmetric provider (regression guard)', () => {
+ const opts = dimsProviderOptions('native-openai', 'text-embedding-3-large', 1024, 'query');
+ expect(opts).toEqual({ openai: { dimensions: 1024 } });
+ expect(JSON.stringify(opts)).not.toContain('input_type');
+ });
+});
+
+describe('dimsProviderOptions — OpenAI on openai-compatible adapter (Azure case)', () => {
+ test('text-embedding-3-large at 1024d via openai-compat path returns dimensions=1024', () => {
+ const opts = dimsProviderOptions('openai-compatible', 'text-embedding-3-large', 1024);
+ expect(opts).toEqual({ openaiCompatible: { dimensions: 1024 } });
+ });
+
+ test('text-embedding-3-large at 5000d via openai-compat path throws', () => {
+ expect(() => dimsProviderOptions('openai-compatible', 'text-embedding-3-large', 5000))
+ .toThrow(AIConfigError);
+ });
+
+ test('inputType ignored on OpenAI symmetric provider via openai-compat path', () => {
+ const opts = dimsProviderOptions('openai-compatible', 'text-embedding-3-large', 1024, 'query');
+ expect(opts).toEqual({ openaiCompatible: { dimensions: 1024 } });
+ expect(JSON.stringify(opts)).not.toContain('input_type');
+ });
+});
diff --git a/test/ai/gateway.test.ts b/test/ai/gateway.test.ts
index a97fc6cfe5..e82f1e4b35 100644
--- a/test/ai/gateway.test.ts
+++ b/test/ai/gateway.test.ts
@@ -32,10 +32,13 @@ describe('gateway configuration', () => {
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
});
- test('defaults preserve v0.13 OpenAI behavior', () => {
+ test('defaults are ZE 1280d 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
+ // CHANGELOG.md; the rationale lives in src/core/ai/gateway.ts:45-54.
configureGateway({ env: {} });
- expect(getEmbeddingModel()).toBe('openai:text-embedding-3-large');
- expect(getEmbeddingDimensions()).toBe(1536);
+ expect(getEmbeddingModel()).toBe('zeroentropyai:zembed-1');
+ expect(getEmbeddingDimensions()).toBe(1280);
expect(getExpansionModel()).toBe('anthropic:claude-haiku-4-5-20251001');
});
});
diff --git a/test/asymmetric-encoding-contract.test.ts b/test/asymmetric-encoding-contract.test.ts
new file mode 100644
index 0000000000..cb435f1edc
--- /dev/null
+++ b/test/asymmetric-encoding-contract.test.ts
@@ -0,0 +1,134 @@
+/**
+ * v0.36.0.0 (D8 + D17) — Asymmetric encoding contract.
+ *
+ * Pins that the search read path (hybridSearch + expansion) uses
+ * `gateway.embedQuery()` for user-supplied query strings, which threads
+ * `inputType: 'query'` through `dimsProviderOptions`. Index-side writes
+ * use `gateway.embed()` with default 'document' encoding.
+ *
+ * Why this test exists (D17):
+ * The original audit was a source-text grep — fragile under refactors
+ * that rename `gateway` to `gw` or alias-import `{ embed }`. This test
+ * uses the `__setEmbedTransportForTests` mock to capture every HTTP
+ * body the transport sees during a representative search call, then
+ * asserts the query call carries `input_type: 'query'`.
+ *
+ * The complementary source-text check stays here as a SECOND layer
+ * (cheap belt-and-suspenders): if `hybrid.ts` ever stops importing
+ * `embedQuery`, this test fails before the regression ships.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
+import {
+ configureGateway,
+ resetGateway,
+ embed,
+ embedQuery,
+ __setEmbedTransportForTests,
+} from '../src/core/ai/gateway.ts';
+
+function configureZE() {
+ configureGateway({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: 1280,
+ env: { ZEROENTROPY_API_KEY: 'sk-fake' },
+ });
+}
+
+function fakeEmbeddings(count: number, dims: number) {
+ return {
+ embeddings: Array.from({ length: count }, () =>
+ Array.from({ length: dims }, () => 0.1),
+ ),
+ };
+}
+
+afterEach(() => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+});
+
+describe('Search read path uses embedQuery (D17 behavior contract)', () => {
+ test('embedQuery threads input_type=query through transport for ZE', async () => {
+ configureZE();
+ let capturedOpts: any = null;
+ __setEmbedTransportForTests((async (args: any) => {
+ capturedOpts = args.providerOptions;
+ return fakeEmbeddings(1, 1280);
+ }) 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();
+ let capturedOpts: any = null;
+ __setEmbedTransportForTests((async (args: any) => {
+ capturedOpts = args.providerOptions;
+ return fakeEmbeddings(args.values.length, 1280);
+ }) as any);
+
+ await embed(['this is a document being indexed']);
+ expect(capturedOpts?.openaiCompatible?.input_type).toBe('document');
+ });
+});
+
+describe('Source-text contract (cheap belt + suspenders)', () => {
+ // These tests fail-fast if a refactor accidentally swaps embedQuery → embed
+ // on the search read path. The behavior test above catches the runtime
+ // regression; this catches the static one (broken import, renamed helper).
+
+ test('src/core/search/hybrid.ts imports embedQuery from embedding.ts', () => {
+ const src = readFileSync(
+ resolve(process.cwd(), 'src/core/search/hybrid.ts'),
+ 'utf8',
+ );
+ // The import must include embedQuery; matches both `embedQuery` and `{ embed, embedQuery }`.
+ expect(src).toMatch(/from '..\/embedding.ts'/);
+ expect(src).toContain('embedQuery');
+ });
+
+ test('src/core/search/hybrid.ts calls embedQuery at the search-time query path', () => {
+ const src = readFileSync(
+ resolve(process.cwd(), 'src/core/search/hybrid.ts'),
+ 'utf8',
+ );
+ // Look for the call site (any whitespace shape). The line at 414 today is
+ // `await Promise.all(queries.map(q => embedQuery(q)))`. The regex stays
+ // permissive: match `embedQuery(` anywhere in the file body.
+ expect(src).toMatch(/embedQuery\s*\(/);
+ });
+
+ test('src/core/embedding.ts re-exports both embed and embedQuery', () => {
+ const src = readFileSync(
+ resolve(process.cwd(), 'src/core/embedding.ts'),
+ 'utf8',
+ );
+ // The embedding module is the seam between gateway and search.
+ // Both functions MUST be exported so consumers can route correctly.
+ expect(src).toMatch(/export\s+(?:async\s+)?function\s+embed\s*\(|export\s*\{[^}]*\bembed\b/);
+ expect(src).toMatch(/export\s+(?:async\s+)?function\s+embedQuery\s*\(|export\s*\{[^}]*\bembedQuery\b/);
+ });
+});
+
+describe('Symmetric providers ignore input_type (OpenAI regression guard)', () => {
+ test('OpenAI text-embedding-3-large produces no input_type field', async () => {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1024,
+ env: { OPENAI_API_KEY: 'sk-fake' },
+ });
+ let capturedOpts: any = null;
+ __setEmbedTransportForTests((async (args: any) => {
+ capturedOpts = args.providerOptions;
+ return fakeEmbeddings(1, 1024);
+ }) as any);
+
+ await embedQuery('hello');
+ // OpenAI is symmetric — input_type would be rejected by the API.
+ expect(JSON.stringify(capturedOpts)).not.toContain('input_type');
+ });
+});
diff --git a/test/balanced-reranker-default.test.ts b/test/balanced-reranker-default.test.ts
new file mode 100644
index 0000000000..9f8a2ad6a9
--- /dev/null
+++ b/test/balanced-reranker-default.test.ts
@@ -0,0 +1,158 @@
+/**
+ * v0.36.0.0 (D6 + C2) — balanced mode bundle now defaults reranker_enabled=true.
+ *
+ * Pins:
+ * - MODE_BUNDLES.balanced.reranker_enabled === true (the flip)
+ * - applyReranker honors the flag (calls injected rerankerFn)
+ * - Fail-open contract: missing key / network error returns input unchanged
+ * - rerankerFn is called with input_type-equivalent shape for the query path
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { MODE_BUNDLES } from '../src/core/search/mode.ts';
+import { applyReranker, type RerankerOpts } from '../src/core/search/rerank.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { RerankError } from '../src/core/ai/gateway.ts';
+
+describe('Mode bundle defaults (D6)', () => {
+ test('balanced.reranker_enabled is true (the v0.36.0.0 flip)', () => {
+ expect(MODE_BUNDLES.balanced.reranker_enabled).toBe(true);
+ });
+
+ test('balanced reranker model is zeroentropyai:zerank-2', () => {
+ expect(MODE_BUNDLES.balanced.reranker_model).toBe('zeroentropyai:zerank-2');
+ });
+
+ test('conservative reranker stays off (cheap tier)', () => {
+ expect(MODE_BUNDLES.conservative.reranker_enabled).toBe(false);
+ });
+
+ test('tokenmax reranker still on', () => {
+ expect(MODE_BUNDLES.tokenmax.reranker_enabled).toBe(true);
+ });
+});
+
+function makeResults(n: number): SearchResult[] {
+ const out: SearchResult[] = [];
+ for (let i = 0; i < n; i++) {
+ out.push({
+ slug: `doc/${i}`,
+ page_id: i + 1,
+ title: `Doc ${i}`,
+ type: 'note',
+ chunk_text: `This is doc ${i}, an example chunk text for rerank testing.`,
+ chunk_source: 'compiled_truth',
+ chunk_id: i + 100,
+ chunk_index: 0,
+ score: 1 / (i + 1),
+ stale: false,
+ });
+ }
+ return out;
+}
+
+describe('applyReranker — fail-open contract (D6 + R8)', () => {
+ test('reranker disabled: passthrough', async () => {
+ const results = makeResults(5);
+ const opts: RerankerOpts = {
+ enabled: false,
+ topNIn: 30,
+ topNOut: null,
+ rerankerFn: async () => { throw new Error('should not be called'); },
+ };
+ const out = await applyReranker('test query', results, opts);
+ expect(out).toEqual(results);
+ });
+
+ test('reranker enabled + thrown error: returns input order unchanged', async () => {
+ const results = makeResults(5);
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 30,
+ topNOut: null,
+ rerankerFn: async () => {
+ throw new RerankError('missing ZEROENTROPY_API_KEY', 'auth');
+ },
+ };
+ const out = await applyReranker('test query', results, opts);
+ // Fail-open: original order preserved.
+ expect(out.map(r => r.slug)).toEqual(results.map(r => r.slug));
+ });
+
+ test('reranker enabled + happy path: reorders by relevance_score', async () => {
+ const results = makeResults(3);
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 30,
+ topNOut: null,
+ rerankerFn: async () => {
+ // Reverse the order: doc/2 first, doc/0 last.
+ return [
+ { index: 2, relevanceScore: 0.95 },
+ { index: 1, relevanceScore: 0.50 },
+ { index: 0, relevanceScore: 0.10 },
+ ];
+ },
+ };
+ const out = await applyReranker('test query', results, opts);
+ expect(out.map(r => r.slug)).toEqual(['doc/2', 'doc/1', 'doc/0']);
+ });
+
+ test('empty results: passthrough (no upstream call)', async () => {
+ let called = false;
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 30,
+ topNOut: null,
+ rerankerFn: async () => { called = true; return []; },
+ };
+ const out = await applyReranker('test query', [], opts);
+ expect(out).toEqual([]);
+ expect(called).toBe(false);
+ });
+
+ test('preserves un-reranked tail past topNIn (recall protection)', async () => {
+ const results = makeResults(10);
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 3, // only rerank top 3
+ topNOut: null,
+ rerankerFn: async () => [
+ { index: 2, relevanceScore: 0.99 },
+ { index: 0, relevanceScore: 0.50 },
+ { index: 1, relevanceScore: 0.10 },
+ ],
+ };
+ const out = await applyReranker('test query', results, opts);
+ // Head: reranked. Tail: original positions 3-9 in order.
+ expect(out.slice(0, 3).map(r => r.slug)).toEqual(['doc/2', 'doc/0', 'doc/1']);
+ expect(out.slice(3).map(r => r.slug)).toEqual([
+ 'doc/3', 'doc/4', 'doc/5', 'doc/6', 'doc/7', 'doc/8', 'doc/9',
+ ]);
+ });
+});
+
+describe('Reranker invocation receives query + documents', () => {
+ test('rerankerFn called with query + document texts from top N', async () => {
+ const results = makeResults(5);
+ let received: { query: string; documents: string[] } | null = null;
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 3,
+ topNOut: null,
+ rerankerFn: async (input) => {
+ received = { query: input.query, documents: input.documents };
+ return [
+ { index: 0, relevanceScore: 0.9 },
+ { index: 1, relevanceScore: 0.5 },
+ { index: 2, relevanceScore: 0.1 },
+ ];
+ },
+ };
+ await applyReranker('what is foo?', results, opts);
+ expect(received).not.toBeNull();
+ expect(received!.query).toBe('what is foo?');
+ expect(received!.documents.length).toBe(3);
+ expect(received!.documents[0]).toContain('doc 0');
+ });
+});
diff --git a/test/consolidate-valid-until.test.ts b/test/consolidate-valid-until.test.ts
index bc682624b9..807e57a10c 100644
--- a/test/consolidate-valid-until.test.ts
+++ b/test/consolidate-valid-until.test.ts
@@ -15,10 +15,23 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';
+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).
+ // 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
+ // file is hermetic against cross-file state.
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-fake' },
+ });
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
@@ -26,6 +39,7 @@ beforeAll(async () => {
afterAll(async () => {
await engine.disconnect();
+ resetGateway();
});
beforeEach(async () => {
diff --git a/test/doctor-ze-checks.test.ts b/test/doctor-ze-checks.test.ts
new file mode 100644
index 0000000000..a779702028
--- /dev/null
+++ b/test/doctor-ze-checks.test.ts
@@ -0,0 +1,119 @@
+/**
+ * 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 } from './helpers/with-env.ts';
+import {
+ checkZeEmbeddingHealth,
+ checkEmbeddingWidthConsistency,
+} from '../src/commands/doctor.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', () => {
+ test('not on ZE: returns ok with skip message', async () => {
+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
+ const check = await checkZeEmbeddingHealth(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('not ZeroEntropy');
+ });
+
+ test('on ZE + no key: warns with setup hint', async () => {
+ await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ // Clear the env var for the no-key path (user's real env may have it set).
+ await withEnv({ ZEROENTROPY_API_KEY: undefined }, async () => {
+ const check = await checkZeEmbeddingHealth(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('ZEROENTROPY_API_KEY');
+ expect(check.message).toContain('zeroentropy.dev');
+ });
+ });
+
+ test('on ZE + env key: ok', async () => {
+ await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake-test' }, async () => {
+ const check = await checkZeEmbeddingHealth(engine);
+ expect(check.status).toBe('ok');
+ });
+ });
+
+ test('on ZE + config key (not env): ok', async () => {
+ await engine.setConfig('embedding_model', 'zeroentropyai:zembed-1');
+ await engine.setConfig('zeroentropy_api_key', 'sk-fake-config');
+ const check = await checkZeEmbeddingHealth(engine);
+ expect(check.status).toBe('ok');
+ });
+});
+
+describe('checkEmbeddingWidthConsistency', () => {
+ test('config matches schema width: ok', async () => {
+ // Fresh schema is sized to DEFAULT_EMBEDDING_DIMENSIONS via initSchema.
+ // We just need config to declare the same number. The actual default is
+ // 1280 after the v0.36.0.0 flip but PGLite initSchema reads what the
+ // gateway was last configured for; bypass by reading the actual column.
+ // The check itself is what we're testing.
+ 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);
+
+ await engine.setConfig('embedding_dimensions', String(schemaDim));
+ 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 () => {
+ // Pick an obviously-different number. The schema is whatever initSchema
+ // produced; we just need config to say something else.
+ await engine.setConfig('embedding_dimensions', '99999');
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('mismatch');
+ expect(check.message).toContain('ze-switch --resume');
+ });
+
+ test('missing config: ok with hint about defaults', async () => {
+ // No embedding_dimensions key set.
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('defaults');
+ });
+
+ test('invalid config value: warns', async () => {
+ await engine.setConfig('embedding_dimensions', 'not-a-number');
+ const check = await checkEmbeddingWidthConsistency(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('not a positive integer');
+ });
+});
diff --git a/test/e2e/v0_28_5-fix-wave.test.ts b/test/e2e/v0_28_5-fix-wave.test.ts
index 563493c8ca..93c19ac683 100644
--- a/test/e2e/v0_28_5-fix-wave.test.ts
+++ b/test/e2e/v0_28_5-fix-wave.test.ts
@@ -221,7 +221,17 @@ describe('v0.28.5 A4 — existing-brain dim mismatch loud failure', () => {
const engine = new PGLiteEngine();
await engine.connect({});
try {
- // Default initSchema with no gateway override → 1536.
+ // v0.36.0.0: default flipped to 1280; explicitly configure the gateway
+ // to 1536 so the test still exercises the "existing brain at 1536d"
+ // path it was designed for. This mirrors how a real v0.18-vintage brain
+ // would look post-upgrade.
+ const { configureGateway, resetGateway } = await import('../../src/core/ai/gateway.ts');
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-fake' },
+ });
await engine.initSchema();
const existing = await readContentChunksEmbeddingDim(engine);
expect(existing.exists).toBe(true);
diff --git a/test/openai-compat-multimodal.test.ts b/test/openai-compat-multimodal.test.ts
index 0aecdfdfb0..b028e95f73 100644
--- a/test/openai-compat-multimodal.test.ts
+++ b/test/openai-compat-multimodal.test.ts
@@ -129,23 +129,23 @@ describe('embedMultimodal — openai-compat routing (#875)', () => {
expect((caught as Error).message).toContain('gpt-4o-multimodal');
});
- test('D12 — default embedding_dimensions (1536) applies when not explicitly set', async () => {
- // configureGateway normalizes embedding_dimensions to 1536 when unset
- // (the DEFAULT_EMBEDDING_DIMENSIONS). 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.
+ 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
+ // 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.
configureGateway({
embedding_model: 'litellm:any-model',
- // intentionally NO embedding_dimensions → falls back to 1536
+ // intentionally NO embedding_dimensions → falls back to 1280
env: { LITELLM_BASE_URL: 'http://localhost:4000' },
base_urls: { litellm: 'http://localhost:4000' },
});
- fetchHandler = async () => okResponse(1536, 1);
+ fetchHandler = async () => okResponse(1280, 1);
const result = await embedMultimodal([{ kind: 'image_base64', data: 'x', mime: 'image/png' }]);
expect(result.length).toBe(1);
- expect(result[0].length).toBe(1536);
+ expect(result[0].length).toBe(1280);
});
test('provider returns 401 → AIConfigError with model id in message', async () => {
diff --git a/test/query-cache.test.ts b/test/query-cache.test.ts
index 734ba39af7..ed77f0dcfa 100644
--- a/test/query-cache.test.ts
+++ b/test/query-cache.test.ts
@@ -18,6 +18,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { SemanticQueryCache, cacheRowId } from '../src/core/search/query-cache.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import type { SearchResult, HybridSearchMeta } from '../src/core/types.ts';
let engine: PGLiteEngine;
@@ -79,6 +80,18 @@ const META: HybridSearchMeta = {
};
beforeAll(async () => {
+ // v0.36.2.0: DEFAULT_EMBEDDING_DIMENSIONS flipped to 1280 (ZE 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
+ // explicitly so this file is hermetic regardless of cross-file state.
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-fake' },
+ });
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
@@ -86,6 +99,7 @@ beforeAll(async () => {
afterAll(async () => {
try { await engine.disconnect(); } catch { /* ignore */ }
+ resetGateway();
});
beforeEach(async () => {
diff --git a/test/readme-hero-anchors.test.ts b/test/readme-hero-anchors.test.ts
new file mode 100644
index 0000000000..0a44723f76
--- /dev/null
+++ b/test/readme-hero-anchors.test.ts
@@ -0,0 +1,46 @@
+/**
+ * v0.36.0.0 (D9) — README hero anchor regression test.
+ *
+ * Pins 5 load-bearing strings in the first ~50 lines of README.md so future
+ * "cleanup" PRs can't silently drop the headline metrics or the
+ * OpenClaw/Hermes credit. The anchors are intentionally NARROW (5 substrings,
+ * not full hero text) so legitimate voice/structure edits don't fight the
+ * test.
+ *
+ * If this test fails, ask: did we deliberately rotate the headline?
+ * - If yes: update the anchors here AND in the plan's D9 section.
+ * - If no: the README rewrite dropped something it shouldn't have.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
+
+describe('README hero anchors (D9 regression guard)', () => {
+ const readme = readFileSync(resolve(process.cwd(), 'README.md'), 'utf8');
+ // First 50 lines is enough headroom for hero + first sub-section.
+ const hero = readme.split('\n').slice(0, 50).join('\n');
+
+ test('mentions OpenClaw (the public agent platform credit)', () => {
+ expect(hero).toContain('OpenClaw');
+ });
+
+ test('mentions Hermes (the public agent platform credit)', () => {
+ expect(hero).toContain('Hermes');
+ });
+
+ test('mentions ZeroEntropy (the v0.36.0.0 default story)', () => {
+ // Accept either spelling — "ZeroEntropy" or the "ZE" short form.
+ expect(hero).toMatch(/ZeroEntropy|\bZE\b/);
+ });
+
+ test('includes at least one production number (pages/people/companies)', () => {
+ // Matches "17,888 pages", "4,383 people", "723 companies" style.
+ expect(hero).toMatch(/\d{1,3},?\d{3}\s+(pages|people|companies)/i);
+ });
+
+ test('includes BrainBench framing (P@5 or R@5)', () => {
+ // Either P@5 or R@5 anchors the retrieval-eval credibility story.
+ expect(hero).toMatch(/P@5|R@5/);
+ });
+});
diff --git a/test/retrieval-upgrade-planner.test.ts b/test/retrieval-upgrade-planner.test.ts
new file mode 100644
index 0000000000..1b5f0ddf5f
--- /dev/null
+++ b/test/retrieval-upgrade-planner.test.ts
@@ -0,0 +1,339 @@
+/**
+ * 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');
+ });
+});
+
+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/search-mode.test.ts b/test/search-mode.test.ts
index 6883f2fcfa..eb2e887ce3 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -59,6 +59,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
});
test('balanced bundle values are canonical', () => {
+ // v0.36.0.0 (D6): reranker_enabled flipped from false → true. The 60%
+ // top-1 reshuffle reaches the 80% of installs that stay on `balanced`.
expect(MODE_BUNDLES.balanced).toEqual({
cache_enabled: true,
cache_similarity_threshold: 0.92,
@@ -67,7 +69,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
tokenBudget: 12000,
expansion: false,
searchLimit: 25,
- reranker_enabled: false,
+ reranker_enabled: true,
reranker_model: 'zeroentropyai:zerank-2',
reranker_top_n_in: 30,
reranker_top_n_out: null,
diff --git a/test/ze-switch-cli.test.ts b/test/ze-switch-cli.test.ts
new file mode 100644
index 0000000000..0178f1534a
--- /dev/null
+++ b/test/ze-switch-cli.test.ts
@@ -0,0 +1,238 @@
+/**
+ * v0.36.0.0 (T3) — `gbrain ze-switch` CLI tests.
+ *
+ * Pins:
+ * - --dry-run prints a plan, applies nothing
+ * - --non-interactive without key exits 1 (unless --ignore-missing-key)
+ * - --non-interactive --ignore-missing-key applies + exits 0
+ * - --json envelope shape: {status: ..., plan: {...}}
+ * - --resume completes a half-applied switch
+ * - --undo without snapshot exits 1
+ * - --help exits 0 without touching the engine
+ *
+ * Engine lifecycle: each test creates + disconnects its own PGLite engine
+ * to keep process.exit() semantics clean. The CLI calls process.exit at
+ * the end of every path; we intercept via a stub.
+ */
+
+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 } from './helpers/with-env.ts';
+import { runZeSwitch } from '../src/commands/ze-switch.ts';
+import {
+ KEY_APPLIED,
+ KEY_REQUESTED,
+ KEY_PREVIOUS_SNAPSHOT,
+ ZE_TARGET_EMBEDDING_DIM,
+} from '../src/core/retrieval-upgrade-planner.ts';
+
+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 seedPages(n: number) {
+ for (let i = 0; i < n; i++) {
+ await engine.putPage(`seed/page-${i}`, {
+ title: `Seed ${i}`,
+ compiled_truth: `Body text ${i} with enough chars to flow through cost math.`,
+ timeline: '',
+ type: 'note',
+ });
+ }
+}
+
+async function setLegacyConfig() {
+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
+ await engine.setConfig('embedding_dimensions', '1536');
+}
+
+describe('--help', () => {
+ test('exits 0 with usage text', async () => {
+ const r = await captureExit(() => runZeSwitch(['--help'], engine));
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain('gbrain ze-switch');
+ expect(r.stdout).toContain('--dry-run');
+ expect(r.stdout).toContain('--undo');
+ });
+});
+
+describe('--dry-run', () => {
+ test('human output prints plan, changes nothing', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+
+ const r = await captureExit(() => runZeSwitch(['--dry-run'], engine));
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain('Current model');
+ expect(r.stdout).toContain('Target model');
+ // Nothing changed:
+ expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
+ });
+
+ test('--json output emits a planned envelope', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+
+ const r = await captureExit(() => runZeSwitch(['--dry-run', '--json'], engine));
+ expect(r.exitCode).toBe(0);
+ const env = JSON.parse(r.stdout);
+ expect(env.status).toBe('planned');
+ expect(env.plan).toBeDefined();
+ expect(env.plan.target_embedding_model).toBe('zeroentropyai:zembed-1');
+ expect(env.plan.target_dim).toBe(ZE_TARGET_EMBEDDING_DIM);
+ });
+});
+
+describe('--non-interactive', () => {
+ test('without ZE key + without --ignore-missing-key: exits 1', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+
+ // Clear the env var so the test runs the no-key path even when the
+ // contributor has ZEROENTROPY_API_KEY set in their shell.
+ await withEnv({ ZEROENTROPY_API_KEY: undefined }, async () => {
+ const r = await captureExit(() => runZeSwitch(['--non-interactive'], engine));
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('ZEROENTROPY_API_KEY');
+ });
+ });
+
+ test('without ZE key + with --ignore-missing-key: applies, exits 0', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+
+ const r = await captureExit(() =>
+ runZeSwitch(['--non-interactive', '--ignore-missing-key'], engine),
+ );
+ expect(r.exitCode).toBe(0);
+ expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
+ expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
+ expect(await engine.getConfig('embedding_dimensions')).toBe(String(ZE_TARGET_EMBEDDING_DIM));
+ });
+
+ test('with env ZE key set: applies', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+ await withEnv({ ZEROENTROPY_API_KEY: 'sk-fake' }, async () => {
+ const r = await captureExit(() => runZeSwitch(['--non-interactive'], engine));
+ expect(r.exitCode).toBe(0);
+ expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
+ });
+ });
+
+ test('--json + --non-interactive: emits {status: "applied"}', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+ const r = await captureExit(() =>
+ runZeSwitch(['--non-interactive', '--ignore-missing-key', '--json'], engine),
+ );
+ expect(r.exitCode).toBe(0);
+ const env = JSON.parse(r.stdout);
+ expect(env.status).toBe('applied');
+ });
+});
+
+describe('--resume', () => {
+ test('completes a half-applied switch', async () => {
+ await setLegacyConfig();
+ await seedPages(150);
+ // Simulate crash partway: requested but not applied.
+ await engine.setConfig(KEY_REQUESTED, 'true');
+
+ const r = await captureExit(() => runZeSwitch(['--resume'], engine));
+ expect(r.exitCode).toBe(0);
+ expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
+ expect(await engine.getConfig('embedding_model')).toBe('zeroentropyai:zembed-1');
+ });
+});
+
+describe('--undo', () => {
+ test('without snapshot exits 1', async () => {
+ const r = await captureExit(() =>
+ runZeSwitch(['--undo', '--non-interactive', '--confirm-reembed'], engine),
+ );
+ expect(r.exitCode).toBe(1);
+ });
+
+ test('--non-interactive without --confirm-reembed exits 1', async () => {
+ const r = await captureExit(() => runZeSwitch(['--undo', '--non-interactive'], engine));
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('confirm-reembed');
+ });
+
+ test('with snapshot + --confirm-reembed: reverses the switch', async () => {
+ // Set up: apply switch, then undo.
+ await setLegacyConfig();
+ await seedPages(150);
+ await captureExit(() =>
+ runZeSwitch(['--non-interactive', '--ignore-missing-key'], engine),
+ );
+ expect(await engine.getConfig(KEY_APPLIED)).toBe('true');
+
+ const r = await captureExit(() =>
+ runZeSwitch(['--undo', '--non-interactive', '--confirm-reembed'], engine),
+ );
+ expect(r.exitCode).toBe(0);
+ // Reverted to prior model.
+ expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
+ expect(await engine.getConfig('embedding_dimensions')).toBe('1536');
+ expect(await engine.getConfig(KEY_APPLIED)).toBeNull();
+ });
+});