Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.37.8.0 feat: voyage-code-3 discoverability + reindex-code cost-preview fix (#1267)
Garry Tan54a062974584
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 696a8e100b..cd60bccd67 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,53 @@All notable changes to GBrain will be documented in this file.+## [0.37.8.0] - 2026-05-20++**For agents indexing source code with gbrain, the right embedding model is now obvious — and the brain tells you so out loud.**++If you point a gbrain instance at a repo full of source code (the gstack per-worktree code-brain pattern) and you embed with OpenAI's text-embedding-3-large, you're leaving real retrieval quality on the table. Voyage publishes voyage-code-3, a code-tuned embedding model with head-to-head numbers above their general flagships on code retrieval. The model was already registered in gbrain since pre-v0.33, but nothing in the discovery path said "use this for code." The decision tree in the docs routed to voyage-4-large. The Topology 3 setup section said zero about embedding choice. `gbrain reindex --code` happily embedded with whatever you had configured. The recommendation was hiding in plain sight.++This release closes the discovery gap on four surfaces. The embedding-providers doc grows a "Code-heavy brain" branch in the decision tree. Topology 3 in the architecture doc gets a "Recommended embedding model" subsection with a paste-ready `gbrain init --pglite --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024`. The setup skill points at it. And `gbrain reindex --code` itself prints a short stderr nudge when the configured embedding model isn't code-tuned, with the exact `gbrain config set` lines you'd run to switch. Opt out per-environment with `GBRAIN_NO_CODE_MODEL_NUDGE=1` if you're on OpenAI for compliance or single-vendor procurement.++Same diff also fixes a smaller bug that would have made the nudge land badly. Before v0.37.8.0, `gbrain reindex --code` printed its cost preview with a hardcoded `text-embedding-3-large` model name, even when you had `voyage:voyage-code-3` configured. The constant was a v0.13-era back-compat shim that nobody noticed had drifted. The preview now reads the gateway-configured model directly, so the line above the new nudge is finally truthful.++### How to use it++For a fresh gstack per-worktree code brain:++```bash+export GBRAIN_HOME=/path/to/worktree/.conductor/gbrain+gbrain init --pglite \+ --embedding-model voyage:voyage-code-3 \+ --embedding-dimensions 1024+```++For an already-initialized brain:++```bash+gbrain config set embedding_model voyage:voyage-code-3+gbrain config set embedding_dimensions 1024+gbrain reindex --code --yes+```++To stay on a non-code-tuned model and silence the nudge:++```bash+export GBRAIN_NO_CODE_MODEL_NUDGE=1+```++### Itemized changes++- `src/commands/reindex-code.ts` — new exported `shouldNudgeCodeModel(bareModelName)` pure helper returning a tagged `NudgeDecision` union. Wired into `runReindexCode` (not the CLI wrapper) so dry-run AND execute paths both surface the nudge — codex outside-voice caught that the CLI wrapper's `--dry-run` branch returns before its gate block, which is where the original plan placed the nudge. Allowlist of code-tuned bare model names: `new Set(['voyage-code-3'])` (case-insensitive); the helper takes the bare name that `getEmbeddingModelName()` actually returns (gateway strips the provider prefix) and emits the qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line. Three suppression gates: `opts.json`, `opts.noEmbed`, `process.env.GBRAIN_NO_CODE_MODEL_NUDGE === '1'`. Same file: cost-preview model field swapped from the hardcoded `EMBEDDING_MODEL` back-compat shim at `src/core/embedding.ts:126` to `getEmbeddingModelName()` at all five usage sites (was producing a directly-contradictory model name next to the nudge).+- `docs/integrations/embedding-providers.md` — "Code-heavy brain (gstack per-worktree, source repos)" branch added to the Decision tree; Voyage section gains a dedicated `voyage-code-3` paragraph linking to voyageai.com/blog for head-to-head numbers (vendor claims softened per codex review).+- `docs/architecture/topologies.md` — Topology 3 gets a "Recommended embedding model" subsection between "How it works" and "CRITICAL: alias-level routing is manual". Uses `gbrain init --embedding-model` one-shot to avoid the `config set` + `init` ordering ambiguity codex caught.+- `skills/setup/SKILL.md` — Topology 3 option in the deployment-shape picker grows a one-liner pointing at voyage-code-3 + the topology doc for the full setup recipe.+- `test/ai/voyage-code-3-recipe.test.ts` — new regression pin: voyage-code-3 in the recipe `models[]` list, in `VOYAGE_OUTPUT_DIMENSION_MODELS`, accepted by `supportsVoyageOutputDimension`, and routed through `dimsProviderOptions` on the SDK-supported `dimensions` field (not the wire-key `output_dimension` — that's the v0.33.1.0 bug class).+- `test/reindex-code-nudge.serial.test.ts` — new test, serial: 6 pure-function cases over `shouldNudgeCodeModel` (text-embedding-3-large fires, text-embedding-3-small fires, voyage-4-large fires, voyage-code-3 doesn't, Voyage-Code-3 case-insensitive doesn't, empty/null/undefined/whitespace doesn't) + 5 CLI integration cases pinning the suppression contract (default fires on stderr not stdout, `--no-embed` suppresses, `--json` suppresses, `GBRAIN_NO_CODE_MODEL_NUDGE=1` suppresses, already-optimal voyage-code-3 no-ops).+- `test/reindex-code-model-source.serial.test.ts` — new IRON-RULE regression test pinning the cost-preview correctness fix: `runReindexCode({dryRun: true}).model` equals the gateway-configured embedding model name (voyage-code-3, text-embedding-3-small, voyage-4-large round-trip), NOT the legacy hardcoded `'text-embedding-3-large'` constant.+- `test/reindex-code.test.ts` — updated: now configures the gateway with `openai:text-embedding-3-large` in `beforeAll` (`getEmbeddingModelName()` requires gateway state; the existing model-name assertion at `:80` still passes verbatim) and sets `GBRAIN_NO_CODE_MODEL_NUDGE=1` so test stderr stays clean.+- `CLAUDE.md` — new Key Files entry for `src/commands/reindex-code.ts`; Voyage recipe entry annotated with the v0.37.8.0 discoverability surfaces.+## [0.37.7.0] - 2026-05-21**Your federated brain stops silently writing to the wrong source. Your autopilot stops thrashing when you point it at a second brain. A handful of CLI surfaces that crashed on first call stop crashing.**@@ -446,6 +493,7 @@ upgrade is purely the binary swap.The brain-first detection is regex-based and will hit false-positives onskills that NAME but don't CALL the external tools. Declarative opt-out(`brain_first: exempt`) is the canonical answer for that class.+## [0.37.2.0] - 2026-05-19**Your grading script writes "unresolvable" verdicts now. Before this fix, every single one was rejected at the database layer — 0 of 34 writes landed in a recent production run.**diff --git a/CLAUDE.md b/CLAUDE.mdindex c4eb0dec9d..67195c736d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -51,6 +51,7 @@ strict behavior when unset.- `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.- `src/core/post-upgrade-reembed.ts` (v0.32.7 CJK wave) — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails out with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.- `src/commands/reindex.ts` (v0.32.7 CJK wave) — `gbrain reindex --markdown [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks `pages WHERE page_kind = 'markdown' AND chunker_version < MARKDOWN_CHUNKER_VERSION` in 100-row batches, ordered by id. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent` against the stored `compiled_truth`. **Both paths pass `forceRechunk: true`** to bypass `importFromContent`'s `content_hash` short-circuit — without that flag (codex post-merge F1), the chunker version bump never reaches pages whose source content hasn't changed since last sync, AND master's v0.32.2 stripFactsFence privacy strip never applies to pre-strip chunks. Idempotent — partial-completion re-runs pick up where they left off via id-ordered batches. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`.+- `src/commands/reindex-code.ts` (v0.21.0 Cathedral II E2, extended v0.37.3.0) — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. **v0.37.3.0:** cost-preview model field now reads `getEmbeddingModelName()` from the gateway instead of the back-compat `EMBEDDING_MODEL` constant — preview reflects what the gateway will actually embed with. Same wave adds an informational stderr nudge inside `runReindexCode` (not the CLI wrapper, so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist currently `{'voyage-code-3'}`, case-insensitive bare match against gateway-returned name), prints a 4-line recommendation to switch to `voyage:voyage-code-3`. Suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` helper returns a tagged `NudgeDecision` union; the helper takes the bare model name (matches gateway return shape) and emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, and `test/reindex-code-model-source.serial.test.ts` (the latter is the IRON-RULE regression for the cost-preview fix).- `src/commands/sync.ts:resolveSlugByPathOrSourcePath` (v0.32.7 CJK wave, codex post-merge F4) — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and as of v0.12.3 `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). **v0.26.9 (D14):** adds `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated. Replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback path. Reusable from any future code that needs the same column-existence probe semantics. **v0.32.8 (PR #860):** adds `validateSourceId(id)` that throws on anything outside `^[a-z0-9_-]+$`. Used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` call so source_id can't traverse out of brainDir. `rowToPage` updated to populate the now-required `Page.source_id` field from the SELECT projection (`scripts/check-source-id-projection.sh` enforces that every projection feeding `rowToPage` includes the column).- `src/core/db.ts` — Connection management, schema initialization. v0.22.1 (#363, contributed by @orendi84): `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults: 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT` / `GBRAIN_IDLE_TX_TIMEOUT` / `GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (unlike the prior `setSessionDefaults` post-pool SET, kept as a back-compat no-op shim).@@ -104,7 +105,7 @@ strict behavior when unset.- `src/core/rerank-audit.ts` (v0.35.0.0) — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. **Deliberately no `logRerankSuccess`** (CDX2-F22 in plan review): writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text is SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/search/embedding-column.ts` (v0.36.3.0) — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a `ResolvedColumn` descriptor (frozen `{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default. Throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default — a user who repointed the `embedding` builtin at Voyage doesn't accidentally serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough path) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch` (resolves once at the boundary, threads a `ResolvedColumn` into per-engine `searchVector` instead of a raw string), `gateway.embedQuery(text, {embeddingModel, dimensions})` (resolved column's provider drives the query-time embed call), `cosineReScore` (engine pulls vectors from the active column, not the hardcoded `embedding`), and the `query` MCP op (per-call `embedding_column` param). 538 lines of pure resolver, 511 unit cases in `test/search/embedding-column.test.ts` covering the 16 codex-flagged corners (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison).- `src/core/search/rerank.ts` (v0.35.0.0) — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, and appends the un-reranked tail unchanged (recall protection). **Fail-open on every `RerankError.reason`**: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` which means "fall through to mode bundle" (CDX2-F16). Test seam: `opts.rerankerFn` lets tests stub `gateway.rerank` without touching the network.-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe. **v0.28.7 (#680):** declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio). Closes the v0.27 backfill loop where ~26% of the corpus stayed un-embedded because tiktoken-grounded budgeting silently undercounted Voyage's actual token usage. **v0.28.11 (#719):** declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. **v0.33.1.1 (#962, fixup):** recipe docstring at `:7-16` tightened to name the seven hosted flexible-dim models that accept `output_dimension` explicitly (`voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`) and call out that `voyage-4-nano` is the open-weight variant listed separately by Voyage as fixed 1024-dim — does NOT accept the parameter. The "all v4 variants are flexible" misread is what caused the original PR to include nano in `VOYAGE_OUTPUT_DIMENSION_MODELS`; the negative regression assertion in `test/ai/gateway.test.ts` (`dimsProviderOptions` returns `undefined` for `voyage-4-nano`) pins the contract.+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe. **v0.28.7 (#680):** declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio). Closes the v0.27 backfill loop where ~26% of the corpus stayed un-embedded because tiktoken-grounded budgeting silently undercounted Voyage's actual token usage. **v0.28.11 (#719):** declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. **v0.33.1.1 (#962, fixup):** recipe docstring at `:7-16` tightened to name the seven hosted flexible-dim models that accept `output_dimension` explicitly (`voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`) and call out that `voyage-4-nano` is the open-weight variant listed separately by Voyage as fixed 1024-dim — does NOT accept the parameter. The "all v4 variants are flexible" misread is what caused the original PR to include nano in `VOYAGE_OUTPUT_DIMENSION_MODELS`; the negative regression assertion in `test/ai/gateway.test.ts` (`dimsProviderOptions` returns `undefined` for `voyage-4-nano`) pins the contract. **v0.37.3.0:** `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`). Registration was already in the `models` list since pre-v0.33; the v0.37.3.0 wave adds discoverability surfaces — decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe-shape regression pinned by `test/ai/voyage-code-3-recipe.test.ts`.- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). **v0.31.12:** chat and expansion `models:` lists drop the v0.31.6 phantom `claude-sonnet-4-6-20250929` date suffix — canonical id is `claude-sonnet-4-6`. The wrong-direction alias `claude-sonnet-4-6 → claude-sonnet-4-6-20250929` is removed; a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize` set by v0.31.6 installs). Recipe-shape regression pinned by `test/anthropic-model-ids.test.ts` (6 cases, verbatim cherry-pick of PR #830 plus the reverse-alias rescue case).- `src/core/anthropic-pricing.ts` — Single source of truth for Anthropic model pricing (per-MTok input/output). **v0.31.12:** Opus 4.7 corrected from `$15/$75` to `$5/$25` (the old number was from Opus 4 generation, never refreshed when 4.7 shipped); Opus 4.6 also corrected. Consumed by `src/core/budget-meter.ts` and `src/core/cross-modal-eval/runner.ts` — the cross-modal estimator now reads `ANTHROPIC_PRICING` for Anthropic models instead of duplicating the table, killing the v0.31.6 drift bug class.- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). **v0.31.12:** four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. Resolution chain is now 8 steps: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. Two new exports — `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern, and `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves to a non-Anthropic provider, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` instead of letting the Anthropic Messages API tool-loop attempt to run on OpenAI/Gemini. `_resetDeprecationWarningsForTest()` now also clears `_subagentTierWarningsEmitted` so tests re-emit.diff --git a/TODOS.md b/TODOS.mdindex 62be880ffd..63f80ac808 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,6 +1,10 @@# TODOS+## 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.+## v0.37.7.0 federated-brains + autopilot safety follow-ups (v0.37.x+)- [ ] **.sql file indexing (#1173) — dropped from v0.37.7.0 because tree-sitter-sql.wasm is not in `src/assets/wasm/grammars/`.** The grammars directory ships 35 languages but SQL is not among them. Plan deliberately verify-first-gated this (codex CF11). Re-file as a dedicated wave that: (a) ships tree-sitter-sql.wasm (vendor from upstream), (b) extends the sync walker's `.md|.markdown|.txt` extension filter to include `.sql`, (c) routes `.sql` through `importCodeFile()` with `page_kind='code'`, (d) addresses the slug-shape collision codex flagged with #1172's punted "flatten extensions" work — `slugifyCodePath('docs/auth.sql')` produces a slug shape that may collide with `docs/auth.md` if #1172 ever ships. Verify-first the slug round-trip before merging.@@ -9,7 +13,6 @@- [ ] **Tier 5N doctor check — `subagent_terminal_dead_letters`.** v0.37.7.0 shipped T9 (the subagent dead-letter fix) but deferred the doctor sweep that surfaces historical dead-lettered jobs whose final message is a text-only assistant turn (the #1151 fingerprint). The fix prevents new occurrences; the doctor check would help users discover existing dead-letters from before the upgrade so they can `gbrain jobs prune --status dead --queue default` cleanly. Add the check in v0.37.8+ once a clean conflict-resolved doctor.ts is available.-## v0.37.6.0 OpenRouter recipe follow-ups (v0.37.x+ / v0.38.x)- [ ] **v0.37.x: Verify `tool_use_id` stability through OpenRouter with a live test, then decide whether to relax `isAnthropicProvider()`'s subagent-only gate.** v0.37.6.0 ships `supports_subagent_loop: false` on the OR recipe as informational only — the real gate is `isAnthropicProvider()` in `src/core/model-config.ts`, which hard-rejects every non-Anthropic provider at subagent submit time. OR proxies Anthropic-direct models that DO support stable `tool_use_id` by contract, but OR's response normalization may strip or re-encode them. A short live test: spin up a real OR account, run a subagent loop via `openrouter:anthropic/claude-haiku-4.5`, deliberately abort mid-loop, retry. Assert tool_use_id blocks are byte-identical across attempts. If they are, the `isAnthropicProvider()` check could relax to allow Anthropic models proxied through OR, giving users OR's price/availability story for subagent work. This is a deeper structural change than a recipe-flag flip; needs its own /plan-eng-review pass. Filed during v0.37.6.0 codex review.@@ -20,7 +23,6 @@- [ ] **v0.37.x: Guard cli.ts `main()` so importing `buildGatewayConfig` doesn't print help.** v0.37.6.0 exported `buildGatewayConfig` from `src/cli.ts` for test access. Importing it triggers the file's top-level `main()` which prints help to stdout during tests — functionally harmless (tests pass) but noisy. Fix: wrap `main()` in `if (import.meta.main)` so it only runs when cli.ts is the entry point, not when imported. Touches one line; trivial. Filed during v0.37.6.0 implementation.-## v0.37.5.0 NESTED_QUOTES validator follow-up- [ ] **v0.37.x+: unify `serializeFrontmatter` tag/title quoting with `brain-writer.ts:184`'s single-quote-with-`''`-escape style for consistency.** Cosmetic only now that the validator at `src/core/markdown.ts:219-238` is YAML-aware (v0.37.5.0). Today the emitter still produces `tags: ["yc"]` (double-quoted via `JSON.stringify`) while the repair path produces `tags: ['yc']` (single-quoted). Both are valid YAML and the validator accepts both, so this is cosmetic — but new writes drifting from repair-side output reads as inconsistency. Original signal: PR #1217 by @garrytan-agents (closed in favor of the validator fix). Touch `src/core/frontmatter-inference.ts:391-416` only; should be ~5 LOC + the existing test at `test/frontmatter-inference.test.ts:239` updated.diff --git a/VERSION b/VERSIONindex 1cb2c7ed33..776c322d17 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.37.7.0\ No newline at end of file+0.37.8.0\ No newline at end of filediff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 8782eea6d0..9f6706ed05 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -266,6 +266,36 @@ alias. Tool names are namespaced as `mcp__<alias>__<tool>`, so the agentcalls `mcp__gbrain_code__search` for code lookups and `mcp__gbrain_artifacts__search`for artifact lookups.+### Recommended embedding model++Per-worktree code brains index source files only — no meeting notes,+no people pages, no transcripts. Configure each code brain to use+Voyage's code-tuned model at init time so the config can't be lost to a+later `init` overwrite:++```bash+export GBRAIN_HOME=/path/to/worktree-A/.conductor/gbrain+gbrain init --pglite \+ --embedding-model voyage:voyage-code-3 \+ --embedding-dimensions 1024+```++`voyage-code-3` is Voyage's code-specialized embedding model with+head-to-head numbers above their general flagships on code retrieval+([voyageai.com/blog](https://voyageai.com/blog)). For already-initialized+brains, switch later:++```bash+gbrain config set embedding_model voyage:voyage-code-3+gbrain config set embedding_dimensions 1024+gbrain reindex --code --yes+```++`gbrain reindex --code` prints a recommendation when the configured+embedding model isn't code-tuned. Suppress with+`GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another+provider (single-vendor procurement, compliance, no Voyage key).+### CRITICAL: alias-level routing is manualTopology 3 has no smart per-tool routing inside gbrain. The agent picksdiff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.mdindex 6ff03d900e..a37881e311 100644--- a/docs/integrations/embedding-providers.md+++ b/docs/integrations/embedding-providers.md@@ -37,6 +37,7 @@ gbrain init --pglite --model voyage # use a non-default provider- **Cost-sensitive, English-only**: Ollama (free, local) or Voyage (paid, best quality per dollar).- **Quality-first**: Voyage `voyage-4-large` (1024-2048 dims, ~3-4× more dense tokens than OpenAI tiktoken).+- **Code-heavy brain (gstack per-worktree, source repos)**: Voyage `voyage-code-3` (1024 default; supports 256/512/1024/2048). Tuned on programming languages. Voyage publishes head-to-head numbers showing it outperforms their general flagships on code retrieval ([voyageai.com/blog](https://voyageai.com/blog)). For gstack's per-worktree pglite-backed code brain, this is the right default — see Topology 3 in `docs/architecture/topologies.md`.- **Reranking pair**: Voyage (their reranker `rerank-2.5` pairs cleanly with Voyage embeddings).- **One key for many hosted models**: OpenRouter. Set `OPENROUTER_API_KEY` and use `openrouter:<provider>/<model>` for chat against GPT-5.2, Claude 4.x, Gemini 3, DeepSeek, and dozens more without juggling per-provider keys. Embedding catalog includes OpenAI, Google, Qwen, BGE-M3.- **Enterprise compliance**: Azure OpenAI (data residency + private endpoints) or self-hosted via llama-server / Ollama.@@ -56,6 +57,15 @@ Best-in-class quality on the Voyage 4 family (Jan 2026 release). Set `VOYAGE_APIVoyage 4 family shares an embedding space across all variants, so you can index with `voyage-4-large` and query with `voyage-4-lite` without reindexing. Dims: 256, 512, 1024, 2048. **2048 exceeds pgvector's HNSW cap of 2000** — those brains fall back to exact vector scans (still correct, just slower).+**For brains that index source code** (gstack's per-worktree pglite-backed code brain — see Topology 3 in `docs/architecture/topologies.md`), prefer `voyage-code-3` over `voyage-4-large`. Voyage tunes it on programming languages and publishes head-to-head numbers vs their general flagships on code retrieval. Configure with:++```bash+gbrain config set embedding_model voyage:voyage-code-3+gbrain config set embedding_dimensions 1024+```++`gbrain reindex --code` will print a recommendation when run against a brain whose configured embedding model isn't code-tuned; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another model (single-vendor procurement, compliance, etc.).+### Google GeminiSet `GOOGLE_GENERATIVE_AI_API_KEY` (the AI Studio public API key). Model: `gemini-embedding-001`. Default 768 dims; Matryoshka up to 3072. Cheap.diff --git a/llms-full.txt b/llms-full.txtindex d4cd9e471d..11cc932da0 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -187,6 +187,7 @@ strict behavior when unset.- `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.- `src/core/post-upgrade-reembed.ts` (v0.32.7 CJK wave) — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails out with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.- `src/commands/reindex.ts` (v0.32.7 CJK wave) — `gbrain reindex --markdown [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks `pages WHERE page_kind = 'markdown' AND chunker_version < MARKDOWN_CHUNKER_VERSION` in 100-row batches, ordered by id. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent` against the stored `compiled_truth`. **Both paths pass `forceRechunk: true`** to bypass `importFromContent`'s `content_hash` short-circuit — without that flag (codex post-merge F1), the chunker version bump never reaches pages whose source content hasn't changed since last sync, AND master's v0.32.2 stripFactsFence privacy strip never applies to pre-strip chunks. Idempotent — partial-completion re-runs pick up where they left off via id-ordered batches. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`.+- `src/commands/reindex-code.ts` (v0.21.0 Cathedral II E2, extended v0.37.3.0) — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. **v0.37.3.0:** cost-preview model field now reads `getEmbeddingModelName()` from the gateway instead of the back-compat `EMBEDDING_MODEL` constant — preview reflects what the gateway will actually embed with. Same wave adds an informational stderr nudge inside `runReindexCode` (not the CLI wrapper, so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist currently `{'voyage-code-3'}`, case-insensitive bare match against gateway-returned name), prints a 4-line recommendation to switch to `voyage:voyage-code-3`. Suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` helper returns a tagged `NudgeDecision` union; the helper takes the bare model name (matches gateway return shape) and emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, and `test/reindex-code-model-source.serial.test.ts` (the latter is the IRON-RULE regression for the cost-preview fix).- `src/commands/sync.ts:resolveSlugByPathOrSourcePath` (v0.32.7 CJK wave, codex post-merge F4) — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and as of v0.12.3 `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). **v0.26.9 (D14):** adds `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated. Replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback path. Reusable from any future code that needs the same column-existence probe semantics. **v0.32.8 (PR #860):** adds `validateSourceId(id)` that throws on anything outside `^[a-z0-9_-]+$`. Used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` call so source_id can't traverse out of brainDir. `rowToPage` updated to populate the now-required `Page.source_id` field from the SELECT projection (`scripts/check-source-id-projection.sh` enforces that every projection feeding `rowToPage` includes the column).- `src/core/db.ts` — Connection management, schema initialization. v0.22.1 (#363, contributed by @orendi84): `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults: 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT` / `GBRAIN_IDLE_TX_TIMEOUT` / `GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (unlike the prior `setSessionDefaults` post-pool SET, kept as a back-compat no-op shim).@@ -240,7 +241,7 @@ strict behavior when unset.- `src/core/rerank-audit.ts` (v0.35.0.0) — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. **Deliberately no `logRerankSuccess`** (CDX2-F22 in plan review): writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text is SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/search/embedding-column.ts` (v0.36.3.0) — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a `ResolvedColumn` descriptor (frozen `{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default. Throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default — a user who repointed the `embedding` builtin at Voyage doesn't accidentally serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough path) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch` (resolves once at the boundary, threads a `ResolvedColumn` into per-engine `searchVector` instead of a raw string), `gateway.embedQuery(text, {embeddingModel, dimensions})` (resolved column's provider drives the query-time embed call), `cosineReScore` (engine pulls vectors from the active column, not the hardcoded `embedding`), and the `query` MCP op (per-call `embedding_column` param). 538 lines of pure resolver, 511 unit cases in `test/search/embedding-column.test.ts` covering the 16 codex-flagged corners (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison).- `src/core/search/rerank.ts` (v0.35.0.0) — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, and appends the un-reranked tail unchanged (recall protection). **Fail-open on every `RerankError.reason`**: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` which means "fall through to mode bundle" (CDX2-F16). Test seam: `opts.rerankerFn` lets tests stub `gateway.rerank` without touching the network.-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe. **v0.28.7 (#680):** declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio). Closes the v0.27 backfill loop where ~26% of the corpus stayed un-embedded because tiktoken-grounded budgeting silently undercounted Voyage's actual token usage. **v0.28.11 (#719):** declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. **v0.33.1.1 (#962, fixup):** recipe docstring at `:7-16` tightened to name the seven hosted flexible-dim models that accept `output_dimension` explicitly (`voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`) and call out that `voyage-4-nano` is the open-weight variant listed separately by Voyage as fixed 1024-dim — does NOT accept the parameter. The "all v4 variants are flexible" misread is what caused the original PR to include nano in `VOYAGE_OUTPUT_DIMENSION_MODELS`; the negative regression assertion in `test/ai/gateway.test.ts` (`dimsProviderOptions` returns `undefined` for `voyage-4-nano`) pins the contract.+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe. **v0.28.7 (#680):** declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio). Closes the v0.27 backfill loop where ~26% of the corpus stayed un-embedded because tiktoken-grounded budgeting silently undercounted Voyage's actual token usage. **v0.28.11 (#719):** declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. **v0.33.1.1 (#962, fixup):** recipe docstring at `:7-16` tightened to name the seven hosted flexible-dim models that accept `output_dimension` explicitly (`voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`) and call out that `voyage-4-nano` is the open-weight variant listed separately by Voyage as fixed 1024-dim — does NOT accept the parameter. The "all v4 variants are flexible" misread is what caused the original PR to include nano in `VOYAGE_OUTPUT_DIMENSION_MODELS`; the negative regression assertion in `test/ai/gateway.test.ts` (`dimsProviderOptions` returns `undefined` for `voyage-4-nano`) pins the contract. **v0.37.3.0:** `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`). Registration was already in the `models` list since pre-v0.33; the v0.37.3.0 wave adds discoverability surfaces — decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe-shape regression pinned by `test/ai/voyage-code-3-recipe.test.ts`.- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). **v0.31.12:** chat and expansion `models:` lists drop the v0.31.6 phantom `claude-sonnet-4-6-20250929` date suffix — canonical id is `claude-sonnet-4-6`. The wrong-direction alias `claude-sonnet-4-6 → claude-sonnet-4-6-20250929` is removed; a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize` set by v0.31.6 installs). Recipe-shape regression pinned by `test/anthropic-model-ids.test.ts` (6 cases, verbatim cherry-pick of PR #830 plus the reverse-alias rescue case).- `src/core/anthropic-pricing.ts` — Single source of truth for Anthropic model pricing (per-MTok input/output). **v0.31.12:** Opus 4.7 corrected from `$15/$75` to `$5/$25` (the old number was from Opus 4 generation, never refreshed when 4.7 shipped); Opus 4.6 also corrected. Consumed by `src/core/budget-meter.ts` and `src/core/cross-modal-eval/runner.ts` — the cross-modal estimator now reads `ANTHROPIC_PRICING` for Anthropic models instead of duplicating the table, killing the v0.31.6 drift bug class.- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). **v0.31.12:** four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. Resolution chain is now 8 steps: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. Two new exports — `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern, and `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves to a non-Anthropic provider, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` instead of letting the Anthropic Messages API tool-loop attempt to run on OpenAI/Gemini. `_resetDeprecationWarningsForTest()` now also clears `_subagentTierWarningsEmitted` so tests re-emit.diff --git a/package.json b/package.jsonindex efe8df8f91..01b9eae400 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.37.7.0",+ "version": "0.37.8.0","description": "Postgres-native personal knowledge brain with hybrid RAG search","type": "module","main": "src/core/index.ts",diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex 2ecc2650b9..bc217bd226 100644--- a/skills/setup/SKILL.md+++ b/skills/setup/SKILL.md@@ -86,7 +86,10 @@ Ask the user this BEFORE running `gbrain init`:> calls it over MCP. No local DB on this machine.> 3. **Per-worktree code + shared remote artifacts** — Conductor users with> multiple worktrees indexing the same code repo. Each worktree owns its-> own code engine; artifacts live on a shared remote brain.+> own code engine; artifacts live on a shared remote brain. For code+> engines, configure Voyage's code-tuned model:+> `gbrain init --pglite --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024`+> (full guidance in `docs/architecture/topologies.md` Topology 3).>> Which fits?"diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.tsindex 2fbfc63964..527a0610f5 100644--- a/src/commands/reindex-code.ts+++ b/src/commands/reindex-code.ts@@ -26,7 +26,7 @@import type { BrainEngine } from '../core/engine.ts';import { importCodeFile } from '../core/import-file.ts';import { estimateTokens } from '../core/chunkers/code.ts';-import { EMBEDDING_MODEL, estimateEmbeddingCostUsd } from '../core/embedding.ts';+import { getEmbeddingModelName, estimateEmbeddingCostUsd } from '../core/embedding.ts';import { errorFor, serializeError } from '../core/errors.ts';import { createInterface } from 'readline';import { createProgress } from '../core/progress.ts';@@ -55,6 +55,46 @@ export interface ReindexCodeResult {failures?: Array<{ slug: string; error: string }>;}+/**+ * Voyage publishes voyage-code-3, a code-specialized embedding model that+ * outperforms their general flagships on code retrieval. Per-worktree code+ * brains (Topology 3) are pure source-code, so the recommendation is clean.+ * The nudge surfaces this from `gbrain reindex --code` on dry-run AND+ * execute paths so an agent sees it before spending Anthropic/OpenAI tokens.+ *+ * Allowlist matches against the BARE model name (what getEmbeddingModelName()+ * returns — the gateway strips the provider prefix). Lives in runReindexCode+ * (not the CLI wrapper) because the CLI wrapper's dry-run branch returns+ * before the gate block.+ */+const CODE_TUNED_BARE_MODELS = new Set(['voyage-code-3']);++export type NudgeDecision =+ | { shouldNudge: false }+ | { shouldNudge: true; currentModel: string; recommendedModel: 'voyage:voyage-code-3' };++export function shouldNudgeCodeModel(bareModelName: string | undefined | null): NudgeDecision {+ if (!bareModelName || typeof bareModelName !== 'string') return { shouldNudge: false };+ const trimmed = bareModelName.trim();+ if (!trimmed) return { shouldNudge: false };+ if (CODE_TUNED_BARE_MODELS.has(trimmed.toLowerCase())) return { shouldNudge: false };+ return {+ shouldNudge: true,+ currentModel: trimmed,+ recommendedModel: 'voyage:voyage-code-3',+ };+}++/** Render the nudge to stderr. Pure-stderr by construction so --json stdout stays clean. */+function printCodeModelNudge(decision: Extract<NudgeDecision, { shouldNudge: true }>): void {+ process.stderr.write(+ `[reindex-code] Configured embedding model is \`${decision.currentModel}\`. For pure code retrieval, Voyage's code-tuned \`voyage-code-3\` typically outperforms general-purpose models. Switch:\n` ++ ` gbrain config set embedding_model ${decision.recommendedModel}\n` ++ ` gbrain config set embedding_dimensions 1024\n` ++ `Suppress with GBRAIN_NO_CODE_MODEL_NUDGE=1.\n`,+ );+}+interface CodePageRow {slug: string;compiled_truth: string;@@ -138,6 +178,20 @@ export async function runReindexCode(const { totalTokens, totalPages } = await estimateReindexCost(engine, opts.sourceId, batchSize);const costUsd = estimateEmbeddingCostUsd(totalTokens);+ // Code-model nudge: fire when there's actual work, the operator hasn't opted+ // out, and JSON-mode isn't active. Lives here (not in runReindexCodeCli) so+ // dry-run paths surface it too — the CLI wrapper's dry-run branch returns+ // before its gate block, which is where any UI placed there would be missed.+ if (+ totalPages > 0 &&+ !opts.json &&+ !opts.noEmbed &&+ process.env.GBRAIN_NO_CODE_MODEL_NUDGE !== '1'+ ) {+ const decision = shouldNudgeCodeModel(getEmbeddingModelName());+ if (decision.shouldNudge) printCodeModelNudge(decision);+ }+if (opts.dryRun) {return {status: 'dry_run',@@ -147,7 +201,7 @@ export async function runReindexCode(failed: 0,totalTokens,costUsd,- model: EMBEDDING_MODEL,+ model: getEmbeddingModelName(),};}@@ -160,7 +214,7 @@ export async function runReindexCode(failed: 0,totalTokens: 0,costUsd: 0,- model: EMBEDDING_MODEL,+ model: getEmbeddingModelName(),};}@@ -230,7 +284,7 @@ export async function runReindexCode(failed,totalTokens,costUsd,- model: EMBEDDING_MODEL,+ model: getEmbeddingModelName(),failures: failures.length > 0 ? failures : undefined,};}@@ -271,11 +325,11 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Prconst previewMsg =`reindex-code: ${preview.totalPages} code page(s), ` +`~${preview.totalTokens.toLocaleString()} tokens, ` +- `est. $${costUsd.toFixed(2)} on ${EMBEDDING_MODEL}.`;+ `est. $${costUsd.toFixed(2)} on ${getEmbeddingModelName()}.`;if (preview.totalPages === 0) {if (json) {- console.log(JSON.stringify({ status: 'ok', codePages: 0, reindexed: 0, skipped: 0, failed: 0, totalTokens: 0, costUsd: 0, model: EMBEDDING_MODEL }));+ console.log(JSON.stringify({ status: 'ok', codePages: 0, reindexed: 0, skipped: 0, failed: 0, totalTokens: 0, costUsd: 0, model: getEmbeddingModelName() }));} else {console.log('No code pages to reindex.');}@@ -291,7 +345,7 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Prmessage: previewMsg,hint: 'Pass --yes to proceed, or --dry-run to see the preview and exit 0.',}));- console.log(JSON.stringify({ error: envelope, preview, costUsd, model: EMBEDDING_MODEL }));+ console.log(JSON.stringify({ error: envelope, preview, costUsd, model: getEmbeddingModelName() }));process.exit(2);}console.log(previewMsg);diff --git a/test/ai/voyage-code-3-recipe.test.ts b/test/ai/voyage-code-3-recipe.test.tsnew file mode 100644index 0000000000..3ab8126371--- /dev/null+++ b/test/ai/voyage-code-3-recipe.test.ts@@ -0,0 +1,63 @@+/**+ * v0.37.3 — voyage-code-3 registration regression pin.+ *+ * voyage-code-3 is the user-facing recommendation for gstack per-worktree+ * code brains (Topology 3 in docs/architecture/topologies.md). The model+ * was already registered before v0.37.3 but never surfaced as the right+ * default for code indexing. These assertions guard against a future+ * Voyage recipe refactor silently dropping voyage-code-3 from either the+ * allowlist or the flexible-dim set.+ *+ * Also pins voyage-code-3 on the SDK-supported `dimensions` field path+ * via dimsProviderOptions() — that's the v0.33.1.0 wire-key bug class.+ */++import { describe, expect, test } from 'bun:test';+import { getRecipe } from '../../src/core/ai/recipes/index.ts';+import {+ supportsVoyageOutputDimension,+ isValidVoyageOutputDim,+ dimsProviderOptions,+ VOYAGE_VALID_OUTPUT_DIMS,+} from '../../src/core/ai/dims.ts';++describe('recipe: voyage — voyage-code-3 registration', () => {+ test('voyage-code-3 is in the embedding touchpoint models list', () => {+ const r = getRecipe('voyage');+ expect(r).toBeDefined();+ expect(r!.touchpoints.embedding).toBeDefined();+ expect(r!.touchpoints.embedding!.models).toContain('voyage-code-3');+ });++ test('voyage-code-3 supports flexible output dimensions', () => {+ expect(supportsVoyageOutputDimension('voyage-code-3')).toBe(true);+ });++ test('all four canonical Voyage dims are accepted', () => {+ // The set is locked at 256/512/1024/2048 — flexible-dim Voyage models+ // (incl. voyage-code-3) accept exactly this set. Pinning each one+ // catches the v0.33.1.0-class regression where a Voyage flexible-dim+ // model accidentally falls back to default 1024 because dim validation+ // drifts.+ for (const dims of [256, 512, 1024, 2048]) {+ expect(isValidVoyageOutputDim(dims)).toBe(true);+ }+ expect([...VOYAGE_VALID_OUTPUT_DIMS]).toEqual([256, 512, 1024, 2048]);+ });++ test('dimsProviderOptions returns SDK-shape dimensions field (not output_dimension wire-key)', () => {+ // The v0.33.1.0 bug class: sending Voyage's `output_dimension` wire-key+ // through the AI SDK gets silently dropped (SDK doesn't recognize it),+ // Voyage falls back to default 1024, and any brain configured for+ // 2048 silently embeds at the wrong width. The fix in v0.33.1.1 routes+ // through the SDK-supported `dimensions` field; the voyageCompatFetch+ // shim then translates to output_dimension on the wire.+ const opts = dimsProviderOptions('openai-compatible', 'voyage-code-3', 1024);+ expect(opts).toBeDefined();+ // Shape: { openaiCompatible: { dimensions: 1024 } }+ expect(opts).toHaveProperty('openaiCompatible.dimensions', 1024);+ // Negative regression: no output_dimension on the providerOptions surface+ const raw = JSON.stringify(opts);+ expect(raw).not.toContain('output_dimension');+ });+});diff --git a/test/reindex-code-model-source.serial.test.ts b/test/reindex-code-model-source.serial.test.tsnew file mode 100644index 0000000000..16c859cf11--- /dev/null+++ b/test/reindex-code-model-source.serial.test.ts@@ -0,0 +1,90 @@+/**+ * v0.37.3 — MANDATORY REGRESSION (IRON RULE).+ *+ * SERIAL: gateway is process-global; configureGateway() in this file+ * would race with other parallel-loop tests that read getEmbeddingModelName().+ *+ * Pre-v0.37.3, runReindexCode returned `model: EMBEDDING_MODEL` where+ * `EMBEDDING_MODEL` was a back-compat shim hardcoded to+ * 'text-embedding-3-large'. The cost-preview message printed that+ * stale name even when the user had configured `voyage:voyage-code-3`,+ * producing a directly-contradictory line right next to the new code-+ * model nudge.+ *+ * v0.37.3 routes the model field through `getEmbeddingModelName()` so+ * the preview reflects what the gateway will actually use. This test+ * pins that contract: the model field MUST equal the gateway-configured+ * embedding model name, not the legacy hardcoded constant.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runReindexCode } from '../src/commands/reindex-code.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';++describe('runReindexCode — model field reflects gateway (IRON RULE regression)', () => {+ let engine: PGLiteEngine;+ let prevNudgeEnv: string | undefined;++ beforeAll(async () => {+ // Suppress nudge so it doesn't write to stderr during this test.+ prevNudgeEnv = process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ process.env.GBRAIN_NO_CODE_MODEL_NUDGE = '1';++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ await engine.putPage('src-foo-ts', {+ type: 'code',+ page_kind: 'code',+ title: 'src/foo.ts (typescript)',+ compiled_truth: 'export function foo() { return 42; }',+ timeline: '',+ frontmatter: { language: 'typescript', file: 'src/foo.ts' },+ });+ });++ afterAll(async () => {+ await engine.disconnect();+ resetGateway();+ if (prevNudgeEnv === undefined) delete process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ else process.env.GBRAIN_NO_CODE_MODEL_NUDGE = prevNudgeEnv;+ }, 30_000);++ test('voyage:voyage-code-3 configured → result.model is "voyage-code-3", NOT "text-embedding-3-large"', async () => {+ configureGateway({+ embedding_model: 'voyage:voyage-code-3',+ embedding_dimensions: 1024,+ env: { VOYAGE_API_KEY: 'pa-test' },+ });+ const result = await runReindexCode(engine, { dryRun: true });+ expect(result.model).toBe('voyage-code-3');+ expect(result.model).not.toBe('text-embedding-3-large');+ resetGateway();+ });++ test('openai:text-embedding-3-small configured → result.model is "text-embedding-3-small"', async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-small',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ const result = await runReindexCode(engine, { dryRun: true });+ expect(result.model).toBe('text-embedding-3-small');+ resetGateway();+ });++ test('voyage:voyage-4-large configured → result.model is "voyage-4-large"', async () => {+ // Regression coverage: any provider:model the gateway accepts should+ // round-trip through the cost preview as the bare name.+ configureGateway({+ embedding_model: 'voyage:voyage-4-large',+ embedding_dimensions: 2048,+ env: { VOYAGE_API_KEY: 'pa-test' },+ });+ const result = await runReindexCode(engine, { dryRun: true });+ expect(result.model).toBe('voyage-4-large');+ resetGateway();+ });+});diff --git a/test/reindex-code-nudge.serial.test.ts b/test/reindex-code-nudge.serial.test.tsnew file mode 100644index 0000000000..271978682b--- /dev/null+++ b/test/reindex-code-nudge.serial.test.ts@@ -0,0 +1,207 @@+/**+ * v0.37.3 — code-model nudge: pure helper + CLI integration coverage.+ *+ * SERIAL: this file mutates process.env AND monkey-patches process.stderr.write+ * to capture the nudge output. Both are process-global; running alongside+ * other tests in the same shard would race.+ *+ * shouldNudgeCodeModel() is a pure function over the bare model name+ * (what getEmbeddingModelName() returns — the gateway strips the+ * provider prefix). The nudge fires from runReindexCode (not the CLI+ * wrapper) so dry-run AND execute paths both surface it. The integration+ * tests guard the three suppression flags (--json, GBRAIN_NO_CODE_MODEL_NUDGE,+ * --no-embed) + the stderr-vs-stdout placement contract.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ shouldNudgeCodeModel,+ runReindexCode,+} from '../src/commands/reindex-code.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';++describe('shouldNudgeCodeModel — pure function', () => {+ test('text-embedding-3-large → nudge fires', () => {+ const d = shouldNudgeCodeModel('text-embedding-3-large');+ expect(d.shouldNudge).toBe(true);+ if (d.shouldNudge) {+ expect(d.currentModel).toBe('text-embedding-3-large');+ expect(d.recommendedModel).toBe('voyage:voyage-code-3');+ }+ });++ test('text-embedding-3-small → nudge fires', () => {+ const d = shouldNudgeCodeModel('text-embedding-3-small');+ expect(d.shouldNudge).toBe(true);+ });++ test('voyage-4-large (general-purpose Voyage) → nudge fires', () => {+ // Voyage's general flagships are NOT code-tuned; nudge still fires.+ const d = shouldNudgeCodeModel('voyage-4-large');+ expect(d.shouldNudge).toBe(true);+ });++ test('voyage-code-3 (already optimal) → no nudge', () => {+ const d = shouldNudgeCodeModel('voyage-code-3');+ expect(d.shouldNudge).toBe(false);+ });++ test('Voyage-Code-3 (case-insensitive) → no nudge', () => {+ const d = shouldNudgeCodeModel('Voyage-Code-3');+ expect(d.shouldNudge).toBe(false);+ });++ test('empty / null / undefined / whitespace → no nudge (fail-open)', () => {+ expect(shouldNudgeCodeModel('').shouldNudge).toBe(false);+ expect(shouldNudgeCodeModel(' ').shouldNudge).toBe(false);+ expect(shouldNudgeCodeModel(null).shouldNudge).toBe(false);+ expect(shouldNudgeCodeModel(undefined).shouldNudge).toBe(false);+ });+});++describe('runReindexCode — nudge integration (dry-run path reaches nudge)', () => {+ let engine: PGLiteEngine;+ let prevNudgeEnv: string | undefined;+ let stderrBuf: string;+ let stdoutBuf: string;+ let origStderr: typeof process.stderr.write;+ let origStdout: typeof process.stdout.write;++ beforeAll(async () => {+ prevNudgeEnv = process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ delete process.env.GBRAIN_NO_CODE_MODEL_NUDGE;++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // Seed one code page so totalPages > 0 (nudge gate requires work).+ await engine.putPage('src-foo-ts', {+ type: 'code',+ page_kind: 'code',+ title: 'src/foo.ts (typescript)',+ compiled_truth: 'export function foo() { return 42; }',+ timeline: '',+ frontmatter: { language: 'typescript', file: 'src/foo.ts' },+ });+ });++ afterAll(async () => {+ await engine.disconnect();+ resetGateway();+ if (prevNudgeEnv === undefined) delete process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ else process.env.GBRAIN_NO_CODE_MODEL_NUDGE = prevNudgeEnv;+ }, 30_000);++ function captureStreams() {+ stderrBuf = '';+ stdoutBuf = '';+ origStderr = process.stderr.write.bind(process.stderr);+ origStdout = process.stdout.write.bind(process.stdout);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stderr as any).write = (s: string | Uint8Array) => {+ stderrBuf += typeof s === 'string' ? s : Buffer.from(s).toString();+ return true;+ };+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stdout as any).write = (s: string | Uint8Array) => {+ stdoutBuf += typeof s === 'string' ? s : Buffer.from(s).toString();+ return true;+ };+ }++ function restoreStreams() {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stderr as any).write = origStderr;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (process.stdout as any).write = origStdout;+ }++ test('non-code-tuned model + default invocation → nudge fires on stderr (NOT stdout)', async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ captureStreams();+ try {+ await runReindexCode(engine, { dryRun: true });+ } finally {+ restoreStreams();+ }+ expect(stderrBuf).toContain('[reindex-code]');+ expect(stderrBuf).toContain('voyage:voyage-code-3');+ expect(stderrBuf).toContain('text-embedding-3-large'); // current model echoed+ expect(stdoutBuf).toBe(''); // nudge MUST NOT pollute stdout+ resetGateway();+ });++ test('--no-embed (noEmbed: true) → nudge suppressed even on non-code-tuned model', async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ captureStreams();+ try {+ await runReindexCode(engine, { dryRun: true, noEmbed: true });+ } finally {+ restoreStreams();+ }+ expect(stderrBuf).not.toContain('[reindex-code]');+ resetGateway();+ });++ test('json mode (opts.json: true) → no nudge anywhere', async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ captureStreams();+ try {+ await runReindexCode(engine, { dryRun: true, json: true });+ } finally {+ restoreStreams();+ }+ expect(stderrBuf).not.toContain('[reindex-code]');+ expect(stdoutBuf).toBe(''); // runReindexCode never writes stdout itself+ resetGateway();+ });++ test('GBRAIN_NO_CODE_MODEL_NUDGE=1 → nudge suppressed', async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ process.env.GBRAIN_NO_CODE_MODEL_NUDGE = '1';+ captureStreams();+ try {+ await runReindexCode(engine, { dryRun: true });+ } finally {+ restoreStreams();+ delete process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ }+ expect(stderrBuf).not.toContain('[reindex-code]');+ resetGateway();+ });++ test('voyage-code-3 configured (already optimal) → no nudge', async () => {+ configureGateway({+ embedding_model: 'voyage:voyage-code-3',+ embedding_dimensions: 1024,+ env: { VOYAGE_API_KEY: 'pa-test' },+ });+ captureStreams();+ try {+ await runReindexCode(engine, { dryRun: true });+ } finally {+ restoreStreams();+ }+ expect(stderrBuf).not.toContain('[reindex-code]');+ expect(stderrBuf).not.toContain('Switch:');+ resetGateway();+ });+});diff --git a/test/reindex-code.test.ts b/test/reindex-code.test.tsindex e842ab940d..c585eb6bfc 100644--- a/test/reindex-code.test.ts+++ b/test/reindex-code.test.ts@@ -14,11 +14,26 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runReindexCode } from '../src/commands/reindex-code.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';describe('Layer 13 E2 — runReindexCode', () => {let engine: PGLiteEngine;+ let prevNudgeEnv: string | undefined;beforeAll(async () => {+ // v0.37.3 — runReindexCode now reads getEmbeddingModelName() from the+ // gateway for both the cost-preview model field and the code-model+ // nudge. Configure the gateway with the historical default so the+ // existing model-name assertion stays exact, and suppress the nudge+ // so test stderr stays clean.+ prevNudgeEnv = process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ process.env.GBRAIN_NO_CODE_MODEL_NUDGE = '1';+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();@@ -63,6 +78,9 @@ describe('Layer 13 E2 — runReindexCode', () => {afterAll(async () => {await engine.disconnect();+ resetGateway();+ if (prevNudgeEnv === undefined) delete process.env.GBRAIN_NO_CODE_MODEL_NUDGE;+ else process.env.GBRAIN_NO_CODE_MODEL_NUDGE = prevNudgeEnv;}, 30_000);test('counts code pages, ignores markdown', async () => {