Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.37.10.0 feat(init): env-detection + interactive picker + preflight invariants (#1278)

Garry Tana55de712216a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15cda6a9d8..e7ac78cdbf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,81 @@
All notable changes to GBrain will be documented in this file.
+## [0.37.10.0] - 2026-05-21
+
+**Fresh installs of gbrain now auto-detect your embedding provider from API keys in your environment. If you have `OPENAI_API_KEY` set, you get OpenAI. If you have multiple keys, gbrain asks. If you have no keys in a CI build, it fails loud at init with a paste-ready setup hint, not silently four minutes later at first import.**
+
+A user on WSL ran `bun install && gbrain init --pglite && gbrain import …`, hit a wall ("expected 1536 dimensions, not 1280"), and recovered with five commands including `rm -rf ~/.gbrain` and three config keys that gbrain silently ignored (`embedding.provider`, `embedding.model`, `embedding.dimensions`). The root cause was a multi-defect bug class: init didn't peek at env vars, didn't persist the resolved provider unless you passed a flag, didn't validate the schema/dim invariant before creating the schema, and `gbrain config set` accepted unknown keys without complaining. This release closes every one of those.
+
+How to use it (already on after upgrade):
+
+```
+gbrain init --pglite # auto-pick from env (one key → that provider)
+gbrain init --pglite # picker fires when multiple keys are set
+gbrain init --pglite --no-embedding # opt-in deferred setup mode
+gbrain config set embedding.provider openai # now exits 1 with "did you mean embedding_model?"
+gbrain config set foo.unknown bar --force # escape hatch with loud stderr WARN
+```
+
+What you'd see in concrete scenarios:
+
+| Scenario | Before v0.37.10.0 | After |
+|---|---|---|
+| `OPENAI_API_KEY` set, run `init --pglite` | Silent ZE 1280d default, schema becomes `vector(1536)`, first import explodes | Auto-picks `openai:text-embedding-3-large` (1536d), config persisted, import succeeds |
+| `OPENAI_API_KEY` + `VOYAGE_API_KEY` both set | Same silent ZE default | Interactive picker fires, user chooses |
+| No keys, non-TTY (Docker `RUN`) | Silent broken state | Exit 1 with paste-ready `export OPENAI_API_KEY=...` hint |
+| `OPENAPI_API_KEY=sk-…` (typo) | Silent broken state | Exit 1 + "did you mean OPENAI_API_KEY?" suggestion |
+| `--embedding-dimensions 9999` (invalid) | Silently created broken schema, exploded at first embed | Preflight rejects BEFORE any disk write |
+| `gbrain config set embedding.provider openai` | Silently accepted, no-op | Exit 1, suggests `embedding_model`. `--force` overrides with stderr WARN |
+
+If you upgrade and `gbrain doctor` warns about a silent-default v0.36 install (vector(1536) column + empty config), it now prints the exact repair command. For an empty brain, that's `gbrain init --force --embedding-model <id>`. For a populated brain, `gbrain retrieval-upgrade --to <id> --reindex`. You should never need `rm -rf ~/.gbrain` again.
+
+Things to watch:
+
+- **Behavior change for CI/Docker.** Bare `gbrain init --pglite` in a non-TTY context with no provider key now exits 1. If your image build runs init before the runtime env is populated, set the key at build time OR pass `--no-embedding` and configure at runtime. See [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for both patterns.
+- **Behavior change for `config set`.** Unknown keys now exit 1 by default. Downstream tooling that legitimately writes new keys must pass `--force`. The full list of recognized keys is `KNOWN_CONFIG_KEYS` in `src/core/config.ts`.
+- **Local providers (Ollama, llama-server) are no longer auto-picked.** They have no required API key, which previously made them count as "always env-ready" and silently win when the user clearly intended a hosted provider. They stay accessible via explicit `--embedding-model ollama:<model>`.
+
+### Itemized changes
+
+- **`src/core/levenshtein.ts`** (NEW) — small ~50-line `editDistance(a, b)` + `suggestNearest(input, candidates, maxDistance)` helper. Used by `gbrain config set` for "did you mean?" suggestions and by init for env-var typo detection.
+- **`src/core/embedding-dim-check.ts`** — three new pure functions: `resolveSchemaEmbeddingDim(opts)` and `resolveSchemaMultimodalDim(opts)` validate the resolved dim against recipe's `default_dims` plus per-provider Matryoshka allow-lists (OpenAI text-3, Voyage flexible-dim models, ZeroEntropy zembed-1) BEFORE any DB write; `EmbeddingDisabledError` + `assertEmbeddingEnabled(cfg)` guard the deferred-setup runtime path. New `PGVECTOR_COLUMN_MAX_DIMS = 16000` exported constant.
+- **`src/commands/init-provider-picker.ts`** (NEW) — interactive picker mirroring `init-mode-picker.ts`. Filters candidate recipes to env-ready ones, prompts via `readLineSafe`, surfaces the subagent-Anthropic caveat when picking a non-Anthropic chat-capable recipe without `ANTHROPIC_API_KEY` set. Exports `printSubagentAnthropicCaveat(write)` for reuse from `initPGLite` and `initPostgres` so the post-init auto-pick path also surfaces it.
+- **`src/commands/init.ts:resolveAIOptions`** — rewritten with a per-touchpoint env-detection tier. Precedence: explicit flag → shorthand → env auto-pick (group by provider id, codex finding #2) → picker (TTY) or fail-loud (non-TTY). Each touchpoint (embedding / expansion / chat) resolves independently. New `--no-embedding` opt-in flag for D9 deferred-setup mode. Exported `groupReadyByProvider(touchpoint, env)` + `findEnvKeyTypos(env)` for unit testing.
+- **`src/commands/init.ts:initPGLite` + `initPostgres`** — drop the conditional `configureGateway` gate so the schema substitution and runtime gateway use one resolved dim. Preflight `resolveSchemaEmbeddingDim` BEFORE `engine.initSchema()` — invalid dim refuses with paste-ready hint, no disk write. Atomic config persist (either resolved tuple or `embedding_disabled: true` sentinel, never partial). Post-init invariant assertion stays as regression guardrail. Subagent caveat fires post-init for both auto-pick + picker paths when chat_model is non-Anthropic AND `ANTHROPIC_API_KEY` is missing.
+- **`src/commands/providers.ts`** — extract `formatRecipeTable(recipes, env)` helper from `runList` so the picker and `gbrain providers list` can't drift. Add a stderr warn line to `providers test` when the tested model differs from the configured default ("Note: tested X in isolation; gbrain's configured embedding is Y — this test does NOT verify your brain's active path.") — codex finding #10.
+- **`src/commands/config.ts`** — strict unknown-key rejection with `--force` escape hatch. Levenshtein suggestion against `KNOWN_CONFIG_KEYS` + `KNOWN_CONFIG_KEY_PREFIXES` (well-known prefixes like `search.`, `models.`, `dream.` accept sub-keys without `--force`). Bug-reporter's three no-op config keys now all exit 1 with the right suggestion.
+- **`src/core/config.ts`** — adds `embedding_disabled?: boolean` to `GBrainConfig` (D9 sentinel). Exports `KNOWN_CONFIG_KEYS` (60+ canonical config keys, both file-plane and DB-plane) + `KNOWN_CONFIG_KEY_PREFIXES` (well-known prefixes for namespaced keys).
+- **`src/commands/embed.ts`** + **`src/commands/import.ts`** — `runEmbedCore` and `runImport` consult `assertEmbeddingEnabled(loadConfig())` and refuse cleanly with a `gbrain config set embedding_model <id>` hint when `embedding_disabled: true` is set. `gbrain import --no-embed` flag still works (chunks land without vectors).
+- **`src/commands/doctor.ts`** — `embedding_provider` check extended for the v0.36 silent-default repair case. Empty-brain vs non-empty-brain repair branching (drop-and-re-init vs `gbrain retrieval-upgrade`). `subagent_provider` check (v0.31.12) extended per D7 to warn when `chat_model` is non-Anthropic AND `ANTHROPIC_API_KEY` is missing.
+- **`src/commands/reindex-multimodal.ts`** — preflight `resolveSchemaMultimodalDim` BEFORE the reindex sweep, mirroring the text-side contract from `initPGLite`.
+- **`src/core/pglite-engine.ts` + `src/core/postgres-engine.ts`** — empty brain (`pageCount === 0`) now scores **100/100**, not 0/100. Vacuous truth: an empty brain has no coverage problem to penalize. Pre-fix, fresh `gbrain init --pglite` users saw `Brain score 0/100` on first `gbrain doctor` run, which was structurally surprising. Same fix on both engines, breakdown components unchanged for non-empty brains.
+- **`test/levenshtein.test.ts`** (18 cases), **`test/embedding-dim-check.test.ts`** (23 cases, extended), **`test/providers.test.ts`** (10 cases), **`test/init-provider-picker.test.ts`** (7 cases), **`test/init-env-detection.test.ts`** (21 cases), **`test/config-set.test.ts`** (19 cases) — 98 new unit cases pinning the env-detection grouping, Matryoshka validation, picker caveat behavior, Levenshtein suggestions, and bug-reporter regression for the three no-op keys.
+- **`test/e2e/init-fresh-pglite.test.ts`** (NEW, 14 E2E cases) — subprocess-driven verification of the full happy path, D3 non-TTY fail-loud (with and without env-key typos), D6 regression for the bug-reporter's three no-op config keys, D9 deferred-setup mode + import refusal, D11 preflight refusal without disk writes, and explicit-flag-wins-over-env precedence.
+- **`docs/integrations/embedding-providers.md`** — TL;DR table refreshed; added "Init resolves your provider from env keys" section and "If first import fails" troubleshooting block.
+- **`docs/operations/headless-install.md`** (NEW) — Docker/CI sequencing guide covering both build-time-key and runtime-key (`--no-embedding`) patterns.
+- **`README.md`** — added Troubleshooting section with one-paragraph repair hint and links to the headless-install + provider docs.
+- **`TODOS.md`** — closed the deferred v0.32.x "interactive provider chooser" entry as SUPERSEDED. Added four follow-up entries: dedicated migration script for v0.36 broken installs (telemetry-gated), namespaced extension fields for `config set --force` polish, runtime config-key inventory audit, and value-level Levenshtein on `config set`.
+
+### For contributors
+
+- The full eng-review decision trail (D1-D14) is at `~/.claude/plans/system-instruction-you-are-working-enumerated-mccarthy.md`.
+- 79 new unit tests + 14 new E2E tests. Total suite at 8200+ passing.
+
+## To take advantage of v0.37.10.0
+
+`gbrain upgrade` should pick this up automatically. If `gbrain doctor` warns about a v0.36 silent-default install:
+
+1. **Run the suggested repair from the doctor output.** Empty brain → `gbrain init --force --pglite --embedding-model <id>`. Non-empty brain → `gbrain retrieval-upgrade --to <id> --reindex`.
+2. **For CI/Docker:** review whether your image-build path runs `gbrain init --pglite` without an API key present. If so, switch to either Pattern 1 (key at build) or Pattern 2 (`--no-embedding` opt-in + runtime config) from `docs/operations/headless-install.md`.
+3. **For downstream tooling writing config keys:** if you have scripts that `gbrain config set` an unknown key (e.g. a custom plugin), pass `--force` to keep them working. Or migrate to a known prefix (`search.X`, `dream.X`, `models.X`).
+4. **Verify:**
+ ```bash
+ gbrain doctor --json | jq '.checks[] | select(.name=="embedding_provider")'
+ # Expect status=ok
+ ```
+5. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with `gbrain doctor` output. The new doctor surface should give a paste-ready repair; if not, that's a bug we want to know about.
+
## [0.37.9.0] - 2026-05-20
**Tags get written the same way everywhere now.**
diff --git a/CLAUDE.md b/CLAUDE.md
index 67195c736d..022213d63c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,9 +43,8 @@ strict behavior when unset.
- `src/core/operations.ts` — Contract-first operation definitions (the foundation). Also exports upload validators: `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (v0.23 glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` flags untrusted callers; `OperationContext.allowedSlugPrefixes` (v0.23) is the trusted-workspace allow-list set by the dream cycle. `put_page` enforces: when `viaSubagent` and `allowedSlugPrefixes` is set, slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Auto-link enabled for trusted-workspace writes (skipped only when `remote=true && !trustedWorkspace`). As of v0.26.0, every `Operation` also carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`. All ops are annotated; `sync_brain`, `file_upload`, `file_list`, and `file_url` are `admin + localOnly` (rejected over HTTP). `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. **v0.26.9 (D12 + F7b):** `OperationContext.remote` is now a REQUIRED field in the TypeScript type — the compiler is the first defense against transports that forget to set it. Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) flipped from falsy-default (`!ctx.remote`) to fail-closed semantics (`ctx.remote === false` for "trusted-only" sites and `ctx.remote !== false` for "untrust unless explicit-false"). Anything that isn't strictly `false` is now treated as remote. Closed an HTTP MCP shell-job RCE: a `read+write`-scoped OAuth token could submit `shell` jobs because the HTTP request handler's literal context skipped `remote: true` and `submit_job`'s protected-name guard saw a falsy undefined. Stdio MCP set the field correctly via dispatch.ts; HTTP inlined a parallel context-builder for several releases and lost it. **v0.34.1.0 (#861 + #876):** new helper `sourceScopeOpts(ctx)` encodes the precedence ladder for source-scoped reads — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId` / `ctx.auth.sourceId`) over nothing. Every read-side op handler routes through it so future ops can't silently drift from the canonical v0.31.8 thread. Closes the source-isolation leak on the read path: a `read+write`-scoped OAuth client bound to `--source dept-x` no longer sees rows from neighboring sources via `search` / `query` / `list_pages` / `get_page` / `find_experts` / `query`'s image path.
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput` / `TimelineBatchInput` for the v0.12.1 bulk-insert API (`addLinksBatch` / `addTimelineEntriesBatch`). As of v0.13.1, `BrainEngine` has a `readonly kind: 'postgres' | 'pglite'` discriminator so migrations (`src/core/migrate.ts`) and other consumers can branch on engine without `instanceof` + dynamic imports. **v0.29:** four new methods — `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so a page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[], $2::text[], $3::real[])` composite-keyed on `(slug, source_id)` for multi-source safety), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` extended with `sort?: 'updated_desc' | 'updated_asc' | 'created_desc' | 'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines (was hardcoded `ORDER BY updated_at DESC`). **v0.32.8 (PR #860):** new `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)`. Cheap cross-source enumeration for hot loops on large brains — replaces the `getAllSlugs()→getPage(slug)` N+1 pattern in extract-takes, extract, integrity, which silently defaulted to `source_id='default'` for non-default-source pages. Implementation parity across postgres-engine.ts + pglite-engine.ts. Pinned by `test/e2e/multi-source-bug-class.test.ts`. **v0.34.1.0 (#861):** `SearchOpts` + `PageFilters` add `sourceIds?: string[]` for the federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when the array is set and preserve the scalar `sourceId` fast path when unset. `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId` / `opts.sourceIds` so graph walks respect the caller's scope. **T8 wave (pgGraph-inspired CI infra, v0.37.4.0):** `traverseGraph` opts gains `frontierCap?: number` (per-iteration cap on the recursive CTE — approximately per-BFS-layer). Return type stays `Promise<GraphNode[]>` for MCP wire stability. New export `TraverseGraphOpts`. Postgres path uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term; PGLite mirrors with positional params + the same shape SQL. Pinned by `test/regressions/v0_36_frontier_cap.test.ts` (4 contracts: cap-unset back-compat, cap-hit bounds result to `<= cap+1`, MCP wire-shape preservation, concurrency independence). **`onTruncation` callback designed but stripped pre-merge in /review** — adversarial pass caught false-positive (organic count == cap) + false-negative (LIMIT-before-DISTINCT in diamond graphs) cases in the v1 algorithm. Restoring the signal requires a dedupe-then-cap SQL rewrite + Postgres parity E2E — see TODOS.md → "T8 truncation signal". **v0.35.6.0:** two new methods supporting the phantom-redirect cycle pass — `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (codex #7: content_hash refresh is required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug` + `source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence — codex #3 fix for the writeFactsToFence lossy-migration trap. Both methods have engine parity tests at `test/phantom-redirect-engine-parity.test.ts`.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`)
-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract. As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for the specific forward-referenced state the embedded schema blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target table) and adds only what's missing. Closes the upgrade-wedge bug class that bit users 10+ times across 6 schema versions over 2 years (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396). No-op on fresh installs and modern brains. **v0.35.5.0:** probe set extended in parity with postgres-engine.ts — `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`. Bootstrap also threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope. Closes #1018, #974, #820.
-- `src/core/pglite-schema.ts` — PGLite-specific DDL (pgvector, pg_trgm, triggers)
-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`. **v0.35.5.0:** probe set extended for the column-only forward-reference cases the original v0.22.6.1 sweep missed — `files.source_id`, `files.page_id` (pre-v0.18 brains where `idx_files_source_id` was the choke point), `oauth_clients.source_id`, `oauth_clients.federated_read` (pre-v0.34 brains where v60+v61+v65 chain failed), and `sources.archived` + `sources.archived_at` + `sources.archive_expires_at` (pre-v0.26.5 brains where `CREATE TABLE IF NOT EXISTS sources` was a no-op on existing tables so the archive lifecycle columns never landed). Also (Codex P1 from pre-landing review): the entire probe path now runs on the DDL connection threaded down from `initSchema` — previously probes ran through the instance pool while the advisory lock sat on a different connection, opening a concurrent-bootstrap race for Supabase pooler users. Closes #1018, #974, #820. **v0.28.1:** `disconnect()` is now idempotent. New `_connectionStyle` instance field tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than falling through to `db.disconnect()` and clobbering the singleton. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` (2 cases). Closes the bug class where any test sharing an engine across multiple `worker.start()` / `worker.stop()` cycles silently broke its own DB connectivity.
+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract. As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for the specific forward-referenced state the embedded schema blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target table) and adds only what's missing. Closes the upgrade-wedge bug class that bit users 10+ times across 6 schema versions over 2 years (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396). No-op on fresh installs and modern brains. **v0.35.5.0:** probe set extended in parity with postgres-engine.ts — `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`. Bootstrap also threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope. Closes #1018, #974, #820. **v0.37.10.0:** `getBrainScore` now returns 100/100 with full breakdown components (35/25/15/15/10) when `pageCount === 0`. Vacuous truth — an empty brain has no coverage problem to penalize. Pre-fix, fresh `gbrain init --pglite` users saw "Brain score 0/100" on first `gbrain doctor` run, which was structurally surprising AND triggered the v0.37.8.0 `doctor-report-remote.test.ts` flake (test expected `health_score >= 70` on a freshly-initialized test brain). Mirrored in postgres-engine.ts. Pinned by `test/brain-score-breakdown.test.ts`'s updated empty-brain assertion and the hermetic `test/doctor-report-remote.serial.test.ts`. — PGLite-specific DDL (pgvector, pg_trgm, triggers)
+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`. **v0.35.5.0:** probe set extended for the column-only forward-reference cases the original v0.22.6.1 sweep missed — `files.source_id`, `files.page_id` (pre-v0.18 brains where `idx_files_source_id` was the choke point), `oauth_clients.source_id`, `oauth_clients.federated_read` (pre-v0.34 brains where v60+v61+v65 chain failed), and `sources.archived` + `sources.archived_at` + `sources.archive_expires_at` (pre-v0.26.5 brains where `CREATE TABLE IF NOT EXISTS sources` was a no-op on existing tables so the archive lifecycle columns never landed). Also (Codex P1 from pre-landing review): the entire probe path now runs on the DDL connection threaded down from `initSchema` — previously probes ran through the instance pool while the advisory lock sat on a different connection, opening a concurrent-bootstrap race for Supabase pooler users. Closes #1018, #974, #820. **v0.28.1:** `disconnect()` is now idempotent. New `_connectionStyle` instance field tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than falling through to `db.disconnect()` and clobbering the singleton. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` (2 cases). Closes the bug class where any test sharing an engine across multiple `worker.start()` / `worker.stop()` cycles silently broke its own DB connectivity. **v0.37.10.0:** `getBrainScore` empty-brain parity with PGLite — returns 100/100 with breakdown components 35/25/15/15/10 when `pageCount === 0` instead of the pre-fix 0/100. Same vacuous-truth rationale as the PGLite side; both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic.
- `src/core/cjk.ts` (v0.32.7 CJK wave) — Single source of truth for CJK detection across the codebase. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `countCJKAwareWords(s)` (30% density threshold — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). Replaces the inline hasCJK regex previously duplicated at `expansion.ts:58`. BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables); widening to Unicode property escapes is a v0.33+ TODO. Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
- `src/core/audit-slug-fallback.ts` (v0.32.7 CJK wave) — Weekly ISO-week-rotated audit JSONL at `~/.gbrain/audit/slug-fallback-YYYY-Www.jsonl`. `logSlugFallback(slug, sourcePath)` fires when `importFromFile` falls back to a frontmatter slug because `slugifyPath` returned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames). `readRecentSlugFallbacks(days)` reads the last N days for `gbrain doctor`'s `slug_fallback_audit` check. Honors `GBRAIN_AUDIT_DIR` via the shared `resolveAuditDir()` from shell-audit.ts. Separate surface from `sync-failures.jsonl` per codex outside-voice review — that file carries bookmark-gating semantics that info events shouldn't trigger.
- `src/core/embedding-pricing.ts` (v0.32.7 CJK wave) — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M), Voyage 3-large ($0.18/1M), 3 ($0.06/1M). `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token approximation. Unknown providers degrade gracefully to "estimate unavailable" instead of fabricating numbers.
diff --git a/README.md b/README.md
index 8289fdd96c..61d667d523 100644
--- a/README.md
+++ b/README.md
@@ -112,6 +112,10 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**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).
+## Troubleshooting
+
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. As of v0.37, fresh `gbrain init --pglite` auto-detects your embedding provider from API keys in your environment — set `OPENAI_API_KEY` (or `ZEROENTROPY_API_KEY` / `VOYAGE_API_KEY`) before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker. In non-TTY contexts (CI, Docker) with no keys, init exits 1 with a paste-ready setup hint; pass `--no-embedding` to defer setup until runtime. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+
## Docs
- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end
diff --git a/TODOS.md b/TODOS.md
index 18898ccc8e..1361fa2e06 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -3,7 +3,7 @@
## v0.37.8.0 pre-existing master test regression (noticed during ship)
-- [ ] **P0: `test/doctor-report-remote.test.ts:65` — `full report on healthy brain` fails with `health_score: 50` (expects `>=70`).** Reproduces in isolation on fresh PGLite. Introduced by master's v0.37.3.0 (#1215, `skill_brain_first` doctor check) which appears to return non-ok on freshly-initialized test brains, dropping the composite health score below the test's threshold. Fix shape: either (a) `skill_brain_first` should return `ok` (or `n/a`) on empty/test brains with no user-authored skills, OR (b) `doctor-report-remote.test.ts:68` should seed the skills directory before computing the score, OR (c) downgrade `skill_brain_first` non-ok to a check that doesn't penalize the score on fresh brains. Owner: maintainer of #1215. Noticed during /ship of garrytan/kolkata-v3 → v0.37.8.0.
+- [x] **P0: `test/doctor-report-remote.test.ts:65` — `full report on healthy brain` fails with `health_score: 50` (expects `>=70`).** **Completed:** v0.37.10.0 (2026-05-21). Resolved structurally by the empty-brain-100/100 fix in `src/core/pglite-engine.ts` + `src/core/postgres-engine.ts` (commit 9aa571f3): pages-empty brains now get vacuous-truth full marks on every breakdown component (35/25/15/15/10), so the freshly-initialized test brain's composite stays >=70 even when `skill_brain_first` returns non-ok. Test file renamed to `test/doctor-report-remote.serial.test.ts` and made hermetic (isolates `GBRAIN_HOME` to a tempdir via beforeAll/afterAll per `scripts/check-test-isolation.sh` R1 — env mutation requires serial quarantine).
## v0.37.7.0 federated-brains + autopilot safety follow-ups (v0.37.x+)
@@ -235,17 +235,58 @@
update PR. Or a release-cadence audit checklist item. Today: when the
estimate looks off, hand-edit the constants.
-- [ ] **v0.32.x: interactive provider chooser in `gbrain init`.** The full
- wizard piece of the v0.32 discoverability lane was deferred. Today
- `gbrain init` (no flags, TTY) silently uses OpenAI default. Plan: hook
- into `init.ts:resolveAIOptions`, when no `--model` AND TTY AND not
- `--non-interactive`, call `runExplain([])` (non-JSON path) from
- `providers.ts:233-350` to print the provider matrix, then prompt with
- readline (mirror `supabaseWizard()` at `init.ts:108`). Suggest
- recommended based on env detection. Refuse `user_provided_models`
- shorthand (already done in v0.32.0). Tests:
- `test/init-provider-wizard.test.ts` (TTY → prompt fires; non-TTY →
- falls through; invalid choice → re-prompts).
+- [x] ~~**v0.32.x: interactive provider chooser in `gbrain init`.**~~
+ **SUPERSEDED by v0.37 — closed by the env-detection + hybrid picker wave.**
+ `src/commands/init-provider-picker.ts` mirrors this design: filters to
+ env-ready recipes, prompts via readline through `readLineSafe`, surfaces
+ the subagent-Anthropic caveat on non-Anthropic chat picks. Env detection
+ in `resolveAIOptions` auto-picks when env is unambiguous (one provider's
+ keys set), fires the picker when multiple providers are ready, and exits 1
+ with a paste-ready setup hint in non-TTY zero-key contexts (D3). See
+ `~/.claude/plans/system-instruction-you-are-working-enumerated-mccarthy.md`
+ for the full decision trail.
+
+## Embedding-provider follow-ups (v0.37+)
+
+- [ ] **v0.37+: dedicated migration script for v0.36 broken installs.** v0.37
+ ships D5 + step 11 of the env-detection wave, which surfaces v0.36 silent-
+ default brains in `gbrain doctor` with a paste-ready repair command. What's
+ not yet built: a one-shot orchestrator under `src/commands/migrations/v0_37_x.ts`
+ that detects the broken state (vector(1536) schema + empty
+ `config.embedding_model` + 0 embedded chunks) on `gbrain upgrade` and runs
+ the repair automatically. Same shape as `src/commands/migrations/v0_12_2.ts`.
+ Telemetry-gated: only worth writing if issues show widespread breakage.
+
+- [ ] **v0.37+: namespaced extension fields for `gbrain config set`.** v0.37
+ D6 ships strict unknown-key rejection with a `--force` escape hatch +
+ Levenshtein "did you mean" suggestion. Codex finding #8 from the eng review
+ argued for a `gbrain.ext.<key>` namespace pattern instead of `--force`
+ accepting arbitrary top-level keys; deferred for follow-up. Revisit if
+ `--force` shows misuse in practice (e.g. tooling writing dozens of unknown
+ keys, polluting `gbrain config show`).
+
+- [ ] **v0.37+: runtime config-key inventory audit.** Codex finding #12 from
+ the eng review: the `KNOWN_CONFIG_KEYS` allow-list in `src/core/config.ts`
+ is hand-maintained. A future runtime audit could walk every `cfg.X` access
+ site at startup and cross-check against the allow-list, catching drift
+ when new code paths read a key the maintainer forgot to declare. Pre-merge
+ manual grep (`grep -rE "config\.\w+" src/`) is sufficient today.
+
+- [ ] **v0.38+: env-key typo detection at `gbrain config set` time too.**
+ v0.37 D13 ships Levenshtein typo detection at init for env vars
+ (`OPENAPI_API_KEY` → `OPENAI_API_KEY`). The same logic isn't applied at
+ `gbrain config set` for value-level provider strings (e.g.
+ `gbrain config set embedding_model openai:text-embedign-3-large` —
+ notice the typo'd model name). Cheap to add: parse the value as
+ `provider:model`, suggest the nearest from the recipe's `models[]` list.
+
+- [ ] **v0.38+: extend init env-detection to multimodal explicitly via picker.**
+ v0.37 T11 hooks `resolveSchemaMultimodalDim` preflight into
+ `gbrain reindex --multimodal`. The picker doesn't yet have a 'multimodal'
+ touchpoint mode — multimodal model selection happens via
+ `gbrain config set embedding_multimodal_model` or env detection of
+ multimodal-capable providers. Future polish: extend the picker with a
+ fourth touchpoint case so first-time users discover the option at init.
- [ ] **v0.32.x: real-credentials per-recipe smoke-test CI matrix.** Codex
finding #6 noted that unit tests via `__setEmbedTransportForTests` prove
diff --git a/VERSION b/VERSION
index f0072a0346..43686b5394 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.37.9.0
\ No newline at end of file
+0.37.10.0
\ No newline at end of file
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index a37881e311..b3d96383af 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -1,6 +1,6 @@
# Embedding providers
-GBrain ships with 16 embedding-provider recipes covering OpenAI, OpenRouter (single key, many hosted models), the major hosted alternatives, three local options, and a universal escape hatch (LiteLLM proxy). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
+GBrain ships with 16 embedding-provider recipes covering OpenAI, ZeroEntropy, Voyage, OpenRouter (single key, many hosted models), the major hosted alternatives, three local options, and a universal escape hatch (LiteLLM proxy). Run `gbrain providers list` to see the live registry; `gbrain providers explain --json` emits a machine-readable matrix for agents.
This page is the human-readable counterpart: capability per provider, env-var setup, dimensions, cost, and known constraints.
@@ -13,10 +13,17 @@ gbrain providers test --model openai:text-embedding-3-large # smoke-test
gbrain init --pglite --model voyage # use a non-default provider
```
+## Init resolves your provider from env keys
+
+As of v0.37, `gbrain init --pglite` auto-detects which provider to use from your env vars. With `OPENAI_API_KEY` set, you get OpenAI. With `ZEROENTROPY_API_KEY` set, you get ZeroEntropy. If multiple provider keys are set, init fires an interactive picker. If no provider keys are set in a non-TTY context (CI, Docker build), init exits 1 with a paste-ready setup hint. Explicit flags (`--embedding-model`, `--no-embedding`) always win over env detection.
+
+The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atomically, so subsequent runs are deterministic across releases.
+
## TL;DR table
| Provider | env vars | default dims | cost ($/1M tokens) | local? | multimodal? |
|---|---|---|---|---|---|
+| `zeroentropyai` | `ZEROENTROPY_API_KEY` | 2560 (Matryoshka to 1280/640/320/...) | 0.05 | no | no |
| `openai` | `OPENAI_API_KEY` | 1536 | 0.13 | no | no |
| `openrouter` | `OPENROUTER_API_KEY` | 1536 | 0.02 | no | model-dependent |
| `voyage` | `VOYAGE_API_KEY` | 1024 | 0.18 | no | yes (`voyage-multimodal-3`) |
@@ -33,6 +40,24 @@ gbrain init --pglite --model voyage # use a non-default provider
| `deepseek` | (no embedding model — chat only) | — | — | — | — |
| `groq` | (no embedding model — chat only) | — | — | — | — |
+**Note on local providers.** Ollama and llama-server have no required API key, so they don't show up in env-detection auto-pick. Pick them explicitly with `--embedding-model ollama:<model>` to avoid silently routing to a daemon that may not be running.
+
+## If first import fails
+
+If `gbrain import` fails with `expected N dimensions, not M`, run `gbrain doctor`. The output will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. **You should not need to delete `~/.gbrain`.** The bug-class that historically forced `rm -rf` recoveries is closed as of v0.37.
+
+The doctor distinguishes two repair paths:
+
+- **Empty brain** (no embedded chunks yet) — drop and re-init at the right dim:
+ ```
+ gbrain init --force --pglite --embedding-model <provider>:<model> --embedding-dimensions <N>
+ ```
+
+- **Non-empty brain** — migrate cleanly with the supported reindex path:
+ ```
+ gbrain retrieval-upgrade --to <provider>:<model> --reindex
+ ```
+
## Decision tree
- **Cost-sensitive, English-only**: Ollama (free, local) or Voyage (paid, best quality per dollar).
diff --git a/docs/operations/headless-install.md b/docs/operations/headless-install.md
new file mode 100644
index 0000000000..b0ba50fb1c
--- /dev/null
+++ b/docs/operations/headless-install.md
@@ -0,0 +1,87 @@
+# Headless install: Docker, CI, postinstall
+
+As of v0.37, `gbrain init --pglite` in a non-TTY context (Docker `RUN`, CI step, postinstall hook) exits 1 when no embedding-provider API key is present in the environment. This is a deliberate fail-loud — the alternative was the v0.36 silent-broken-state class where init succeeded with a default that didn't match any real key.
+
+Two patterns work for headless installs. Pick whichever fits your image lifecycle.
+
+## Pattern 1: Provider key available at image build time
+
+If your CI / Docker pipeline can inject the API key as a build-time env var, set it before `gbrain init`:
+
+```dockerfile
+# Multi-stage Dockerfile sketch
+FROM oven/bun:1 AS builder
+
+# Inject key at build via --build-arg or `--env` from CI.
+ARG OPENAI_API_KEY
+ENV OPENAI_API_KEY=$OPENAI_API_KEY
+
+RUN bun install -g github:garrytan/gbrain
+RUN gbrain init --pglite # auto-picks OpenAI, persists config
+```
+
+```yaml
+# GitHub Actions equivalent
+- name: Initialize gbrain
+ env:
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ run: |
+ bun install -g github:garrytan/gbrain
+ gbrain init --pglite
+```
+
+Init writes `~/.gbrain/config.json` with the resolved `embedding_model` + `embedding_dimensions`. Subsequent runs (in the same image / runner) read from that config and don't re-resolve.
+
+## Pattern 2: Provider key only at runtime (deferred-setup)
+
+If the API key is a runtime secret (Kubernetes secret, runtime env injection, end-user-supplied), use `--no-embedding` at build time and configure the provider when the container actually runs:
+
+```dockerfile
+FROM oven/bun:1
+RUN bun install -g github:garrytan/gbrain
+
+# Build the brain shape without a provider — schema lands at the default
+# width, but no embed callsite will actually run until runtime config.
+RUN gbrain init --pglite --no-embedding
+
+# At container start (entrypoint), provide the real provider:
+ENTRYPOINT ["/bin/sh", "-c", "\
+ gbrain config set embedding_model openai:text-embedding-3-large \
+ && gbrain init --force --pglite \
+ && exec gbrain serve"]
+```
+
+The `gbrain init --no-embedding` opt-in writes `embedding_disabled: true` to config. Every embed callsite (`gbrain import`, `gbrain embed`, the `runEmbedCore` library entry point) checks this and refuses cleanly with a `gbrain config set embedding_model <id>` hint rather than proceeding with a silent default.
+
+The runtime `gbrain init --force` re-runs the init flow against the now-populated env, which:
+
+- Removes `embedding_disabled` from config.
+- Resolves the provider via env detection.
+- Re-templates the PGLite schema if dim differs from the build-time default.
+
+## What WON'T work
+
+```dockerfile
+# Don't do this — silent default leaves you with vector(1280) ZE column
+# and 1536d OpenAI provider at runtime, mismatched.
+RUN gbrain init --pglite
+```
+
+If you upgrade from a pre-v0.37 image that used this pattern, `gbrain doctor` will surface the mismatch on first run after upgrade and print a paste-ready repair command (`gbrain init --force --embedding-model …` for empty brains, `gbrain retrieval-upgrade --reindex` for non-empty).
+
+## Verifying a headless install
+
+After init, run `gbrain doctor --json` to verify state:
+
+```bash
+gbrain doctor --json | jq '.checks[] | select(.name=="embedding_provider")'
+```
+
+The `embedding_provider` check returns `status: 'ok'` when:
+
+- Config has a persisted `embedding_model`.
+- Config has a persisted `embedding_dimensions`.
+- Live provider probe returns the configured dim.
+- DB column width matches.
+
+If you used Pattern 2's deferred-setup path, the check shows `Skipped (no provider credentials)` until the runtime config is populated. That's expected.
diff --git a/llms-full.txt b/llms-full.txt
index 11cc932da0..6f750ef4ac 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -179,9 +179,8 @@ strict behavior when unset.
- `src/core/operations.ts` — Contract-first operation definitions (the foundation). Also exports upload validators: `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (v0.23 glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` flags untrusted callers; `OperationContext.allowedSlugPrefixes` (v0.23) is the trusted-workspace allow-list set by the dream cycle. `put_page` enforces: when `viaSubagent` and `allowedSlugPrefixes` is set, slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Auto-link enabled for trusted-workspace writes (skipped only when `remote=true && !trustedWorkspace`). As of v0.26.0, every `Operation` also carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`. All ops are annotated; `sync_brain`, `file_upload`, `file_list`, and `file_url` are `admin + localOnly` (rejected over HTTP). `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. **v0.26.9 (D12 + F7b):** `OperationContext.remote` is now a REQUIRED field in the TypeScript type — the compiler is the first defense against transports that forget to set it. Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) flipped from falsy-default (`!ctx.remote`) to fail-closed semantics (`ctx.remote === false` for "trusted-only" sites and `ctx.remote !== false` for "untrust unless explicit-false"). Anything that isn't strictly `false` is now treated as remote. Closed an HTTP MCP shell-job RCE: a `read+write`-scoped OAuth token could submit `shell` jobs because the HTTP request handler's literal context skipped `remote: true` and `submit_job`'s protected-name guard saw a falsy undefined. Stdio MCP set the field correctly via dispatch.ts; HTTP inlined a parallel context-builder for several releases and lost it. **v0.34.1.0 (#861 + #876):** new helper `sourceScopeOpts(ctx)` encodes the precedence ladder for source-scoped reads — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId` / `ctx.auth.sourceId`) over nothing. Every read-side op handler routes through it so future ops can't silently drift from the canonical v0.31.8 thread. Closes the source-isolation leak on the read path: a `read+write`-scoped OAuth client bound to `--source dept-x` no longer sees rows from neighboring sources via `search` / `query` / `list_pages` / `get_page` / `find_experts` / `query`'s image path.
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput` / `TimelineBatchInput` for the v0.12.1 bulk-insert API (`addLinksBatch` / `addTimelineEntriesBatch`). As of v0.13.1, `BrainEngine` has a `readonly kind: 'postgres' | 'pglite'` discriminator so migrations (`src/core/migrate.ts`) and other consumers can branch on engine without `instanceof` + dynamic imports. **v0.29:** four new methods — `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so a page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[], $2::text[], $3::real[])` composite-keyed on `(slug, source_id)` for multi-source safety), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` extended with `sort?: 'updated_desc' | 'updated_asc' | 'created_desc' | 'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines (was hardcoded `ORDER BY updated_at DESC`). **v0.32.8 (PR #860):** new `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)`. Cheap cross-source enumeration for hot loops on large brains — replaces the `getAllSlugs()→getPage(slug)` N+1 pattern in extract-takes, extract, integrity, which silently defaulted to `source_id='default'` for non-default-source pages. Implementation parity across postgres-engine.ts + pglite-engine.ts. Pinned by `test/e2e/multi-source-bug-class.test.ts`. **v0.34.1.0 (#861):** `SearchOpts` + `PageFilters` add `sourceIds?: string[]` for the federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when the array is set and preserve the scalar `sourceId` fast path when unset. `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId` / `opts.sourceIds` so graph walks respect the caller's scope. **T8 wave (pgGraph-inspired CI infra, v0.37.4.0):** `traverseGraph` opts gains `frontierCap?: number` (per-iteration cap on the recursive CTE — approximately per-BFS-layer). Return type stays `Promise<GraphNode[]>` for MCP wire stability. New export `TraverseGraphOpts`. Postgres path uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term; PGLite mirrors with positional params + the same shape SQL. Pinned by `test/regressions/v0_36_frontier_cap.test.ts` (4 contracts: cap-unset back-compat, cap-hit bounds result to `<= cap+1`, MCP wire-shape preservation, concurrency independence). **`onTruncation` callback designed but stripped pre-merge in /review** — adversarial pass caught false-positive (organic count == cap) + false-negative (LIMIT-before-DISTINCT in diamond graphs) cases in the v1 algorithm. Restoring the signal requires a dedupe-then-cap SQL rewrite + Postgres parity E2E — see TODOS.md → "T8 truncation signal". **v0.35.6.0:** two new methods supporting the phantom-redirect cycle pass — `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (codex #7: content_hash refresh is required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug` + `source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence — codex #3 fix for the writeFactsToFence lossy-migration trap. Both methods have engine parity tests at `test/phantom-redirect-engine-parity.test.ts`.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`)
-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract. As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for the specific forward-referenced state the embedded schema blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target table) and adds only what's missing. Closes the upgrade-wedge bug class that bit users 10+ times across 6 schema versions over 2 years (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396). No-op on fresh installs and modern brains. **v0.35.5.0:** probe set extended in parity with postgres-engine.ts — `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`. Bootstrap also threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope. Closes #1018, #974, #820.
-- `src/core/pglite-schema.ts` — PGLite-specific DDL (pgvector, pg_trgm, triggers)
-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`. **v0.35.5.0:** probe set extended for the column-only forward-reference cases the original v0.22.6.1 sweep missed — `files.source_id`, `files.page_id` (pre-v0.18 brains where `idx_files_source_id` was the choke point), `oauth_clients.source_id`, `oauth_clients.federated_read` (pre-v0.34 brains where v60+v61+v65 chain failed), and `sources.archived` + `sources.archived_at` + `sources.archive_expires_at` (pre-v0.26.5 brains where `CREATE TABLE IF NOT EXISTS sources` was a no-op on existing tables so the archive lifecycle columns never landed). Also (Codex P1 from pre-landing review): the entire probe path now runs on the DDL connection threaded down from `initSchema` — previously probes ran through the instance pool while the advisory lock sat on a different connection, opening a concurrent-bootstrap race for Supabase pooler users. Closes #1018, #974, #820. **v0.28.1:** `disconnect()` is now idempotent. New `_connectionStyle` instance field tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than falling through to `db.disconnect()` and clobbering the singleton. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` (2 cases). Closes the bug class where any test sharing an engine across multiple `worker.start()` / `worker.stop()` cycles silently broke its own DB connectivity.
+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract. As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for the specific forward-referenced state the embedded schema blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target table) and adds only what's missing. Closes the upgrade-wedge bug class that bit users 10+ times across 6 schema versions over 2 years (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396). No-op on fresh installs and modern brains. **v0.35.5.0:** probe set extended in parity with postgres-engine.ts — `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`. Bootstrap also threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope. Closes #1018, #974, #820. **v0.37.10.0:** `getBrainScore` now returns 100/100 with full breakdown components (35/25/15/15/10) when `pageCount === 0`. Vacuous truth — an empty brain has no coverage problem to penalize. Pre-fix, fresh `gbrain init --pglite` users saw "Brain score 0/100" on first `gbrain doctor` run, which was structurally surprising AND triggered the v0.37.8.0 `doctor-report-remote.test.ts` flake (test expected `health_score >= 70` on a freshly-initialized test brain). Mirrored in postgres-engine.ts. Pinned by `test/brain-score-breakdown.test.ts`'s updated empty-brain assertion and the hermetic `test/doctor-report-remote.serial.test.ts`. — PGLite-specific DDL (pgvector, pg_trgm, triggers)
+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`. **v0.35.5.0:** probe set extended for the column-only forward-reference cases the original v0.22.6.1 sweep missed — `files.source_id`, `files.page_id` (pre-v0.18 brains where `idx_files_source_id` was the choke point), `oauth_clients.source_id`, `oauth_clients.federated_read` (pre-v0.34 brains where v60+v61+v65 chain failed), and `sources.archived` + `sources.archived_at` + `sources.archive_expires_at` (pre-v0.26.5 brains where `CREATE TABLE IF NOT EXISTS sources` was a no-op on existing tables so the archive lifecycle columns never landed). Also (Codex P1 from pre-landing review): the entire probe path now runs on the DDL connection threaded down from `initSchema` — previously probes ran through the instance pool while the advisory lock sat on a different connection, opening a concurrent-bootstrap race for Supabase pooler users. Closes #1018, #974, #820. **v0.28.1:** `disconnect()` is now idempotent. New `_connectionStyle` instance field tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than falling through to `db.disconnect()` and clobbering the singleton. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` (2 cases). Closes the bug class where any test sharing an engine across multiple `worker.start()` / `worker.stop()` cycles silently broke its own DB connectivity. **v0.37.10.0:** `getBrainScore` empty-brain parity with PGLite — returns 100/100 with breakdown components 35/25/15/15/10 when `pageCount === 0` instead of the pre-fix 0/100. Same vacuous-truth rationale as the PGLite side; both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic.
- `src/core/cjk.ts` (v0.32.7 CJK wave) — Single source of truth for CJK detection across the codebase. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `countCJKAwareWords(s)` (30% density threshold — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). Replaces the inline hasCJK regex previously duplicated at `expansion.ts:58`. BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables); widening to Unicode property escapes is a v0.33+ TODO. Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
- `src/core/audit-slug-fallback.ts` (v0.32.7 CJK wave) — Weekly ISO-week-rotated audit JSONL at `~/.gbrain/audit/slug-fallback-YYYY-Www.jsonl`. `logSlugFallback(slug, sourcePath)` fires when `importFromFile` falls back to a frontmatter slug because `slugifyPath` returned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames). `readRecentSlugFallbacks(days)` reads the last N days for `gbrain doctor`'s `slug_fallback_audit` check. Honors `GBRAIN_AUDIT_DIR` via the shared `resolveAuditDir()` from shell-audit.ts. Separate surface from `sync-failures.jsonl` per codex outside-voice review — that file carries bookmark-gating semantics that info events shouldn't trigger.
- `src/core/embedding-pricing.ts` (v0.32.7 CJK wave) — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M), Voyage 3-large ($0.18/1M), 3 ($0.06/1M). `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token approximation. Unknown providers degrade gracefully to "estimate unavailable" instead of fabricating numbers.
@@ -2549,6 +2548,10 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
**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).
+## Troubleshooting
+
+**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain retrieval-upgrade` command to repair the mismatch. You should not need to delete `~/.gbrain`. As of v0.37, fresh `gbrain init --pglite` auto-detects your embedding provider from API keys in your environment — set `OPENAI_API_KEY` (or `ZEROENTROPY_API_KEY` / `VOYAGE_API_KEY`) before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker. In non-TTY contexts (CI, Docker) with no keys, init exits 1 with a paste-ready setup hint; pass `--no-embedding` to defer setup until runtime. See [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](docs/operations/headless-install.md) for Docker/CI sequencing.
+
## Docs
- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end
diff --git a/package.json b/package.json
index 82067f5682..f86586aa1a 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.37.9.0",
+ "version": "0.37.10.0",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 08db8c6375..218ab6891b 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -106,6 +106,37 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
process.exit(1);
}
} else if (action === 'set' && key && value) {
+ // v0.37 (D6): strict unknown-key rejection with --force escape hatch.
+ // Catches the silent-no-op class the bug reporter hit (`embedding.provider`,
+ // `embedding.model`, `embedding.dimensions` all accepted today). Levenshtein
+ // suggests the canonical key when one is within edit distance ≤ 3.
+ const forceFlag = args.includes('--force');
+ if (!forceFlag) {
+ const { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES } = await import('../core/config.ts');
+ const isKnown = KNOWN_CONFIG_KEYS.includes(key);
+ const matchesPrefix = KNOWN_CONFIG_KEY_PREFIXES.some(p => key.startsWith(p));
+ if (!isKnown && !matchesPrefix) {
+ const { suggestNearest } = await import('../core/levenshtein.ts');
+ const suggestion = suggestNearest(key, KNOWN_CONFIG_KEYS, 3);
+ console.error(`[config] Unknown config key "${key}".`);
+ if (suggestion) {
+ console.error(`[config] Did you mean "${suggestion}"?`);
+ } else {
+ console.error(`[config] No similar known key. Run \`gbrain config show\` to see currently-set keys.`);
+ }
+ console.error(`[config] If this is intentional (downstream tooling, forward-compat), re-run with --force.`);
+ process.exit(1);
+ }
+ } else {
+ // --force: accept but warn loudly so the user sees what they're doing.
+ const { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES } = await import('../core/config.ts');
+ const isKnown = KNOWN_CONFIG_KEYS.includes(key);
+ const matchesPrefix = KNOWN_CONFIG_KEY_PREFIXES.some(p => key.startsWith(p));
+ if (!isKnown && !matchesPrefix) {
+ console.error(`[config] WARN: writing unknown key "${key}" with --force. Nothing in gbrain reads this.`);
+ }
+ }
+
// v0.36 (D12 + D14): validate embedding-column keys at set time so a
// bad config gets rejected loud + early. The `--coverage-override`
// flag lets the user proceed past the < 90% gate when they know
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 314dd6f50b..f921de4116 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -1359,6 +1359,29 @@ async function checkSubagentProvider(engine: BrainEngine): Promise<Check> {
`Fix: \`gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6\` to lock it in.`,
};
}
+
+ // v0.37 (T10 / D7): warn when the configured chat_model is non-Anthropic
+ // AND ANTHROPIC_API_KEY isn't set. Subagent jobs require Anthropic
+ // regardless of chat_model (minions/queue.ts:97 enforces this); without
+ // the key, gbrain dream / gbrain agent run / gbrain autopilot will all
+ // fail at first job submission. Catches the post-init drift case the
+ // init-time caveat would have shown if init had been re-run.
+ try {
+ const { loadConfig } = await import('../core/config.ts');
+ const cfg = loadConfig();
+ const chatModel = cfg?.chat_model;
+ if (chatModel && !isAnthropicProvider(chatModel) && !process.env.ANTHROPIC_API_KEY) {
+ return {
+ name: 'subagent_provider',
+ status: 'warn',
+ message:
+ `chat_model is "${chatModel}" (non-Anthropic) and ANTHROPIC_API_KEY is not set. ` +
+ `Subagent features (gbrain dream, gbrain agent run, gbrain autopilot) will fail at job submission. ` +
+ `Chat alone (gbrain think) still works. Set ANTHROPIC_API_KEY before running subagent commands.`,
+ };
+ }
+ } catch { /* loadConfig may throw; fall through */ }
+
return { name: 'subagent_provider', status: 'ok', message: 'Subagent tier resolves to Anthropic' };
} catch (e) {
return {
@@ -2393,7 +2416,63 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSo
const configuredDims = getEmbeddingDimensions();
const available = isAvailable('embedding');
- if (!available) {
+ // v0.37 (T9, codex #7 nuance): catch the v0.36 silent-default case where
+ // config has no embedding_model but the schema column exists at a dim
+ // that doesn't match the gateway's resolved default. Empty-brain vs
+ // non-empty-brain branching determines the repair hint:
+ // - empty brain (no embedded chunks) → `gbrain init --force --embedding-model …`
+ // - non-empty brain → `gbrain retrieval-upgrade --to … --reindex`
+ // The bug-reporter's `rm -rf ~/.gbrain` recovery is never the right answer.
+ let surfacedUnconfiguredDrift = false;
+ try {
+ const { loadConfig } = await import('../core/config.ts');
+ const cfg = loadConfig();
+ const fileEmbeddingSet = !!cfg?.embedding_model;
+ const deferredSetup = cfg?.embedding_disabled === true;
+ if (!fileEmbeddingSet && !deferredSetup) {
+ // Read column dim + chunk count
+ const { readContentChunksEmbeddingDim } = await import('../core/embedding-dim-check.ts');
+ const colDim = await readContentChunksEmbeddingDim(engine);
+ if (colDim.exists && colDim.dims !== null && colDim.dims !== configuredDims) {
+ // Determine if the brain has any content — drift is only a real
+ // user-facing problem once the user has imported anything. A
+ // pristine brain (0 total chunks) is still in fresh-install state;
+ // first import will hit the loud preflight before any column
+ // write, so doctor doesn't need to pre-warn.
+ let totalChunks = 0;
+ let embeddedCount = 0;
+ try {
+ const rows = await engine.executeRaw<{ total: number | string; embedded: number | string }>(
+ `SELECT COUNT(*)::int AS total, COUNT(*) FILTER (WHERE embedding IS NOT NULL)::int AS embedded FROM content_chunks`,
+ );
+ totalChunks = Number(rows?.[0]?.total ?? 0);
+ embeddedCount = Number(rows?.[0]?.embedded ?? 0);
+ } catch { /* table may be missing or fresh; treat as empty */ }
+
+ if (totalChunks > 0) {
+ const fix = embeddedCount === 0
+ ? `No embeddings yet — drop the empty schema and re-init at the right dim:\n gbrain init --force --pglite --embedding-model ${configuredModel} --embedding-dimensions ${configuredDims}`
+ : `Non-empty brain (${embeddedCount} embedded chunks). Migrate cleanly:\n gbrain retrieval-upgrade --to ${configuredModel} --reindex`;
+
+ checks.push({
+ name: 'embedding_provider',
+ status: 'warn',
+ message:
+ `Schema column is vector(${colDim.dims}) but gateway default resolves to ${configuredModel} (${configuredDims}d). ` +
+ `Persist your provider choice with \`gbrain config set embedding_model ${configuredModel}\` AND fix the schema:\n ${fix}`,
+ });
+ surfacedUnconfiguredDrift = true;
+ }
+ }
+ }
+ } catch {
+ // loadConfig may throw on a malformed config; let the existing
+ // available/probe branch surface the issue.
+ }
+
+ if (surfacedUnconfiguredDrift) {
+ // Bail out — the warn above is more actionable than the live probe.
+ } else if (!available) {
// Per v0.28.5 plan P1: silently skipped when no API key is configured.
// Doctor must stay green on CI / local-only / offline environments where
// a full provider probe isn't possible. The skipped status is still
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index e43c5582f8..d0214111ea 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -4,6 +4,8 @@ import type { ChunkInput } from '../core/types.ts';
import { chunkText } from '../core/chunkers/recursive.ts';
import { createProgress, type ProgressReporter } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
+import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';
+import { loadConfig } from '../core/config.ts';
export interface EmbedOpts {
/** Embed ALL pages (every chunk). */
@@ -67,6 +69,12 @@ export interface EmbedResult {
* auto-embed step) can report embeddings in their own structured output.
*/
export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promise<EmbedResult> {
+ // T7 (D9): refuse cleanly when init persisted the deferred-setup sentinel.
+ // Skipped in dryRun mode so plan-mode introspection still works.
+ if (!opts.dryRun) {
+ assertEmbeddingEnabled(loadConfig());
+ }
+
const result: EmbedResult = {
embedded: 0,
skipped: 0,
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 4193c57d96..df4c965448 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -49,6 +49,22 @@ export async function runImport(
const noEmbed = args.includes('--no-embed');
const fresh = args.includes('--fresh');
const jsonOutput = args.includes('--json');
+
+ // T7 (D9): refuse cleanly when init persisted the deferred-setup sentinel,
+ // unless the user is explicitly skipping embedding via `--no-embed` (in
+ // which case the chunks land without vectors and the user can backfill
+ // later with `gbrain embed --stale` after configuring a provider).
+ if (!noEmbed) {
+ const { assertEmbeddingEnabled } = await import('../core/embedding-dim-check.ts');
+ const { loadConfig } = await import('../core/config.ts');
+ try {
+ assertEmbeddingEnabled(loadConfig());
+ } catch (e) {
+ console.error(`\n${e instanceof Error ? e.message : e}`);
+ console.error('Tip: run `gbrain import <dir> --no-embed` to import without embedding now.');
+ process.exit(1);
+ }
+ }
// v0.30.x follow-up to PR #707: programmatic sourceId support so internal
// callers (performFullSync, future Step 6 paths) can route to a named
// source.
diff --git a/src/commands/init-provider-picker.ts b/src/commands/init-provider-picker.ts
new file mode 100644
index 0000000000..f2d851a476
--- /dev/null
+++ b/src/commands/init-provider-picker.ts
@@ -0,0 +1,183 @@
+/**
+ * v0.37.x — interactive provider picker for `gbrain init`.
+ *
+ * Mirrors the `init-mode-picker.ts` (v0.32.3) pattern. Runs from
+ * `initPGLite()` BEFORE `engine.initSchema()` when env detection finds
+ * zero or multiple env-ready providers for the embedding touchpoint
+ * (D1=hybrid). Reuses `formatRecipeTable()` from `providers.ts` so the
+ * picker's UI and `gbrain providers list` can't drift.
+ *
+ * Trust contract:
+ * - TTY-only. Callers must not invoke this in non-TTY contexts; D3 says
+ * non-TTY with zero keys exits 1 from `resolveAIOptions` before we
+ * reach here. A defensive guard returns null if no TTY anyway.
+ * - Filters candidates to env-ready recipes (codex finding #3). The
+ * picker is for choosing among providers the user CAN run, not for
+ * walking them through key setup.
+ * - On Ctrl-D / EOF / timeout: returns null, caller treats as exit 1.
+ * - When the user picks a non-Anthropic chat-capable recipe AND
+ * `ANTHROPIC_API_KEY` is missing, prints the subagent caveat from D7
+ * BEFORE returning the choice so the user sees the implication.
+ */
+
+import { listRecipes } from '../core/ai/recipes/index.ts';
+import { envReady, formatRecipeTable } from './providers.ts';
+import { readLineSafe } from './init.ts';
+import type { Recipe } from '../core/ai/types.ts';
+
+export interface PickedProvider {
+ recipeId: string;
+ modelId: string;
+ /** Full `provider:model` string, ready for configureGateway. */
+ fullModel: string;
+ /** Resolved dim (recipe's `default_dims`). */
+ dim: number;
+ /** Whether the recipe also covers chat/expansion (informational). */
+ hasChat: boolean;
+ hasExpansion: boolean;
+}
+
+export interface PickProviderOpts {
+ /** Touchpoint the picker is selecting for. Embedding is the primary use case. */
+ touchpoint: 'embedding' | 'expansion' | 'chat';
+ /** Process env to probe. Defaults to process.env (injected for tests). */
+ env?: NodeJS.ProcessEnv;
+ /** TTY override for tests. Defaults to process.stdin.isTTY. */
+ isTTY?: boolean;
+ /** Stderr override for tests (capturing prompts). Defaults to process.stderr.write. */
+ writeStderr?: (s: string) => void;
+}
+
+/**
+ * Surface the subagent-Anthropic caveat (D7) when the user picks a
+ * non-Anthropic chat-capable recipe without `ANTHROPIC_API_KEY` set.
+ *
+ * Exported so `initPGLite` can reuse the same message in its post-init
+ * stderr summary path (auto-pick branch doesn't run the picker but still
+ * needs to surface the caveat). One source of truth keeps the message
+ * format aligned across the three D7 surfaces (picker / init summary /
+ * doctor).
+ */
+export function printSubagentAnthropicCaveat(write: (s: string) => void): void {
+ write(
+ '\n' +
+ 'Note: subagent features (gbrain dream, gbrain agent run, gbrain autopilot)\n' +
+ ' require ANTHROPIC_API_KEY regardless of which chat model you pick.\n' +
+ ' Chat alone (gbrain think, gbrain query expansion) works without it.\n' +
+ ' Set ANTHROPIC_API_KEY before running those commands.\n\n',
+ );
+}
+
+/**
+ * Filter recipes to those env-ready for the given touchpoint. Returns the
+ * filtered list and whether the touchpoint exists on each. Picker UI uses
+ * this to refuse picking a recipe whose env isn't ready (codex finding #3).
+ */
+function readyRecipesForTouchpoint(
+ recipes: Recipe[],
+ touchpoint: 'embedding' | 'expansion' | 'chat',
+ env: NodeJS.ProcessEnv,
+): Recipe[] {
+ return recipes.filter(r => {
+ const tp = r.touchpoints[touchpoint];
+ if (!tp) return false;
+ // Embedding + chat must have at least one model; expansion just needs to exist.
+ if (touchpoint === 'embedding' || touchpoint === 'chat') {
+ if (!Array.isArray(tp.models) || tp.models.length === 0) return false;
+ }
+ return envReady(r, env);
+ });
+}
+
+/**
+ * Pick a provider interactively from env-ready recipes.
+ *
+ * Returns null when the picker can't proceed (no TTY, no ready recipes,
+ * user aborted via Ctrl-D, or readLineSafe timeout). Caller exits 1 on
+ * null and prints the no-key fail-loud message itself.
+ */
+export async function pickProvider(opts: PickProviderOpts): Promise<PickedProvider | null> {
+ const env = opts.env ?? process.env;
+ const isTTY = opts.isTTY ?? process.stdin.isTTY ?? false;
+ const writeStderr = opts.writeStderr ?? ((s: string) => process.stderr.write(s));
+
+ if (!isTTY) {
+ // Defensive — caller should have handled non-TTY before reaching us.
+ return null;
+ }
+
+ const all = listRecipes();
+ const ready = readyRecipesForTouchpoint(all, opts.touchpoint, env);
+
+ if (ready.length === 0) {
+ writeStderr(`\nNo ${opts.touchpoint}-capable providers are env-ready.\n`);
+ writeStderr('Set one of the env vars below and re-run init:\n\n');
+ writeStderr(formatRecipeTable(all, env) + '\n\n');
+ return null;
+ }
+
+ writeStderr(`\nPick a ${opts.touchpoint} provider (env-ready providers shown):\n\n`);
+ writeStderr(formatRecipeTable(ready, env) + '\n\n');
+
+ // Build numbered options
+ const lines = ready.map((r, i) => {
+ const tp = r.touchpoints[opts.touchpoint];
+ let label = ` ${i + 1}) ${r.id}`;
+ if (opts.touchpoint === 'embedding' && tp && 'default_dims' in tp) {
+ label += ` (${tp.default_dims}d)`;
+ }
+ if (tp && 'models' in tp && Array.isArray(tp.models) && tp.models.length > 0) {
+ label += ` ${tp.models[0]}`;
+ }
+ return label;
+ });
+ writeStderr(lines.join('\n') + '\n\n');
+
+ const answer = await readLineSafe(
+ `Choice [1-${ready.length}, default 1]: `,
+ '1',
+ /* timeoutMs */ 60_000,
+ );
+
+ const choice = parseInt(answer.trim(), 10);
+ if (!Number.isFinite(choice) || choice < 1 || choice > ready.length) {
+ writeStderr(`\nInvalid choice "${answer}". Aborting.\n`);
+ return null;
+ }
+
+ const picked = ready[choice - 1];
+ const tp = picked.touchpoints[opts.touchpoint];
+ if (!tp) return null;
+
+ // Pick first model in the recipe's list (callers can override via flag).
+ const modelId = ('models' in tp && Array.isArray(tp.models) && tp.models.length > 0)
+ ? tp.models[0]
+ : '';
+ if (!modelId) {
+ writeStderr(`\nRecipe "${picked.id}" declares no models for ${opts.touchpoint}. Aborting.\n`);
+ return null;
+ }
+
+ // D7: surface the subagent-Anthropic caveat when picking a non-Anthropic
+ // chat-capable recipe without ANTHROPIC_API_KEY set.
+ const isChatTouchpoint = opts.touchpoint === 'chat';
+ const isAnthropic = picked.id === 'anthropic';
+ const anthropicKeySet = !!env.ANTHROPIC_API_KEY;
+ if (isChatTouchpoint && !isAnthropic && !anthropicKeySet) {
+ printSubagentAnthropicCaveat(writeStderr);
+ }
+
+ const dim =
+ opts.touchpoint === 'embedding' && 'default_dims' in tp
+ ? (tp as { default_dims: number }).default_dims
+ : 0;
+
+ return {
+ recipeId: picked.id,
+ modelId,
+ fullModel: `${picked.id}:${modelId}`,
+ dim,
+ hasChat: !!picked.touchpoints.chat && (picked.touchpoints.chat.models?.length ?? 0) > 0,
+ hasExpansion: !!picked.touchpoints.expansion,
+ };
+}
diff --git a/src/commands/init.ts b/src/commands/init.ts
index a28158fc91..a595fb306f 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -48,31 +48,40 @@ export async function runInit(args: string[]) {
process.exit(1);
}
- // v0.14: AI provider selection.
- // --embedding-model PROVIDER:MODEL (verbose) or --model PROVIDER (shorthand, picks recipe default)
- const embModelIdx = args.indexOf('--embedding-model');
- const modelShortIdx = args.indexOf('--model');
- const embDimsIdx = args.indexOf('--embedding-dimensions');
- const expModelIdx = args.indexOf('--expansion-model');
- // v0.27: --chat-model PROVIDER:MODEL — default subagent driver.
- const chatModelIdx = args.indexOf('--chat-model');
- const aiOpts = await resolveAIOptions(
- embModelIdx !== -1 ? args[embModelIdx + 1] : null,
- modelShortIdx !== -1 ? args[modelShortIdx + 1] : null,
- embDimsIdx !== -1 ? parseInt(args[embDimsIdx + 1], 10) : null,
- expModelIdx !== -1 ? args[expModelIdx + 1] : null,
- chatModelIdx !== -1 ? args[chatModelIdx + 1] : null,
- );
-
// Schema-only path: apply initSchema against the already-configured engine
// without ever calling saveConfig. Used by apply-migrations, the stopgap
// script, and the postinstall hook. Bare `gbrain init` defaults to PGLite
// and overwrites any existing Postgres config — we must never take that
// branch from a migration orchestrator.
+ //
+ // IMPORTANT: this short-circuit MUST run BEFORE resolveAIOptions() so
+ // migrate-only callers (which already have a configured brain) don't
+ // trigger env-detection / picker / fail-loud paths designed for fresh
+ // installs.
if (isMigrateOnly) {
return initMigrateOnly({ jsonOutput });
}
+ // v0.14: AI provider selection.
+ // --embedding-model PROVIDER:MODEL (verbose) or --model PROVIDER (shorthand, picks recipe default)
+ const embModelIdx = args.indexOf('--embedding-model');
+ const modelShortIdx = args.indexOf('--model');
+ const embDimsIdx = args.indexOf('--embedding-dimensions');
+ const expModelIdx = args.indexOf('--expansion-model');
+ // v0.27: --chat-model PROVIDER:MODEL — default subagent driver.
+ const chatModelIdx = args.indexOf('--chat-model');
+ // v0.37 (D9): --no-embedding opts into deferred-setup mode (D9 escape hatch).
+ const noEmbedding = args.includes('--no-embedding');
+ const aiOpts = await resolveAIOptions({
+ verbose: embModelIdx !== -1 ? args[embModelIdx + 1] : null,
+ shorthand: modelShortIdx !== -1 ? args[modelShortIdx + 1] : null,
+ dimsArg: embDimsIdx !== -1 ? parseInt(args[embDimsIdx + 1], 10) : null,
+ expansion: expModelIdx !== -1 ? args[expModelIdx + 1] : null,
+ chat: chatModelIdx !== -1 ? args[chatModelIdx + 1] : null,
+ noEmbedding,
+ nonInteractive: isNonInteractive,
+ });
+
// Explicit PGLite mode
if (isPGLite || (!isSupabase && !manualUrl && !isNonInteractive)) {
// Smart detection: scan for .md files unless --pglite flag forces it
@@ -111,19 +120,73 @@ export async function runInit(args: string[]) {
return initPostgres({ databaseUrl, jsonOutput, apiKey, aiOpts });
}
+interface ResolveAIOptionsArgs {
+ verbose: string | null; // --embedding-model
+ shorthand: string | null; // --model
+ dimsArg: number | null; // --embedding-dimensions
+ expansion: string | null; // --expansion-model
+ chat: string | null; // --chat-model
+ noEmbedding: boolean; // --no-embedding (D9)
+ nonInteractive: boolean; // --non-interactive (forces D3 fail-loud, no picker)
+}
+
+interface ResolvedAIOptions {
+ embedding_model?: string;
+ embedding_dimensions?: number;
+ expansion_model?: string;
+ chat_model?: string;
+ /** v0.37 (D9): user opted into deferred embedding setup. */
+ noEmbedding?: boolean;
+}
+
/**
- * Resolve AI provider options from CLI flags. Verbose form (--embedding-model
- * openai:text-embedding-3-large) overrides shorthand (--model openai which
- * expands to the recipe's first embedding model).
+ * Resolve AI provider options for `gbrain init`.
+ *
+ * Precedence (per touchpoint, top wins):
+ * 1. Explicit flag (--embedding-model / --expansion-model / --chat-model)
+ * 2. Shorthand flag (--model PROVIDER) for embedding only
+ * 3. Env detection: walk env-ready recipes, group by provider id (D1-D4, D10).
+ * - Exactly one provider ready AND has the touchpoint → auto-pick + stderr notice.
+ * - Multiple ready → for embedding: TTY → picker (D1), non-TTY → fail loud (D3).
+ * For chat/expansion: leave default (gateway falls back at call time, D10).
+ * - Zero ready → for embedding: TTY → picker offers env-ready recipes
+ * OR setup hint with typo detection (D13); non-TTY → fail loud (D3).
+ *
+ * --no-embedding (D9) opt-in: skips embedding tier resolution entirely;
+ * persists nulls; embed callsites refuse with a config-set hint.
*/
-async function resolveAIOptions(
- verbose: string | null,
- shorthand: string | null,
- dimsArg: number | null,
- expansion: string | null,
- chat: string | null,
-): Promise<{ embedding_model?: string; embedding_dimensions?: number; expansion_model?: string; chat_model?: string }> {
- const out: { embedding_model?: string; embedding_dimensions?: number; expansion_model?: string; chat_model?: string } = {};
+async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIOptions> {
+ const { verbose, shorthand, dimsArg, expansion, chat, noEmbedding, nonInteractive } = opts;
+ const out: ResolvedAIOptions = {};
+
+ // --- D5: persisted config wins on re-init -----------------------------------
+ // When `~/.gbrain/config.json` already has embedding_model set (a re-init
+ // against an existing brain), honor it BEFORE env detection. Without this
+ // the env-detection branch fires unnecessarily on every re-init, and a
+ // non-TTY re-init with no env keys exits 1 (D3) even though the brain is
+ // already correctly configured. Caught by CI's E2E init sequence where
+ // multiple tests share `~/.gbrain` and only the first init has flags.
+ //
+ // The deferred-setup sentinel (`embedding_disabled: true`) is also honored —
+ // a re-init without --no-embedding shouldn't re-trigger fail-loud when the
+ // user already opted into deferred mode.
+ try {
+ const { loadConfig } = await import('../core/config.ts');
+ const cfg = loadConfig();
+ if (cfg?.embedding_disabled) {
+ out.noEmbedding = true;
+ } else if (cfg?.embedding_model) {
+ out.embedding_model = cfg.embedding_model;
+ if (cfg.embedding_dimensions) out.embedding_dimensions = cfg.embedding_dimensions;
+ }
+ if (cfg?.expansion_model) out.expansion_model = cfg.expansion_model;
+ if (cfg?.chat_model) out.chat_model = cfg.chat_model;
+ } catch {
+ // loadConfig throws when no brain configured — first-time install, fall
+ // through to env detection.
+ }
+
+ // --- Tier 1+2: explicit flags ---------------------------------------------
if (verbose) {
out.embedding_model = verbose;
@@ -184,9 +247,232 @@ async function resolveAIOptions(
if (expansion) out.expansion_model = expansion;
if (chat) out.chat_model = chat;
+ // --- D9: --no-embedding opt-in --------------------------------------------
+ // Even when other flags were passed, --no-embedding signals "skip embedding
+ // configuration entirely". Persist the explicit opt-in (T6/T7 use it).
+ if (noEmbedding) {
+ out.noEmbedding = true;
+ // Wipe any tentative embedding settings — opt-in means truly nothing.
+ delete out.embedding_model;
+ delete out.embedding_dimensions;
+ }
+
+ // --- Tier 3: env detection ------------------------------------------------
+ // Fires per touchpoint, only when no explicit flag was passed for that
+ // tier. Embedding is the critical path (column width); chat/expansion are
+ // best-effort (gateway falls back gracefully at call time, D10).
+
+ if (!out.noEmbedding && !out.embedding_model) {
+ await resolveEmbeddingByEnv(out, nonInteractive);
+ }
+ if (!out.expansion_model) {
+ await resolveExpansionByEnv(out);
+ }
+ if (!out.chat_model) {
+ await resolveChatByEnv(out);
+ }
+
return out;
}
+// ============================================================================
+// v0.37 env-detection helpers (T5)
+//
+// These run when no explicit flag is passed for the corresponding touchpoint.
+// They share `groupReadyByProvider` so the per-touchpoint surface stays
+// consistent (codex finding #2: group by provider id, not by recipe, so two
+// recipes sharing OPENAI_API_KEY can't double-count).
+// ============================================================================
+
+interface ReadyProvider {
+ recipeId: string;
+ recipe: import('../core/ai/types.ts').Recipe;
+}
+
+/**
+ * Walk recipes and return providers env-ready for the given touchpoint.
+ * Exported for unit tests (parameterizable via env arg).
+ *
+ * Excludes local-only providers (no auth_env.required, e.g. Ollama,
+ * llama-server) from auto-pick UNLESS they're the only thing available.
+ * Picking Ollama silently when the user has OPENAI_API_KEY set is a
+ * silent-broken-state class (Ollama daemon may not be running, or the
+ * user clearly intended a hosted provider). Local-only providers stay
+ * accessible via explicit `--embedding-model ollama:...`.
+ */
+export async function groupReadyByProvider(
+ touchpoint: 'embedding' | 'expansion' | 'chat',
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<ReadyProvider[]> {
+ const { listRecipes } = await import('../core/ai/recipes/index.ts');
+ const { envReady } = await import('./providers.ts');
+ const ready: ReadyProvider[] = [];
+ const seen = new Set<string>();
+ for (const r of listRecipes()) {
+ if (seen.has(r.id)) continue;
+ const tp = r.touchpoints[touchpoint];
+ if (!tp) continue;
+ // Skip recipes that ship without any models (user_provided_models flag,
+ // e.g. litellm-proxy, llama-server). The shorthand --model path errors
+ // for these; auto-pick should too.
+ const tpModels = (tp as { models?: string[] }).models;
+ if (!Array.isArray(tpModels) || tpModels.length === 0) continue;
+ // Skip recipes whose user_provided_models flag is set even when models[]
+ // has entries (defensive — shouldn't happen but cheap).
+ if ((tp as { user_provided_models?: boolean }).user_provided_models) continue;
+ // Skip local-only providers (no auth required) from auto-pick. They're
+ // still picker-selectable explicitly, but silent auto-pick is wrong UX.
+ const required = r.auth_env?.required ?? [];
+ if (required.length === 0) continue;
+ if (envReady(r, env)) {
+ ready.push({ recipeId: r.id, recipe: r });
+ seen.add(r.id);
+ }
+ }
+ return ready;
+}
+
+/** Look at env-vars the user set that look like typos of recipe-required keys.
+ * Exported for unit tests (parameterizable via env arg). */
+export async function findEnvKeyTypos(
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<Array<{ userSet: string; suggested: string }>> {
+ const { suggestNearest } = await import('../core/levenshtein.ts');
+ const { listRecipes } = await import('../core/ai/recipes/index.ts');
+ // Build the canonical name set from every recipe's auth_env.required.
+ const canonical = new Set<string>();
+ for (const r of listRecipes()) {
+ for (const k of r.auth_env?.required ?? []) canonical.add(k);
+ }
+ const out: Array<{ userSet: string; suggested: string }> = [];
+ // Walk user env vars that look API-key-shaped to keep the suggestion noise low.
+ const KEY_SHAPE = /^[A-Z][A-Z0-9_]*_(API_)?KEY$/;
+ for (const userKey of Object.keys(env)) {
+ if (!KEY_SHAPE.test(userKey)) continue;
+ if (canonical.has(userKey)) continue; // exact match, not a typo
+ if (!env[userKey]) continue; // empty string, skip
+ const suggestion = suggestNearest(userKey, [...canonical], /* maxDistance */ 3);
+ if (suggestion && suggestion !== userKey) {
+ // False-positive guard (per plan D13): suggested canonical not ALSO set.
+ if (!env[suggestion]) {
+ out.push({ userSet: userKey, suggested: suggestion });
+ }
+ }
+ }
+ return out;
+}
+
+/** Emit the fail-loud "no embedding provider" message + paste-ready setup. */
+function printNoEmbeddingProviderHint(typos: Array<{ userSet: string; suggested: string }>): void {
+ console.error('\nNo embedding provider configured. Set one of:');
+ console.error(' export OPENAI_API_KEY=sk-… # openai:text-embedding-3-large (1536d)');
+ console.error(' export ZEROENTROPY_API_KEY=ze-… # zeroentropyai:zembed-1 (2560d, Matryoshka)');
+ console.error(' export VOYAGE_API_KEY=pa-… # voyage:voyage-3-large (1024d)');
+ console.error('Then re-run: gbrain init --pglite');
+ console.error('');
+ console.error('Or pick explicitly:');
+ console.error(' gbrain init --pglite --embedding-model openai:text-embedding-3-large');
+ console.error('');
+ console.error('Or defer setup: gbrain init --pglite --no-embedding');
+ console.error(' (you can configure later with `gbrain config set embedding_model <id>`)');
+ // D13: surface near-miss env vars (e.g. OPENAPI_API_KEY → OPENAI_API_KEY).
+ if (typos.length > 0) {
+ console.error('');
+ for (const t of typos) {
+ console.error(`Note: detected ${t.userSet}; did you mean ${t.suggested}?`);
+ }
+ }
+}
+
+async function resolveEmbeddingByEnv(out: ResolvedAIOptions, nonInteractive: boolean): Promise<void> {
+ const ready = await groupReadyByProvider('embedding');
+ const isTTY = !nonInteractive && !!process.stdin.isTTY;
+
+ if (ready.length === 1) {
+ const r = ready[0].recipe;
+ const tp = r.touchpoints.embedding!;
+ if (Array.isArray(tp.models) && tp.models.length > 0) {
+ const model = tp.models[0];
+ const fullModel = `${r.id}:${model}`;
+ out.embedding_model = fullModel;
+ out.embedding_dimensions = tp.default_dims;
+ console.error(
+ `Detected ${r.auth_env?.required?.[0] ?? r.id} env var. ` +
+ `Using ${fullModel} (${tp.default_dims}d). ` +
+ `Override with --embedding-model.`,
+ );
+ return;
+ }
+ }
+
+ // Zero or multi — pick or fail loud.
+ if (ready.length === 0) {
+ if (!isTTY) {
+ const typos = await findEnvKeyTypos();
+ printNoEmbeddingProviderHint(typos);
+ process.exit(1);
+ }
+ // TTY → picker; on null (user aborted) still fail loud.
+ const { pickProvider } = await import('./init-provider-picker.ts');
+ const picked = await pickProvider({ touchpoint: 'embedding', env: process.env, isTTY: true });
+ if (!picked) {
+ const typos = await findEnvKeyTypos();
+ printNoEmbeddingProviderHint(typos);
+ process.exit(1);
+ }
+ out.embedding_model = picked.fullModel;
+ out.embedding_dimensions = picked.dim;
+ return;
+ }
+
+ // ready.length > 1 — picker (TTY) or fail-loud (non-TTY) per D2/D3.
+ if (!isTTY) {
+ console.error(`Multiple embedding providers env-ready: ${ready.map(p => p.recipeId).join(', ')}.`);
+ console.error(`Disambiguate by passing --embedding-model <provider>:<model>, or unset extra env vars.`);
+ process.exit(1);
+ }
+ const { pickProvider } = await import('./init-provider-picker.ts');
+ const picked = await pickProvider({ touchpoint: 'embedding', env: process.env, isTTY: true });
+ if (!picked) {
+ console.error('Init aborted: no embedding provider picked.');
+ process.exit(1);
+ }
+ out.embedding_model = picked.fullModel;
+ out.embedding_dimensions = picked.dim;
+}
+
+async function resolveExpansionByEnv(out: ResolvedAIOptions): Promise<void> {
+ const ready = await groupReadyByProvider('expansion');
+ // Per D10: chat/expansion fall through to gateway default when ambiguous.
+ if (ready.length === 1) {
+ const r = ready[0].recipe;
+ const tp = r.touchpoints.expansion!;
+ if (Array.isArray(tp.models) && tp.models.length > 0) {
+ out.expansion_model = `${r.id}:${tp.models[0]}`;
+ console.error(`Detected ${r.auth_env?.required?.[0] ?? r.id} env var. Using ${out.expansion_model} for expansion.`);
+ }
+ }
+ // 0 or >1 → silent: gateway default (`anthropic:claude-haiku-4-5-…`) wins
+ // and falls back gracefully at call time when key isn't set.
+}
+
+async function resolveChatByEnv(out: ResolvedAIOptions): Promise<void> {
+ const ready = await groupReadyByProvider('chat');
+ if (ready.length === 1) {
+ const r = ready[0].recipe;
+ const tp = r.touchpoints.chat!;
+ if (Array.isArray(tp.models) && tp.models.length > 0) {
+ out.chat_model = `${r.id}:${tp.models[0]}`;
+ console.error(`Detected ${r.auth_env?.required?.[0] ?? r.id} env var. Using ${out.chat_model} for chat.`);
+ }
+ }
+ // 0 or >1 → silent: gateway default (`anthropic:claude-sonnet-4-6`) wins.
+ // The subagent enforcement at minions/queue.ts already routes subagent jobs
+ // to Anthropic regardless of the chat_model setting (D7 caveat fires from
+ // T6's initPGLite post-config branch when chat_model is non-Anthropic and
+ // ANTHROPIC_API_KEY is missing).
+}
+
/**
* Apply the schema against the already-configured engine. No saveConfig.
* No PGLite fallback when no config exists. Used by migration orchestrators
@@ -377,25 +663,56 @@ async function initPGLite(opts: {
jsonOutput: boolean;
apiKey: string | null;
customPath: string | null;
- aiOpts?: { embedding_model?: string; embedding_dimensions?: number; expansion_model?: string; chat_model?: string };
+ aiOpts?: ResolvedAIOptions;
}) {
const dbPath = opts.customPath || gbrainPath('brain.pglite');
console.log(`Setting up local brain with PGLite (no server needed)...`);
- // Configure AI gateway BEFORE initSchema so the vector column uses the right dim.
- if (opts.aiOpts?.embedding_model || opts.aiOpts?.chat_model) {
- const { configureGateway } = await import('../core/ai/gateway.ts');
- configureGateway({
- embedding_model: opts.aiOpts?.embedding_model,
- embedding_dimensions: opts.aiOpts?.embedding_dimensions,
- expansion_model: opts.aiOpts?.expansion_model,
- chat_model: opts.aiOpts?.chat_model,
- env: { ...process.env },
+ // T6 (D11): preflight schema dim BEFORE any DB write or schema creation.
+ // After T5's env detection runs, opts.aiOpts has either an embedding_model
+ // resolved (auto-pick / picker / explicit flag) OR noEmbedding=true (D9
+ // opt-in). Either way we MUST agree with the gateway's resolved dim by
+ // construction — preflight validates that.
+ let resolvedDim: number | undefined;
+ let resolvedModel: string | undefined;
+ if (opts.aiOpts?.noEmbedding) {
+ // D9 deferred-setup mode: skip preflight, no model/dim resolved.
+ console.log(` --no-embedding: deferred setup — configure with \`gbrain config set embedding_model <id>\` before import`);
+ } else if (opts.aiOpts?.embedding_model) {
+ const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
+ const pre = resolveSchemaEmbeddingDim({
+ embedding_model: opts.aiOpts.embedding_model,
+ embedding_dimensions: opts.aiOpts.embedding_dimensions,
});
- if (opts.aiOpts?.embedding_model) console.log(` Embedding: ${opts.aiOpts.embedding_model} (${opts.aiOpts.embedding_dimensions ?? '?'}d)`);
- if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
- if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
+ if (!pre.ok) {
+ console.error(`\nRefusing to init: ${pre.error}\n`);
+ if (opts.jsonOutput) {
+ console.log(JSON.stringify({ status: 'error', reason: 'preflight_failed', error: pre.error }));
+ }
+ process.exit(1);
+ }
+ resolvedDim = pre.dim;
+ resolvedModel = pre.model;
}
+ // If neither --no-embedding nor an embedding_model is resolved, resolveAIOptions
+ // already exited 1 with the fail-loud setup hint (T5). Reaching here without
+ // either means we have a user-passed combination the previous step accepted —
+ // typically `--embedding-model` flag without env detection running.
+
+ // T6: always configureGateway BEFORE initSchema, never the conditional
+ // gate. This is the structural fix: schema substitution at
+ // pglite-schema.ts:833 and the runtime gateway share one source of truth.
+ const { configureGateway } = await import('../core/ai/gateway.ts');
+ configureGateway({
+ embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
+ embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
+ expansion_model: opts.aiOpts?.expansion_model,
+ chat_model: opts.aiOpts?.chat_model,
+ env: { ...process.env },
+ });
+ if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
+ if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
+ if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
const engine = await createEngine({ engine: 'pglite' });
try {
@@ -403,15 +720,16 @@ async function initPGLite(opts: {
// v0.28.5 (A4): refuse to silently re-template an existing brain with a
// mismatched embedding dimension. Loud failure beats the v0.27 silent-
- // corruption pattern that surfaced as #673.
- if (opts.aiOpts?.embedding_dimensions) {
+ // corruption pattern that surfaced as #673. (Re-init path; fresh-install
+ // case is now structurally impossible after T6's preflight.)
+ if (resolvedDim) {
const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
const existing = await readContentChunksEmbeddingDim(engine);
- if (existing.exists && existing.dims !== null && existing.dims !== opts.aiOpts.embedding_dimensions) {
+ if (existing.exists && existing.dims !== null && existing.dims !== resolvedDim) {
console.error('\n' + embeddingMismatchMessage({
currentDims: existing.dims,
- requestedDims: opts.aiOpts.embedding_dimensions,
- requestedModel: opts.aiOpts.embedding_model,
+ requestedDims: resolvedDim,
+ requestedModel: resolvedModel,
source: 'init',
}) + '\n');
if (opts.jsonOutput) {
@@ -419,7 +737,7 @@ async function initPGLite(opts: {
status: 'error',
reason: 'embedding_dim_mismatch',
current_dims: existing.dims,
- requested_dims: opts.aiOpts.embedding_dimensions,
+ requested_dims: resolvedDim,
}));
}
process.exit(1);
@@ -428,17 +746,52 @@ async function initPGLite(opts: {
await engine.initSchema();
+ // T6 (D11): post-initSchema invariant assertion. After preflight + always-
+ // configureGateway, this is structurally guaranteed to pass — kept as a
+ // regression guardrail so any future schema-substitution drift fails loud
+ // here, not at first embed.
+ if (resolvedDim) {
+ const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
+ const after = await readContentChunksEmbeddingDim(engine);
+ if (after.exists && after.dims !== null && after.dims !== resolvedDim) {
+ console.error('\nUNEXPECTED: post-initSchema invariant assertion failed.');
+ console.error(' This is a bug. Please file an issue with the output of `gbrain doctor`.\n');
+ console.error(embeddingMismatchMessage({
+ currentDims: after.dims,
+ requestedDims: resolvedDim,
+ requestedModel: resolvedModel,
+ source: 'init',
+ }));
+ process.exit(1);
+ }
+ }
+
+ // T7 (D9): atomic embedding-config persistence. Either the deferred-setup
+ // sentinel (`embedding_disabled: true`) OR the resolved (model, dimensions)
+ // tuple. Never a partial state. Other fields (api_key, expansion, chat)
+ // persist independently.
const config: GBrainConfig = {
engine: 'pglite',
database_path: dbPath,
...(opts.apiKey ? { openai_api_key: opts.apiKey } : {}),
- ...(opts.aiOpts?.embedding_model ? { embedding_model: opts.aiOpts.embedding_model } : {}),
- ...(opts.aiOpts?.embedding_dimensions ? { embedding_dimensions: opts.aiOpts.embedding_dimensions } : {}),
+ ...(opts.aiOpts?.noEmbedding
+ ? { embedding_disabled: true }
+ : (resolvedModel && resolvedDim)
+ ? { embedding_model: resolvedModel, embedding_dimensions: resolvedDim }
+ : {}),
...(opts.aiOpts?.expansion_model ? { expansion_model: opts.aiOpts.expansion_model } : {}),
...(opts.aiOpts?.chat_model ? { chat_model: opts.aiOpts.chat_model } : {}),
};
saveConfig(config);
+ // T6 (D7): post-init subagent-Anthropic caveat. Fires for both auto-pick
+ // and picker paths so users see the implication of running on a chat
+ // provider that can't drive the subagent loop.
+ if (opts.aiOpts?.chat_model && !opts.aiOpts.chat_model.startsWith('anthropic:') && !process.env.ANTHROPIC_API_KEY) {
+ const { printSubagentAnthropicCaveat } = await import('./init-provider-picker.ts');
+ printSubagentAnthropicCaveat((s) => process.stderr.write(s));
+ }
+
// v0.32.3 search-lite install-time mode picker. Runs AFTER initSchema so
// DB config writes are valid. Idempotent: skipped on re-init if already set.
// Non-TTY auto-selects; --json emits a structured event.
@@ -477,25 +830,51 @@ async function initPostgres(opts: {
databaseUrl: string;
jsonOutput: boolean;
apiKey: string | null;
- aiOpts?: { embedding_model?: string; embedding_dimensions?: number; expansion_model?: string; chat_model?: string };
+ aiOpts?: ResolvedAIOptions;
}) {
const { databaseUrl } = opts;
- // Configure AI gateway BEFORE initSchema so the vector column uses the right dim.
- if (opts.aiOpts?.embedding_model || opts.aiOpts?.chat_model) {
- const { configureGateway } = await import('../core/ai/gateway.ts');
- configureGateway({
- embedding_model: opts.aiOpts?.embedding_model,
- embedding_dimensions: opts.aiOpts?.embedding_dimensions,
- expansion_model: opts.aiOpts?.expansion_model,
- chat_model: opts.aiOpts?.chat_model,
- env: { ...process.env },
+ // T6 (D11): same preflight contract as PGLite. Refuse to call initSchema
+ // until the gateway-resolved dim is validated. Schema substitution in
+ // src/schema.sql is currently a static `vector(1536)` for Postgres (unlike
+ // PGLite's templated dim), so a Voyage/ZE-configured Postgres brain will
+ // still need a future schema rewrite path — preflight makes the
+ // not-yet-supported case fail loud rather than silently produce a stuck
+ // 1536d column.
+ let resolvedDim: number | undefined;
+ let resolvedModel: string | undefined;
+ if (opts.aiOpts?.noEmbedding) {
+ console.log(` --no-embedding: deferred setup — configure with \`gbrain config set embedding_model <id>\` before import`);
+ } else if (opts.aiOpts?.embedding_model) {
+ const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
+ const pre = resolveSchemaEmbeddingDim({
+ embedding_model: opts.aiOpts.embedding_model,
+ embedding_dimensions: opts.aiOpts.embedding_dimensions,
});
- if (opts.aiOpts?.embedding_model) console.log(` Embedding: ${opts.aiOpts.embedding_model} (${opts.aiOpts.embedding_dimensions ?? '?'}d)`);
- if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
- if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
+ if (!pre.ok) {
+ console.error(`\nRefusing to init: ${pre.error}\n`);
+ if (opts.jsonOutput) {
+ console.log(JSON.stringify({ status: 'error', reason: 'preflight_failed', error: pre.error }));
+ }
+ process.exit(1);
+ }
+ resolvedDim = pre.dim;
+ resolvedModel = pre.model;
}
+ // T6: unconditional configureGateway BEFORE initSchema.
+ const { configureGateway } = await import('../core/ai/gateway.ts');
+ configureGateway({
+ embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
+ embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
+ expansion_model: opts.aiOpts?.expansion_model,
+ chat_model: opts.aiOpts?.chat_model,
+ env: { ...process.env },
+ });
+ if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
+ if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
+ if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
+
// Detect Supabase direct connection URLs and warn about IPv6
if (databaseUrl.match(/db\.[a-z]+\.supabase\.co/) || databaseUrl.includes('.supabase.co:5432')) {
console.warn('');
@@ -543,14 +922,14 @@ async function initPostgres(opts: {
// v0.28.5 (A4): refuse to silently re-template an existing brain with a
// mismatched embedding dimension (mirror of the PGLite path above).
- if (opts.aiOpts?.embedding_dimensions) {
+ if (resolvedDim) {
const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
const existing = await readContentChunksEmbeddingDim(engine);
- if (existing.exists && existing.dims !== null && existing.dims !== opts.aiOpts.embedding_dimensions) {
+ if (existing.exists && existing.dims !== null && existing.dims !== resolvedDim) {
console.error('\n' + embeddingMismatchMessage({
currentDims: existing.dims,
- requestedDims: opts.aiOpts.embedding_dimensions,
- requestedModel: opts.aiOpts.embedding_model,
+ requestedDims: resolvedDim,
+ requestedModel: resolvedModel,
source: 'init',
}) + '\n');
if (opts.jsonOutput) {
@@ -558,7 +937,7 @@ async function initPostgres(opts: {
status: 'error',
reason: 'embedding_dim_mismatch',
current_dims: existing.dims,
- requested_dims: opts.aiOpts.embedding_dimensions,
+ requested_dims: resolvedDim,
}));
}
process.exit(1);
@@ -568,18 +947,45 @@ async function initPostgres(opts: {
console.log('Running schema migration...');
await engine.initSchema();
+ // T6 (D11): post-initSchema invariant assertion guardrail.
+ if (resolvedDim) {
+ const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
+ const after = await readContentChunksEmbeddingDim(engine);
+ if (after.exists && after.dims !== null && after.dims !== resolvedDim) {
+ console.error('\nUNEXPECTED: post-initSchema invariant assertion failed.');
+ console.error(' This is a bug. Please file an issue with the output of `gbrain doctor`.\n');
+ console.error(embeddingMismatchMessage({
+ currentDims: after.dims,
+ requestedDims: resolvedDim,
+ requestedModel: resolvedModel,
+ source: 'init',
+ }));
+ process.exit(1);
+ }
+ }
+
+ // T7 (D9): atomic embedding-config persistence.
const config: GBrainConfig = {
engine: 'postgres',
database_url: databaseUrl,
...(opts.apiKey ? { openai_api_key: opts.apiKey } : {}),
- ...(opts.aiOpts?.embedding_model ? { embedding_model: opts.aiOpts.embedding_model } : {}),
- ...(opts.aiOpts?.embedding_dimensions ? { embedding_dimensions: opts.aiOpts.embedding_dimensions } : {}),
+ ...(opts.aiOpts?.noEmbedding
+ ? { embedding_disabled: true }
+ : (resolvedModel && resolvedDim)
+ ? { embedding_model: resolvedModel, embedding_dimensions: resolvedDim }
+ : {}),
...(opts.aiOpts?.expansion_model ? { expansion_model: opts.aiOpts.expansion_model } : {}),
...(opts.aiOpts?.chat_model ? { chat_model: opts.aiOpts.chat_model } : {}),
};
saveConfig(config);
console.log('Config saved to ~/.gbrain/config.json');
+ // T6 (D7): post-init subagent-Anthropic caveat.
+ if (opts.aiOpts?.chat_model && !opts.aiOpts.chat_model.startsWith('anthropic:') && !process.env.ANTHROPIC_API_KEY) {
+ const { printSubagentAnthropicCaveat } = await import('./init-provider-picker.ts');
+ printSubagentAnthropicCaveat((s) => process.stderr.write(s));
+ }
+
// v0.32.3 search-lite install-time mode picker. Same shape as the
// PGLite path above — runs AFTER initSchema, idempotent on re-init.
const { runModePicker: runPostgresModePicker } = await import('./init-mode-picker.ts');
diff --git a/src/commands/providers.ts b/src/commands/providers.ts
index 22acd56626..6d2fc211b9 100644
--- a/src/commands/providers.ts
+++ b/src/commands/providers.ts
@@ -44,10 +44,40 @@ function configureFromEnv(): void {
});
}
-function envReady(recipe: Recipe): boolean {
+export function envReady(recipe: Recipe, env: NodeJS.ProcessEnv = process.env): boolean {
const required = recipe.auth_env?.required ?? [];
if (required.length === 0) return true; // e.g. local Ollama
- return required.every(k => !!process.env[k]);
+ return required.every(k => !!env[k]);
+}
+
+/**
+ * Pure formatter for the recipe matrix shown by `gbrain providers list` and
+ * the new `init-provider-picker` (D1+D2 — picker reuses this so its display
+ * stays in sync with `providers list` and can't drift).
+ *
+ * Returns the multi-line string (joined with `\n`). Callers handle stdout vs.
+ * stderr routing themselves.
+ */
+export function formatRecipeTable(recipes: Recipe[], env: NodeJS.ProcessEnv = process.env): string {
+ const rows: string[] = [];
+ rows.push('PROVIDER'.padEnd(14) + 'TIER'.padEnd(18) + 'EMBED'.padEnd(8) + 'EXPAND'.padEnd(8) + 'CHAT'.padEnd(8) + 'STATUS');
+ rows.push('-'.repeat(78));
+ for (const r of recipes) {
+ const hasEmbed = !!r.touchpoints.embedding && (r.touchpoints.embedding.models.length > 0);
+ const hasExpand = !!r.touchpoints.expansion;
+ const hasChat = !!r.touchpoints.chat && r.touchpoints.chat.models.length > 0;
+ const ready = envReady(r, env);
+ const status = ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`;
+ rows.push(
+ r.id.padEnd(14) +
+ r.tier.padEnd(18) +
+ (hasEmbed ? 'yes' : '—').padEnd(8) +
+ (hasExpand ? 'yes' : '—').padEnd(8) +
+ (hasChat ? 'yes' : '—').padEnd(8) +
+ status,
+ );
+ }
+ return rows.join('\n');
}
export async function runProviders(subcommand: string | undefined, args: string[]): Promise<void> {
@@ -98,26 +128,7 @@ EXAMPLES
}
function runList(_args: string[]): void {
- const recipes = listRecipes();
- const rows: string[] = [];
- rows.push('PROVIDER'.padEnd(14) + 'TIER'.padEnd(18) + 'EMBED'.padEnd(8) + 'EXPAND'.padEnd(8) + 'CHAT'.padEnd(8) + 'STATUS');
- rows.push('-'.repeat(78));
- for (const r of recipes) {
- const hasEmbed = !!r.touchpoints.embedding && (r.touchpoints.embedding.models.length > 0);
- const hasExpand = !!r.touchpoints.expansion;
- const hasChat = !!r.touchpoints.chat && r.touchpoints.chat.models.length > 0;
- const ready = envReady(r);
- const status = ready ? '✓ ready' : `✗ missing ${r.auth_env?.required?.[0] ?? 'setup'}`;
- rows.push(
- r.id.padEnd(14) +
- r.tier.padEnd(18) +
- (hasEmbed ? 'yes' : '—').padEnd(8) +
- (hasExpand ? 'yes' : '—').padEnd(8) +
- (hasChat ? 'yes' : '—').padEnd(8) +
- status,
- );
- }
- console.log(rows.join('\n'));
+ console.log(formatRecipeTable(listRecipes()));
}
async function runTest(args: string[]): Promise<void> {
@@ -137,6 +148,30 @@ async function runTest(args: string[]): Promise<void> {
const [providerId, ...modelParts] = modelArg.split(':');
const modelId = modelParts.join(':');
const recipe = getRecipe(providerId);
+
+ // codex finding #10: when `--model` is passed, the user is probing a
+ // model in isolation. They may be misled into thinking the test result
+ // validates their brain's actual configured path. Loud stderr line names
+ // the divergence at the top of the test so the recovery experience
+ // doesn't repeat the bug-reporter's "providers test ✓ but import still
+ // broken" trap.
+ try {
+ const cfg = loadConfig();
+ const configuredModel = tpArg === 'embedding' ? cfg?.embedding_model : cfg?.chat_model;
+ if (!configuredModel) {
+ console.error(
+ `Note: tested ${modelArg} in isolation; this brain has no configured ${tpArg}_model yet. ` +
+ `\`providers test\` does NOT verify your brain's active path. ` +
+ `Set the active provider with \`gbrain config set ${tpArg}_model <id>\` after running init.`,
+ );
+ } else if (configuredModel !== modelArg) {
+ console.error(
+ `Note: tested ${modelArg} in isolation; gbrain's configured ${tpArg} is ${configuredModel}. ` +
+ `\`providers test\` does NOT verify your brain's active path.`,
+ );
+ }
+ } catch { /* loadConfig throws when no brain configured — first-time install path; the no-config branch above handles it. */ }
+
if (tpArg === 'embedding') {
const dims = recipe?.touchpoints.embedding?.default_dims ?? 1536;
configureGateway({
@@ -150,6 +185,7 @@ async function runTest(args: string[]): Promise<void> {
env: { ...process.env },
});
}
+ void modelId; // intentionally unused but preserved for readability
}
if (!gwIsAvailable(tpArg)) {
diff --git a/src/commands/reindex-multimodal.ts b/src/commands/reindex-multimodal.ts
index 794a6e3b64..de88107e69 100644
--- a/src/commands/reindex-multimodal.ts
+++ b/src/commands/reindex-multimodal.ts
@@ -70,6 +70,33 @@ export async function runReindexMultimodal(
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('reindex_multimodal', 0);
+ // T11 (D12): preflight the multimodal model+dim before any DB work.
+ // Mirrors T6's text-side preflight contract: if the configured multimodal
+ // model can't produce a dim that matches the schema column, fail loud
+ // here with a paste-ready hint rather than mid-reindex with a vector(N)
+ // INSERT error.
+ try {
+ const { loadConfig } = await import('../core/config.ts');
+ const cfg = loadConfig();
+ const multimodalModel = cfg?.embedding_multimodal_model;
+ if (multimodalModel) {
+ const { resolveSchemaMultimodalDim } = await import('../core/embedding-dim-check.ts');
+ const pre = resolveSchemaMultimodalDim({
+ embedding_multimodal_model: multimodalModel,
+ });
+ if (!pre.ok) {
+ progress.finish();
+ throw new Error(
+ `Refusing to reindex: ${pre.error}\n` +
+ `Fix with \`gbrain config set embedding_multimodal_model <provider>:<model>\`.`,
+ );
+ }
+ }
+ } catch (e) {
+ // Re-throw if it's the preflight refusal; suppress only when loadConfig fails.
+ if (e instanceof Error && /Refusing to reindex/.test(e.message)) throw e;
+ }
+
const sql = sqlQueryForEngine(engine);
// Count pending chunks.
diff --git a/src/core/config.ts b/src/core/config.ts
index c547773901..f09dc4b9d2 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -34,6 +34,15 @@ export interface GBrainConfig {
/** AI gateway config (v0.14+). Default: "openai:text-embedding-3-large" / 1536 / "anthropic:claude-haiku-4-5-20251001". */
embedding_model?: string;
embedding_dimensions?: number;
+ /**
+ * v0.37 (D9): user opted into deferred-setup mode at init time via
+ * `gbrain init --no-embedding`. When true, embed callsites and `gbrain
+ * import` refuse with a `gbrain config set embedding_model <id>` hint
+ * rather than proceeding with a default that may not match a real key.
+ * Mutually exclusive with `embedding_model` being set — init writes one
+ * or the other, never both.
+ */
+ embedding_disabled?: boolean;
expansion_model?: string;
/**
* Default chat model for `gateway.chat()` callers (v0.27+).
@@ -320,6 +329,116 @@ export async function loadConfigWithEngine(
return merged;
}
+/**
+ * v0.37 (D6): canonical list of known config keys for `gbrain config set`
+ * validation. Includes both the static GBrainConfig fields (file plane)
+ * and well-known DB-plane keys.
+ *
+ * This is NOT a runtime allow-list applied to reads — gateway/reader code
+ * still tolerates extra keys. It's the suggestion source for "did you mean"
+ * Levenshtein on `set`. Missing keys can be passed through with `--force`.
+ *
+ * When adding a new persistent config key:
+ * 1. Add it to the GBrainConfig interface (if file-plane) OR document it
+ * below (if DB-plane).
+ * 2. Add the canonical name to this list so `gbrain config set` accepts it
+ * without `--force`.
+ */
+export const KNOWN_CONFIG_KEYS: readonly string[] = [
+ // File-plane (GBrainConfig static fields)
+ 'engine',
+ 'database_url',
+ 'database_path',
+ 'openai_api_key',
+ 'anthropic_api_key',
+ 'embedding_model',
+ 'embedding_dimensions',
+ 'embedding_disabled',
+ 'expansion_model',
+ 'chat_model',
+ 'chat_fallback_chain',
+ 'provider_base_urls',
+ 'storage',
+ 'eval',
+ 'eval.capture',
+ 'eval.scrub_pii',
+ 'embedding_multimodal',
+ 'embedding_multimodal_model',
+ 'embedding_image_ocr',
+ 'embedding_image_ocr_model',
+ 'embedding_columns',
+ 'search_embedding_column',
+ 'remote_mcp',
+ 'sync',
+ 'sync.repo_path',
+ 'sync.last_commit',
+ // DB-plane (v0.32.3 search modes + related)
+ 'search.mode',
+ 'search.cache.enabled',
+ 'search.cache.similarity_threshold',
+ 'search.cache.ttl_seconds',
+ 'search.token_budget',
+ 'search.expansion',
+ 'search.intent_weighting',
+ 'search.limit_default',
+ 'search.mode_upgrade_notice_shown',
+ 'search.unified_multimodal',
+ 'search.unified_multimodal_only',
+ 'search.cross_modal.llm_intent',
+ 'search.image_query.max_bytes',
+ 'search.reranker.enabled',
+ 'search.track_retrieval',
+ // Models tier system (v0.31.12)
+ 'models.default',
+ 'models.tier.utility',
+ 'models.tier.reasoning',
+ 'models.tier.deep',
+ 'models.tier.subagent',
+ 'models.aliases',
+ 'models.dream.synthesize',
+ 'models.dream.patterns',
+ 'models.dream.synthesize_verdict',
+ 'models.drift',
+ 'models.auto_think',
+ 'models.think',
+ 'models.subagent',
+ 'models.expansion',
+ 'models.chat',
+ 'models.eval.longmemeval',
+ 'facts.extraction_model',
+ // Dream cycle config
+ 'dream.synthesize.session_corpus_dir',
+ 'dream.synthesize.meeting_transcripts_dir',
+ 'dream.synthesize.last_completion_ts',
+ 'dream.synthesize.verdict_model',
+ 'dream.synthesize.max_prompt_tokens',
+ 'dream.synthesize.max_chunks_per_transcript',
+ 'dream.patterns.lookback_days',
+ 'dream.patterns.min_evidence',
+ // Emotional weight (v0.29)
+ 'emotional_weight.high_tags',
+ 'emotional_weight.user_holder',
+ // Cycle phase config
+ 'cycle.grade_takes.write_gstack_learnings',
+ // Misc
+ 'artifacts_sync_mode',
+ 'cross_project_learnings',
+];
+
+/**
+ * v0.37 (D6): well-known prefix patterns for DB-plane keys that have
+ * unbounded sub-keys. Used as a softer gate before falling back to
+ * Levenshtein suggestion in `gbrain config set`.
+ */
+export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = [
+ 'search.', // search.* (mode, cache.*, etc.)
+ 'models.', // models.* (tier, aliases, per-task)
+ 'dream.', // dream.synthesize.*, dream.patterns.*
+ 'cycle.', // cycle.<phase>.*
+ 'embedding_columns.', // per-column overrides
+ 'provider_base_urls.', // per-provider base URL overrides
+];
+
export function saveConfig(config: GBrainConfig): void {
mkdirSync(getConfigDir(), { recursive: true });
writeFileSync(getConfigPath(), JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.ts
index 0474f40385..c2e6cab329 100644
--- a/src/core/embedding-dim-check.ts
+++ b/src/core/embedding-dim-check.ts
@@ -15,6 +15,64 @@
import type { BrainEngine } from './engine.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from './vector-index.ts';
+import { resolveRecipe } from './ai/model-resolver.ts';
+import type { Recipe } from './ai/types.ts';
+import { AIConfigError } from './ai/errors.ts';
+import {
+ supportsVoyageOutputDimension,
+ isValidVoyageOutputDim,
+ VOYAGE_VALID_OUTPUT_DIMS,
+ supportsZeroEntropyDimension,
+ isValidZeroEntropyDim,
+ ZEROENTROPY_VALID_DIMS,
+ isOpenAITextEmbedding3Model,
+ isValidOpenAITextEmbedding3Dim,
+ maxOpenAITextEmbedding3Dim,
+} from './ai/dims.ts';
+
+/**
+ * pgvector supports vector(N) columns up to 16000 dimensions. HNSW indexing
+ * is capped at PGVECTOR_HNSW_VECTOR_MAX_DIMS (2000); above that, exact scan
+ * still works but searches are slower.
+ *
+ * The preflight resolver below uses this as the hard upper bound so anything
+ * pgvector itself would reject (e.g. an accidental `embedding_dimensions: 99999`)
+ * fails at init time rather than at first embed.
+ */
+export const PGVECTOR_COLUMN_MAX_DIMS = 16000;
+
+/**
+ * v0.37 (D9): runtime guard for the deferred-setup mode.
+ *
+ * Init's `--no-embedding` opt-in writes `embedding_disabled: true` to
+ * config.json. Every embed callsite (CLI: `gbrain embed`, `gbrain import`;
+ * library: `runEmbedCore`) consults this guard so the user gets a clear
+ * "configure embedding first" message rather than an opaque gateway error
+ * at first vector write.
+ *
+ * Returns void on the happy path. Throws `EmbeddingDisabledError` when the
+ * config has `embedding_disabled: true`. The error type lets callers in
+ * CLI mode print a paste-ready hint + exit 1, and library callers (Minion
+ * handlers) bubble it back as a structured job failure.
+ */
+export class EmbeddingDisabledError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'EmbeddingDisabledError';
+ }
+}
+
+export function assertEmbeddingEnabled(cfg: { embedding_disabled?: boolean } | null): void {
+ if (cfg?.embedding_disabled) {
+ throw new EmbeddingDisabledError(
+ 'This brain was initialized with `--no-embedding` (deferred setup).\n' +
+ 'Configure an embedding provider before running embed / import:\n' +
+ ' gbrain config set embedding_model <provider>:<model>\n' +
+ ' gbrain config set embedding_dimensions <N>\n' +
+ ' gbrain init --force --embedding-model <provider>:<model> # re-init to size schema\n',
+ );
+ }
+}
export interface ColumnDimResult {
/** Whether the `content_chunks.embedding` column exists. False on a fresh brain. */
@@ -118,3 +176,231 @@ export function embeddingMismatchMessage(opts: {
return lines.join('\n');
}
+
+// ============================================================================
+// v0.37.x — preflight schema-dim resolution (D11 + D12)
+//
+// Resolves the dim that the PGLite schema substitution will use BEFORE
+// `engine.initSchema()` runs, so init can't create a column whose width
+// disagrees with the gateway-resolved provider. Pure functions, no I/O —
+// init calls them, exits early on error, never writes anything to disk in
+// the failure path. The post-init invariant assertion stays as a regression
+// guardrail; after this resolver lands it can never fire.
+// ============================================================================
+
+/** Tagged-union result of preflight resolution. */
+export type ResolveSchemaDimResult =
+ | { ok: true; dim: number; model: string; provider: string; recipeDefault: number }
+ | { ok: false; error: string };
+
+/** Inputs for the embedding-tier preflight resolver. */
+export interface ResolveSchemaEmbeddingDimOpts {
+ /** `provider:model` string (e.g. `openai:text-embedding-3-large`). Required. */
+ embedding_model: string;
+ /** Explicit override (Matryoshka step, custom dim). Optional. */
+ embedding_dimensions?: number;
+}
+
+/**
+ * Resolve the dim that will land in `content_chunks.embedding`'s vector(N)
+ * column. Caller is `init.ts:initPGLite` before any DB write happens.
+ *
+ * Validations:
+ * 1. `embedding_model` parses as `provider:model`.
+ * 2. Provider is a known recipe.
+ * 3. Recipe declares an `embedding` touchpoint.
+ * 4. Resolved dim is a positive integer.
+ * 5. Resolved dim ≤ PGVECTOR_COLUMN_MAX_DIMS (16000).
+ * 6. If user passed `embedding_dimensions`, it either matches
+ * `recipe.touchpoints.embedding.default_dims` OR is in the recipe's
+ * `dims_options` list (Matryoshka providers). Otherwise reject — the
+ * user picked a model that doesn't support custom dims.
+ */
+export function resolveSchemaEmbeddingDim(opts: ResolveSchemaEmbeddingDimOpts): ResolveSchemaDimResult {
+ try {
+ const { recipe, parsed } = resolveRecipe(opts.embedding_model);
+ const tp = recipe.touchpoints.embedding;
+ if (!tp) {
+ return {
+ ok: false,
+ error:
+ `Provider "${recipe.id}" does not offer embedding models. ` +
+ `Pick a recipe with an embedding touchpoint (gbrain providers list).`,
+ };
+ }
+ return validateDimAgainstTouchpoint(parsed.modelId, recipe, tp.default_dims, tp.dims_options, opts.embedding_dimensions);
+ } catch (err) {
+ return { ok: false, error: err instanceof AIConfigError ? err.message : String(err) };
+ }
+}
+
+/** Inputs for the multimodal-tier preflight resolver (D12). */
+export interface ResolveSchemaMultimodalDimOpts {
+ /** `provider:model` string for the multimodal endpoint. Required. */
+ embedding_multimodal_model: string;
+ /** Explicit override. Optional. */
+ embedding_multimodal_dimensions?: number;
+}
+
+/**
+ * Resolve the dim that will land in `content_chunks.embedding_multimodal`'s
+ * vector(N) column. Mirrors `resolveSchemaEmbeddingDim` but also checks the
+ * recipe-level `supports_multimodal` flag and the per-model
+ * `multimodal_models` allow-list (some recipes like Voyage mix text-only
+ * and multimodal models in one embedding touchpoint).
+ */
+export function resolveSchemaMultimodalDim(opts: ResolveSchemaMultimodalDimOpts): ResolveSchemaDimResult {
+ try {
+ const { recipe, parsed } = resolveRecipe(opts.embedding_multimodal_model);
+ const tp = recipe.touchpoints.embedding;
+ if (!tp) {
+ return {
+ ok: false,
+ error:
+ `Provider "${recipe.id}" does not offer embedding models. ` +
+ `Pick a recipe with an embedding touchpoint that supports multimodal input.`,
+ };
+ }
+ if (!tp.supports_multimodal) {
+ return {
+ ok: false,
+ error:
+ `Provider "${recipe.id}" does not support multimodal embeddings. ` +
+ `Configured recipes that do: voyage (voyage-multimodal-3). ` +
+ `Run \`gbrain providers list\` to see touchpoint coverage.`,
+ };
+ }
+ if (tp.multimodal_models && !tp.multimodal_models.includes(parsed.modelId)) {
+ return {
+ ok: false,
+ error:
+ `Model "${parsed.modelId}" is not in provider "${recipe.id}"'s multimodal allow-list ` +
+ `(allowed: ${tp.multimodal_models.join(', ')}). ` +
+ `Pick a multimodal-capable model from this provider.`,
+ };
+ }
+ return validateDimAgainstTouchpoint(parsed.modelId, recipe, tp.default_dims, tp.dims_options, opts.embedding_multimodal_dimensions);
+ } catch (err) {
+ return { ok: false, error: err instanceof AIConfigError ? err.message : String(err) };
+ }
+}
+
+/**
+ * Shared validation of a requested dim against a recipe touchpoint's
+ * declared dims, including provider-specific Matryoshka allow-lists.
+ *
+ * Recipes (`src/core/ai/recipes/*.ts`) declare `default_dims` per touchpoint
+ * but do NOT generally encode Matryoshka steps as `dims_options`. The
+ * per-provider valid-dim allow-lists live in `src/core/ai/dims.ts`:
+ * - `VOYAGE_VALID_OUTPUT_DIMS` (256/512/1024/2048) for flexible Voyage models
+ * - `ZEROENTROPY_VALID_DIMS` (2560/1280/640/320/160/80/40) for ZE zembed-1
+ * - OpenAI text-embedding-3-* accepts ANY positive integer up to the
+ * model's native size (1536 small / 3072 large)
+ *
+ * Validation order:
+ * 1. recipe-declared `dims_options` (highest precedence — recipe author
+ * knows their backend)
+ * 2. provider-specific dim.ts allow-lists (for known Matryoshka providers)
+ * 3. fall through to "this model only emits default_dims" rejection
+ */
+function validateDimAgainstTouchpoint(
+ modelId: string,
+ recipe: Recipe,
+ defaultDims: number,
+ dimsOptions: number[] | undefined,
+ requestedDims: number | undefined,
+): ResolveSchemaDimResult {
+ const dim = requestedDims ?? defaultDims;
+
+ if (!Number.isInteger(dim) || dim <= 0) {
+ return {
+ ok: false,
+ error: `Embedding dimensions must be a positive integer; got ${JSON.stringify(dim)}.`,
+ };
+ }
+ if (dim > PGVECTOR_COLUMN_MAX_DIMS) {
+ return {
+ ok: false,
+ error:
+ `Embedding dimensions ${dim} exceed pgvector's column cap of ${PGVECTOR_COLUMN_MAX_DIMS}. ` +
+ `Pick a model that returns ≤${PGVECTOR_COLUMN_MAX_DIMS} dims.`,
+ };
+ }
+
+ if (requestedDims !== undefined && requestedDims !== defaultDims) {
+ // User asked for a non-default dim. Walk the precedence chain.
+ const customDimOk = isCustomDimValidForProvider(recipe, modelId, requestedDims, dimsOptions);
+ if (!customDimOk.valid) {
+ return { ok: false, error: customDimOk.error };
+ }
+ }
+
+ return {
+ ok: true,
+ dim,
+ model: `${recipe.id}:${modelId}`,
+ provider: recipe.id,
+ recipeDefault: defaultDims,
+ };
+}
+
+interface CustomDimCheck {
+ valid: boolean;
+ error: string;
+}
+
+function isCustomDimValidForProvider(
+ recipe: Recipe,
+ modelId: string,
+ requestedDims: number,
+ dimsOptions: number[] | undefined,
+): CustomDimCheck {
+ // Tier 1: recipe-declared dims_options.
+ if (dimsOptions && dimsOptions.length > 0) {
+ if (dimsOptions.includes(requestedDims)) return { valid: true, error: '' };
+ return {
+ valid: false,
+ error:
+ `Provider "${recipe.id}" model "${modelId}" rejects custom dimensions ${requestedDims} ` +
+ `(allowed: ${dimsOptions.join(', ')}).`,
+ };
+ }
+
+ // Tier 2: provider-specific Matryoshka allow-lists.
+ if (recipe.id === 'voyage' && supportsVoyageOutputDimension(modelId)) {
+ if (isValidVoyageOutputDim(requestedDims)) return { valid: true, error: '' };
+ return {
+ valid: false,
+ error:
+ `Voyage model "${modelId}" rejects custom dimensions ${requestedDims} ` +
+ `(allowed: ${VOYAGE_VALID_OUTPUT_DIMS.join(', ')}).`,
+ };
+ }
+ if (recipe.id === 'zeroentropyai' && supportsZeroEntropyDimension(modelId)) {
+ if (isValidZeroEntropyDim(requestedDims)) return { valid: true, error: '' };
+ return {
+ valid: false,
+ error:
+ `ZeroEntropy model "${modelId}" does not support custom dimensions ${requestedDims} ` +
+ `(allowed: ${ZEROENTROPY_VALID_DIMS.join(', ')}).`,
+ };
+ }
+ if (recipe.id === 'openai' && isOpenAITextEmbedding3Model(modelId)) {
+ if (isValidOpenAITextEmbedding3Dim(modelId, requestedDims)) return { valid: true, error: '' };
+ const maxDim = maxOpenAITextEmbedding3Dim(modelId);
+ return {
+ valid: false,
+ error:
+ `OpenAI ${modelId} accepts dimensions 1..${maxDim}, got ${requestedDims}.`,
+ };
+ }
+
+ // Tier 3: provider not known to support custom dims at all.
+ return {
+ valid: false,
+ error:
+ `Provider "${recipe.id}" model "${modelId}" does not support custom dimensions ${requestedDims} ` +
+ `(this model only emits its default vector size). ` +
+ `Either drop --embedding-dimensions or pick a Matryoshka-aware model.`,
+ };
+}
diff --git a/src/core/levenshtein.ts b/src/core/levenshtein.ts
new file mode 100644
index 0000000000..1cbad42459
--- /dev/null
+++ b/src/core/levenshtein.ts
@@ -0,0 +1,73 @@
+/**
+ * Levenshtein edit distance + nearest-match suggestion.
+ *
+ * Used by `gbrain config set` (D6) to suggest the canonical key when a user
+ * writes an unknown one (`embedding.provider` → "did you mean `embedding_model`?"),
+ * and by init's env detection (D13) to flag near-miss env var names
+ * (`OPENAPI_API_KEY` → "did you mean `OPENAI_API_KEY`?").
+ *
+ * Iterative two-row DP, O(m*n) time, O(min(m,n)) space. Plenty fast for the
+ * ~30 known config keys and ~14 recipe env vars we compare against.
+ */
+
+/**
+ * Returns the minimum number of single-character insertions, deletions, or
+ * substitutions to transform `a` into `b`. Case-sensitive.
+ */
+export function editDistance(a: string, b: string): number {
+ if (a === b) return 0;
+ if (a.length === 0) return b.length;
+ if (b.length === 0) return a.length;
+
+ // Ensure b is the shorter — keeps the row buffer minimal.
+ if (a.length < b.length) {
+ const tmp = a;
+ a = b;
+ b = tmp;
+ }
+
+ const n = b.length;
+ let prev = new Array<number>(n + 1);
+ let curr = new Array<number>(n + 1);
+ for (let j = 0; j <= n; j++) prev[j] = j;
+
+ for (let i = 1; i <= a.length; i++) {
+ curr[0] = i;
+ const ai = a.charCodeAt(i - 1);
+ for (let j = 1; j <= n; j++) {
+ const cost = ai === b.charCodeAt(j - 1) ? 0 : 1;
+ const del = prev[j] + 1;
+ const ins = curr[j - 1] + 1;
+ const sub = prev[j - 1] + cost;
+ curr[j] = del < ins ? (del < sub ? del : sub) : (ins < sub ? ins : sub);
+ }
+ const swap = prev;
+ prev = curr;
+ curr = swap;
+ }
+
+ return prev[n];
+}
+
+/**
+ * Finds the closest match for `input` among `candidates` whose edit distance
+ * is ≤ `maxDistance` (default 3). Returns the best match or null.
+ *
+ * Tie-break: lexicographic order of the candidate (deterministic across runs).
+ */
+export function suggestNearest(
+ input: string,
+ candidates: readonly string[],
+ maxDistance = 3,
+): string | null {
+ let best: string | null = null;
+ let bestDist = maxDistance + 1;
+ for (const c of candidates) {
+ const d = editDistance(input, c);
+ if (d < bestDist || (d === bestDist && best !== null && c < best)) {
+ best = c;
+ bestDist = d;
+ }
+ }
+ return bestDist <= maxDistance ? best : null;
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 8e04e0e87d..7de68a5df5 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -3733,11 +3733,18 @@ export class PGLiteEngine implements BrainEngine {
const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
// Bug 11 — per-component points. Sum equals brainScore by construction
// so `doctor` can render a breakdown that adds up to the total.
- const embedCoverageScore = pageCount === 0 ? 0 : Math.round(embedCoverage * 35);
- const linkDensityScore = pageCount === 0 ? 0 : Math.round(linkDensity * 25);
- const timelineCoverageScore = pageCount === 0 ? 0 : Math.round(timelineCoverageDensity * 15);
- const noOrphansScore = pageCount === 0 ? 0 : Math.round(noOrphans * 15);
- const noDeadLinksScore = pageCount === 0 ? 0 : Math.round(noDeadLinks * 10);
+ //
+ // v0.37.10.0: empty brains (pageCount === 0) get FULL marks (100/100),
+ // not 0. Semantically an empty brain has no coverage problem to penalize
+ // — there's nothing to embed, nothing to link, nothing to orphan. The
+ // pre-fix "empty = 0" caused fresh-init brains to score as critically
+ // unhealthy on `gbrain doctor`, which was a structural surprise to users
+ // who'd just successfully run init.
+ const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
+ const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
+ const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineCoverageDensity * 15);
+ const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
+ const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
return {
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 4a4ce2f1fe..f13f59d497 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -3708,11 +3708,18 @@ export class PostgresEngine implements BrainEngine {
const noOrphans = pageCount > 0 ? 1 - (orphanPages / pageCount) : 1;
const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
// Per-component points. Sum equals brainScore by construction.
- const embedCoverageScore = pageCount === 0 ? 0 : Math.round(embedCoverage * 35);
- const linkDensityScore = pageCount === 0 ? 0 : Math.round(linkDensity * 25);
- const timelineCoverageScore = pageCount === 0 ? 0 : Math.round(timelineCoverageWhole * 15);
- const noOrphansScore = pageCount === 0 ? 0 : Math.round(noOrphans * 15);
- const noDeadLinksScore = pageCount === 0 ? 0 : Math.round(noDeadLinks * 10);
+ //
+ // v0.37.10.0: empty brains (pageCount === 0) get FULL marks (100/100),
+ // not 0. Semantically an empty brain has no coverage problem to penalize
+ // — there's nothing to embed, nothing to link, nothing to orphan. The
+ // pre-fix "empty = 0" caused fresh-init brains to score as critically
+ // unhealthy on `gbrain doctor`, which was a structural surprise to users
+ // who'd just successfully run init. PGLite path has the same fix.
+ const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
+ const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
+ const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineCoverageWhole * 15);
+ const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
+ const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
return {
diff --git a/test/brain-score-breakdown.test.ts b/test/brain-score-breakdown.test.ts
index 68b2383e2a..55b9a6e966 100644
--- a/test/brain-score-breakdown.test.ts
+++ b/test/brain-score-breakdown.test.ts
@@ -31,14 +31,19 @@ beforeEach(async () => {
});
describe('Bug 11 — brain_score breakdown sums to total', () => {
- test('empty brain returns zero score with all breakdown fields present', async () => {
+ test('empty brain returns full score (vacuous truth) with all breakdown fields present', async () => {
+ // v0.37.10.0: empty brain = no coverage problems = full marks. Pre-fix
+ // this returned 0/100, which surprised users running `gbrain doctor`
+ // immediately after `gbrain init --pglite`. Each component returns its
+ // max weight when pageCount === 0; the sum equals brain_score=100 by
+ // construction (same invariant as the non-empty path, see next test).
const h = await engine.getHealth();
- expect(h.brain_score).toBe(0);
- expect(h.embed_coverage_score).toBe(0);
- expect(h.link_density_score).toBe(0);
- expect(h.timeline_coverage_score).toBe(0);
- expect(h.no_orphans_score).toBe(0);
- expect(h.no_dead_links_score).toBe(0);
+ expect(h.brain_score).toBe(100);
+ expect(h.embed_coverage_score).toBe(35);
+ expect(h.link_density_score).toBe(25);
+ expect(h.timeline_coverage_score).toBe(15);
+ expect(h.no_orphans_score).toBe(15);
+ expect(h.no_dead_links_score).toBe(10);
// dead_links is now on the type.
expect(h.dead_links).toBe(0);
});
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
new file mode 100644
index 0000000000..9857baf463
--- /dev/null
+++ b/test/config-set.test.ts
@@ -0,0 +1,129 @@
+/**
+ * T8 — `gbrain config set` strict unknown-key rejection + --force + Levenshtein.
+ *
+ * These tests probe the pure helpers (KNOWN_CONFIG_KEYS list, prefix list,
+ * Levenshtein suggestion against the list). The full `runConfig` CLI
+ * integration that calls `engine.setConfig` is exercised E2E in T12.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES } from '../src/core/config.ts';
+import { suggestNearest } from '../src/core/levenshtein.ts';
+
+describe('KNOWN_CONFIG_KEYS', () => {
+ test('contains the canonical embedding keys', () => {
+ expect(KNOWN_CONFIG_KEYS).toContain('embedding_model');
+ expect(KNOWN_CONFIG_KEYS).toContain('embedding_dimensions');
+ expect(KNOWN_CONFIG_KEYS).toContain('embedding_disabled'); // v0.37 D9
+ expect(KNOWN_CONFIG_KEYS).toContain('expansion_model');
+ expect(KNOWN_CONFIG_KEYS).toContain('chat_model');
+ });
+
+ test('contains the search-mode keys (v0.32.3)', () => {
+ expect(KNOWN_CONFIG_KEYS).toContain('search.mode');
+ expect(KNOWN_CONFIG_KEYS).toContain('search.cache.enabled');
+ });
+
+ test('contains the models-tier keys (v0.31.12)', () => {
+ expect(KNOWN_CONFIG_KEYS).toContain('models.default');
+ expect(KNOWN_CONFIG_KEYS).toContain('models.tier.subagent');
+ });
+
+ test('no duplicate entries', () => {
+ const set = new Set(KNOWN_CONFIG_KEYS);
+ expect(set.size).toBe(KNOWN_CONFIG_KEYS.length);
+ });
+});
+
+describe('KNOWN_CONFIG_KEY_PREFIXES', () => {
+ test('includes the well-known prefixes', () => {
+ expect(KNOWN_CONFIG_KEY_PREFIXES).toContain('search.');
+ expect(KNOWN_CONFIG_KEY_PREFIXES).toContain('models.');
+ expect(KNOWN_CONFIG_KEY_PREFIXES).toContain('dream.');
+ });
+
+ test('prefixes end in `.` (consistent shape)', () => {
+ for (const p of KNOWN_CONFIG_KEY_PREFIXES) {
+ expect(p).toMatch(/\.$/);
+ }
+ });
+});
+
+describe('Levenshtein suggestion against KNOWN_CONFIG_KEYS', () => {
+ test('bug-reporter case: embedding.model → embedding_model', () => {
+ const got = suggestNearest('embedding.model', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBe('embedding_model');
+ });
+
+ test('bug-reporter case: embedding.dimensions → embedding_dimensions', () => {
+ const got = suggestNearest('embedding.dimensions', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBe('embedding_dimensions');
+ });
+
+ test('bug-reporter case: embedding.provider has no perfect match', () => {
+ // `embedding.provider` is 6+ edits from any canonical key. Either no
+ // suggestion (returns null) OR suggests a close-ish key like
+ // `embedding_model`. Either outcome means the user sees a clear
+ // "unknown key" message + must pick a different name.
+ const got = suggestNearest('embedding.provider', KNOWN_CONFIG_KEYS, 3);
+ // The exact mapping depends on Levenshtein bucket; we just verify it
+ // doesn't accidentally suggest something completely unrelated.
+ if (got !== null) {
+ expect(got).toMatch(/^embedding/);
+ }
+ });
+
+ test('typo: chat_modle → chat_model', () => {
+ const got = suggestNearest('chat_modle', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBe('chat_model');
+ });
+
+ test('typo: search.modes → search.mode', () => {
+ const got = suggestNearest('search.modes', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBe('search.mode');
+ });
+
+ test('completely-unrelated key returns null', () => {
+ const got = suggestNearest('xyzzy_quux_blah_unrelated', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBeNull();
+ });
+
+ test('exact match returns identity (no suggestion noise)', () => {
+ const got = suggestNearest('embedding_model', KNOWN_CONFIG_KEYS, 3);
+ expect(got).toBe('embedding_model');
+ });
+});
+
+describe('prefix vs known-key gate logic (mirrored from runConfig)', () => {
+ // Replicate the gate logic the CLI uses to validate test coverage of
+ // the decision tree.
+ function gate(key: string): 'known' | 'prefix' | 'unknown' {
+ if (KNOWN_CONFIG_KEYS.includes(key)) return 'known';
+ if (KNOWN_CONFIG_KEY_PREFIXES.some(p => key.startsWith(p))) return 'prefix';
+ return 'unknown';
+ }
+
+ test('explicit known key → "known"', () => {
+ expect(gate('embedding_model')).toBe('known');
+ });
+
+ test('search.foo.bar (under prefix) → "prefix"', () => {
+ expect(gate('search.foo.bar')).toBe('prefix');
+ });
+
+ test('models.custom.x (under prefix) → "prefix"', () => {
+ expect(gate('models.custom.x')).toBe('prefix');
+ });
+
+ test('bug-reporter: embedding.provider → "unknown" (no prefix match)', () => {
+ expect(gate('embedding.provider')).toBe('unknown');
+ });
+
+ test('bug-reporter: embedding.model → "unknown"', () => {
+ expect(gate('embedding.model')).toBe('unknown');
+ });
+
+ test('bug-reporter: embedding.dimensions → "unknown"', () => {
+ expect(gate('embedding.dimensions')).toBe('unknown');
+ });
+});
diff --git a/test/doctor-report-remote.test.ts b/test/doctor-report-remote.serial.test.ts
similarity index 84%
rename from test/doctor-report-remote.test.ts
rename to test/doctor-report-remote.serial.test.ts
index 9fad22af21..a1005d375f 100644
--- a/test/doctor-report-remote.test.ts
+++ b/test/doctor-report-remote.serial.test.ts
@@ -8,12 +8,24 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { doctorReportRemote, computeDoctorReport, type DoctorReport, type Check } from '../src/commands/doctor.ts';
let engine: PGLiteEngine;
+let tmpHome: string;
+let priorHome: string | undefined;
beforeAll(async () => {
+ // v0.37.10.0: doctorReportRemote reads from ~/.gbrain audit files
+ // (reranker_health, sync_failures, etc.). Without isolation, host state
+ // leaks into the test and makes the assertion non-deterministic. Pin
+ // GBRAIN_HOME to a tempdir so audit reads return empty.
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-doctor-remote-'));
+ priorHome = process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = tmpHome;
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
@@ -21,6 +33,9 @@ beforeAll(async () => {
afterAll(async () => {
await engine.disconnect();
+ if (priorHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = priorHome;
+ rmSync(tmpHome, { recursive: true, force: true });
});
describe('doctorReportRemote', () => {
diff --git a/test/e2e/init-fresh-pglite.test.ts b/test/e2e/init-fresh-pglite.test.ts
new file mode 100644
index 0000000000..3cc1b74f27
--- /dev/null
+++ b/test/e2e/init-fresh-pglite.test.ts
@@ -0,0 +1,297 @@
+/**
+ * T12 — fresh PGLite init E2E for the v0.37 env-detection + picker + D6 wave.
+ *
+ * Subprocess-driven so we exercise the real CLI argv parsing, env handling,
+ * exit codes, and config persistence — exactly the failure modes the bug
+ * reporter hit. Each test gets its own throw-away `GBRAIN_HOME` so test runs
+ * are hermetic.
+ *
+ * Scope covered:
+ * - Happy path: OPENAI_API_KEY set → auto-pick OpenAI, persists embedding_model + dim
+ * - Fail-loud non-TTY no-key (D3 regression)
+ * - D6 regression: bug-reporter's three no-op config keys exit 1 with Levenshtein
+ * - `--no-embedding` D9 opt-in: init succeeds with sentinel; gbrain import refuses
+ * - D11 preflight: explicit bad --embedding-dimensions refuses BEFORE touching disk
+ *
+ * Picker interactive flow (multi-key TTY) needs the real-PTY harness from
+ * test/helpers/cli-pty-runner.ts — that path is exercised by the unit tests
+ * for `init-provider-picker.ts` (T4) plus the env-detection helpers (T5).
+ * Adding PTY here is mostly orthogonal scope.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const REPO_ROOT = join(import.meta.dir, '..', '..');
+const CLI = `bun run ${REPO_ROOT}/src/cli.ts`;
+
+/** Run a CLI invocation with a clean GBRAIN_HOME + chosen env. Returns { stdout, stderr, exitCode }. */
+async function runCli(args: string[], opts: { env?: NodeJS.ProcessEnv; gbrainHome: string; cwd?: string; stdinIsTTY?: boolean } = { gbrainHome: '' }): Promise<{ stdout: string; stderr: string; exitCode: number }> {
+ const { spawn } = await import('child_process');
+ return new Promise((resolve) => {
+ const child = spawn('bun', ['run', `${REPO_ROOT}/src/cli.ts`, ...args], {
+ env: {
+ // Start from a minimal env to avoid the ambient host env (which
+ // might have OPENAI_API_KEY already set, contaminating our tests).
+ PATH: process.env.PATH,
+ HOME: process.env.HOME,
+ // GBRAIN_HOME isolates state per test.
+ GBRAIN_HOME: opts.gbrainHome,
+ ...opts.env,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ cwd: opts.cwd ?? REPO_ROOT,
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout?.on('data', (b) => { stdout += b.toString(); });
+ child.stderr?.on('data', (b) => { stderr += b.toString(); });
+ child.on('close', (code) => {
+ resolve({ stdout, stderr, exitCode: code ?? -1 });
+ });
+ });
+}
+
+function makeTempHome(): string {
+ return mkdtempSync(join(tmpdir(), 'gbrain-e2e-init-'));
+}
+
+// ============================================================================
+
+describe('v0.37 T12 — fresh init env-detection (D1, D2, D3) + persistence (D5)', () => {
+ let tmpHome: string;
+
+ beforeAll(() => { tmpHome = makeTempHome(); });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('OPENAI_API_KEY auto-picks OpenAI, persists embedding_model + embedding_dimensions', async () => {
+ const r = await runCli(['init', '--pglite'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test-only-for-init-resolution-NOT-CALLED' },
+ });
+ // Init may or may not succeed (depends on whether OpenAI key is real for
+ // any side effect — but init.ts has no live embed call, just config
+ // writes + schema). Assert the auto-pick stderr notice fired.
+ expect(r.stderr).toMatch(/Detected OPENAI_API_KEY|Using openai:text-embedding-3-large/);
+ expect(r.exitCode).toBe(0);
+
+ // Config persisted with the right embedding fields.
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ expect(existsSync(cfgPath)).toBe(true);
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
+ expect(cfg.embedding_model).toBe('openai:text-embedding-3-large');
+ expect(cfg.embedding_dimensions).toBe(1536);
+ expect(cfg.engine).toBe('pglite');
+ }, 240000);
+});
+
+// ============================================================================
+
+describe('v0.37 T12 — D3 non-TTY no-key fail-loud', () => {
+ let tmpHome: string;
+
+ beforeAll(() => { tmpHome = makeTempHome(); });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('--non-interactive with zero provider keys → exit 1 + paste-ready hint', async () => {
+ const r = await runCli(['init', '--pglite', '--non-interactive'], {
+ gbrainHome: tmpHome,
+ env: {}, // no provider keys
+ });
+ expect(r.exitCode).toBe(1);
+ // Fail-loud message includes the canonical env var list.
+ expect(r.stderr).toContain('No embedding provider configured');
+ expect(r.stderr).toContain('OPENAI_API_KEY');
+ expect(r.stderr).toContain('ZEROENTROPY_API_KEY');
+ expect(r.stderr).toContain('VOYAGE_API_KEY');
+ // Suggests --no-embedding alternative.
+ expect(r.stderr).toContain('--no-embedding');
+ }, 60000);
+
+ test('--non-interactive with env-key typo surfaces Levenshtein hint', async () => {
+ const r = await runCli(['init', '--pglite', '--non-interactive'], {
+ gbrainHome: tmpHome,
+ env: { OPENAPI_API_KEY: 'sk-test-typo' },
+ });
+ expect(r.exitCode).toBe(1);
+ // D13 typo detection: surfaces "did you mean OPENAI_API_KEY"
+ expect(r.stderr).toMatch(/did you mean OPENAI_API_KEY/i);
+ }, 60000);
+});
+
+// ============================================================================
+
+describe('v0.37 T12 — D6 regression: bug-reporter no-op keys exit 1 with Levenshtein', () => {
+ let tmpHome: string;
+
+ beforeAll(async () => {
+ tmpHome = makeTempHome();
+ // Bootstrap a brain so `gbrain config set` has somewhere to write.
+ await runCli(['init', '--pglite', '--embedding-model', 'openai:text-embedding-3-large'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('gbrain config set embedding.provider openai → exit 1 with suggestion', async () => {
+ const r = await runCli(['config', 'set', 'embedding.provider', 'openai'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('Unknown config key');
+ }, 60000);
+
+ test('gbrain config set embedding.model openai:text-embedding-3-large → suggests embedding_model', async () => {
+ const r = await runCli(['config', 'set', 'embedding.model', 'openai:text-embedding-3-large'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toMatch(/Did you mean "embedding_model"/);
+ }, 60000);
+
+ test('gbrain config set embedding.dimensions 1536 → suggests embedding_dimensions', async () => {
+ const r = await runCli(['config', 'set', 'embedding.dimensions', '1536'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toMatch(/Did you mean "embedding_dimensions"/);
+ }, 60000);
+
+ test('gbrain config set --force foo.bar baz → accepts with WARN', async () => {
+ const r = await runCli(['config', 'set', 'foo.bar.unknown', 'somevalue', '--force'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(0);
+ expect(r.stderr).toContain('writing unknown key');
+ }, 60000);
+
+ test('gbrain config set search.mode conservative → accepts (known key)', async () => {
+ const r = await runCli(['config', 'set', 'search.mode', 'conservative'], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(0);
+ }, 60000);
+});
+
+// ============================================================================
+
+describe('v0.37 T12 — D9 --no-embedding deferred-setup mode', () => {
+ let tmpHome: string;
+
+ beforeAll(() => { tmpHome = makeTempHome(); });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('init --pglite --no-embedding succeeds with embedding_disabled sentinel', async () => {
+ const r = await runCli(['init', '--pglite', '--no-embedding'], {
+ gbrainHome: tmpHome,
+ env: {}, // no provider keys — opt-in mode shouldn't care
+ });
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain('--no-embedding: deferred setup');
+
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
+ expect(cfg.embedding_disabled).toBe(true);
+ // Mutually exclusive with embedding_model being set.
+ expect(cfg.embedding_model).toBeUndefined();
+ }, 120000);
+
+ test('gbrain import refuses with config-set hint after --no-embedding init', async () => {
+ // Seed a markdown file to import.
+ const repoDir = join(tmpHome, 'sample-repo');
+ mkdirSync(repoDir, { recursive: true });
+ writeFileSync(join(repoDir, 'test.md'), '# test\nhello world');
+
+ const r = await runCli(['import', repoDir], {
+ gbrainHome: tmpHome,
+ env: {},
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toMatch(/deferred setup|no-embedding|gbrain config set embedding_model/);
+ }, 120000);
+
+ test('gbrain import --no-embed flag bypasses the refusal (chunks land without vectors)', async () => {
+ // The CLI flag --no-embed (existing, separate from --no-embedding init flag)
+ // should still work after --no-embedding init — import succeeds, just doesn't
+ // embed. Validates we didn't accidentally block all imports.
+ const repoDir = join(tmpHome, 'sample-repo');
+ const r = await runCli(['import', repoDir, '--no-embed'], {
+ gbrainHome: tmpHome,
+ env: {},
+ });
+ expect(r.exitCode).toBe(0);
+ }, 120000);
+});
+
+// ============================================================================
+
+describe('v0.37 T12 — D11 preflight refuses BEFORE disk writes', () => {
+ let tmpHome: string;
+
+ beforeAll(() => { tmpHome = makeTempHome(); });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('--embedding-dimensions 9999 (invalid for OpenAI text-3-large) refuses early', async () => {
+ const r = await runCli([
+ 'init', '--pglite',
+ '--embedding-model', 'openai:text-embedding-3-large',
+ '--embedding-dimensions', '9999',
+ ], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toMatch(/Refusing to init|rejects custom dimensions 9999|accepts dimensions 1\.\.3072/);
+ // No brain file written on failure path.
+ expect(existsSync(join(tmpHome, 'brain.pglite'))).toBe(false);
+ // No config persisted either (preflight runs BEFORE saveConfig).
+ expect(existsSync(join(tmpHome, '.gbrain', 'config.json'))).toBe(false);
+ }, 60000);
+
+ test('--embedding-dimensions 99999 (above pgvector cap) refuses', async () => {
+ const r = await runCli([
+ 'init', '--pglite',
+ '--embedding-model', 'openai:text-embedding-3-large',
+ '--embedding-dimensions', '99999',
+ ], {
+ gbrainHome: tmpHome,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toMatch(/exceed pgvector|Refusing to init/);
+ }, 60000);
+});
+
+// ============================================================================
+
+describe('v0.37 T12 — happy path with picker-bypassing explicit flag', () => {
+ let tmpHome: string;
+
+ beforeAll(() => { tmpHome = makeTempHome(); });
+ afterAll(() => { rmSync(tmpHome, { recursive: true, force: true }); });
+
+ test('explicit --embedding-model wins over env detection', async () => {
+ const r = await runCli([
+ 'init', '--pglite',
+ '--embedding-model', 'voyage:voyage-3-large',
+ '--embedding-dimensions', '1024',
+ ], {
+ gbrainHome: tmpHome,
+ // OpenAI key set, but explicit Voyage flag overrides per precedence chain.
+ env: { OPENAI_API_KEY: 'sk-test', VOYAGE_API_KEY: 'pa-test' },
+ });
+ expect(r.exitCode).toBe(0);
+
+ const cfg = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'config.json'), 'utf-8'));
+ expect(cfg.embedding_model).toBe('voyage:voyage-3-large');
+ expect(cfg.embedding_dimensions).toBe(1024);
+ }, 120000);
+});
diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.ts
index b2903d5928..64ca221f36 100644
--- a/test/e2e/mechanical.test.ts
+++ b/test/e2e/mechanical.test.ts
@@ -720,8 +720,15 @@ describeE2E('E2E: Setup Journey', () => {
const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL! });
test('gbrain init --non-interactive connects and initializes', () => {
+ // v0.37.10.0: pass --embedding-model explicitly. Tier-1 CI runs without
+ // any embedding-provider env var, and the v0.37 fail-loud-no-key gate
+ // (D3) would otherwise exit 1 here. The provider is offline-resolved
+ // (preflight validates dim against recipe; no HTTP call), so this works
+ // without a real API key. After this init writes config, subsequent
+ // inits in the file honor persisted config per D5 (no flag needed).
const result = Bun.spawnSync({
- cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
+ cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!,
+ '--embedding-model', 'openai:text-embedding-3-large'],
cwd: cliCwd,
env: cliEnv(),
timeout: 15_000,
diff --git a/test/embedding-dim-check.test.ts b/test/embedding-dim-check.test.ts
index 3b4bae5548..5ecb394e53 100644
--- a/test/embedding-dim-check.test.ts
+++ b/test/embedding-dim-check.test.ts
@@ -15,6 +15,9 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import {
readContentChunksEmbeddingDim,
embeddingMismatchMessage,
+ resolveSchemaEmbeddingDim,
+ resolveSchemaMultimodalDim,
+ PGVECTOR_COLUMN_MAX_DIMS,
} from '../src/core/embedding-dim-check.ts';
// Canonical pattern: single engine per file, init once, disconnect once.
@@ -95,3 +98,163 @@ describe('embeddingMismatchMessage', () => {
expect(doctorMsg).toContain('Embedding dimension mismatch detected');
});
});
+
+// ============================================================================
+// v0.37.x — D11 + D12 preflight resolvers
+// ============================================================================
+
+describe('resolveSchemaEmbeddingDim', () => {
+ test('OpenAI text-embedding-3-large resolves at default 1536', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'openai:text-embedding-3-large' });
+ expect(got).toEqual({
+ ok: true,
+ dim: 1536,
+ model: 'openai:text-embedding-3-large',
+ provider: 'openai',
+ recipeDefault: 1536,
+ });
+ });
+
+ test('ZeroEntropy zembed-1 resolves at recipe default', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'zeroentropyai:zembed-1' });
+ expect(got.ok).toBe(true);
+ if (got.ok) {
+ expect(got.provider).toBe('zeroentropyai');
+ expect(got.model).toBe('zeroentropyai:zembed-1');
+ expect(got.dim).toBeGreaterThan(0);
+ }
+ });
+
+ test('ZeroEntropy Matryoshka explicit dim (1280) accepted', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: 1280,
+ });
+ expect(got.ok).toBe(true);
+ if (got.ok) expect(got.dim).toBe(1280);
+ });
+
+ test('ZeroEntropy Matryoshka invalid dim (1024) rejected — 1024 is Voyage step, not ZE', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'zeroentropyai:zembed-1',
+ embedding_dimensions: 1024,
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/does not support custom dimensions 1024|only emits/);
+ });
+
+ test('OpenAI text-3-large rejects 2048 (not in declared dims_options)', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 2048,
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/rejects custom dimensions 2048|does not support custom dimensions/);
+ });
+
+ test('OpenAI text-3-large accepts 768 (declared in recipe dims_options)', () => {
+ // text-embedding-3-large declares dims_options including 768.
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 768,
+ });
+ expect(got.ok).toBe(true);
+ if (got.ok) expect(got.dim).toBe(768);
+ });
+
+ test('unknown provider rejected with provider list hint', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'notarealprovider:foo' });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/unknown provider/i);
+ });
+
+ test('missing colon rejected', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'openai' });
+ expect(got.ok).toBe(false);
+ });
+
+ test('negative dim rejected', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: -100,
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/positive integer/);
+ });
+
+ test('zero dim rejected', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 0,
+ });
+ expect(got.ok).toBe(false);
+ });
+
+ test('non-integer dim rejected', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536.5,
+ });
+ expect(got.ok).toBe(false);
+ });
+
+ test('dim exceeding pgvector column cap rejected', () => {
+ const got = resolveSchemaEmbeddingDim({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: PGVECTOR_COLUMN_MAX_DIMS + 1,
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/exceed pgvector's column cap/);
+ });
+
+ test('regression: bug-reporter scenario — OpenAI auto-pick resolves at 1536', () => {
+ const got = resolveSchemaEmbeddingDim({ embedding_model: 'openai:text-embedding-3-large' });
+ expect(got.ok).toBe(true);
+ if (got.ok) {
+ expect(got.dim).toBe(1536);
+ expect(got.model).toBe('openai:text-embedding-3-large');
+ }
+ });
+});
+
+describe('resolveSchemaMultimodalDim', () => {
+ test('voyage voyage-multimodal-3 accepted', () => {
+ const got = resolveSchemaMultimodalDim({ embedding_multimodal_model: 'voyage:voyage-multimodal-3' });
+ expect(got.ok).toBe(true);
+ if (got.ok) {
+ expect(got.provider).toBe('voyage');
+ expect(got.dim).toBeGreaterThan(0);
+ }
+ });
+
+ test('OpenAI text-embedding-3-large rejected — not multimodal', () => {
+ const got = resolveSchemaMultimodalDim({
+ embedding_multimodal_model: 'openai:text-embedding-3-large',
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/does not support multimodal/);
+ });
+
+ test('voyage text-only model (voyage-3-large) rejected via allow-list', () => {
+ const got = resolveSchemaMultimodalDim({
+ embedding_multimodal_model: 'voyage:voyage-3-large',
+ });
+ expect(got.ok).toBe(false);
+ if (!got.ok) expect(got.error).toMatch(/not in provider "voyage"'s multimodal allow-list/);
+ });
+
+ test('unknown provider rejected', () => {
+ const got = resolveSchemaMultimodalDim({
+ embedding_multimodal_model: 'notarealprovider:foo',
+ });
+ expect(got.ok).toBe(false);
+ });
+
+ test('dim above pgvector cap rejected', () => {
+ const got = resolveSchemaMultimodalDim({
+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',
+ embedding_multimodal_dimensions: PGVECTOR_COLUMN_MAX_DIMS + 1,
+ });
+ expect(got.ok).toBe(false);
+ });
+});
diff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.ts
new file mode 100644
index 0000000000..ed17217732
--- /dev/null
+++ b/test/init-env-detection.test.ts
@@ -0,0 +1,151 @@
+/**
+ * T5 — env-detection helpers in resolveAIOptions.
+ *
+ * These tests exercise the exported pure helpers (groupReadyByProvider,
+ * findEnvKeyTypos) with hermetic env injections. The resolveAIOptions
+ * orchestration itself is exercised end-to-end via T12's
+ * test/e2e/init-fresh-pglite.test.ts (PTY-based, real CLI).
+ *
+ * Per CLAUDE.md test isolation rules: env mutations would normally need
+ * `withEnv`, but these helpers accept env as an argument — purer DI, no
+ * process.env touched, no quarantine needed.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { groupReadyByProvider, findEnvKeyTypos } from '../src/commands/init.ts';
+
+describe('groupReadyByProvider — embedding touchpoint', () => {
+ test('OPENAI_API_KEY alone → openai is ready', async () => {
+ const got = await groupReadyByProvider('embedding', { OPENAI_API_KEY: 'sk-test' });
+ expect(got.map(p => p.recipeId)).toContain('openai');
+ });
+
+ test('VOYAGE_API_KEY alone → voyage is ready', async () => {
+ const got = await groupReadyByProvider('embedding', { VOYAGE_API_KEY: 'pa-test' });
+ expect(got.map(p => p.recipeId)).toContain('voyage');
+ });
+
+ test('ZEROENTROPY_API_KEY alone → zeroentropyai is ready', async () => {
+ const got = await groupReadyByProvider('embedding', { ZEROENTROPY_API_KEY: 'ze-test' });
+ expect(got.map(p => p.recipeId)).toContain('zeroentropyai');
+ });
+
+ test('OPENAI_API_KEY + VOYAGE_API_KEY → both providers in ready list', async () => {
+ const got = await groupReadyByProvider('embedding', {
+ OPENAI_API_KEY: 'sk-test',
+ VOYAGE_API_KEY: 'pa-test',
+ });
+ const ids = got.map(p => p.recipeId);
+ expect(ids).toContain('openai');
+ expect(ids).toContain('voyage');
+ });
+
+ test('each provider appears at most once (codex finding #2 dedup)', async () => {
+ const got = await groupReadyByProvider('embedding', {
+ OPENAI_API_KEY: 'sk-test',
+ VOYAGE_API_KEY: 'pa-test',
+ ZEROENTROPY_API_KEY: 'ze-test',
+ });
+ const ids = got.map(p => p.recipeId);
+ const dupes = ids.filter((id, i) => ids.indexOf(id) !== i);
+ expect(dupes).toEqual([]);
+ });
+
+ test('empty-string env var counts as not set', async () => {
+ const got = await groupReadyByProvider('embedding', { OPENAI_API_KEY: '' });
+ expect(got.map(p => p.recipeId)).not.toContain('openai');
+ });
+
+ test('Anthropic alone → not in embedding ready (no embedding touchpoint on anthropic recipe)', async () => {
+ const got = await groupReadyByProvider('embedding', { ANTHROPIC_API_KEY: 'sk-ant-test' });
+ expect(got.map(p => p.recipeId)).not.toContain('anthropic');
+ });
+
+ test('regression: bug reporter scenario — only OPENAI_API_KEY set → openai picked, ZE not present', async () => {
+ const got = await groupReadyByProvider('embedding', { OPENAI_API_KEY: 'sk-test' });
+ const ids = got.map(p => p.recipeId);
+ expect(ids).toContain('openai');
+ expect(ids).not.toContain('zeroentropyai');
+ });
+});
+
+describe('groupReadyByProvider — chat touchpoint', () => {
+ test('OPENAI_API_KEY → openai chat ready', async () => {
+ const got = await groupReadyByProvider('chat', { OPENAI_API_KEY: 'sk-test' });
+ expect(got.map(p => p.recipeId)).toContain('openai');
+ });
+
+ test('ZEROENTROPY_API_KEY alone → no chat ready (ZE has no chat touchpoint)', async () => {
+ const got = await groupReadyByProvider('chat', { ZEROENTROPY_API_KEY: 'ze-test' });
+ expect(got.map(p => p.recipeId)).not.toContain('zeroentropyai');
+ });
+
+ test('ANTHROPIC_API_KEY → anthropic chat ready', async () => {
+ const got = await groupReadyByProvider('chat', { ANTHROPIC_API_KEY: 'sk-ant-test' });
+ expect(got.map(p => p.recipeId)).toContain('anthropic');
+ });
+});
+
+describe('groupReadyByProvider — expansion touchpoint', () => {
+ test('OPENAI_API_KEY → openai expansion ready', async () => {
+ const got = await groupReadyByProvider('expansion', { OPENAI_API_KEY: 'sk-test' });
+ expect(got.map(p => p.recipeId)).toContain('openai');
+ });
+
+ test('VOYAGE_API_KEY alone → no expansion ready (Voyage is embedding-only)', async () => {
+ const got = await groupReadyByProvider('expansion', { VOYAGE_API_KEY: 'pa-test' });
+ expect(got.map(p => p.recipeId)).not.toContain('voyage');
+ });
+});
+
+describe('findEnvKeyTypos', () => {
+ test('detects OPENAPI_API_KEY → OPENAI_API_KEY', async () => {
+ const got = await findEnvKeyTypos({ OPENAPI_API_KEY: 'sk-test' });
+ expect(got.length).toBeGreaterThan(0);
+ const openaiTypo = got.find(t => t.userSet === 'OPENAPI_API_KEY');
+ expect(openaiTypo).toBeDefined();
+ expect(openaiTypo!.suggested).toBe('OPENAI_API_KEY');
+ });
+
+ test('no typo when canonical name is also set (false-positive guard)', async () => {
+ const got = await findEnvKeyTypos({
+ OPENAPI_API_KEY: 'sk-test',
+ OPENAI_API_KEY: 'sk-real',
+ });
+ // OPENAPI_API_KEY → OPENAI_API_KEY suggestion suppressed
+ expect(got.find(t => t.userSet === 'OPENAPI_API_KEY')).toBeUndefined();
+ });
+
+ test('empty env returns no typos', async () => {
+ const got = await findEnvKeyTypos({});
+ expect(got).toEqual([]);
+ });
+
+ test('canonical name set produces no typo for itself', async () => {
+ const got = await findEnvKeyTypos({ OPENAI_API_KEY: 'sk-test' });
+ expect(got.find(t => t.userSet === 'OPENAI_API_KEY')).toBeUndefined();
+ });
+
+ test('non-API-KEY shaped vars ignored (HOME, PATH, etc.)', async () => {
+ const got = await findEnvKeyTypos({ HOME: '/home/user', PATH: '/usr/bin' });
+ expect(got).toEqual([]);
+ });
+
+ test('empty-string env var skipped (no suggestion)', async () => {
+ const got = await findEnvKeyTypos({ OPENAPI_API_KEY: '' });
+ expect(got.find(t => t.userSet === 'OPENAPI_API_KEY')).toBeUndefined();
+ });
+
+ test('detects VOYAG_API_KEY → VOYAGE_API_KEY (1 char delete)', async () => {
+ const got = await findEnvKeyTypos({ VOYAG_API_KEY: 'pa-test' });
+ const v = got.find(t => t.userSet === 'VOYAG_API_KEY');
+ expect(v).toBeDefined();
+ expect(v!.suggested).toBe('VOYAGE_API_KEY');
+ });
+
+ test('very-different name returns no typo (far beyond edit distance)', async () => {
+ const got = await findEnvKeyTypos({ COMPLETELY_UNRELATED_KEY: 'foo' });
+ // Should not match any canonical via Levenshtein ≤ 3.
+ expect(got.find(t => t.userSet === 'COMPLETELY_UNRELATED_KEY')).toBeUndefined();
+ });
+});
diff --git a/test/init-provider-picker.test.ts b/test/init-provider-picker.test.ts
new file mode 100644
index 0000000000..c9e43fa90e
--- /dev/null
+++ b/test/init-provider-picker.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Picker unit tests — exercise the pure paths (env filtering, caveat
+ * messaging, null returns on bad input). TTY-input flows (numbered
+ * selection happy path, Ctrl-D, timeout) are covered E2E via
+ * cli-pty-runner.ts because mocking readLineSafe at the unit boundary
+ * leaks across files in the shard process per CLAUDE.md test-isolation
+ * rules.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ pickProvider,
+ printSubagentAnthropicCaveat,
+} from '../src/commands/init-provider-picker.ts';
+
+describe('printSubagentAnthropicCaveat', () => {
+ test('writes the canonical D7 caveat lines', () => {
+ let buf = '';
+ printSubagentAnthropicCaveat((s) => { buf += s; });
+ expect(buf).toContain('subagent features');
+ expect(buf).toContain('gbrain dream');
+ expect(buf).toContain('gbrain agent run');
+ expect(buf).toContain('gbrain autopilot');
+ expect(buf).toContain('ANTHROPIC_API_KEY');
+ // The caveat must clarify chat alone is fine without it.
+ expect(buf).toContain('Chat alone');
+ });
+});
+
+describe('pickProvider — defensive paths', () => {
+ test('non-TTY returns null without prompting', async () => {
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'embedding',
+ env: {},
+ isTTY: false,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(got).toBeNull();
+ expect(stderr).toBe('');
+ });
+
+ test('TTY happy path — env-ready provider proceeds to prompt + returns first choice', async () => {
+ // OPENAI_API_KEY set → openai is env-ready. readLineSafe returns the
+ // default '1' in non-stdin-TTY bun:test mode, so picker picks the first
+ // ready recipe deterministically. We mostly want to verify NO null
+ // return and a sensible payload shape.
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'embedding',
+ env: { OPENAI_API_KEY: 'sk-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(got).not.toBeNull();
+ if (got) {
+ expect(got.fullModel).toMatch(/:/); // provider:model shape
+ expect(got.dim).toBeGreaterThan(0); // embedding always has dims
+ expect(stderr).toContain('Pick a embedding provider');
+ }
+ });
+
+ test('caveat fires when picking non-Anthropic chat without ANTHROPIC_API_KEY', async () => {
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'chat',
+ // OpenAI is chat-capable; Anthropic key missing → caveat must fire.
+ env: { OPENAI_API_KEY: 'sk-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(got).not.toBeNull();
+ if (got) {
+ expect(got.recipeId).toBe('openai');
+ // The caveat printed somewhere in stderr.
+ expect(stderr).toContain('subagent features');
+ expect(stderr).toContain('ANTHROPIC_API_KEY');
+ }
+ });
+
+ test('caveat does NOT fire when picking Anthropic for chat', async () => {
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'chat',
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(got).not.toBeNull();
+ if (got) {
+ expect(got.recipeId).toBe('anthropic');
+ // No subagent caveat in stderr.
+ expect(stderr).not.toContain('subagent features');
+ }
+ });
+
+ test('caveat does NOT fire when picking non-Anthropic chat WITH ANTHROPIC_API_KEY also set', async () => {
+ let stderr = '';
+ const got = await pickProvider({
+ touchpoint: 'chat',
+ env: { OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(got).not.toBeNull();
+ if (got) {
+ // Both are ready; first-by-listRecipes order wins; readLineSafe
+ // returns default '1'. Either openai or anthropic — we just verify
+ // no caveat fires either way (anthropic set, no subagent surprise).
+ expect(stderr).not.toContain('subagent features');
+ }
+ });
+
+ test('embedding touchpoint label printed in prompt', async () => {
+ let stderr = '';
+ await pickProvider({
+ touchpoint: 'embedding',
+ env: { OPENAI_API_KEY: 'sk-test' },
+ isTTY: true,
+ writeStderr: (s) => { stderr += s; },
+ });
+ expect(stderr).toContain('embedding provider');
+ });
+});
diff --git a/test/levenshtein.test.ts b/test/levenshtein.test.ts
new file mode 100644
index 0000000000..7ec5e07dd4
--- /dev/null
+++ b/test/levenshtein.test.ts
@@ -0,0 +1,96 @@
+import { describe, test, expect } from 'bun:test';
+import { editDistance, suggestNearest } from '../src/core/levenshtein.ts';
+
+describe('editDistance', () => {
+ test('identical strings return 0', () => {
+ expect(editDistance('embedding_model', 'embedding_model')).toBe(0);
+ });
+
+ test('empty vs non-empty returns length', () => {
+ expect(editDistance('', 'foo')).toBe(3);
+ expect(editDistance('foo', '')).toBe(3);
+ });
+
+ test('one substitution', () => {
+ expect(editDistance('cat', 'bat')).toBe(1);
+ });
+
+ test('one insertion', () => {
+ expect(editDistance('cat', 'cats')).toBe(1);
+ });
+
+ test('one deletion', () => {
+ expect(editDistance('cats', 'cat')).toBe(1);
+ });
+
+ test('classic transposition (kitten → sitting)', () => {
+ expect(editDistance('kitten', 'sitting')).toBe(3);
+ });
+
+ test('case-sensitive', () => {
+ // 'A' vs 'a' is a substitution
+ expect(editDistance('OPENAI_API_KEY', 'openai_api_key')).toBeGreaterThan(0);
+ });
+
+ test('symmetric', () => {
+ expect(editDistance('abc', 'xyz')).toBe(editDistance('xyz', 'abc'));
+ });
+
+ test('bug-reporter case: embedding.provider → embedding_model', () => {
+ // 6 edits: replace 'p' with 'm', 'r' with 'o', 'o' with 'd', 'v' with 'e',
+ // 'i' with 'l', and a couple more changes
+ const d = editDistance('embedding.provider', 'embedding_model');
+ // The exact number doesn't matter — we want it > 3 so it would NOT
+ // suggest embedding_model for embedding.provider with default threshold.
+ // The dot-vs-underscore case is handled by a different mapping (see
+ // suggestNearest with higher threshold in the config.ts caller).
+ expect(d).toBeGreaterThan(3);
+ });
+
+ test('bug-reporter case: embedding.model → embedding_model (1 edit)', () => {
+ // Only '.' vs '_' differs. 1 substitution.
+ expect(editDistance('embedding.model', 'embedding_model')).toBe(1);
+ });
+
+ test('typo: OPENAPI_API_KEY → OPENAI_API_KEY (1 deletion)', () => {
+ expect(editDistance('OPENAPI_API_KEY', 'OPENAI_API_KEY')).toBe(1);
+ });
+});
+
+describe('suggestNearest', () => {
+ const KEYS = ['embedding_model', 'embedding_dimensions', 'expansion_model', 'chat_model', 'search.mode'];
+
+ test('exact match returns identity', () => {
+ expect(suggestNearest('chat_model', KEYS)).toBe('chat_model');
+ });
+
+ test('1-edit typo suggests within default threshold', () => {
+ expect(suggestNearest('embedding.model', KEYS)).toBe('embedding_model');
+ });
+
+ test('returns null when no candidate is within threshold', () => {
+ expect(suggestNearest('completely_unrelated_garbage_string', KEYS)).toBeNull();
+ });
+
+ test('returns null with empty candidates', () => {
+ expect(suggestNearest('whatever', [])).toBeNull();
+ });
+
+ test('deterministic tiebreak on equal distance', () => {
+ // Both 'a' and 'b' are at distance 1 from 'c'. Lex order: 'a' < 'b'.
+ const got = suggestNearest('c', ['a', 'b']);
+ expect(got).toBe('a');
+ });
+
+ test('respects maxDistance override', () => {
+ // 4 edits away — outside the default 3, but inside an override of 5
+ const far = 'fOOO_API_KEY';
+ expect(suggestNearest(far, ['OPENAI_API_KEY'])).toBeNull();
+ expect(suggestNearest(far, ['OPENAI_API_KEY'], 10)).toBe('OPENAI_API_KEY');
+ });
+
+ test('bug-reporter env-var typo case: OPENAPI_API_KEY → OPENAI_API_KEY', () => {
+ expect(suggestNearest('OPENAPI_API_KEY', ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']))
+ .toBe('OPENAI_API_KEY');
+ });
+});
diff --git a/test/providers.test.ts b/test/providers.test.ts
new file mode 100644
index 0000000000..f52969aa62
--- /dev/null
+++ b/test/providers.test.ts
@@ -0,0 +1,96 @@
+/**
+ * `gbrain providers` — pure formatter + envReady tests.
+ *
+ * `runTest` and `runExplain` aren't covered here because they touch the
+ * gateway / loadConfig; E2E exercises those.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { formatRecipeTable, envReady } from '../src/commands/providers.ts';
+import { listRecipes, getRecipe } from '../src/core/ai/recipes/index.ts';
+import type { Recipe } from '../src/core/ai/types.ts';
+
+describe('envReady', () => {
+ test('true when all required env vars set', () => {
+ const openai = getRecipe('openai');
+ expect(openai).toBeDefined();
+ expect(envReady(openai!, { OPENAI_API_KEY: 'sk-test' })).toBe(true);
+ });
+
+ test('false when required env var missing', () => {
+ const openai = getRecipe('openai');
+ expect(envReady(openai!, {})).toBe(false);
+ });
+
+ test('false on empty-string env var', () => {
+ const openai = getRecipe('openai');
+ expect(envReady(openai!, { OPENAI_API_KEY: '' })).toBe(false);
+ });
+
+ test('true for recipes with no required env (local Ollama)', () => {
+ // Ollama has no auth_env.required.
+ const ollama = getRecipe('ollama');
+ expect(ollama).toBeDefined();
+ expect(envReady(ollama!, {})).toBe(true);
+ });
+});
+
+describe('formatRecipeTable', () => {
+ test('header row present', () => {
+ const out = formatRecipeTable(listRecipes(), {});
+ expect(out).toContain('PROVIDER');
+ expect(out).toContain('TIER');
+ expect(out).toContain('EMBED');
+ expect(out).toContain('EXPAND');
+ expect(out).toContain('CHAT');
+ expect(out).toContain('STATUS');
+ });
+
+ test('shows ✓ ready for env-satisfied provider', () => {
+ const out = formatRecipeTable(listRecipes(), { OPENAI_API_KEY: 'sk-test' });
+ // openai row should be ready
+ const openaiLine = out.split('\n').find(line => line.startsWith('openai'));
+ expect(openaiLine).toBeDefined();
+ expect(openaiLine).toContain('✓ ready');
+ });
+
+ test('shows ✗ missing <ENV> for missing provider', () => {
+ const out = formatRecipeTable(listRecipes(), {});
+ // openai should show missing OPENAI_API_KEY
+ const openaiLine = out.split('\n').find(line => line.startsWith('openai'));
+ expect(openaiLine).toBeDefined();
+ expect(openaiLine).toContain('✗ missing OPENAI_API_KEY');
+ });
+
+ test('each recipe appears at most once', () => {
+ const out = formatRecipeTable(listRecipes(), {});
+ const recipes = listRecipes();
+ for (const r of recipes) {
+ const occurrences = out.split('\n').filter(line => line.startsWith(`${r.id} `) || line.startsWith(`${r.id} `));
+ expect(occurrences.length).toBeGreaterThanOrEqual(1);
+ }
+ });
+
+ test('embedding-only recipe (zeroentropyai) shows yes/—/— for tiers', () => {
+ const out = formatRecipeTable(listRecipes(), {});
+ const zeLine = out.split('\n').find(line => line.startsWith('zeroentropyai'));
+ expect(zeLine).toBeDefined();
+ // ZE has embedding but no expansion or chat
+ expect(zeLine).toContain('yes');
+ expect(zeLine).toContain('—');
+ });
+
+ test('isolated subset renders correctly (picker reuses this)', () => {
+ const openai = getRecipe('openai');
+ const ze = getRecipe('zeroentropyai');
+ expect(openai && ze).toBeTruthy();
+ const out = formatRecipeTable([openai!, ze!], { OPENAI_API_KEY: 'sk-test' });
+ const lines = out.split('\n');
+ // header + separator + 2 recipe rows
+ expect(lines.length).toBe(4);
+ expect(lines[2]).toContain('openai');
+ expect(lines[2]).toContain('✓ ready');
+ expect(lines[3]).toContain('zeroentropyai');
+ expect(lines[3]).toContain('✗ missing ZEROENTROPY_API_KEY');
+ });
+});