Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.21.0 feat(models): key-aware routing — fact extraction without Anthropic + latest-model discovery (#4298)

Garry Tan649ffe5f8baf
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 578e74bb49..42a8f435d4 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 5bda67fe7a..38f10d28c7 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d38d19bfe1..826763aa44 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.20.0 -->
+<!-- gbrain-runbook-stamp: 0.46.21.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
@@ -96,8 +96,10 @@ registration only with `--mcp-even-if-plugin`.
INSTALL_FOR_AGENTS.md Step 3.5); they can change it any time with
`gbrain search modes`. The one thing to raise here is the OPTIONAL provider
key — with no key you run keyless: keyword search plus memory you author
- yourself through the write tools; everything works, one key upgrades search to
- semantic and enables automatic fact extraction. Never pressure for a key. If the
+ yourself through the write tools; everything works. One key upgrades
+ capabilities per provider: OpenAI unlocks semantic search + automatic fact
+ extraction; Voyage unlocks semantic search; Anthropic unlocks automatic fact
+ extraction. Never pressure for a key. If the
human provides one, pass it to the CLI prompt — it goes to the 0600 config file,
never into the interview answers, never into chat logs you keep.
3. **Interview.** `gbrain bootstrap interview --init`, then ask the questions from
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01cc720565..e81c97a701 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,88 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.21.0] - 2026-08-18
+
+**Fact extraction no longer requires an Anthropic key — and OpenAI defaults
+never go stale.** Model routing now honors whichever provider key you have:
+an OpenAI-only install gets automatic fact extraction, query expansion,
+synthesis, and dream cycles routed to OpenAI instead of silently failing
+against Anthropic defaults. On OpenAI-keyed installs, gbrain discovers the
+newest usable models from your own account (priced-only, cached, fail-open)
+so nothing is ever pinned to a model generation that has since been
+superseded. Keyless installs stay useful and honest: `extract_facts` tells
+the calling agent to extract facts itself via the `remember` verb, and
+doctor/bootstrap-verify report the real state instead of certifying a dead
+pipeline.
+
+### Added
+- Key-aware tier defaults: model resolution's final step consults which
+ provider keys are actually present (config-file keys folded with the
+ environment) instead of assuming Anthropic. Anthropic still wins when both
+ keys exist — zero change for working installs.
+- Latest-model discovery for OpenAI (`GET /v1/models` on your own account):
+ per-tier defaults follow the newest model family that has a pricing row,
+ with a conservative id grammar so unfamiliar future names degrade safely.
+ 24h cache with atomic writes; stale cache beats static fallback; failures
+ back off across process boundaries; `GBRAIN_MODEL_DISCOVERY=off` disables.
+- Keyless `extract_facts` returns a structured `extraction_unavailable`
+ envelope instructing the agent to self-extract (one `remember` call per
+ fact, visibility pinned so facts stay private); other extractor failures
+ return their specific reason instead of a lying `inserted: 0`.
+- One canonical provider-key/env fold (`src/core/ai/provider-env.ts`) shared
+ by the gateway, capability report, and model routing — the Gemini alias
+ and Azure OpenAI fields now reach every consumer identically.
+
+### Changed
+- An explicit `chat_model` pin in `~/.gbrain/config.json` survives engine
+ reconnect when its provider key is present; a pin whose key is gone falls
+ back to the key-aware default with one clear stderr note (prefix-less pins
+ get their own diagnosis). `gbrain init` no longer persists auto-detected
+ chat pins — runtime resolution replaced install-time pinning.
+- `bootstrap verify` and `gbrain doctor` report extraction health against
+ the model extraction will actually call, per provider; keyless installs
+ read as "keyless" with the fence/`remember` guidance, not as healthy
+ automatic extraction.
+- The jobs worker re-reads file-plane config before facts-absorb jobs, so an
+ API key added to `~/.gbrain/config.json` reaches a long-lived worker at the
+ next job without a restart.
+- Config writes are atomic (temp file + rename), so concurrent readers never
+ see a torn `config.json`.
+- Install/bootstrap copy states per-provider truth: OpenAI = semantic search
+ + automatic fact extraction; Voyage = semantic search; Anthropic =
+ fact extraction.
+
+### Fixed
+- Fact extraction gated on the wrong model: it probed the global chat model,
+ then called the extraction model — the two can disagree in both
+ directions. It now gates on the model it actually calls (classification
+ same fix).
+- Extraction failures were silently swallowed as "0 facts": provider errors
+ and truncation now raise typed errors that the durable job lane retries
+ visibly (5 attempts, 60s backoff, parked as re-runnable failed jobs — a
+ page write never fails because its facts backstop threw); refusals and
+ malformed output are logged with the resolved model named. Keyless
+ installs write no log spam — one calm stderr note.
+- Provider error bodies (which can echo partial credentials) no longer flow
+ into MCP responses or persisted logs from extraction failures.
+
+To take advantage of v0.46.21.0:
+- `gbrain upgrade` (or reinstall the binary), then restart any long-running
+ `gbrain jobs work` daemons so workers pick up the new routing.
+- **Spend note:** if you have an `OPENAI_API_KEY` (env or config), features
+ that previously no-oped without an Anthropic key now actually run against
+ your OpenAI account: automatic fact extraction on eligible page writes,
+ query expansion (only in the `tokenmax` search mode), and LLM dream-cycle
+ phases you invoke. Controls: `gbrain config set facts.extraction_enabled
+ false` (extraction kill switch), `models.*` pins for explicit routing, and
+ your search mode's expansion knob. Anthropic-keyed installs see no routing
+ change.
+- OpenAI-only installs: run `gbrain bootstrap verify` — extraction should
+ report available via openai. Nothing else to configure.
+- Keyless installs: nothing breaks; `extract_facts` now hands your agent
+ explicit self-extraction instructions, and doctor explains the keyless
+ state honestly.
+
## [0.46.20.0] - 2026-08-17
**Source freshness decoupled from synthesis.** A per-source maintenance cycle
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index f95edb9760..bd04d296f4 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -72,14 +72,18 @@ the playbook at `skills/migrations/v0.46.3.0.md` — one command migrates both.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
-export OPENAI_API_KEY=sk-... # alternative for vector search; also used for chat models
-export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search quality via query expansion
+export OPENAI_API_KEY=sk-... # alternative for vector search; also powers automatic fact extraction + chat models
+export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models; also improves search via query expansion
```
Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). Do
-NOT use `gbrain config set` for API keys — it writes the DB plane, which the embedding
+NOT use `gbrain config set` for API keys — it writes the DB plane, which the provider
pipeline never reads. Without any embedding provider, keyword search still works.
-Without Anthropic, search works but skips query expansion.
+Chat-shaped features (automatic fact extraction, enrichment, synthesis, query
+expansion) route to whichever supported chat key is present (Anthropic or OpenAI) —
+Anthropic when both are set, OpenAI when it is the only one; other chat providers
+need an explicit `models.*` pin. With neither key, extraction stays off and memory
+comes from agent-authored `## Facts` fences and the `remember` verb.
## Step 3: Create the Brain
diff --git a/TODOS.md b/TODOS.md
index b305de0c33..e36a41d7c0 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,102 @@
# TODOS
+## Key-aware model routing wave follow-ups (filed 2026-08-17; plan: ~/.claude/plans/system-instruction-you-are-working-enchanted-lark.md)
+
+- [ ] **P2 — More providers in `PROVIDER_TIER_DEFAULTS` (+ discovery).** **What:**
+ extend the key-aware tier-default table (src/core/model-config.ts) beyond
+ anthropic/openai — google, deepseek, groq, openrouter each need a curated
+ per-tier model choice, and ideally a latest-model discovery adapter like
+ OpenAI's (`src/core/ai/openai-latest.ts` — provider models endpoint →
+ grammar-ranked, priced-only, cached; Anthropic also has GET /v1/models).
+ **Why:** a GOOGLE_GENERATIVE_AI_API_KEY-only install still resolves tier
+ defaults to Anthropic (unservable) and degrades to the honest keyless path
+ instead of using the key it has; and every static entry rots the way the
+ openai gpt-5.2 pin did. **Context:** the mechanism is done — one table
+ entry per provider; the work is choosing tier grammar per provider and
+ asserting recipe capability fit (tool support for subagent). Start:
+ `PROVIDER_TIER_DEFAULTS` + `test/model-config.serial.test.ts` matrix +
+ the openai-latest ranking pattern. **Effort:** S-M per provider.
+ **Depends on:** nothing.
+- [ ] **P3 — Key-aware `DEFAULT_SYNOPSIS_MODEL` (page-summary).** **What:**
+ `src/core/page-summary.ts` pins the synopsis default to Anthropic Haiku.
+ **Why deferred:** the model id feeds `computeCorpusGeneration` hashing
+ (contextual-retrieval-service.ts) — making it key-dependent churns the
+ corpus generation hash per-environment. Needs a hash-stable design (e.g.
+ exclude the model from the hash, or version the generation) before touching.
+ **Effort:** M.
+- [ ] **P3 — Structured agent-side extraction protocol.** **What:** upgrade
+ the keyless `extract_facts` envelope (skipped: extraction_unavailable +
+ prose `agent_action`) into a structured handoff (taxonomy fields, per-fact
+ write-back contract, conformance test). **Why:** the prose instruction
+ works but agent compliance is unmeasured; a typed contract makes keyless
+ extraction quality testable. Start: `src/core/ops/facts.ts` envelope +
+ `skills/brain-ops/SKILL.md`. **Effort:** M.
+- [ ] **P2 — Durable-job parking/requeue without consuming attempts.**
+ **What:** facts-absorb jobs that fail `chat_unavailable` retry 5× at a 60s
+ exponential base, then park as visible failures; a true "parked —
+ reactivate when a key appears" state would survive arbitrarily long
+ operator delay without manual `jobs retry`. **Why:** config drift is fixed
+ on human timescales; retry windows are minutes. Start:
+ `src/core/minions/queue.ts` (new status or delayed-until-capability
+ semantics). **Effort:** M-L.
+- [ ] **P2 — Chat-side extraction budget/rate cap.** **What:** the spend
+ system (docs/operations/spend-controls.md) is embedding-focused; the facts
+ backstop has no per-source budget or rate cap on chat calls. **Why:** a key
+ activates uncapped extraction on eligible writes; today's controls are the
+ kill switch + model pins only (disclosed in CHANGELOG). Start: a leaser like
+ the contextual-reindex Haiku rate-leaser, keyed per source. **Effort:** M.
+- [ ] **P2 — Route `gbrain config set *_api_key` to the file plane.** **What:**
+ `config set <provider>_api_key` writes the DB plane, which
+ `loadConfigWithEngine()` deliberately never merges for key fields
+ (documented at src/core/config.ts) — so those writes never reach the
+ gateway, and the per-job worker re-fold (src/commands/jobs.ts
+ refreshGatewayForJob) only sees file-plane edits. **Why:** closes a
+ long-standing operator trap AND makes worker key-refresh complete. Start:
+ `src/commands/config.ts` set handler (redirect key fields to the 0600
+ config.json write path). **Effort:** S-M.
+- [ ] **P2 — Doctor `facts_extraction_health` can't see the WORKER's env.**
+ **What:** the zero-rows branch gates on `isAvailable('chat', model)` in the
+ doctor process; a launchd worker with a different env (no keys) skips every
+ extraction calmly while a keyed operator shell's doctor reports healthy.
+ Sharper edge (adversarial review): the calm skip COMPLETES the job, and the
+ queue's content-hash idempotency then returns the completed row for
+ identical resubmissions — so those turns' facts are never extracted even
+ after the key is repaired, unless the page changes.
+ **Fix direction:** keyless-skip in the worker records a low-volume marker
+ (job result field or daily absorb row) doctor can read — doctor already
+ reads job results. Start: src/commands/jobs.ts facts-absorb handler +
+ src/commands/doctor.ts facts_extraction_health. **Effort:** S-M.
+- [ ] **P3 — Cap/dedupe absorb-log rows on keyed extraction failure.**
+ **What:** a keyed-but-failing extraction writes one ingest_log row PER
+ RETRY ATTEMPT (5 per job); a 10k-page sync during a revoked-key day yields
+ ~50k rows + 10k parked jobs. **Fix direction:** one absorb row per job
+ (stamp attempt count into it), or a per-source daily cap. Visibility was
+ the goal; unbounded growth wasn't. Start: src/core/facts/backstop.ts
+ `surfaceExtractionFailure` call sites. **Effort:** S.
+- [ ] **P2 — Classify provider HTTP status into extraction retry policy.**
+ **What:** `FactsExtractionError` deliberately drops the provider error body
+ (redaction), but it also drops the STATUS — the worker retries 401s (
+ permanent), 429s (needs longer backoff), and 5xx (transient) identically,
+ 5 attempts each. **Fix direction:** carry a sanitized `status?: number` on
+ the typed error (a number can't leak a key), map 401/403 →
+ UnrecoverableError (park immediately with the fix hint), 429 → longer
+ backoff. Start: src/core/facts/extract.ts provider_error arm +
+ src/commands/jobs.ts facts-absorb handler. **Effort:** S-M.
+- [ ] **P2 — Live-key e2e for latest-model discovery.** **What:** discovery
+ is off in ALL test lanes (provider-keys preload); the authenticated
+ /v1/models path, endpoint override, fingerprint switch, and real response
+ shape have zero e2e coverage — only the manual scratch-HOME smoke. **Fix
+ direction:** a skip-gated e2e (runs only when OPENAI_API_KEY + an explicit
+ opt-in env is set, like the live embed parity tests) asserting a real
+ refresh lands priced tiers. Start: test/e2e/ + scripts/run-e2e.sh
+ scrub-allowlist for GBRAIN_MODEL_DISCOVERY. **Effort:** S.
+- [ ] **P3 — mtime-memoize `loadConfig()`.** **What:** key-aware resolution
+ put sync read+parse of config.json on per-resolution hot paths
+ (`resolveTierDefault` step 7, `classifyUnavailable`). Bulk syncs multiply
+ it. **Fix direction:** the exact mtime-keyed memo pattern in
+ src/core/ai/openai-latest.ts `readCacheFile`. Same cost profile as the
+ old `hasAnthropicKey` precedent, so P3 not P2. Start: src/core/config.ts
+ `loadConfig`. **Effort:** S.
## Dream freshness split follow-ups (v0.46.20.0)
- [ ] **P2 — automatic background lane for `SOURCE_BACKGROUND_PHASES`.**
@@ -1447,7 +1544,12 @@ Deferred from the BrainBench wave (eng-reviewed; plan + GSTACK REVIEW REPORT at
- [ ] **`eval compare` markdown rendering for `mode: 'n/a'` rows.** EvalRunRecord v3 records brainbench under 'n/a'; the markdown renderer iterates SEARCH_MODES only, so those rows surface in `--json` output but not the mode table (documented in the v3 docstring). Add an un-grouped section to `renderMarkdown`. Priority: P3.
- [ ] **Periodic re-baselining (the ratchet doesn't auto-tighten).** Improvements aren't banked into master's baseline until a PR updates it, so a regression back to a stale baseline level passes. Documented as an accepted residual in `docs/eval/BRAINBENCH.md`; the fix is an operator habit or a scheduled job that re-runs `--update-baseline` after metric-improving merges. Priority: P3.
-- [ ] **Hermetic-ize the 7 env-sensitive LLM-availability tests.** `test/think-gateway-adapter.test.ts`, `test/conversation-parser/llm-base.test.ts`/`llm-fallback.test.ts`, `test/doctor-ze-checks.test.ts` assert behavior "when ANTHROPIC_API_KEY is unset" by reading the live process env — they fail on any dev shell that exports provider keys (verified failing on clean master in such a shell; green in keyless CI). Stub/save-restore the env per test so local runs match CI. Priority: P2.
+- [x] **Hermetic-ize the 7 env-sensitive LLM-availability tests.** DONE in
+ v0.46.21.0, structurally: `test/helpers/provider-keys-preload.ts` (bunfig
+ preload) strips ambient provider keys before any unit-test file loads, so
+ dev shells match keyless CI by definition; tests that want keys inject them
+ explicitly. Escape hatch `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` (set by
+ scripts/run-e2e.sh).
## #2416 follow-ups (query-steering wave)
- [x] **P2 — MCP-envelope `hint` field for concept-shaped `search` calls.**
diff --git a/VERSION b/VERSION
index dd9d967696..b13dfd0594 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.20.0
\ No newline at end of file
+0.46.21.0
\ No newline at end of file
diff --git a/bunfig.toml b/bunfig.toml
index 91fd3b9f21..09884e9340 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -38,4 +38,12 @@ timeout = 60_000
# GIT_CONFIG_COUNT env config so a dev box's global signing config can't
# route test-repo commits through gpg-agent (which intermittently fails
# under full-suite load). See test/helpers/git-hermetic-preload.ts.
-preload = ["./test/helpers/database-url-guard-preload.ts", "./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts", "./test/helpers/gbrain-home-preload.ts", "./test/helpers/git-hermetic-preload.ts"]
+#
+# provider-keys-preload: strip ambient ANTHROPIC_API_KEY/OPENAI_API_KEY so
+# key-aware model routing (resolveTierDefault) resolves identically to
+# keyless CI — a chat key exported in the dev shell otherwise flips default-
+# model assertions AND turns gated paths into real network calls (observed:
+# 183 failures + 15-minute retry hangs on an OPENAI-only shell). The e2e
+# wrapper sets GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 to opt back in. See
+# test/helpers/provider-keys-preload.ts.
+preload = ["./test/helpers/database-url-guard-preload.ts", "./test/helpers/provider-keys-preload.ts", "./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts", "./test/helpers/gbrain-home-preload.ts", "./test/helpers/git-hermetic-preload.ts"]
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 1b20bac989..0a7ace68f1 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -52,10 +52,17 @@ API keys live in `~/.gbrain/config.json` (file plane) or env vars (`VOYAGE_API_K
```bash
export VOYAGE_API_KEY=pa-... # default embedding (voyage-4) + reranker (rerank-2.5) — one key
-export OPENAI_API_KEY=sk-... # alternative embeddings; also used for chat models
-export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search via query expansion
+export OPENAI_API_KEY=sk-... # alternative embeddings; also powers automatic fact extraction + chat models
+export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models; also improves search via query expansion
```
+Chat-shaped features (automatic fact extraction, enrichment, synthesis, query
+expansion) route to whichever supported chat key is present (Anthropic or
+OpenAI) — Anthropic when both are set, OpenAI when it is the only one; other
+chat providers need an explicit `models.*` pin. With neither key, they stay off
+calmly and memory comes from agent-authored `## Facts` fences and the
+`remember` verb.
+
`ZEROENTROPY_API_KEY` is still honored but deprecated — the ZeroEntropy hosted API shuts down 2026-09-04. Off-ramp: the agent playbook at [`skills/migrations/v0.46.3.0.md`](../skills/migrations/v0.46.3.0.md) (one command migrates embeddings + reranker) with the full reference in [`docs/guides/embedding-migration.md`](guides/embedding-migration.md).
Common follow-ups:
diff --git a/docs/TESTING.md b/docs/TESTING.md
index cbd1823549..f05a31ea26 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -383,6 +383,23 @@ discipline as the database-URL vars — so a dev shell configured for a real
brain can't ride through. `GBRAIN_DEBUG_PRELOAD=1` prints the allocated
scratch home for debugging.
+**Provider-key strip preload.** `test/helpers/provider-keys-preload.ts` (bunfig
+`[test]` preload) strips the ambient provider credentials the canonical fold
+recognizes (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Gemini/Google, Voyage,
+OpenRouter, ZeroEntropy, DashScope, and the Azure OpenAI endpoint fields) and
+defaults `GBRAIN_MODEL_DISCOVERY=off` (respecting an explicit operator
+override), so key-aware model routing (`resolveTierDefault`) resolves
+identically to keyless CI and latest-model discovery never makes a real
+network call from a test. Without it, a chat key exported in the dev shell
+flips default-model assertions AND turns gated paths into live provider calls
+(observed: 183 unit failures + 15-minute retry hangs on an
+`OPENAI_API_KEY`-exporting shell). Tests that want keys inject them explicitly
+(`configureGateway({env})`, `withEnv`, serial-file `process.env`) — the
+preload removes ambient shell state only, before any test file loads. The e2e
+wrapper (`scripts/run-e2e.sh`) opts back in at its boundary via
+`GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` — e2e is the lane where real keys are
+deliberate (live embed/parity tests skip-gate on them).
+
**Database-URL run guard (#3485).** A `bun test` invocation REFUSES to start while
`DATABASE_URL` or `GBRAIN_DATABASE_URL` is ambient in the environment, because some
tests run destructive SQL against whatever those URLs point at (a bare `bun test`
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 3bb9148327..b9c7f3022d 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -135,7 +135,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:<model>`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook (#4194/CDX-7): optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'` (#4088): a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state (#4201): `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported, #4087) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`) and drives `defaultMaxOutputTokens`'s 32k thinking headroom; think/index.ts shares it. `expand()` and `generateOcrText()` also record on the ambient tracker (#4121 — they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`, so their spend was previously invisible to every cap and ledger): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `__setGenerateObjectTransportForTests` mirrors the generateText seam. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts`
- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by regression in `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned by regression). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); the recipe itself is deleted in the September removal release.
- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Same wave adds: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (closes file-plane / DB-plane divergence where doctor said "not configured" while live search was actively reranking — the field-plane `getRerankerModel()` read nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
-- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (#4114; gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is INFORMATIONAL — the real gate is `isAnthropicProvider()` in `src/core/model-config.ts` which hard-pins gbrain's subagent infra to Anthropic-direct. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
+- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (#4114; gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is INFORMATIONAL — the real gate is `enforceSubagentCapable()` in `src/core/model-config.ts` (capability verdicts from `classifyCapabilities()`: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn). Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text 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` — 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 frozen `ResolvedColumn` descriptor (`{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 so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison).
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network.
@@ -152,11 +152,14 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/diarize/payload-fitter.ts` — generic fit-arbitrarily-large-items-into-per-call-token-budget utility. `'batch'` strategy is deterministic token-budgeted chunking with no LLM calls. `'summarize'` strategy embed-clusters into ceil(items/4) groups via cheap deterministic nearest-neighbor on cosine, Haiku-summarizes each cluster via `Promise.allSettled` at parallelism=4. Each Haiku call composes the active BudgetTracker via the AsyncLocalStorage. Quality gate: when `success_ratio < min_success_ratio` (default 0.75), result is flagged `degraded: true` — the fitter preserves the successful subset; the caller decides whether to surface a partial result or abort.
- `src/core/brainstorm/checkpoint.ts` — crash-resilient checkpoint for `gbrain brainstorm` and `gbrain lsd`. Persists FULL idea bodies (~50KB/run) so resume MERGES pre-crash ideas with post-resume ideas before the judge runs (a resume that produces only second-run output is silent partial output). `run_id = sha256(question + profile + sort(close_slugs) + sort(far_slugs)).slice(0,16)` — NO embedding bits, stable across embedding-model swaps. Atomic write via `.tmp + rename`. ONE resume flag (`--resume <run_id>` covers both failed AND never-attempted crosses); `--list-runs` prints run_ids mtime-newest-first; `--force-resume` bypasses the 7-day staleness gate. Cycle purge phase (`gbrain dream --phase purge`) GCs checkpoints older than 7 days via `gcStaleCheckpoints(7)`. Pinned by `test/e2e/brainstorm-resume.test.ts` (20 unit + 3 E2E cases incl. the merge contract).
- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Pinned by 13 unit cases.
-- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). 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`. 8-step resolution chain: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves non-Anthropic, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` (the Anthropic Messages API tool-loop can't run on OpenAI/Gemini). `_resetDeprecationWarningsForTest()` also clears `_subagentTierWarningsEmitted`. Pinned by `test/model-config.serial.test.ts`.
+- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). 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`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.default` → `models.tier.<tier>` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback; `resolveModel()` is the thin wrapper for callers that only want the string. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); no key at all → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (#4123 — configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id fell through to `default_dims` and `gbrain init` built a wrong-width column), before falling back to `default_dims`.
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (13 `PER_TASK_KEYS`, now including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and used to false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/zeroentropy/dashscope/google, #2662 — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
-- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Single owner of folding file-plane API keys (openai/anthropic/zeroentropy) into the gateway env and threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
+- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
+- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called from `reconfigureGatewayWithEngine`, TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.
+- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/google + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped per #1249), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — the old buildGatewayConfig/capability duplicate-and-sync pair is dead; drift is structurally impossible.
+- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries, `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.
- `src/core/skill-catalog.ts` — host-repo skill catalog backing the MCP `list_skills` / `get_skill` ops. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `crossReferenceTools(declared, ctx)` splits a skill's declared `tools:` into `usable_tools` vs `unavailable_tools`; `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. Skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). Three ops register in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade): `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax regressions) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K).
@@ -374,7 +377,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, and `run-verify-parallel.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (MIGRATIONS + PGLITE_SCHEMA_SQL are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.
- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — the transaction-mode teardown bug class (#1972/#2015/#2084) reproduced in the local gate instead of only in production. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 regression guards (skills/, untracked files, unmapped src/) — 24 cases.
-- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed.
+- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed.
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
- `AGENTS.md` — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors `CLAUDE.md` intent via relative links. Claude Code keeps using `CLAUDE.md`.
- `docs/UPGRADING_DOWNSTREAM_AGENTS.md` — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.
@@ -566,7 +569,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched.
- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob.
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP).
-- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (`keyless mode: keyword search, agent-authored memory; add ONE key to unlock…`) rendered by verify and the runbook.
+- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.
- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo).
- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index ec30d2b22a..c07f3c8186 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -106,8 +106,9 @@ automatic fact extraction; Voyage unlocks semantic search; Anthropic unlocks
fact extraction (Anthropic has no embeddings API, so it does not enable
semantic search). The key goes to the 0600 config file, never into the repo or
the interview answers. API spend is metered separately from your subscription and is
-zero in keyless mode; with a key, the standard spend gates apply
-([spend-controls](../operations/spend-controls.md)).
+zero in keyless mode; with a key, the embedding spend gates apply
+([spend-controls](../operations/spend-controls.md)) and automatic fact extraction has
+a kill switch (`gbrain config set facts.extraction_enabled false`).
## Security posture
diff --git a/llms-full.txt b/llms-full.txt
index 513d64bdb8..5dc5467791 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1132,14 +1132,18 @@ the playbook at `skills/migrations/v0.46.3.0.md` — one command migrates both.
```bash
export VOYAGE_API_KEY=pa-... # default embedding + reranker (one key covers both)
-export OPENAI_API_KEY=sk-... # alternative for vector search; also used for chat models
-export ANTHROPIC_API_KEY=sk-ant-... # optional, improves search quality via query expansion
+export OPENAI_API_KEY=sk-... # alternative for vector search; also powers automatic fact extraction + chat models
+export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models; also improves search via query expansion
```
Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). Do
-NOT use `gbrain config set` for API keys — it writes the DB plane, which the embedding
+NOT use `gbrain config set` for API keys — it writes the DB plane, which the provider
pipeline never reads. Without any embedding provider, keyword search still works.
-Without Anthropic, search works but skips query expansion.
+Chat-shaped features (automatic fact extraction, enrichment, synthesis, query
+expansion) route to whichever supported chat key is present (Anthropic or OpenAI) —
+Anthropic when both are set, OpenAI when it is the only one; other chat providers
+need an explicit `models.*` pin. With neither key, extraction stays off and memory
+comes from agent-authored `## Facts` fences and the `remember` verb.
## Step 3: Create the Brain
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index cd9514e87e..9b817a6645 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index fdba7d8dc5..7c411f3433 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 057677c978..129f60cd8a 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 39da0c2189..96cd4a2dc9 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index f80106ca68..958c7b7223 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.20.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
index 645a5e96fa..487e856847 100644
--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
@@ -45,6 +45,16 @@ flows through in both directions.
> `put_page` / `add_link` / `add_timeline_entry` stay the page/graph write path.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
+>
+> **Keyless brains:** when `extract_facts` returns `skipped:
+> extraction_unavailable`, YOU are the extractor — pull the facts from the turn
+> yourself and write each one via `remember` with `kind` set (event | preference
+> | commitment | belief) and the visibility the envelope's `agent_action` names
+> (default private — pin it; `remember` defaults to world), or author a
+> `## Facts` fence on the entity page. A `skipped: extraction_failed` envelope
+> (server-side extractor errored on this turn; `reason` names why) invites the
+> same manual `remember` fallback for that turn — automatic extraction stays
+> on for future writes.
## Contract
diff --git a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
index 1740e39f55..8c392ddf81 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
@@ -15,7 +15,17 @@ Four tiers:
| `utility` | fast classification, expansion, verdict, dedup | `claude-haiku-4-5-20251001` | query expansion, facts contradiction classifier, dream triage judge (prefers `models.dream.triage`) |
| `reasoning` | default chat, synthesis, generation | `claude-sonnet-4-6` | gateway chat, dream synthesize, patterns, facts extraction |
| `deep` | slow, expensive reasoning | `claude-opus-4-7` | `gbrain think`, auto-think, cross-modal eval slot B |
-| `subagent` | Anthropic-only multi-turn tool loop | `claude-sonnet-4-6` | `gbrain agent run` |
+| `subagent` | multi-turn tool loop (capability-gated) | `claude-sonnet-4-6` | `gbrain agent run` |
+
+The Default column shows the Anthropic defaults — used when
+`ANTHROPIC_API_KEY` is present (Anthropic wins when both keys exist) and kept
+as the keyless floor. **Tier defaults are key-aware (v0.46.21+):** when
+`OPENAI_API_KEY` is the only chat key, every tier resolves to OpenAI instead —
+the newest usable models discovered from your own account (`GET /v1/models`,
+priced-only, 24h cache at `<configDir>/model-cache.json`,
+`GBRAIN_MODEL_DISCOVERY=off` kill switch), with the openai recipe's ranked
+chat list as the offline floor. OpenAI defaults are never pinned to a model
+id that can go stale.
Override priority (highest first):
@@ -25,13 +35,20 @@ Override priority (highest first):
4. **Global default** (`gbrain config set models.default opus`) — single hammer
5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
6. Env var (`GBRAIN_MODEL=opus`)
-7. Tier default (the table above)
+7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
One exception: the dream triage judge pre-reads `models.dream.triage` first —
when that key is set, it wins over this entire chain (`gbrain models` reports
it as the effective route).
+File-plane pins are a separate seam: the gateway's boot/reconnect fallback
+(and the capability report) resolve the effective chat model as `GBRAIN_MODEL`
+env > servable `chat_model` pin in `~/.gbrain/config.json` (honored only while
+its provider's key is present; an unservable pin warns once and falls through)
+> key-aware tier default. `gbrain init` no longer persists auto-detected chat
+pins (v0.46.21+) — only a pin you set yourself survives reconnect.
+
Power-user recipes:
```bash
@@ -54,12 +71,16 @@ gbrain models # print current routing table
gbrain models doctor # 1-token probe to each configured model
```
-**Subagent tier exists because the loop is Anthropic-only.** The handler
-uses Messages API + prompt caching on system + tools. Setting
-`models.default = openai:gpt-5.5` silently breaks the loop, so we isolate
-`tier.subagent`. Three enforcement layers: submit-time guard in
-`MinionQueue.add`, tier-resolution fallback in `resolveModel`, doctor
-`subagent_provider` check.
+**Subagent tier is isolated because the tool loop has real capability
+requirements.** Since v0.38 the loop is provider-agnostic and gated by
+capability, not provider: a model without tool calling (or an unrecognized
+provider) is refused and falls back to `TIER_DEFAULTS.subagent` with a warn; a
+tool-capable provider without prompt caching (e.g. OpenAI) runs the loop hot
+with a once-per-model cost warn. Setting `models.default = openai:gpt-5.5` no
+longer silently breaks the loop — it runs, at higher per-turn cost. Three
+enforcement layers: submit-time guard in `MinionQueue.add`,
+`enforceSubagentCapable` in `resolveModel`, doctor `subagent_capability`
+check.
When adding a new LLM call, route through `resolveModel()` with a tier —
never hardcode a model string. The v0.31.6 chat default
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 5143dad8c1..ba3c09212f 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index e619e2dfa1..941d9d0470 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.46.20.0",
+ "version": "0.46.21.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index ab881cb3ce..45cb9e3b60 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.20.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
index 1740e39f55..8c392ddf81 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
@@ -15,7 +15,17 @@ Four tiers:
| `utility` | fast classification, expansion, verdict, dedup | `claude-haiku-4-5-20251001` | query expansion, facts contradiction classifier, dream triage judge (prefers `models.dream.triage`) |
| `reasoning` | default chat, synthesis, generation | `claude-sonnet-4-6` | gateway chat, dream synthesize, patterns, facts extraction |
| `deep` | slow, expensive reasoning | `claude-opus-4-7` | `gbrain think`, auto-think, cross-modal eval slot B |
-| `subagent` | Anthropic-only multi-turn tool loop | `claude-sonnet-4-6` | `gbrain agent run` |
+| `subagent` | multi-turn tool loop (capability-gated) | `claude-sonnet-4-6` | `gbrain agent run` |
+
+The Default column shows the Anthropic defaults — used when
+`ANTHROPIC_API_KEY` is present (Anthropic wins when both keys exist) and kept
+as the keyless floor. **Tier defaults are key-aware (v0.46.21+):** when
+`OPENAI_API_KEY` is the only chat key, every tier resolves to OpenAI instead —
+the newest usable models discovered from your own account (`GET /v1/models`,
+priced-only, 24h cache at `<configDir>/model-cache.json`,
+`GBRAIN_MODEL_DISCOVERY=off` kill switch), with the openai recipe's ranked
+chat list as the offline floor. OpenAI defaults are never pinned to a model
+id that can go stale.
Override priority (highest first):
@@ -25,13 +35,20 @@ Override priority (highest first):
4. **Global default** (`gbrain config set models.default opus`) — single hammer
5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
6. Env var (`GBRAIN_MODEL=opus`)
-7. Tier default (the table above)
+7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
One exception: the dream triage judge pre-reads `models.dream.triage` first —
when that key is set, it wins over this entire chain (`gbrain models` reports
it as the effective route).
+File-plane pins are a separate seam: the gateway's boot/reconnect fallback
+(and the capability report) resolve the effective chat model as `GBRAIN_MODEL`
+env > servable `chat_model` pin in `~/.gbrain/config.json` (honored only while
+its provider's key is present; an unservable pin warns once and falls through)
+> key-aware tier default. `gbrain init` no longer persists auto-detected chat
+pins (v0.46.21+) — only a pin you set yourself survives reconnect.
+
Power-user recipes:
```bash
@@ -54,12 +71,16 @@ gbrain models # print current routing table
gbrain models doctor # 1-token probe to each configured model
```
-**Subagent tier exists because the loop is Anthropic-only.** The handler
-uses Messages API + prompt caching on system + tools. Setting
-`models.default = openai:gpt-5.5` silently breaks the loop, so we isolate
-`tier.subagent`. Three enforcement layers: submit-time guard in
-`MinionQueue.add`, tier-resolution fallback in `resolveModel`, doctor
-`subagent_provider` check.
+**Subagent tier is isolated because the tool loop has real capability
+requirements.** Since v0.38 the loop is provider-agnostic and gated by
+capability, not provider: a model without tool calling (or an unrecognized
+provider) is refused and falls back to `TIER_DEFAULTS.subagent` with a warn; a
+tool-capable provider without prompt caching (e.g. OpenAI) runs the loop hot
+with a once-per-model cost warn. Setting `models.default = openai:gpt-5.5` no
+longer silently breaks the loop — it runs, at higher per-turn cost. Three
+enforcement layers: submit-time guard in `MinionQueue.add`,
+`enforceSubagentCapable` in `resolveModel`, doctor `subagent_capability`
+check.
When adding a new LLM call, route through `resolveModel()` with a tier —
never hardcode a model string. The v0.31.6 chat default
diff --git a/plugin/README.md b/plugin/README.md
index 7f4e84465b..9159021adf 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.20.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.md
index 645a5e96fa..487e856847 100644
--- a/plugin/skills/brain-ops/SKILL.md
+++ b/plugin/skills/brain-ops/SKILL.md
@@ -45,6 +45,16 @@ flows through in both directions.
> `put_page` / `add_link` / `add_timeline_entry` stay the page/graph write path.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
+>
+> **Keyless brains:** when `extract_facts` returns `skipped:
+> extraction_unavailable`, YOU are the extractor — pull the facts from the turn
+> yourself and write each one via `remember` with `kind` set (event | preference
+> | commitment | belief) and the visibility the envelope's `agent_action` names
+> (default private — pin it; `remember` defaults to world), or author a
+> `## Facts` fence on the entity page. A `skipped: extraction_failed` envelope
+> (server-side extractor errored on this turn; `reason` names why) invites the
+> same manual `remember` fallback for that turn — automatic extraction stays
+> on for future writes.
## Contract
diff --git a/plugin/skills/conventions/model-routing.md b/plugin/skills/conventions/model-routing.md
index 1740e39f55..8c392ddf81 100644
--- a/plugin/skills/conventions/model-routing.md
+++ b/plugin/skills/conventions/model-routing.md
@@ -15,7 +15,17 @@ Four tiers:
| `utility` | fast classification, expansion, verdict, dedup | `claude-haiku-4-5-20251001` | query expansion, facts contradiction classifier, dream triage judge (prefers `models.dream.triage`) |
| `reasoning` | default chat, synthesis, generation | `claude-sonnet-4-6` | gateway chat, dream synthesize, patterns, facts extraction |
| `deep` | slow, expensive reasoning | `claude-opus-4-7` | `gbrain think`, auto-think, cross-modal eval slot B |
-| `subagent` | Anthropic-only multi-turn tool loop | `claude-sonnet-4-6` | `gbrain agent run` |
+| `subagent` | multi-turn tool loop (capability-gated) | `claude-sonnet-4-6` | `gbrain agent run` |
+
+The Default column shows the Anthropic defaults — used when
+`ANTHROPIC_API_KEY` is present (Anthropic wins when both keys exist) and kept
+as the keyless floor. **Tier defaults are key-aware (v0.46.21+):** when
+`OPENAI_API_KEY` is the only chat key, every tier resolves to OpenAI instead —
+the newest usable models discovered from your own account (`GET /v1/models`,
+priced-only, 24h cache at `<configDir>/model-cache.json`,
+`GBRAIN_MODEL_DISCOVERY=off` kill switch), with the openai recipe's ranked
+chat list as the offline floor. OpenAI defaults are never pinned to a model
+id that can go stale.
Override priority (highest first):
@@ -25,13 +35,20 @@ Override priority (highest first):
4. **Global default** (`gbrain config set models.default opus`) — single hammer
5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
6. Env var (`GBRAIN_MODEL=opus`)
-7. Tier default (the table above)
+7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
One exception: the dream triage judge pre-reads `models.dream.triage` first —
when that key is set, it wins over this entire chain (`gbrain models` reports
it as the effective route).
+File-plane pins are a separate seam: the gateway's boot/reconnect fallback
+(and the capability report) resolve the effective chat model as `GBRAIN_MODEL`
+env > servable `chat_model` pin in `~/.gbrain/config.json` (honored only while
+its provider's key is present; an unservable pin warns once and falls through)
+> key-aware tier default. `gbrain init` no longer persists auto-detected chat
+pins (v0.46.21+) — only a pin you set yourself survives reconnect.
+
Power-user recipes:
```bash
@@ -54,12 +71,16 @@ gbrain models # print current routing table
gbrain models doctor # 1-token probe to each configured model
```
-**Subagent tier exists because the loop is Anthropic-only.** The handler
-uses Messages API + prompt caching on system + tools. Setting
-`models.default = openai:gpt-5.5` silently breaks the loop, so we isolate
-`tier.subagent`. Three enforcement layers: submit-time guard in
-`MinionQueue.add`, tier-resolution fallback in `resolveModel`, doctor
-`subagent_provider` check.
+**Subagent tier is isolated because the tool loop has real capability
+requirements.** Since v0.38 the loop is provider-agnostic and gated by
+capability, not provider: a model without tool calling (or an unrecognized
+provider) is refused and falls back to `TIER_DEFAULTS.subagent` with a warn; a
+tool-capable provider without prompt caching (e.g. OpenAI) runs the loop hot
+with a once-per-model cost warn. Setting `models.default = openai:gpt-5.5` no
+longer silently breaks the loop — it runs, at higher per-turn cost. Three
+enforcement layers: submit-time guard in `MinionQueue.add`,
+`enforceSubagentCapable` in `resolveModel`, doctor `subagent_capability`
+check.
When adding a new LLM call, route through `resolveModel()` with a tier —
never hardcode a model string. The v0.31.6 chat default
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 5890c692fd..75d781113b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,29 +3,29 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/commands/doctor.ts 4270 ratchet peel target: containment sprint C8-C13; grown v0.46.11.0 five-issue wave
+src/commands/doctor.ts 4291 ratchet peel target: containment sprint C8-C13; grown v0.46.x keyless not_configured state
src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
src/core/postgres-engine.ts 5816 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave
src/core/pglite-engine.ts 5744 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wave
-src/core/ai/gateway.ts 4364 ratchet watchlist; merged: master waves + dream-wave C1-C3+C7 (thinking predicate, length, providerMetadata, turn permits) + TurnPermit signal form
+src/core/ai/gateway.ts 4428 ratchet watchlist; merged: dream-wave turn permits + key-aware effective-model reconfigure + env-only worker refresh + discovery endpoint-trust docstring
src/cli.ts 3482 ratchet watchlist; merged unions: cathedral-5 compile-context wiring + gap-closure thin-client routing + cathedral-6 register guards + sources self-help
src/core/cycle.ts 3080 ratchet grown v0.46.20.0 phase-boundary split (resolveCyclePhases + normalizeQueuedSourcePhases + deriveStatus exclusion filter)
src/commands/serve-http.ts 2978 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight) + chennai no-grant federated scope
-src/commands/jobs.ts 2960 ratchet grown v0.46.20.0 queue-boundary phase normalization (per-source + maintenance handlers)
+src/commands/jobs.ts 3015 ratchet merged: v0.46.20.0 queue-boundary phase normalization + facts-absorb refresh/retry conversion
src/core/search/hybrid.ts 2500 ratchet
src/core/engine.ts 2345 ratchet
src/commands/autopilot.ts 2301 ratchet
src/commands/extract.ts 2161 ratchet
-src/commands/extract-conversation-facts.ts 2032 ratchet
+src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copy
src/core/import-file.ts 2000 ratchet grown v0.46.11.0 five-issue wave
src/core/cycle/synthesize.ts 2702 ratchet merged: five-issue wave + dream-wave C7 peel + C8 manifest + C9 mode/telemetry/backfill + adversarial fix batches
src/commands/embed.ts 1963 ratchet
src/core/types.ts 1863 ratchet
src/commands/skillpack.ts 1360 ratchet
src/core/minions/queue.ts 2130 ratchet grown v0.46.11.0 five-issue wave
-src/commands/init.ts 1932 ratchet
+src/commands/init.ts 1950 ratchet grown v0.46.x keyless capability notices
src/commands/integrations.ts 1675 ratchet
src/core/minions/handlers/subagent.ts 1818 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches
src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 1500 cap on master)
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index c993034312..346b969705 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -54,6 +54,11 @@ fi
# bare `bun test` runs while DATABASE_URL/GBRAIN_DATABASE_URL is ambient; the
# per-file name floor (test/helpers/db-guard.ts) still applies after this.
export GBRAIN_TEST_ALLOW_DATABASE_URL=1
+# Provider keys: the unit-lane preload (provider-keys-preload.ts) strips
+# ambient ANTHROPIC/OPENAI keys for keyless-CI parity; e2e is the lane where
+# real keys are deliberate (live embed/parity tests skip-gate on them), so
+# opt back in at this boundary.
+export GBRAIN_TEST_KEEP_PROVIDER_KEYS=1
# The e2e suite runs on DATABASE_URL only; an ambient GBRAIN_DATABASE_URL
# would pass the opt-in yet reach CLI-subprocess paths with no name floor —
# drop it here so only the floored variable crosses the boundary.
@@ -111,6 +116,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPEN
GBRAIN_HOME) ;; # required for HOME isolation (set above) — keep
GBRAIN_PGLITE_SNAPSHOT) ;; # snapshot fast-path fixture (exported by ci-local.sh / runners) — keep
GBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keep
+ GBRAIN_TEST_KEEP_PROVIDER_KEYS) ;; # provider-keys preload opt-in (set above) — keep
GBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive it
GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error
# message tells operators to set it; stripping it
diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.md
index 645a5e96fa..487e856847 100644
--- a/skills/brain-ops/SKILL.md
+++ b/skills/brain-ops/SKILL.md
@@ -45,6 +45,16 @@ flows through in both directions.
> `put_page` / `add_link` / `add_timeline_entry` stay the page/graph write path.
> Fall back to the classic ops when the verbs aren't on the surface. Contract:
> `docs/protocol/MEMORY_VERBS_v1.md`.
+>
+> **Keyless brains:** when `extract_facts` returns `skipped:
+> extraction_unavailable`, YOU are the extractor — pull the facts from the turn
+> yourself and write each one via `remember` with `kind` set (event | preference
+> | commitment | belief) and the visibility the envelope's `agent_action` names
+> (default private — pin it; `remember` defaults to world), or author a
+> `## Facts` fence on the entity page. A `skipped: extraction_failed` envelope
+> (server-side extractor errored on this turn; `reason` names why) invites the
+> same manual `remember` fallback for that turn — automatic extraction stays
+> on for future writes.
## Contract
diff --git a/skills/conventions/model-routing.md b/skills/conventions/model-routing.md
index 1740e39f55..8c392ddf81 100644
--- a/skills/conventions/model-routing.md
+++ b/skills/conventions/model-routing.md
@@ -15,7 +15,17 @@ Four tiers:
| `utility` | fast classification, expansion, verdict, dedup | `claude-haiku-4-5-20251001` | query expansion, facts contradiction classifier, dream triage judge (prefers `models.dream.triage`) |
| `reasoning` | default chat, synthesis, generation | `claude-sonnet-4-6` | gateway chat, dream synthesize, patterns, facts extraction |
| `deep` | slow, expensive reasoning | `claude-opus-4-7` | `gbrain think`, auto-think, cross-modal eval slot B |
-| `subagent` | Anthropic-only multi-turn tool loop | `claude-sonnet-4-6` | `gbrain agent run` |
+| `subagent` | multi-turn tool loop (capability-gated) | `claude-sonnet-4-6` | `gbrain agent run` |
+
+The Default column shows the Anthropic defaults — used when
+`ANTHROPIC_API_KEY` is present (Anthropic wins when both keys exist) and kept
+as the keyless floor. **Tier defaults are key-aware (v0.46.21+):** when
+`OPENAI_API_KEY` is the only chat key, every tier resolves to OpenAI instead —
+the newest usable models discovered from your own account (`GET /v1/models`,
+priced-only, 24h cache at `<configDir>/model-cache.json`,
+`GBRAIN_MODEL_DISCOVERY=off` kill switch), with the openai recipe's ranked
+chat list as the offline floor. OpenAI defaults are never pinned to a model
+id that can go stale.
Override priority (highest first):
@@ -25,13 +35,20 @@ Override priority (highest first):
4. **Global default** (`gbrain config set models.default opus`) — single hammer
5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
6. Env var (`GBRAIN_MODEL=opus`)
-7. Tier default (the table above)
+7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
One exception: the dream triage judge pre-reads `models.dream.triage` first —
when that key is set, it wins over this entire chain (`gbrain models` reports
it as the effective route).
+File-plane pins are a separate seam: the gateway's boot/reconnect fallback
+(and the capability report) resolve the effective chat model as `GBRAIN_MODEL`
+env > servable `chat_model` pin in `~/.gbrain/config.json` (honored only while
+its provider's key is present; an unservable pin warns once and falls through)
+> key-aware tier default. `gbrain init` no longer persists auto-detected chat
+pins (v0.46.21+) — only a pin you set yourself survives reconnect.
+
Power-user recipes:
```bash
@@ -54,12 +71,16 @@ gbrain models # print current routing table
gbrain models doctor # 1-token probe to each configured model
```
-**Subagent tier exists because the loop is Anthropic-only.** The handler
-uses Messages API + prompt caching on system + tools. Setting
-`models.default = openai:gpt-5.5` silently breaks the loop, so we isolate
-`tier.subagent`. Three enforcement layers: submit-time guard in
-`MinionQueue.add`, tier-resolution fallback in `resolveModel`, doctor
-`subagent_provider` check.
+**Subagent tier is isolated because the tool loop has real capability
+requirements.** Since v0.38 the loop is provider-agnostic and gated by
+capability, not provider: a model without tool calling (or an unrecognized
+provider) is refused and falls back to `TIER_DEFAULTS.subagent` with a warn; a
+tool-capable provider without prompt caching (e.g. OpenAI) runs the loop hot
+with a once-per-model cost warn. Setting `models.default = openai:gpt-5.5` no
+longer silently breaks the loop — it runs, at higher per-turn cost. Three
+enforcement layers: submit-time guard in `MinionQueue.add`,
+`enforceSubagentCapable` in `resolveModel`, doctor `subagent_capability`
+check.
When adding a new LLM call, route through `resolveModel()` with a tier —
never hardcode a model string. The v0.31.6 chat default
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7c9a96d801..36d8bf8357 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -20,7 +20,7 @@
"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33",
"brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae",
"brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",
- "brain-ops/SKILL.md": "373a08c1d1228c134403876f1716ca9ac3c78e29cb39cee50f9f540dce6f8581",
+ "brain-ops/SKILL.md": "56bdac549eb45849668a7d1b911f758c793ea17ff224779dd32afc035f7ef87b",
"brain-pdf/SKILL.md": "13c3e3162763a4503685db0a10663475d3687c4874b5f04d539af83a990f643e",
"brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734",
"brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60",
@@ -48,7 +48,7 @@
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
"conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",
- "conventions/model-routing.md": "8b28aa706436e7b68493ec481e12be6309b0af1a553930e8b1029d675fa4b3ad",
+ "conventions/model-routing.md": "a8d2010b3cf59d45812e9e744470cfc4426b8928ddae1ce312443e352b976685",
"conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954",
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index eedf896d44..e1e7d8df78 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -3292,11 +3292,46 @@ export async function buildChecks(
);
if (rows.length === 0) {
- checks.push({
- name: 'facts_extraction_health',
- status: 'ok',
- message: 'No facts:absorb failures in the last 24h.',
- });
+ // Zero failure rows is only "healthy" when extraction is actually
+ // configured. Keyless installs deliberately write NO absorb rows (the
+ // calm expected state) — reporting "ok: no failures" there would read
+ // as extraction-healthy while extraction never runs. Doctor HOLDS the
+ // engine, so probe the ACTUAL resolved extraction model (sees DB-plane
+ // facts.extraction_model / models.* overrides the engine-blind
+ // detectCapabilities() cannot) — the same gate the runtime uses.
+ const { getFactsExtractionModel } = await import('../core/facts/extract.ts');
+ const { isAvailable } = await import('../core/ai/gateway.ts');
+ const extractionAvailable = isAvailable('chat', await getFactsExtractionModel(engine));
+ if (!extractionAvailable) {
+ // Keyless vs keyed-but-misrouted split (same classification the
+ // backstop uses): a quiet keyed brain whose pinned extraction model
+ // lost its key must NOT read as calm "(keyless)" — that masks a
+ // fixable misconfiguration.
+ const { KEYLESS_EXTRACTION_GUIDANCE, classifyUnavailable } = await import('../core/facts/backstop.ts');
+ const { getFactsExtractionModel } = await import('../core/facts/extract.ts');
+ const unavailableModel = await getFactsExtractionModel(engine);
+ if ((await classifyUnavailable(unavailableModel)) === 'keyed') {
+ checks.push({
+ name: 'facts_extraction_health',
+ status: 'warn',
+ message:
+ `Automatic fact extraction is misconfigured: resolved model ${unavailableModel} has no usable ` +
+ `provider key. Fix: set the provider's API key, or \`gbrain config set facts.extraction_model <provider:model>\`.`,
+ });
+ } else {
+ checks.push({
+ name: 'facts_extraction_health',
+ status: 'ok',
+ message: `Automatic fact extraction not configured (keyless) — ${KEYLESS_EXTRACTION_GUIDANCE}`,
+ });
+ }
+ } else {
+ checks.push({
+ name: 'facts_extraction_health',
+ status: 'ok',
+ message: 'No facts:absorb failures in the last 24h.',
+ });
+ }
} else {
// Group per source so the breakdown is operator-friendly.
const bySource = new Map<string, Array<{ reason: string; n: number }>>();
diff --git a/src/commands/enrich.ts b/src/commands/enrich.ts
index da59c59d63..a6bfa2ec2d 100644
--- a/src/commands/enrich.ts
+++ b/src/commands/enrich.ts
@@ -811,7 +811,11 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<vo
// reporting an availability error (#2590).
if (!parsed.dryRun && !isAvailable('chat')) configureGatewayIfUninitialized();
if (!parsed.dryRun && !isAvailable('chat')) {
- console.error('Chat gateway unavailable. Configure a chat model (e.g. `gbrain config set chat_model anthropic:claude-haiku-4-5`), or pass --dry-run to preview candidates.');
+ console.error(
+ 'Chat gateway unavailable. Set a provider key (OPENAI_API_KEY or ANTHROPIC_API_KEY — ' +
+ 'chat routes to whichever is present), or configure a model explicitly ' +
+ '(`gbrain config set models.chat <provider:model>`), or pass --dry-run to preview candidates.',
+ );
process.exit(1);
}
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 033aefb6aa..02e70e0a63 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1870,7 +1870,13 @@ export async function runExtractConversationFacts(
// reporting an availability error (#2590).
if (!parsed.dryRun && !isAvailable('chat')) configureGatewayIfUninitialized();
if (!parsed.dryRun && !isAvailable('chat')) {
- console.error('Chat gateway unavailable. Configure an Anthropic or compatible chat model, or pass --dry-run to preview segmentation.');
+ console.error(
+ 'Chat gateway unavailable. Set a provider key (OPENAI_API_KEY or ANTHROPIC_API_KEY — ' +
+ 'extraction routes to whichever is present), or configure a model explicitly ' +
+ '(`gbrain config set facts.extraction_model <provider:model>`), or pass --dry-run to ' +
+ 'preview segmentation. Keyless brains capture memory via agent-authored `## Facts` ' +
+ 'fences and the `remember` verb instead.',
+ );
process.exit(1);
}
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 0b3f4ad9cf..1b1ba354be 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -539,9 +539,10 @@ function printNoEmbeddingProviderHint(typos: Array<{ userSet: string; suggested:
console.error(' (enable semantic search later by re-running with a key:');
console.error(' gbrain init --force --pglite --embedding-model <id>)');
console.error('');
- console.error('Or set a key for semantic search:');
- console.error(' export VOYAGE_API_KEY=pa-… # voyage:voyage-4 (1024d) — default');
- console.error(' export OPENAI_API_KEY=sk-… # openai:text-embedding-3-large (1536d)');
+ console.error('Or set a key to upgrade capabilities:');
+ console.error(' export VOYAGE_API_KEY=pa-… # semantic search (voyage:voyage-4, 1024d) — default');
+ console.error(' export OPENAI_API_KEY=sk-… # semantic search (1536d) + automatic fact extraction');
+ console.error(' export ANTHROPIC_API_KEY=sk-ant-… # automatic fact extraction (no embeddings API)');
console.error('Then re-run: gbrain init --pglite');
console.error('');
console.error('Or pick explicitly:');
@@ -617,9 +618,12 @@ async function writeNewInstallRerankerDefault(
* (it would be a silent no-op), so pointing users there is a dead end. */
function printKeylessContinueNotice(): void {
console.error(
- 'No embedding provider keys detected — continuing in keyless mode:\n' +
+ 'No provider keys detected — continuing in keyless mode:\n' +
' keyword search + memory your agent writes down itself. Everything works.\n' +
- ' One optional key upgrades search to semantic — set the key, then re-run\n' +
+ ' One optional key upgrades capabilities — OpenAI: semantic search + automatic\n' +
+ ' fact extraction; Voyage: semantic search; Anthropic: fact extraction.\n' +
+ ' Fact extraction activates as soon as the key is set (no re-init); semantic\n' +
+ ' search needs a re-run:\n' +
' `gbrain init --force --pglite --embedding-model <id>` (re-imports via `gbrain sync`).',
);
}
@@ -822,21 +826,33 @@ async function resolveExpansionByEnv(out: ResolvedAIOptions): Promise<void> {
// and falls back gracefully at call time when key isn't set.
}
-async function resolveChatByEnv(out: ResolvedAIOptions): Promise<void> {
+/** @internal exported for tests — pins the no-persist contract (key-aware
+ * runtime resolution replaced install-time chat_model pins). */
+export 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.`);
+ // Deliberately does NOT write out.chat_model: key-aware tier defaults
+ // (model-config.ts resolveTierDefault + resolveEffectiveChatModel)
+ // route chat/extraction to this provider at runtime, and a persisted
+ // install-time pin freezes the provider choice — it goes stale the
+ // moment the user switches keys. Detection stays for the init summary;
+ // the displayed model is the same resolution the runtime will use
+ // (discovered-latest for OpenAI, recipe entry otherwise).
+ const { resolveTierDefault } = await import('../core/model-config.ts');
+ const effective = resolveTierDefault('reasoning');
+ const shown = effective.startsWith(`${r.id}:`) ? effective : `${r.id}:${tp.models[0]}`;
+ console.error(
+ `Detected ${r.auth_env?.required?.[0] ?? r.id} env var. Chat + fact extraction will use ` +
+ `${shown} (key-aware default; nothing written to config).`,
+ );
}
}
- // 0 or >1 → silent: gateway default (`anthropic:claude-sonnet-4-6`) wins.
+ // 0 or >1 → silent: the key-aware tier default wins at runtime.
// 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).
+ // via classifyCapabilities regardless of the chat_model setting.
}
/**
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 879df3075d..69a90786d7 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -4,6 +4,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
+import type { FactsBackstopResult } from '../core/facts/backstop.ts';
// Leaf module (no flag surface of its own) — see that file for why this
// isn't imported from extract-conversation-facts.ts directly (#4135).
import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';
@@ -46,16 +47,54 @@ export function resolveJobPull(data: Record<string, unknown>): boolean {
* from DB-backed model config immediately before queued jobs enter gateway-backed
* paths, so a stale process-level default cannot route new work to the wrong
* provider.
+ *
+ * Three staleness tiers (documented in KEY_FILES's refreshGatewayForJob entry):
+ * - DB-plane model config: re-resolved here (reconfigureGatewayWithEngine).
+ * - FILE-plane config (`~/.gbrain/config.json` — incl. provider API keys):
+ * re-folded here, so a key added to config.json reaches the worker at the
+ * next job. NOTE `gbrain config set *_api_key` writes the DB plane, which
+ * loadConfigWithEngine deliberately never merges for key fields — routing
+ * those writes to the file plane is a filed TODO.
+ * - True process env vars: fixed at worker start; need a restart.
*/
-async function refreshGatewayForJob(engine: BrainEngine): Promise<void> {
- const { reconfigureGatewayWithEngine } = await import('../core/ai/gateway.ts');
+export async function refreshGatewayForJob(engine: BrainEngine): Promise<void> {
+ // Env-only refresh: a full configureGateway(buildGatewayConfig(loadConfig()))
+ // would clobber the DB-plane-merged fields the worker's boot fold installed
+ // (provider_base_urls, chat options, …) with file-plane-only values.
+ const { refreshGatewayEnvFromFilePlane, reconfigureGatewayWithEngine } = await import('../core/ai/gateway.ts');
+ refreshGatewayEnvFromFilePlane();
await reconfigureGatewayWithEngine(engine);
}
+/** Shared predicate: an inline result reporting execution-time unavailability. */
+export function factsAbsorbUnavailable(result: FactsBackstopResult): boolean {
+ return (
+ result.mode === 'inline' &&
+ (result.skipped === 'extraction_unavailable' || result.skipped_reason === 'chat_unavailable')
+ );
+}
+
+/**
+ * The facts-absorb retry decision (@internal exported for tests). A job that
+ * finds chat unavailable at EXECUTION in a KEYED worker is config drift — it
+ * must throw (retry/backoff → visible, re-runnable failure), never return
+ * success and silently consume the job. A KEYLESS worker executing a job
+ * enqueued by some other process is the steady expected state — completing
+ * as a calm skip (the execution-time gate already printed the keyless note)
+ * beats a retry loop that parks every page write as a failed job.
+ */
+export function factsAbsorbShouldRetry(
+ result: FactsBackstopResult,
+ classification: 'keyed' | 'keyless',
+): boolean {
+ return classification === 'keyed' && factsAbsorbUnavailable(result);
+}
+
const GATEWAY_REFRESH_JOB_NAMES = new Set([
'embed',
'extract-conversation-facts',
'enrich',
+ 'facts-absorb',
'contextual_reindex_per_chunk',
'autopilot-cycle',
'synthesize',
@@ -2339,8 +2378,10 @@ export async function registerBuiltinHandlers(
// drain aborts it, so backstop.ts submits this job instead and the
// long-lived worker does the LLM work here. Inline mode: errors throw,
// so minion retry/backoff handles transient gateway failures and real
- // failures stay visible in `gbrain jobs list --status failed`.
- worker.register('facts-absorb', async (job) => {
+ // failures stay visible in `gbrain jobs list --status failed`. In the
+ // gateway-refresh set so the worker re-stamps model config (and re-folds
+ // file-plane keys) before every extraction job.
+ registerBuiltinJob(worker, engine, 'facts-absorb', async (job) => {
const slug = typeof job.data.slug === 'string' ? job.data.slug : '';
if (!slug) throw new Error('facts-absorb job requires data.slug');
const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : 'default';
@@ -2351,7 +2392,7 @@ export async function registerBuiltinHandlers(
const source = (KNOWN_SOURCES as readonly string[]).includes(job.data.source as string)
? (job.data.source as typeof KNOWN_SOURCES[number])
: 'mcp:put_page';
- return await runFactsBackstop(
+ const result = await runFactsBackstop(
{
slug: page.slug,
type: page.type,
@@ -2369,6 +2410,26 @@ export async function registerBuiltinHandlers(
...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),
},
);
+ // Execution-time chat_unavailable in a KEYED worker is config drift —
+ // throw (typed) so minion retry/backoff parks it as a VISIBLE, re-runnable
+ // failure instead of consuming the job and silently losing the facts. A
+ // KEYLESS worker completes the job as a calm skip (its execution-time
+ // gate already printed the keyless note; a retry loop would turn every
+ // page write into failed-job noise). The retry conversion lives HERE, not
+ // in the shared pipeline — the same pipeline serves the extract_facts op,
+ // which must return its keyless envelope instead of throwing. The
+ // classification runs in the WORKER process: availability decisions
+ // belong to the process that executes (the submitting hook subprocess may
+ // have a deliberately neutered env).
+ if (factsAbsorbUnavailable(result)) {
+ const { classifyUnavailable } = await import('../core/facts/backstop.ts');
+ const jobModel = typeof job.data.model === 'string' && job.data.model ? job.data.model : undefined;
+ if (factsAbsorbShouldRetry(result, await classifyUnavailable(jobModel))) {
+ const { FactsExtractionError } = await import('../core/facts/extract.ts');
+ throw new FactsExtractionError('chat_unavailable', jobModel);
+ }
+ }
+ return result;
});
// Autopilot-cycle handler: delegates to runCycle. Shares the exact same
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index 9a4aeae0a3..905284448f 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -18,51 +18,14 @@
import type { GBrainConfig } from '../config.ts';
import type { AIGatewayConfig } from './types.ts';
+import { mergedProviderEnv } from './provider-env.ts';
export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
- // v0.32 (#121 reworked): when ~/.gbrain/config.json declares
- // openai_api_key / anthropic_api_key, fold them into the gateway env so
- // recipes that read OPENAI_API_KEY / ANTHROPIC_API_KEY find them. Process
- // env still wins (it's loaded last) — this is a fallback for daemons /
- // launchd-spawned subprocesses that don't propagate ~/.zshrc-sourced keys.
- const envFromConfig: Record<string, string> = {};
- if (c.openai_api_key) envFromConfig.OPENAI_API_KEY = c.openai_api_key;
- if (c.anthropic_api_key) envFromConfig.ANTHROPIC_API_KEY = c.anthropic_api_key;
- // v0.37 fix wave (CDX2-5+6): ZE became the default provider in v0.36 but
- // the env-mapping at this seam never picked it up. `gbrain config set
- // zeroentropy_api_key X` wrote DB plane (ignored by gateway). The file-
- // plane field now exists (GBrainConfig type) and gets mapped here, so
- // setting it via `~/.gbrain/config.json` propagates into the gateway.
- if (c.zeroentropy_api_key) envFromConfig.ZEROENTROPY_API_KEY = c.zeroentropy_api_key;
- // Same seam for OpenRouter: `gbrain config set openrouter_api_key X` (or
- // config.json) must reach the openrouter recipe's OPENROUTER_API_KEY.
- // process.env still wins via the later spread.
- if (c.openrouter_api_key) envFromConfig.OPENROUTER_API_KEY = c.openrouter_api_key;
- // #2662: same seam for Voyage. Before this, config.json's voyage_api_key
- // was accepted at the file plane but never threaded into the gateway env,
- // so launchd/daemon/MCP contexts (no process-env export) silently failed
- // multimodal/image embeds despite config.json looking complete. process.env
- // still wins via the later spread.
- if (c.voyage_api_key) envFromConfig.VOYAGE_API_KEY = c.voyage_api_key;
- // #3500: same seam for DashScope. The dashscope + dashscope-rerank recipes
- // require DASHSCOPE_API_KEY, but the config-plane key was never folded, so
- // daemon/launchd/MCP contexts with no process-env export failed auth
- // despite config.json looking complete. process.env still wins via the
- // later spread.
- if (c.dashscope_api_key) envFromConfig.DASHSCOPE_API_KEY = c.dashscope_api_key;
- // #3500: same seam for Google Gemini. The google recipe reads
- // GOOGLE_GENERATIVE_AI_API_KEY; before this fold, the ONLY way to
- // configure Gemini was exporting that exact env var. (This closes the
- // deferral noted in src/core/brain-score-recommendations.ts, whose
- // HOSTED_EMBED_KEY_CONFIG entry lands in the same change.)
- if (c.google_api_key) envFromConfig.GOOGLE_GENERATIVE_AI_API_KEY = c.google_api_key;
- // Azure OpenAI (keyless/Entra): fold the non-secret endpoint/deployment + the
- // Entra opt-in into the gateway env so the azure-openai recipe works in any
- // shell (incl. non-interactive agent shells). The bearer token is minted at
- // request time via `az`; no secret is stored in config.json.
- if (c.azure_openai_endpoint) envFromConfig.AZURE_OPENAI_ENDPOINT = c.azure_openai_endpoint;
- if (c.azure_openai_deployment) envFromConfig.AZURE_OPENAI_DEPLOYMENT = c.azure_openai_deployment;
- if (c.azure_openai_use_entra) envFromConfig.AZURE_OPENAI_USE_ENTRA = c.azure_openai_use_entra;
+ // The file-plane key fold + env merge live in mergedProviderEnv
+ // (src/core/ai/provider-env.ts) — the single canonical mapping shared with
+ // detectCapabilities and the key-aware model resolution. Config keys are a
+ // fallback for daemons / launchd-spawned subprocesses that don't propagate
+ // ~/.zshrc-sourced keys; process env wins for keys carrying a real value.
// v0.32 codex finding #4+#5 fix: thread local-server _BASE_URL env vars
// into base_urls so the gateway hits the user's configured port. Without
@@ -91,33 +54,7 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
chat_fallback_chain: c.chat_fallback_chain,
base_urls: { ...envBaseUrls, ...(c.provider_base_urls ?? {}) }, // config wins over env
provider_chat_options: c.provider_chat_options,
- // #1249: process.env still wins over the config-plane fallback, BUT only for
- // keys that carry a real value. Claude Code (and some launchers) inject
- // ANTHROPIC_API_KEY='' to neuter subprocess LLM calls; an unconditional
- // `...process.env` lets that empty string clobber a valid config.json key, so
- // every gateway op then throws NO_ANTHROPIC_API_KEY. Drop empty-string /
- // undefined entries before the merge. Only '' and undefined are dropped —
- // '0' and 'false' are legitimate values and survive.
- env: buildEnv(envFromConfig),
+ // #1249 empty-string drop + GEMINI alias applied inside mergedProviderEnv.
+ env: mergedProviderEnv(c, process.env),
};
}
-
-/**
- * Merge config-plane fallbacks with process.env (env wins for keys carrying a
- * real value — see #1249 note above), then apply the GEMINI_API_KEY alias:
- * Google's own docs/SDKs export GEMINI_API_KEY, but the google recipe (and
- * every gateway read site) uses GOOGLE_GENERATIVE_AI_API_KEY. Precedence:
- * env GOOGLE_GENERATIVE_AI_API_KEY > env GEMINI_API_KEY > config
- * google_api_key — i.e. the alias is still process-env, so it beats the
- * config-plane fallback, but never the canonical env name.
- */
-function buildEnv(envFromConfig: Record<string, string>): Record<string, string> {
- const envReal = Object.fromEntries(
- Object.entries(process.env).filter(([, v]) => v !== undefined && v !== ''),
- ) as Record<string, string>;
- const merged = { ...envFromConfig, ...envReal };
- if (!envReal.GOOGLE_GENERATIVE_AI_API_KEY && envReal.GEMINI_API_KEY) {
- merged.GOOGLE_GENERATIVE_AI_API_KEY = envReal.GEMINI_API_KEY;
- }
- return merged;
-}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index bca106c37e..2989f94f1e 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -51,7 +51,7 @@ import {
OPENROUTER_CACHE_HEADER,
openrouterRequiresExplicitPromptCache,
} from './recipes/openrouter.ts';
-import { resolveModel } from '../model-config.ts';
+import { resolveModel, resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';
import { parseLlmJson } from '../llm-json.ts';
import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
@@ -59,6 +59,8 @@ import { hasAnthropicKey } from './anthropic-key.ts';
import { AIConfigError, AITransientError, normalizeAIError } from './errors.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
import { loadConfig } from '../config.ts';
+import type { GBrainConfig } from '../config.ts';
+import { mergedProviderEnv } from './provider-env.ts';
import { buildGatewayConfig } from './build-gateway-config.ts';
// ---- Gateway-wide AI-HTTP timeout (v0.42.20.0, #1762/#1775) ----
@@ -483,6 +485,26 @@ export function configureGateway(config: AIGatewayConfig): void {
warnRecipesMissingBatchTokens();
}
+/**
+ * Re-fold ONLY the provider-key env from the file plane + process env into the
+ * LIVE gateway config, leaving models/base_urls/chat-options untouched. For
+ * long-lived workers: a key added to ~/.gbrain/config.json reaches the gateway
+ * at the next job without clobbering the DB-plane-merged fields the worker's
+ * boot fold installed (a full configureGateway(buildGatewayConfig(loadConfig()))
+ * here would reset those to file-plane-only values). No-op before configure.
+ */
+export function refreshGatewayEnvFromFilePlane(): void {
+ if (!_config) return;
+ let cfg: GBrainConfig | null = null;
+ try {
+ cfg = loadConfig();
+ } catch {
+ cfg = null;
+ }
+ _config = { ..._config, env: mergedProviderEnv(cfg, process.env) };
+ _modelCache.clear();
+}
+
/**
* v0.31.12 — async re-stamp seam.
*
@@ -504,20 +526,62 @@ export function configureGateway(config: AIGatewayConfig): void {
*/
export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promise<AIGatewayConfig> {
const cfg = requireConfig();
+ // Refresh the OpenAI latest-model discovery cache BEFORE resolution so the
+ // key-aware tier defaults below see it. TTL-throttled (one fetch/24h),
+ // 3s-bounded, fail-open, disabled in test lanes via GBRAIN_MODEL_DISCOVERY
+ // — a connect never blocks on or breaks from discovery.
+ const { refreshLatestOpenAIModels } = await import('./openai-latest.ts');
+ // Discovery hits the same endpoint real native-openai calls use:
+ // OPENAI_BASE_URL via resolveNativeBaseUrl — the ENV PLANE, deliberately
+ // NOT cfg.base_urls.openai. Two reasons: (1) defaulting to api.openai.com
+ // when a custom endpoint is configured would send that endpoint's key to
+ // the official host; (2) base_urls can be DB-plane-merged from a mounted
+ // brain, and discovery fires automatically on connect — a hostile shared
+ // brain must never be able to point this process's bearer key at an
+ // attacker URL (native chat calls ignore base_urls for the same reason).
+ await refreshLatestOpenAIModels({
+ env: cfg.env ?? process.env,
+ baseUrl: resolveNativeBaseUrl('openai', cfg),
+ });
// Resolve expansion (utility tier) and chat (reasoning tier). Embedding is
// intentionally NOT re-resolved here — switching embedding models invalidates
// the vector index. Out of scope per v0.31.12 plan ("Embedding tier knob").
- const newExpansion = await resolveModel(engine, {
+ const expansionDetailed = await resolveModelDetailed(engine, {
configKey: 'models.expansion',
tier: 'utility',
fallback: cfg.expansion_model ?? DEFAULT_EXPANSION_MODEL,
});
- const newChat = await resolveModel(engine, {
+ const chatDetailed = await resolveModelDetailed(engine, {
configKey: 'models.chat',
tier: 'reasoning',
fallback: cfg.chat_model ?? DEFAULT_CHAT_MODEL,
});
+ // When no DB-plane override won (source = tier_default/fallback), consult
+ // the RAW file-plane config through the shared effective-model resolver.
+ // The gateway's own cfg can't be used for this: the boot fold stamps
+ // DEFAULT_CHAT_MODEL into it when config.json has no pin, so by now an
+ // explicit pin and a fabricated default are indistinguishable in `cfg`.
+ // resolveEffective*Model keeps a SERVABLE pin (its provider's key is
+ // present), warns once and falls to the key-aware tier default otherwise —
+ // an init-era `chat_model: openai:*` pin survives reconnect when the
+ // OpenAI key is live, and stops freezing provider choice when it isn't.
+ const needsFileCfg = (s: string) => s === 'tier_default' || s === 'fallback';
+ let fileCfg: GBrainConfig | null = null;
+ if (needsFileCfg(chatDetailed.source) || needsFileCfg(expansionDetailed.source)) {
+ try {
+ fileCfg = loadConfig();
+ } catch {
+ fileCfg = null;
+ }
+ }
+ const newChat = needsFileCfg(chatDetailed.source)
+ ? resolveEffectiveChatModel(fileCfg, cfg.env ?? process.env).model
+ : chatDetailed.model;
+ const newExpansion = needsFileCfg(expansionDetailed.source)
+ ? resolveEffectiveExpansionModel(fileCfg, cfg.env ?? process.env).model
+ : expansionDetailed.model;
+
// Resolved values are bare model ids (e.g. `claude-sonnet-4-6`) — prepend
// the existing provider prefix from cfg so the gateway keeps routing to
// the right recipe. If the resolved string already contains a `:`, it
diff --git a/src/core/ai/openai-latest.ts b/src/core/ai/openai-latest.ts
new file mode 100644
index 0000000000..8bbafc065f
--- /dev/null
+++ b/src/core/ai/openai-latest.ts
@@ -0,0 +1,368 @@
+/**
+ * openai-latest — never pin an OpenAI default: discover the newest usable
+ * models from the account itself.
+ *
+ * Why this exists: any hardcoded OpenAI model id goes stale in months (the
+ * repo pinned gpt-5.2 in April 2026; by August the current family was 5.6
+ * with a DIFFERENT tier-naming scheme — sol/terra/luna instead of mini/nano —
+ * so even hardcoded filters rot, not just pins). The account's own
+ * `GET /v1/models` is ground truth for what this key can use.
+ *
+ * Design constraints (all load-bearing):
+ * - SYNC read path. `resolveTierDefault` (src/core/model-config.ts) and the
+ * capability probe are synchronous — discovery WRITES a cache file that
+ * sync callers read. Stale cache beats static fallback (TTL only gates
+ * refresh, never use).
+ * - PRICED models only. BudgetTracker fails closed (`no_pricing`) when a
+ * cost cap is set and the model has no canonical pricing row — selecting
+ * an unpriced model as a DEFAULT would brick every budget-capped backfill
+ * the day a new family ships. Selection filters to canonicalLookup hits;
+ * a newer-but-unpriced id is surfaced once on stderr so a release can add
+ * the one pricing row that unlocks it.
+ * - Conservative id grammar. Only bare family aliases (`gpt-5.6` — OpenAI's
+ * own rolling alias for the family flagship) and known tier suffixes
+ * rank; dated snapshots, `-chat`/`chat-latest` (ChatGPT-Instant class,
+ * weaker at strict JSON — same posture as think/index.ts's
+ * OPENAI_CHAT_SNAPSHOT_RE), realtime/image/transcribe/audio and unknown
+ * future suffixes are ignored. Unknown-suffix rot degrades to "newest
+ * KNOWN shape", never to a wrong pick; the static recipe list remains the
+ * floor.
+ * - Fail-open everywhere. No key / offline / 4xx / malformed body / cache
+ * unwritable → keep whatever we had (stale cache, else static fallback).
+ * Discovery must never break a connect.
+ * - Kill switch: GBRAIN_MODEL_DISCOVERY=off|0 disables refresh (the test
+ * preload sets it — no network in test lanes; incident escape hatch in
+ * prod).
+ *
+ * Tier mapping mirrors the Anthropic ladder in TIER_DEFAULTS:
+ * utility → cheapest class (luna | nano | mini), reasoning/subagent → mid
+ * class (terra, else the flagship), deep → top class (sol | pro, else the
+ * bare family alias).
+ */
+
+import { readFileSync, writeFileSync, mkdirSync, renameSync, statSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { join, dirname } from 'node:path';
+import { configDir } from '../config.ts';
+import { canonicalLookup } from '../model-pricing.ts';
+// Type-only import — erased at compile, so no runtime cycle with
+// model-config.ts (which imports this module for the sync overlay).
+import type { ModelTier } from '../model-config.ts';
+
+export interface OpenAITierPick {
+ utility: string;
+ reasoning: string;
+ deep: string;
+ subagent: string;
+}
+
+interface ModelCacheFile {
+ version: 1;
+ openai?: {
+ tiers: OpenAITierPick;
+ fetched_at: string;
+ /** Newest family seen on the account with NO canonical pricing row (informational). */
+ newest_unpriced?: string;
+ /**
+ * Non-secret identity fingerprint (sha256 of endpoint + key, truncated).
+ * A key/endpoint change within the TTL must trigger an immediate refresh
+ * — the cached tiers belong to the PREVIOUS account and may be
+ * inaccessible to the new one. The sync reader can't check this (no env
+ * in scope), so staleness after an identity switch is bounded by the
+ * first reconfigure, not the 24h TTL.
+ */
+ fingerprint?: string;
+ };
+ /**
+ * Last refresh ATTEMPT (success or fail). Persisted so the failure backoff
+ * survives process boundaries: short-lived CLI invocations on a blackholed
+ * network (captive portal, VPN down) would otherwise each re-pay the full
+ * FETCH_TIMEOUT_MS — module-state backoff only protects long-lived workers.
+ * Scoped by fingerprint: a failed attempt under one identity never
+ * suppresses another identity's first attempt.
+ */
+ last_attempt_at?: string;
+ last_attempt_fingerprint?: string;
+}
+
+const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
+const FETCH_TIMEOUT_MS = 3_000;
+
+function cachePath(): string {
+ return join(configDir(), 'model-cache.json');
+}
+
+/* ── id grammar + ranking (pure; exported for tests) ─────────────────────── */
+
+const TOP_SUFFIXES = ['sol', 'pro'] as const;
+const MID_SUFFIXES = ['terra'] as const;
+const CHEAP_SUFFIXES = ['luna', 'nano', 'mini'] as const;
+const KNOWN_SUFFIXES = new Set<string>([...TOP_SUFFIXES, ...MID_SUFFIXES, ...CHEAP_SUFFIXES]);
+
+export interface ParsedOpenAIChatId {
+ id: string;
+ family: [number, number];
+ /** '' = the bare family alias (OpenAI's rolling flagship alias). */
+ suffix: string;
+}
+
+/** Parse a chat-shaped GPT id; null for anything outside the known grammar. */
+export function parseOpenAIChatId(id: string): ParsedOpenAIChatId | null {
+ const m = /^gpt-(\d+)(?:\.(\d+))?(?:-([a-z]+))?$/.exec(id);
+ if (!m) return null;
+ const suffix = m[3] ?? '';
+ if (suffix !== '' && !KNOWN_SUFFIXES.has(suffix)) return null;
+ return { id, family: [Number(m[1]), Number(m[2] ?? 0)], suffix };
+}
+
+function familyCmp(a: [number, number], b: [number, number]): number {
+ return a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1];
+}
+
+function pickBySuffix(members: ParsedOpenAIChatId[], order: readonly string[]): string | undefined {
+ for (const s of order) {
+ const hit = members.find((p) => p.suffix === s);
+ if (hit) return hit.id;
+ }
+ return undefined;
+}
+
+/**
+ * Rank the account's model ids into per-tier defaults. Only ids with a
+ * canonical pricing row are eligible (see module header); returns null when
+ * nothing usable matched. `newestUnpriced` reports the newest in-grammar id
+ * that lost eligibility to a missing pricing row.
+ */
+export function rankOpenAIChatModels(
+ ids: string[],
+ priced: (id: string) => boolean = (id) => canonicalLookup(`openai:${id}`) !== undefined,
+): { tiers: OpenAITierPick | null; newestUnpriced?: string } {
+ const parsed = ids.map(parseOpenAIChatId).filter((p): p is ParsedOpenAIChatId => p !== null);
+ if (parsed.length === 0) return { tiers: null };
+
+ const eligible = parsed.filter((p) => priced(p.id));
+ const skipped = parsed.filter((p) => !priced(p.id));
+ const newestSkipped = skipped.sort((a, b) => familyCmp(b.family, a.family))[0];
+
+ if (eligible.length === 0) return { tiers: null, newestUnpriced: newestSkipped?.id };
+
+ const newestFamily = eligible.reduce((best, p) =>
+ familyCmp(p.family, best) > 0 ? p.family : best, eligible[0].family);
+ const members = eligible.filter((p) => familyCmp(p.family, newestFamily) === 0);
+ // Only surface an unpriced id when its family is strictly NEWER than the
+ // newest priced family — accounts often still list obsolete unpriced ids
+ // (legacy families), and warning about those tells a release engineer to
+ // add a pricing row for a model nobody should adopt.
+ const newestUnpriced = newestSkipped && familyCmp(newestSkipped.family, newestFamily) > 0
+ ? newestSkipped.id
+ : undefined;
+
+ // Tier picks degrade WITHIN the newest priced family — an account exposing
+ // only a partial family (e.g. terra/luna without sol or the bare alias)
+ // still gets usable tiers rather than tiers:null and a static fallback the
+ // account may not serve. Since `members` is non-empty, every tier resolves.
+ // Top: named top tier, else the bare family alias, else the best remaining.
+ const top = pickBySuffix(members, TOP_SUFFIXES) ?? pickBySuffix(members, [''])
+ ?? pickBySuffix(members, MID_SUFFIXES) ?? pickBySuffix(members, CHEAP_SUFFIXES);
+ // Mid: named mid tier, else the bare alias, else top.
+ const mid = pickBySuffix(members, MID_SUFFIXES) ?? pickBySuffix(members, ['']) ?? top;
+ // Cheap: named cheap tier, else mid.
+ const cheap = pickBySuffix(members, CHEAP_SUFFIXES) ?? mid;
+ if (!top || !mid || !cheap) return { tiers: null, newestUnpriced };
+
+ return {
+ tiers: {
+ utility: `openai:${cheap}`,
+ reasoning: `openai:${mid}`,
+ deep: `openai:${top}`,
+ subagent: `openai:${mid}`,
+ },
+ newestUnpriced,
+ };
+}
+
+/* ── sync cache read (the resolveTierDefault overlay) ─────────────────────── */
+
+// mtime-keyed memo: the sync read fires per model resolution on OpenAI-keyed
+// installs — statSync is far cheaper than read+parse, and staleness is
+// already tolerated by design. Keyed on path too (GBRAIN_HOME can change in
+// tests). Invalidated implicitly: a refresh write bumps the mtime.
+let _cacheMemo: { path: string; mtimeMs: number; value: ModelCacheFile | null } | null = null;
+
+function readCacheFile(): ModelCacheFile | null {
+ const path = cachePath();
+ try {
+ const mtimeMs = statSync(path).mtimeMs;
+ if (_cacheMemo && _cacheMemo.path === path && _cacheMemo.mtimeMs === mtimeMs) {
+ return _cacheMemo.value;
+ }
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as ModelCacheFile;
+ const value = parsed?.version === 1 ? parsed : null;
+ _cacheMemo = { path, mtimeMs, value };
+ return value;
+ } catch {
+ _cacheMemo = null;
+ return null;
+ }
+}
+
+/**
+ * Sync read of the discovered per-tier defaults. STALE ENTRIES ARE USED —
+ * yesterday's discovery beats a months-old static pin; the TTL only gates
+ * refresh. Returns null when never discovered (fresh install, keyless,
+ * discovery disabled) — callers fall back to the recipe-derived static tiers.
+ */
+export function latestOpenAITiers(tier?: ModelTier): OpenAITierPick | string | null {
+ const cached = readCacheFile()?.openai?.tiers ?? null;
+ if (!cached) return null;
+ return tier ? cached[tier] : cached;
+}
+
+/* ── refresh (async, throttled, fail-open) ────────────────────────────────── */
+
+let _refreshInFlight: Promise<void> | null = null;
+let _warnedUnpriced: string | null = null;
+// Failure backoff: a persistently-failing refresh (blackholed network,
+// revoked key, unwritable config dir — nothing lands in the cache, so the
+// TTL throttle never engages) must not re-pay the FETCH_TIMEOUT_MS bound on
+// every engine connect and every gateway-refresh job. One attempt per
+// backoff window, success or fail. The attempt stamp is BOTH module state
+// (fast path) and persisted in the cache file (short-lived CLI processes —
+// each `gbrain <cmd>` is a fresh process, so module state alone would re-pay
+// the timeout per invocation on an offline shell).
+const FAILURE_BACKOFF_MS = 10 * 60 * 1000;
+let _lastAttemptAt = 0;
+let _lastAttemptFp = '';
+
+/** Non-secret identity fingerprint: truncated sha256 of endpoint + key. */
+function accountFingerprint(base: string, apiKey: string): string {
+ return createHash('sha256').update(`${base}|${apiKey}`).digest('hex').slice(0, 16);
+}
+
+/** Atomic cache write (tmp + rename) so a concurrent sync reader never sees a torn file. */
+function writeCacheFile(next: ModelCacheFile): void {
+ const path = cachePath();
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp-${process.pid}`;
+ writeFileSync(tmp, JSON.stringify(next, null, 2));
+ renameSync(tmp, path);
+}
+
+/**
+ * Best-effort: persist the attempt stamp WITHOUT touching the (possibly
+ * stale, still-useful) discovered tiers — UNLESS those tiers belong to a
+ * different identity (fingerprint mismatch), in which case they're another
+ * account's models and honesty is the static floor, so drop them. Its own
+ * try/catch — an unwritable config dir must stay fail-open.
+ */
+function stampAttempt(fp: string): void {
+ try {
+ const prior = readCacheFile();
+ const keepTiers = prior?.openai && prior.openai.fingerprint === fp ? prior.openai : undefined;
+ writeCacheFile({
+ version: 1,
+ ...(keepTiers ? { openai: keepTiers } : {}),
+ last_attempt_at: new Date().toISOString(),
+ last_attempt_fingerprint: fp,
+ });
+ } catch {
+ // Module-state backoff still covers this process.
+ }
+}
+
+export function _resetOpenAILatestForTests(): void {
+ _refreshInFlight = null;
+ _warnedUnpriced = null;
+ _lastAttemptAt = 0;
+ _lastAttemptFp = '';
+ _cacheMemo = null;
+}
+
+export interface RefreshOpts {
+ env?: Record<string, string | undefined>;
+ /** provider_base_urls.openai override; defaults to the official endpoint. */
+ baseUrl?: string;
+ fetchImpl?: typeof fetch;
+ /** Test seam: bypass the TTL throttle. */
+ force?: boolean;
+}
+
+/**
+ * Refresh the discovery cache from `GET /v1/models`, at most once per TTL.
+ * Best-effort by contract: never throws, never blocks longer than
+ * FETCH_TIMEOUT_MS, no-ops without a key or with GBRAIN_MODEL_DISCOVERY=off.
+ * Call sites: reconfigureGatewayWithEngine (engine connect) and — through
+ * it — the jobs worker's per-job gateway refresh.
+ */
+export async function refreshLatestOpenAIModels(opts: RefreshOpts = {}): Promise<void> {
+ const disc = process.env.GBRAIN_MODEL_DISCOVERY;
+ if (disc === 'off' || disc === '0') return;
+ const env = opts.env ?? process.env;
+ const apiKey = env.OPENAI_API_KEY;
+ if (!apiKey) return;
+
+ const base = (opts.baseUrl ?? 'https://api.openai.com/v1').replace(/\/$/, '');
+ const fp = accountFingerprint(base, apiKey);
+ const cacheFile = readCacheFile();
+ const cached = cacheFile?.openai;
+ // TTL and backoff are per-identity: a key/endpoint switch within either
+ // window must refresh immediately (the cached tiers/attempt belong to the
+ // previous account).
+ if (!opts.force && cached && cached.fingerprint === fp
+ && Date.now() - Date.parse(cached.fetched_at) < CACHE_TTL_MS) return;
+ const persistedAttempt = cacheFile?.last_attempt_fingerprint === fp
+ ? Date.parse(cacheFile?.last_attempt_at ?? '') || 0 : 0;
+ const moduleAttempt = _lastAttemptFp === fp ? _lastAttemptAt : 0;
+ if (!opts.force && Date.now() - Math.max(moduleAttempt, persistedAttempt) < FAILURE_BACKOFF_MS) return;
+
+ if (_refreshInFlight) return _refreshInFlight;
+ _lastAttemptAt = Date.now();
+ _lastAttemptFp = fp;
+ _refreshInFlight = (async () => {
+ try {
+ const doFetch = opts.fetchImpl ?? fetch;
+ const res = await doFetch(`${base}/models`, {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!res.ok) { stampAttempt(fp); return; }
+ const body = (await res.json()) as { data?: Array<{ id?: string }> };
+ const ids = (body.data ?? []).map((m) => m.id).filter((x): x is string => typeof x === 'string');
+ if (ids.length === 0) { stampAttempt(fp); return; }
+ const { tiers, newestUnpriced } = rankOpenAIChatModels(ids);
+ if (newestUnpriced && _warnedUnpriced !== newestUnpriced) {
+ _warnedUnpriced = newestUnpriced;
+ process.stderr.write(
+ `[models] OpenAI account offers ${newestUnpriced} but src/core/model-pricing.ts has no row for it — ` +
+ `staying on the newest PRICED family so budget caps keep working. Add the pricing row to adopt it.\n`,
+ );
+ }
+ if (!tiers) {
+ // In-grammar ids but none priced: stamp the attempt so offline/
+ // misconfigured shells don't re-pay the fetch on every invocation.
+ stampAttempt(fp);
+ return;
+ }
+ writeCacheFile({
+ version: 1,
+ openai: {
+ tiers,
+ fetched_at: new Date().toISOString(),
+ fingerprint: fp,
+ ...(newestUnpriced ? { newest_unpriced: newestUnpriced } : {}),
+ },
+ last_attempt_at: new Date().toISOString(),
+ last_attempt_fingerprint: fp,
+ });
+ } catch {
+ // Fail-open: offline / 401 / abort / unwritable dir all keep the prior
+ // state (stale cache or static fallback). Discovery never breaks a
+ // connect. Persist the attempt stamp (best-effort) so the NEXT process
+ // honors the backoff too.
+ stampAttempt(fp);
+ } finally {
+ _refreshInFlight = null;
+ }
+ })();
+ return _refreshInFlight;
+}
diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.ts
new file mode 100644
index 0000000000..511e5a59ea
--- /dev/null
+++ b/src/core/ai/provider-env.ts
@@ -0,0 +1,55 @@
+/**
+ * mergedProviderEnv — THE canonical provider-key/env fold.
+ *
+ * One function owns the mapping from file-plane config keys
+ * (`~/.gbrain/config.json`) to the env names the recipes read, the
+ * env-wins-for-real-values merge, and the GEMINI alias. Consumers:
+ *
+ * - `buildGatewayConfig` (src/core/ai/build-gateway-config.ts) — gateway env
+ * - `detectCapabilities` (src/core/capability.ts) — capability probe
+ * - `resolveTierDefault` / `resolveEffectiveChatModel`
+ * (src/core/model-config.ts) — key-aware model resolution
+ *
+ * Rules folded in from the two prior copies:
+ * - #1249: process/injected env wins over config-plane fallbacks, but ONLY
+ * for keys carrying a real value. Launchers inject `ANTHROPIC_API_KEY=''`
+ * to neuter subprocess LLM calls; an unconditional spread would let that
+ * empty string clobber a valid config.json key. '' and undefined are
+ * dropped; '0' and 'false' are legitimate values and survive.
+ * - GEMINI_API_KEY alias: Google's docs/SDKs export GEMINI_API_KEY, but the
+ * google recipe reads GOOGLE_GENERATIVE_AI_API_KEY. Precedence: env
+ * GOOGLE_GENERATIVE_AI_API_KEY > env GEMINI_API_KEY > config
+ * google_api_key — the alias is still process-env, so it beats the
+ * config-plane fallback but never the canonical env name.
+ * - Azure OpenAI (keyless/Entra): non-secret endpoint/deployment + the
+ * Entra opt-in fold so the azure-openai recipe works in any shell. The
+ * bearer token is minted at request time via `az`; no secret stored.
+ */
+
+import type { GBrainConfig } from '../config.ts';
+
+export function mergedProviderEnv(
+ cfg: GBrainConfig | null,
+ env: Record<string, string | undefined> = process.env,
+): Record<string, string> {
+ const fromConfig: Record<string, string> = {};
+ if (cfg?.openai_api_key) fromConfig.OPENAI_API_KEY = cfg.openai_api_key;
+ if (cfg?.anthropic_api_key) fromConfig.ANTHROPIC_API_KEY = cfg.anthropic_api_key;
+ if (cfg?.zeroentropy_api_key) fromConfig.ZEROENTROPY_API_KEY = cfg.zeroentropy_api_key;
+ if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;
+ if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;
+ if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;
+ if (cfg?.google_api_key) fromConfig.GOOGLE_GENERATIVE_AI_API_KEY = cfg.google_api_key;
+ if (cfg?.azure_openai_endpoint) fromConfig.AZURE_OPENAI_ENDPOINT = cfg.azure_openai_endpoint;
+ if (cfg?.azure_openai_deployment) fromConfig.AZURE_OPENAI_DEPLOYMENT = cfg.azure_openai_deployment;
+ if (cfg?.azure_openai_use_entra) fromConfig.AZURE_OPENAI_USE_ENTRA = cfg.azure_openai_use_entra;
+
+ const envReal = Object.fromEntries(
+ Object.entries(env).filter(([, v]) => v !== undefined && v !== ''),
+ ) as Record<string, string>;
+ const merged = { ...fromConfig, ...envReal };
+ if (!envReal.GOOGLE_GENERATIVE_AI_API_KEY && envReal.GEMINI_API_KEY) {
+ merged.GOOGLE_GENERATIVE_AI_API_KEY = envReal.GEMINI_API_KEY;
+ }
+ return merged;
+}
diff --git a/src/core/ai/recipes/openai.ts b/src/core/ai/recipes/openai.ts
index d453a4db0c..317d28f314 100644
--- a/src/core/ai/recipes/openai.ts
+++ b/src/core/ai/recipes/openai.ts
@@ -25,19 +25,28 @@ export const openai: Recipe = {
max_batch_tokens: 100_000,
},
expansion: {
- models: ['gpt-5.2', 'gpt-4o-mini'],
- cost_per_1m_tokens_usd: 0.15,
- price_last_verified: '2026-04-20',
+ models: ['gpt-5.6-luna', 'gpt-4o-mini'],
+ cost_per_1m_tokens_usd: 1.00, // gpt-5.6-luna baseline
+ price_last_verified: '2026-08-17',
},
chat: {
- models: ['gpt-5.2', 'gpt-4o-mini'],
+ // STATIC FALLBACK ONLY — the runtime default is discovered from the
+ // account's own /v1/models via src/core/ai/openai-latest.ts (ranked by
+ // the same tier grammar), so this list matters only before the first
+ // keyed connect or when discovery is disabled/offline. Order is not
+ // semantic (the ranker classifies by suffix); keep it current-ish at
+ // release time, not perfectly.
+ // gpt-5.2 stays listed: the cross-modal + takes-quality eval judge
+ // panels pin it for baseline reproducibility, and their recipe-
+ // consistency guards require panel models to be listed entry points.
+ models: ['gpt-5.6', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.2', 'gpt-4o-mini'],
supports_tools: true,
supports_subagent_loop: true,
supports_prompt_cache: false,
- max_context_tokens: 200000,
- cost_per_1m_input_usd: 1.25, // gpt-5.2 baseline
- cost_per_1m_output_usd: 10.0,
- price_last_verified: '2026-04-20',
+ max_context_tokens: 1_050_000, // gpt-5.6 family window (GA 2026-07-09)
+ cost_per_1m_input_usd: 2.50, // gpt-5.6-terra baseline (the reasoning-tier default)
+ cost_per_1m_output_usd: 15.0,
+ price_last_verified: '2026-08-17',
},
},
setup_hint: 'Get an API key at https://platform.openai.com/api-keys, then `export OPENAI_API_KEY=...`',
diff --git a/src/core/capability.ts b/src/core/capability.ts
index a38cb2e338..0dce771d38 100644
--- a/src/core/capability.ts
+++ b/src/core/capability.ts
@@ -31,13 +31,15 @@ import { RECIPES } from './ai/recipes/index.ts';
import type { Recipe } from './ai/types.ts';
import { DEFAULT_EMBEDDING_MODEL } from './ai/defaults.ts';
-/**
- * Fallback chat model when config doesn't pin one. Mirrors
- * DEFAULT_CHAT_MODEL in src/core/ai/gateway.ts (module-private there;
- * duplicated here so this probe stays light — it must not load every
- * provider SDK just to name a default).
- */
-const FALLBACK_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';
+// Extraction probes the SAME effective-model resolution the gateway's
+// reconfigure fallback uses (resolveEffectiveChatModel) — runtime routing and
+// this report cannot diverge by construction. Known accepted limitation:
+// DB-plane overrides (`models.default`, `facts.extraction_model`) are
+// invisible to this engine-less probe; the runtime gate in facts/extract.ts
+// and the engine-aware pre-enqueue gate in facts/backstop.ts are the
+// backstops.
+import { resolveEffectiveChatModel } from './model-config.ts';
+import { mergedProviderEnv } from './ai/provider-env.ts';
export interface TouchpointCapability {
available: boolean;
@@ -64,34 +66,10 @@ export interface DetectCapabilitiesOpts {
env?: Record<string, string | undefined>;
}
-/**
- * Fold file-plane API keys into env names the recipes read. SAME mapping as
- * `buildGatewayConfig` (src/core/ai/build-gateway-config.ts) — that module
- * is canonical; keep the two in sync when adding a provider key seam.
- */
-function mergedEnv(
- cfg: GBrainConfig | null,
- env: Record<string, string | undefined>,
-): Record<string, string> {
- const fromConfig: Record<string, string> = {};
- if (cfg?.openai_api_key) fromConfig.OPENAI_API_KEY = cfg.openai_api_key;
- if (cfg?.anthropic_api_key) fromConfig.ANTHROPIC_API_KEY = cfg.anthropic_api_key;
- if (cfg?.zeroentropy_api_key) fromConfig.ZEROENTROPY_API_KEY = cfg.zeroentropy_api_key;
- if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;
- if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;
- if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;
- if (cfg?.google_api_key) fromConfig.GOOGLE_GENERATIVE_AI_API_KEY = cfg.google_api_key;
- // env wins for keys carrying a real value; '' and undefined dropped (#1249).
- const envReal = Object.fromEntries(
- Object.entries(env).filter(([, v]) => v !== undefined && v !== ''),
- ) as Record<string, string>;
- const merged = { ...fromConfig, ...envReal };
- // GEMINI_API_KEY alias (google recipe reads GOOGLE_GENERATIVE_AI_API_KEY).
- if (!envReal.GOOGLE_GENERATIVE_AI_API_KEY && envReal.GEMINI_API_KEY) {
- merged.GOOGLE_GENERATIVE_AI_API_KEY = envReal.GEMINI_API_KEY;
- }
- return merged;
-}
+// The provider-key/env fold lives in src/core/ai/provider-env.ts
+// (mergedProviderEnv) — one canonical mapping shared with buildGatewayConfig
+// and the key-aware model resolution. This probe additionally sees the Azure
+// endpoint/deployment fields the old local copy omitted.
/** `envReady` twin (src/commands/providers.ts:52) — auth-env readiness only. */
function recipeReady(recipe: Recipe, env: Record<string, string>): boolean {
@@ -130,15 +108,20 @@ export function detectCapabilities(opts: DetectCapabilitiesOpts = {}): Capabilit
cfg = null; // unreadable config = fresh-install posture, not a crash
}
}
- const env = mergedEnv(cfg, opts.env ?? process.env);
+ const rawEnv = opts.env ?? process.env;
+ const env = mergedProviderEnv(cfg, rawEnv);
const embeddings = probeTouchpoint(
cfg?.embedding_model ?? DEFAULT_EMBEDDING_MODEL,
'embedding',
env,
);
+ // Probe the model extraction will ACTUALLY use: GBRAIN_MODEL > servable
+ // file pin > key-aware tier default — the same shared resolution the
+ // gateway's reconfigure fallback applies (so a stale unservable pin
+ // degrades identically here and at runtime).
const extraction = probeTouchpoint(
- cfg?.chat_model ?? FALLBACK_CHAT_MODEL,
+ resolveEffectiveChatModel(cfg, rawEnv).model,
'chat',
env,
);
@@ -171,8 +154,9 @@ export function renderCapabilityReport(caps: CapabilityReport): string {
);
if (caps.mode === 'keyless') {
lines.push(
- 'keyless mode: keyword search, agent-authored memory; add ONE key to unlock ' +
- 'embeddings + auto-extraction (see `gbrain providers list` for env-ready options).',
+ 'keyless mode: keyword search, agent-authored memory; one optional key upgrades ' +
+ 'capabilities — OpenAI: semantic search + auto-extraction; Voyage: semantic search; ' +
+ 'Anthropic: auto-extraction (see `gbrain providers list` for env-ready options).',
);
}
return lines.join('\n');
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b75629e201..be8c2efbbf 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -41,7 +41,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'config': ['--all', '--brain', '--column', '--coverage-override', '--detail', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--pattern', '--pglite', '--reset', '--source', '--surface', '--token-ttl', '--yes'],
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
+ 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
'dream': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],
'edges-backfill': ['--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-federated', '--older-than', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--timeout', '--workers'],
'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'],
diff --git a/src/core/config.ts b/src/core/config.ts
index a439bc8893..f340afb6f2 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1,4 +1,4 @@
-import { readFileSync, writeFileSync, mkdirSync, chmodSync, existsSync } from 'fs';
+import { readFileSync, writeFileSync, mkdirSync, chmodSync, existsSync, renameSync } from 'fs';
import { isAbsolute, join } from 'path';
import { homedir } from 'os';
import type { EngineConfig, EmbeddingColumnConfig } from './types.ts';
@@ -1270,7 +1270,13 @@ export function isConfigTruthy(raw: unknown): boolean {
export function saveConfig(config: GBrainConfig): void {
mkdirSync(getConfigDir(), { recursive: true });
- writeFileSync(getConfigPath(), JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
+ // Atomic write (tmp + rename): long-lived workers re-read this file per job
+ // (gateway env refresh, keyed/keyless classification) — a truncate-then-write
+ // here could be read torn, making a keyed install classify as keyless and
+ // calmly consume work it should retry.
+ const tmp = `${getConfigPath()}.tmp-${process.pid}`;
+ writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
+ renameSync(tmp, getConfigPath());
try {
chmodSync(getConfigPath(), 0o600);
} catch {
diff --git a/src/core/facts/absorb-log.ts b/src/core/facts/absorb-log.ts
index 88ca980f92..d7baedc486 100644
--- a/src/core/facts/absorb-log.ts
+++ b/src/core/facts/absorb-log.ts
@@ -35,6 +35,16 @@ export const FACTS_ABSORB_REASONS = [
'queue_shutdown',
'embed_failure',
'pipeline_error',
+ // Extraction-outcome codes (keyed-but-failing states; keyless-expected
+ // states deliberately write NO row — see backstop.ts
+ // surfaceExtractionFailure). Doctor's facts_extraction_health groups by
+ // split_part(summary,':',1), so new codes surface with zero schema change.
+ 'chat_unavailable',
+ 'refusal',
+ 'content_filter',
+ 'malformed_output',
+ 'non_terminal_stop',
+ 'truncated_output',
] as const;
// v0.39.3.0 WARN-4 + CV13 — module-scoped flag so the first-occurrence
@@ -127,6 +137,20 @@ export function classifyFactsAbsorbError(err: unknown): FactsAbsorbReason {
const msg = err instanceof Error ? err.message : String(err);
const name = err instanceof Error ? err.name : '';
+ // Typed extraction failures carry their reason — map precisely instead of
+ // pattern-matching the message (a 401/invalid-model provider_error would
+ // otherwise fall through to the generic 'pipeline_error'). instanceof via
+ // name check: the class lives in extract.ts and this module must stay
+ // import-light; the name is stable and set in the constructor.
+ if (name === 'FactsExtractionError') {
+ const reason = (err as { reason?: string }).reason;
+ if (reason === 'provider_error') return 'gateway_error';
+ if (reason && (FACTS_ABSORB_REASONS as readonly string[]).includes(reason)) {
+ return reason as FactsAbsorbReason;
+ }
+ return 'pipeline_error';
+ }
+
// Anthropic / OpenAI / Voyage all surface 4xx/5xx + timeouts in similar shapes.
if (/timeout|timed?\s?out|ETIMEDOUT/i.test(msg)) return 'gateway_error';
if (/429|rate[\s-]?limit|too many requests/i.test(msg)) return 'gateway_error';
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 9d33676ea3..29c79833d9 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -79,7 +79,7 @@ export type FactsBackstopResult =
mode: 'queue';
enqueued: boolean;
queueDepth: number;
- skipped?: 'extraction_disabled' | 'queue_overflow' | 'queue_shutdown' | `eligibility_failed:${string}`;
+ skipped?: 'extraction_disabled' | 'extraction_unavailable' | 'queue_overflow' | 'queue_shutdown' | `eligibility_failed:${string}`;
}
| {
mode: 'inline';
@@ -87,7 +87,9 @@ export type FactsBackstopResult =
duplicate: number;
superseded: number;
fact_ids: number[];
- skipped?: 'extraction_disabled' | `eligibility_failed:${string}`;
+ skipped?: 'extraction_disabled' | 'extraction_unavailable' | `eligibility_failed:${string}`;
+ /** Set when the LLM extraction step failed non-transport-fatally (see runPipelineWithBody). */
+ skipped_reason?: import('./extract.ts').ExtractFailureReason;
};
interface ParsedPageInput {
@@ -125,6 +127,90 @@ export function __resetBackstopWarningsForTests(): void {
_warnedKeys.clear();
}
+/**
+ * ONE sentence for every keyless-extraction surface (backstop note, doctor's
+ * facts_extraction_health) — a future provider addition edits it here only.
+ */
+export const KEYLESS_EXTRACTION_GUIDANCE =
+ 'memory comes from agent-authored `## Facts` fences and the `remember` verb. ' +
+ 'One optional key enables automatic extraction (OpenAI or Anthropic).';
+
+const KEYLESS_NOTE =
+ `[facts] keyless: automatic fact extraction off — ${KEYLESS_EXTRACTION_GUIDANCE}`;
+
+/**
+ * Classify a chat_unavailable extraction failure: an EXPECTED keyless state
+ * (calm — one stderr note, no ingest_log row) vs a keyed-but-failing state
+ * (visible — absorb-log row + fix hint). Keyless means: the resolved model's
+ * provider has no usable key AND no chat-capable provider key exists at all
+ * (merged file-plane + process env). Computed from the RESOLVED model, never
+ * the engine-blind detectCapabilities() — a servable DB-plane override must
+ * never classify as keyless (CX1).
+ */
+export async function classifyUnavailable(model: string | undefined): Promise<'keyless' | 'keyed'> {
+ const { mergedProviderEnv } = await import('../ai/provider-env.ts');
+ const { providerKeyReady, PROVIDER_TIER_DEFAULTS } = await import('../model-config.ts');
+ let cfg = null;
+ try {
+ const { loadConfig } = await import('../config.ts');
+ cfg = loadConfig();
+ } catch {
+ // Fail toward RETRY, not calm consumption (loadConfig swallows file
+ // errors itself, so this only fires on pathological import failures).
+ return 'keyed';
+ }
+ const merged = mergedProviderEnv(cfg, process.env);
+ if (model && providerKeyReady(model, merged)) return 'keyed';
+ const anyChatKey = PROVIDER_TIER_DEFAULTS.some((e) => !!merged[e.envKey]);
+ if (!anyChatKey) {
+ // Before declaring keyless, check for a config file that EXISTS but
+ // yielded nothing (EACCES, disk error, corrupt JSON — loadConfig returns
+ // null for all of them, indistinguishable from "no config"). That file
+ // may hold the only key this worker has; classifying it keyless would
+ // calmly consume a job that a retry after repair would have served.
+ try {
+ const { loadConfigFileOnly, configPath } = await import('../config.ts');
+ const { existsSync } = await import('node:fs');
+ if (loadConfigFileOnly() === null && existsSync(configPath())) return 'keyed';
+ } catch {
+ return 'keyed';
+ }
+ }
+ return anyChatKey ? 'keyed' : 'keyless';
+}
+
+/**
+ * Shared visibility for a non-transport extraction failure: keyless stays a
+ * calm one-line note with NO log row (expected state); keyed-but-failing
+ * writes one ingest_log row (doctor's facts_extraction_health reads it) plus
+ * a once-per-process fix hint.
+ */
+async function surfaceExtractionFailure(
+ engine: BrainEngine,
+ ref: string,
+ reason: import('./absorb-log.ts').FactsAbsorbReason,
+ model: string | undefined,
+ sourceId: string,
+): Promise<void> {
+ if (reason === 'chat_unavailable' && (await classifyUnavailable(model)) === 'keyless') {
+ warnOnce('facts-keyless', KEYLESS_NOTE);
+ return;
+ }
+ const { writeFactsAbsorbLog } = await import('./absorb-log.ts');
+ await writeFactsAbsorbLog(
+ engine,
+ ref,
+ reason,
+ `extraction ${reason}${model ? ` (model=${model})` : ''}`,
+ sourceId,
+ );
+ warnOnce(
+ `facts-extract-fail-${reason}`,
+ `[facts] extraction ${reason}${model ? ` (model=${model})` : ''}. ` +
+ `Fix: set the provider's API key, or \`gbrain config set facts.extraction_model <provider:model>\`.`,
+ );
+}
+
/**
* Run the facts pipeline for one page write. See module docstring for
* the full lifecycle and mode semantics.
@@ -156,6 +242,35 @@ export async function runFactsBackstop(
: { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped };
}
+ // --- Extraction availability gate (engine-aware, EXECUTION-process only) ---
+ // Resolves the ACTUAL extraction model (facts.extraction_model /
+ // models.default / tier config / GBRAIN_MODEL / key-aware tier default) and
+ // asks the gateway whether it's servable. Deliberately NOT
+ // detectCapabilities(): that probe is engine-blind and would permanently
+ // drop work for installs whose DB-plane override IS servable.
+ //
+ // CRITICAL placement rule: this gate only fires in the process that will
+ // EXECUTE the extraction — the in-process queue lane and the inline lane
+ // (which includes the durable facts-absorb handler running in the jobs
+ // worker). It must NOT fire before the short-lived-CLI durable submit: the
+ // submitting process's env can differ from the worker's (launchers neuter
+ // keys in hook subprocesses — the #1249 class — while the worker holds the
+ // real key and even re-folds file-plane keys per job), so an enqueue-time
+ // skip there would silently drop work a keyed worker could execute.
+ // Returns the resolved model on pass (threaded into the pipeline so
+ // extraction does NOT re-resolve it — the resolve is up to 3 sequential
+ // engine.getConfig round-trips per page write), or null on gate failure.
+ const availabilityGate = async (): Promise<string | null> => {
+ const { getFactsExtractionModel } = await import('./extract.ts');
+ const { isAvailable } = await import('../ai/gateway.ts');
+ const extractionModel = ctx.model ?? (await getFactsExtractionModel(ctx.engine));
+ if (isAvailable('chat', extractionModel)) return extractionModel;
+ await surfaceExtractionFailure(
+ ctx.engine, parsedPage.slug, 'chat_unavailable', extractionModel, ctx.sourceId,
+ );
+ return null;
+ };
+
// --- Mode dispatch ---
if (mode === 'queue') {
// Local patch 2026-06-11: in a one-shot CLI process the in-process queue
@@ -195,7 +310,14 @@ export async function runFactsBackstop(
// Content-hash key: re-submits after edits, dedups rapid
// identical writes (idempotent ON CONFLICT returns existing row).
idempotency_key: `facts-absorb:${ctx.sourceId}:${parsedPage.slug}:${contentHash}`,
- max_attempts: 3,
+ // 5 attempts at a 60s exponential base (not the 3×1s default):
+ // execution-time chat_unavailable is config drift the operator
+ // fixes on a human timescale — 3 attempts in ~seconds would
+ // exhaust before any fix lands. On exhaustion the job parks as a
+ // VISIBLE failure (`gbrain jobs list --status failed`,
+ // re-runnable), never a silent consume.
+ max_attempts: 5,
+ backoff_delay: 60_000,
timeout_ms: 180_000,
},
);
@@ -208,6 +330,12 @@ export async function runFactsBackstop(
);
}
}
+ // In-process queue lane: THIS process executes the extraction — gate here.
+ const queueModel = await availabilityGate();
+ if (!queueModel) {
+ return { mode: 'queue', enqueued: false, queueDepth: 0, skipped: 'extraction_unavailable' };
+ }
+ ctx = { ...ctx, model: queueModel };
const { getFactsQueue } = await import('./queue.ts');
const queue = getFactsQueue();
const enqueued = queue.enqueue(async (signal) => {
@@ -247,7 +375,14 @@ export async function runFactsBackstop(
// (the explicit-call contract). Unlike queue mode, we don't absorb-log
// here because the caller decides whether the failure is interesting
// enough to record (vs. retry, vs. surface directly to the user).
- const r = await runPipeline(parsedPage, ctx, ctx.abortSignal);
+ // Inline executes in THIS process — gate here (this is also the durable
+ // facts-absorb handler's execution-time gate in the jobs worker; the
+ // handler converts a keyed skip into a retryable failure).
+ const inlineModel = await availabilityGate();
+ if (!inlineModel) {
+ return { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_unavailable' };
+ }
+ const r = await runPipeline(parsedPage, { ...ctx, model: inlineModel }, ctx.abortSignal);
return { mode: 'inline', ...r };
}
@@ -286,10 +421,13 @@ export async function runFactsPipeline(
* harvest re-verifies each via source-scoped getPage before banking).
*/
entity_slugs: string[];
+ /** Set when the LLM extraction step failed non-transport-fatally (see runPipelineWithBody). */
+ skipped_reason?: import('./extract.ts').ExtractFailureReason;
}> {
return runPipelineWithBody({
turnText,
isDreamGenerated: false,
+ ref: ctx.sessionId ?? 'inline',
}, ctx, ctx.abortSignal);
}
@@ -306,11 +444,12 @@ async function runPipeline(
parsedPage: ParsedPageInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[] }> {
+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
return runPipelineWithBody(
{
turnText: parsedPage.compiled_truth,
isDreamGenerated: false, // eligibility check already rejected dream pages
+ ref: parsedPage.slug,
},
ctx,
abortSignal,
@@ -344,11 +483,11 @@ async function runPipeline(
* fallback regardless of local_path.
*/
async function runPipelineWithBody(
- input: { turnText: string; isDreamGenerated: boolean },
+ input: { turnText: string; isDreamGenerated: boolean; ref?: string },
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[] }> {
- const { extractFactsFromTurn } = await import('./extract.ts');
+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
+ const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');
const { resolveEntitySlug } = await import('../entities/resolve.ts');
const { cosineSimilarity } = await import('./classify.ts');
const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts');
@@ -357,7 +496,7 @@ async function runPipelineWithBody(
return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };
}
- const facts = await extractFactsFromTurn({
+ const outcome = await extractFactsFromTurnWithOutcome({
turnText: input.turnText,
sessionId: ctx.sessionId,
entityHints: ctx.entityHints,
@@ -368,6 +507,30 @@ async function runPipelineWithBody(
model: ctx.model,
});
+ if (!outcome.ok) {
+ // Transport-class failures PROPAGATE as a typed error: the queue-mode
+ // catch maps them to precise absorb-log codes, the durable facts-absorb
+ // minion gets retry/backoff, and the inline extract_facts op surfaces a
+ // real error instead of lying `inserted: 0`.
+ if (outcome.reason === 'provider_error' || outcome.reason === 'truncated_output') {
+ throw new FactsExtractionError(outcome.reason, outcome.model, outcome.error);
+ }
+ // Everything else (chat_unavailable / refusal / content_filter /
+ // malformed_output / non_terminal_stop) returns zero counts with the
+ // reason attached — keyless stays a calm expected state, keyed failures
+ // land one ingest_log row + a once-per-process fix hint.
+ await surfaceExtractionFailure(
+ ctx.engine,
+ input.ref ?? ctx.sessionId ?? 'turn',
+ outcome.reason,
+ outcome.model,
+ ctx.sourceId,
+ );
+ return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [], skipped_reason: outcome.reason };
+ }
+
+ const facts = outcome.facts;
+
const filter = ctx.notabilityFilter ?? 'all';
// [ENG-8] Explicit ctx.visibility wins; unset resolves the operator-set
// facts.default_visibility (fail-closed to 'private').
diff --git a/src/core/facts/classify.ts b/src/core/facts/classify.ts
index 259882eb27..cd49305149 100644
--- a/src/core/facts/classify.ts
+++ b/src/core/facts/classify.ts
@@ -18,6 +18,7 @@
import { chat, isAvailable } from '../ai/gateway.ts';
import type { ChatResult } from '../ai/gateway.ts';
+import { resolveTierDefault } from '../model-config.ts';
import type { FactRow, FactKind } from '../engine.ts';
/** Classifier output. id is the matching candidate's id when not 'independent'. */
@@ -95,7 +96,11 @@ export async function classifyAgainstCandidates(
}
// Try the classifier. On failure, fall back to cosine ≥ 0.92 → DUPLICATE.
- if (!isAvailable('chat')) {
+ // Engine-free key-aware default (utility tier) + gate on the model this
+ // call will ACTUALLY use — the bare isAvailable('chat') probed the global
+ // chat model, which can disagree with the classifier model.
+ const classifierModel = opts.model ?? resolveTierDefault('utility');
+ if (!isAvailable('chat', classifierModel)) {
if (topId !== null && topScore >= fallback) {
return { decision: 'duplicate', matched_id: topId, reason: 'cosine_fallback' };
}
@@ -105,7 +110,7 @@ export async function classifyAgainstCandidates(
let classifierResult: ChatResult | null = null;
try {
classifierResult = await chat({
- model: opts.model ?? 'anthropic:claude-haiku-4-5-20251001',
+ model: classifierModel,
system: CLASSIFIER_SYSTEM,
messages: [
{
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 13e0e9c7b1..7979de5c1f 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -215,21 +215,60 @@ const EXTRACTOR_SYSTEM = [
const MAX_TURN_TEXT_CHARS = 8000;
+export type ExtractFailureReason =
+ | 'chat_unavailable'
+ | 'provider_error'
+ | 'refusal'
+ | 'content_filter'
+ | 'non_terminal_stop'
+ | 'malformed_output'
+ | 'truncated_output';
+
export type ExtractFactsOutcome =
| { ok: true; facts: ExtractedFact[] }
| {
ok: false;
- reason:
- | 'chat_unavailable'
- | 'provider_error'
- | 'refusal'
- | 'content_filter'
- | 'non_terminal_stop'
- | 'malformed_output'
- | 'truncated_output';
+ reason: ExtractFailureReason;
+ /** The resolved extraction model the failure is about (when known). */
+ model?: string;
error?: unknown;
};
+/**
+ * Typed carrier for extraction failures that must PROPAGATE (throw) rather
+ * than collapse to zero counts — `truncated_output` has no underlying error
+ * object to rethrow and `provider_error.error` is optional, so a synthesized
+ * typed error is the only implementable carrier. The facts backstop throws it
+ * for transport-class failures (queue-mode catch maps it to precise
+ * absorb-log codes; the durable facts-absorb minion gets retry/backoff), and
+ * the facts-absorb job handler throws it for execution-time
+ * `chat_unavailable` so config drift retries instead of consuming the job.
+ */
+export class FactsExtractionError extends Error {
+ readonly reason: ExtractFailureReason;
+ readonly model?: string;
+ constructor(reason: ExtractFailureReason, model?: string, cause?: unknown) {
+ // The MESSAGE deliberately carries only reason + model — never
+ // `cause.message`. This error's message flows to remote MCP callers
+ // (dispatch returns e.message) and into persisted logs (ingest_log,
+ // mcp_request_log), and provider 4xx bodies echo partially-redacted API
+ // keys / org ids. The full cause stays attached for local debugging.
+ super(`[facts-extract] ${reason}${model ? ` (model=${model})` : ''}`);
+ this.name = 'FactsExtractionError';
+ this.reason = reason;
+ this.model = model;
+ // NON-ENUMERABLE cause (matching `new Error(msg, { cause })` semantics):
+ // a plain property assignment would be enumerable, so a future
+ // JSON.stringify(err) / {...err} / own-prop structured logger would ship
+ // the raw provider body — exactly what the message discipline excludes.
+ if (cause !== undefined) {
+ Object.defineProperty(this, 'cause', {
+ value: cause, enumerable: false, writable: true, configurable: true,
+ });
+ }
+ }
+}
+
/** Strict extraction contract for callers that persist completion authority. */
export async function extractFactsFromTurnWithOutcome(
input: ExtractInput,
@@ -243,16 +282,22 @@ export async function extractFactsFromTurnWithOutcome(
cleaned = cleaned.trim();
if (!cleaned) return { ok: true, facts: [] };
- if (!isAvailable('chat')) {
- // No chat gateway → no extraction. Caller still inserts facts via direct
- // `gbrain take add` paths.
- return { ok: false, reason: 'chat_unavailable' };
- }
-
+ // Resolve the model FIRST, then gate on the model extraction will ACTUALLY
+ // call. The bare isAvailable('chat') probes the GLOBAL chat model, which can
+ // disagree with the extraction model in both directions (a servable
+ // facts.extraction_model behind an unservable global, and vice versa).
const cap = Math.max(1, Math.min(input.maxFactsPerTurn ?? 10, 25));
- const defaultModel = await getFactsExtractionModel(input.engine);
+ // When the caller (the backstop availability gate) already resolved the
+ // model, honor it — resolving again costs up to 3 engine.getConfig
+ // round-trips per gated page write.
+ const model = input.model ?? await getFactsExtractionModel(input.engine);
const maxTokens = await getFactsExtractionMaxTokens(input.engine);
- const model = input.model ?? defaultModel;
+
+ if (!isAvailable('chat', model)) {
+ // No servable chat model → no extraction. Caller still inserts facts via
+ // agent-authored `## Facts` fences and the `remember` verb.
+ return { ok: false, reason: 'chat_unavailable', model };
+ }
const userContent = `<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${
input.entityHints && input.entityHints.length
? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, 5).join(', ')}.`
@@ -289,28 +334,28 @@ export async function extractFactsFromTurnWithOutcome(
`(model=${model}); facts for this turn are likely lost. ` +
`Raise the cap: gbrain config set facts.extraction_max_tokens <n>\n`,
);
- return { ok: false, reason: 'truncated_output' };
+ return { ok: false, reason: 'truncated_output', model };
}
}
} catch (err) {
// Re-throw aborts. Strict callers receive a failure outcome; the historical
// wrapper below converts that outcome to [] for best-effort call sites.
if (isAbort(err)) throw err;
- return { ok: false, reason: 'provider_error', error: err };
+ return { ok: false, reason: 'provider_error', model, error: err };
}
- if (result.stopReason === 'refusal') return { ok: false, reason: 'refusal' };
+ if (result.stopReason === 'refusal') return { ok: false, reason: 'refusal', model };
if (result.stopReason === 'content_filter') {
- return { ok: false, reason: 'content_filter' };
+ return { ok: false, reason: 'content_filter', model };
}
if (result.stopReason !== 'end') {
- return { ok: false, reason: 'non_terminal_stop' };
+ return { ok: false, reason: 'non_terminal_stop', model };
}
const parsedShape = parseExtractorJsonDetailed(result.text);
if (!parsedShape ||
(parsedShape.invalidCandidates > 0 && parsedShape.facts.length === 0)) {
- return { ok: false, reason: 'malformed_output' };
+ return { ok: false, reason: 'malformed_output', model };
}
if (parsedShape.invalidCandidates > 0) {
process.stderr.write(
@@ -383,10 +428,31 @@ export async function extractFactsFromTurnWithOutcome(
return { ok: true, facts };
}
+// Once-per-(reason, process) memo for the best-effort wrapper below — its
+// remaining callers (sweep corpus pass, transcripts ingest) previously
+// converted every failure into an invisible []. One warn per reason keeps
+// keyless installs calm while making keyed failures visible.
+const _wrapperWarningsEmitted = new Set<string>();
+/** @internal — test seam */
+export function _resetExtractWrapperWarningsForTests(): void {
+ _wrapperWarningsEmitted.clear();
+}
+
/** Historical best-effort API retained for interactive callers. */
export async function extractFactsFromTurn(input: ExtractInput): Promise<ExtractedFact[]> {
const outcome = await extractFactsFromTurnWithOutcome(input);
- return outcome.ok ? outcome.facts : [];
+ if (!outcome.ok) {
+ if (!_wrapperWarningsEmitted.has(outcome.reason)) {
+ _wrapperWarningsEmitted.add(outcome.reason);
+ process.stderr.write(
+ `[facts-extract] WARN: extraction skipped (${outcome.reason}` +
+ `${outcome.model ? `, model=${outcome.model}` : ''}); facts for this turn were not captured. ` +
+ `Further '${outcome.reason}' skips this process are silent.\n`,
+ );
+ }
+ return [];
+ }
+ return outcome.facts;
}
interface RawExtracted {
diff --git a/src/core/model-config.ts b/src/core/model-config.ts
index 9b993c8d0e..89c00bd129 100644
--- a/src/core/model-config.ts
+++ b/src/core/model-config.ts
@@ -22,6 +22,11 @@
import type { BrainEngine } from './engine.ts';
import { splitProviderModelId } from './model-id.ts';
+import type { GBrainConfig } from './config.ts';
+import { loadConfig } from './config.ts';
+import { mergedProviderEnv } from './ai/provider-env.ts';
+import { RECIPES } from './ai/recipes/index.ts';
+import { latestOpenAITiers, rankOpenAIChatModels } from './ai/openai-latest.ts';
export type ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent';
@@ -59,7 +64,11 @@ export const DEFAULT_ALIASES: Record<string, string> = {
sonnet: 'anthropic:claude-sonnet-4-6',
haiku: 'anthropic:claude-haiku-4-5-20251001',
gemini: 'google:gemini-3-pro',
- gpt: 'openai:gpt-5',
+ // `gpt` resolves DYNAMICALLY in resolveAlias (account-discovered OpenAI
+ // flagship, recipe-ranked static floor) — this entry keeps the alias
+ // enumerable but the value here is only the documentation floor; a pinned
+ // id would 404 within months (the previous 'openai:gpt-5' already did).
+ gpt: 'openai:gpt-5.6',
};
/**
@@ -78,6 +87,197 @@ export const TIER_DEFAULTS: Record<ModelTier, string> = {
subagent: 'anthropic:claude-sonnet-4-6',
};
+/**
+ * OpenAI static tier fallback — NO literal model pins. Derived from the
+ * openai recipe's chat list through the SAME ranking grammar latest-model
+ * discovery uses (openai-latest.ts), so there is exactly one place a human
+ * updates OpenAI entry points (the recipe) and one function that classifies
+ * them. The RUNTIME default overlays this with the account-discovered cache
+ * in resolveTierDefault below. Computed lazily + memoized: recipes are static
+ * data, so this is pure.
+ */
+let _openaiStaticTiers: Record<ModelTier, string> | null = null;
+export function openaiStaticTierFallback(): Record<ModelTier, string> {
+ if (!_openaiStaticTiers) {
+ const recipeModels = RECIPES.get('openai')?.touchpoints.chat?.models ?? [];
+ const ranked = rankOpenAIChatModels(recipeModels, () => true).tiers;
+ // A recipe list that defeats its own grammar would be a build bug; the
+ // Anthropic tier defaults are the never-null floor.
+ _openaiStaticTiers = ranked ?? { ...TIER_DEFAULTS };
+ }
+ return _openaiStaticTiers;
+}
+
+/**
+ * Key-aware tier defaults. The FIRST entry whose env key is present (merged
+ * env: config-file keys folded, env wins, empty strings dropped) supplies the
+ * tier default. Anthropic first preserves today's behavior byte-for-byte on
+ * every keyed install; OpenAI second makes an OPENAI_API_KEY-only install
+ * actually work (fact extraction, expansion, synthesis) instead of routing
+ * every default to a provider whose key is absent. No key at all →
+ * TIER_DEFAULTS unchanged (keyless installs degrade honestly downstream).
+ *
+ * OpenAI tiers are RESOLVED PER CALL, never pinned: the account-discovered
+ * latest (openai-latest.ts cache, refreshed at gateway connect) wins, the
+ * recipe-derived static ranking is the offline floor. The subagent tier runs
+ * without prompt caching on OpenAI → enforceSubagentCapable emits the
+ * degraded:no_caching cost warn.
+ *
+ * Adding a provider here needs a curated per-tier model choice — see the
+ * TODOS.md follow-up before extending.
+ */
+/** Account-discovered latest for a tier, else the recipe-ranked static floor. */
+function discoveredOrStaticOpenAITier(tier: ModelTier): string {
+ const discovered = latestOpenAITiers(tier);
+ return typeof discovered === 'string' ? discovered : openaiStaticTierFallback()[tier];
+}
+
+export const PROVIDER_TIER_DEFAULTS: ReadonlyArray<{
+ provider: 'anthropic' | 'openai';
+ envKey: string;
+ tiers: (tier: ModelTier) => string;
+}> = [
+ { provider: 'anthropic', envKey: 'ANTHROPIC_API_KEY', tiers: (tier) => TIER_DEFAULTS[tier] },
+ { provider: 'openai', envKey: 'OPENAI_API_KEY', tiers: discoveredOrStaticOpenAITier },
+];
+
+/** loadConfig, throw-safe (the hasAnthropicKey pattern): unreadable config = env-only. */
+function throwSafeLoadConfig(): GBrainConfig | null {
+ try {
+ return loadConfig();
+ } catch {
+ return null;
+ }
+}
+
+/** Drop ''/undefined entries (#1249) from an injected env. */
+function realEnv(env: Record<string, string | undefined>): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(env).filter(([, v]) => v !== undefined && v !== ''),
+ ) as Record<string, string>;
+}
+
+/**
+ * Resolve the default model for a tier, honoring which provider keys are
+ * actually present. When `env` is passed it is used EXCLUSIVELY (no config
+ * read — hermetic for tests and pre-merged callers); when omitted, the merged
+ * env is computed from the file-plane config + process.env.
+ */
+export function resolveTierDefault(
+ tier: ModelTier,
+ env?: Record<string, string | undefined>,
+): string {
+ const merged = env ? realEnv(env) : mergedProviderEnv(throwSafeLoadConfig(), process.env);
+ for (const entry of PROVIDER_TIER_DEFAULTS) {
+ if (merged[entry.envKey]) return entry.tiers(tier);
+ }
+ return TIER_DEFAULTS[tier];
+}
+
+/**
+ * True when `model`'s provider can serve CHAT and has every required auth
+ * env var present in `env` (per its recipe's auth_env.required). Bare model
+ * ids (no provider prefix) and unknown providers return false — an
+ * unverifiable pin is not a servable pin. A keyed but chat-less recipe
+ * (e.g. an embedding-only provider pinned as chat_model) is also not ready:
+ * every caller of this function resolves a chat-shaped tier, and honoring
+ * such a pin would install a model `isAvailable('chat')` rejects instead of
+ * falling back to the key-aware default. Recipes with no required keys
+ * (e.g. local Ollama) are always ready.
+ */
+export function providerKeyReady(model: string, env: Record<string, string>): boolean {
+ const { provider } = splitProviderModelId(model);
+ if (!provider) return false;
+ const recipe = RECIPES.get(provider.trim().toLowerCase());
+ if (!recipe) return false;
+ if (!recipe.touchpoints?.chat) return false;
+ const required = recipe.auth_env?.required ?? [];
+ if (required.length === 0) return true;
+ return required.every((k) => !!env[k]);
+}
+
+const _unservablePinWarningsEmitted = new Set<string>();
+
+export type EffectiveModelSource = 'env_model' | 'file_pin' | 'tier_default';
+
+/**
+ * Engine-free effective-model resolution for a chat-shaped tier. ONE shared
+ * function — `reconfigureGatewayWithEngine`'s fallback layer and
+ * `detectCapabilities`' extraction probe both call it, so runtime routing and
+ * the capability report cannot diverge by construction.
+ *
+ * Reads the RAW file-plane config — never gateway state, which stamps
+ * defaults at boot and makes an explicit pin indistinguishable from a
+ * fabricated one. Precedence: GBRAIN_MODEL env > servable file pin (its
+ * provider's keys are present) > key-aware tier default. An unservable pin
+ * (init-era pin whose key is gone, or a provider switch) falls through with
+ * one stderr warn per (pin, process) — availability-aware, never a hard fail.
+ */
+function resolveEffectiveModelForTier(
+ tier: ModelTier,
+ pin: string | undefined,
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined>,
+): { model: string; source: EffectiveModelSource } {
+ const merged = mergedProviderEnv(fileCfg, env);
+ const envModel = merged.GBRAIN_MODEL?.trim();
+ if (envModel) {
+ // Same `gpt` discovery routing as the pin branch below and
+ // resolveAlias — GBRAIN_MODEL=gpt must not resolve differently
+ // depending on which resolver ran.
+ const model = envModel === 'gpt'
+ ? discoveredOrStaticOpenAITier('deep')
+ : DEFAULT_ALIASES[envModel] ?? envModel;
+ return { model, source: 'env_model' };
+ }
+ const rawPin = pin?.trim();
+ if (rawPin) {
+ // A bare `gpt` alias pin resolves through the same discovery path as
+ // resolveAlias('gpt') — the DEFAULT_ALIASES entry is only the
+ // documentation floor and would silently bypass the account-discovered
+ // flagship.
+ const fullPin = rawPin === 'gpt'
+ ? discoveredOrStaticOpenAITier('deep')
+ : DEFAULT_ALIASES[rawPin] ?? rawPin;
+ if (providerKeyReady(fullPin, merged)) return { model: fullPin, source: 'file_pin' };
+ if (!_unservablePinWarningsEmitted.has(fullPin)) {
+ _unservablePinWarningsEmitted.add(fullPin);
+ // Explicit tier→config-key map: an unmapped future caller mislabeling
+ // the warn would be a silent doc bug with a ternary.
+ const PIN_KEY_BY_TIER: Record<ModelTier, string> = {
+ utility: 'expansion_model', reasoning: 'chat_model', deep: 'chat_model', subagent: 'chat_model',
+ };
+ // A prefix-less pin is a DIFFERENT problem than a missing key — saying
+ // "no usable provider key" for `chat_model: "claude-sonnet-4-6"` sends
+ // the user hunting for a key problem they may not have.
+ const diagnosis = splitProviderModelId(fullPin).provider === null
+ ? `has no provider prefix, so its key can't be verified — prefix it (e.g. "anthropic:${fullPin}")`
+ : `has no usable provider key — set the provider's API key, update the pin`;
+ process.stderr.write(
+ `[models] configured ${PIN_KEY_BY_TIER[tier]} "${fullPin}" ${diagnosis}, ` +
+ `or remove it from ~/.gbrain/config.json. Falling back to the key-aware default.\n`,
+ );
+ }
+ }
+ return { model: resolveTierDefault(tier, merged), source: 'tier_default' };
+}
+
+/** Effective chat model (reasoning tier) from raw file config + env. */
+export function resolveEffectiveChatModel(
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined> = process.env,
+): { model: string; source: EffectiveModelSource } {
+ return resolveEffectiveModelForTier('reasoning', fileCfg?.chat_model, fileCfg, env);
+}
+
+/** Effective expansion model (utility tier) from raw file config + env. */
+export function resolveEffectiveExpansionModel(
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined> = process.env,
+): { model: string; source: EffectiveModelSource } {
+ return resolveEffectiveModelForTier('utility', fileCfg?.expansion_model, fileCfg, env);
+}
+
/**
* v0.31.12 subagent runtime enforcement (layer 2).
*
@@ -125,20 +325,35 @@ function emitDeprecationWarning(oldKey: string, newKey: string, ignored: boolean
}
}
+/** Which step of the resolution chain produced the model. */
+export type ResolveSource =
+ | 'cli_flag'
+ | 'config_key'
+ | 'deprecated_key'
+ | 'models_default'
+ | 'tier_config'
+ | 'env'
+ | 'tier_default'
+ | 'fallback';
+
/**
- * Resolve a model name through the 6-tier precedence chain. Async because it
- * reads config from the engine. Pass `engine: null` for callsites that don't
- * have an engine (rare; usually CLI bootstrap before connect).
+ * Resolve a model name through the precedence chain, reporting WHICH step
+ * produced it. Async because it reads config from the engine. Pass
+ * `engine: null` for callsites that don't have an engine (rare; usually CLI
+ * bootstrap before connect). Step 7 (tier default) is key-aware: it routes
+ * through `resolveTierDefault`, so an install whose only key is
+ * OPENAI_API_KEY resolves tier defaults to OpenAI models instead of an
+ * unservable Anthropic default.
*/
-export async function resolveModel(
+export async function resolveModelDetailed(
engine: BrainEngine | null,
opts: ResolveModelOpts,
-): Promise<string> {
+): Promise<{ model: string; source: ResolveSource }> {
const envVar = opts.envVar ?? 'GBRAIN_MODEL';
// 1. CLI flag wins
if (opts.cliFlag && opts.cliFlag.trim()) {
- return await resolveAlias(engine, opts.cliFlag.trim());
+ return { model: await resolveAlias(engine, opts.cliFlag.trim()), source: 'cli_flag' };
}
if (engine) {
@@ -153,7 +368,7 @@ export async function resolveModel(
emitDeprecationWarning(opts.deprecatedConfigKey, opts.configKey, /*ignored=*/ true);
}
}
- return await resolveAlias(engine, v.trim());
+ return { model: await resolveAlias(engine, v.trim()), source: 'config_key' };
}
}
@@ -162,7 +377,7 @@ export async function resolveModel(
const v = await engine.getConfig(opts.deprecatedConfigKey);
if (v && v.trim()) {
emitDeprecationWarning(opts.deprecatedConfigKey, opts.configKey ?? '<no replacement>', /*ignored=*/ false);
- return await resolveAlias(engine, v.trim());
+ return { model: await resolveAlias(engine, v.trim()), source: 'deprecated_key' };
}
}
@@ -170,7 +385,7 @@ export async function resolveModel(
const def = await engine.getConfig('models.default');
if (def && def.trim()) {
const resolved = await resolveAlias(engine, def.trim());
- return enforceSubagentCapable(resolved, opts.tier, 'models.default');
+ return { model: enforceSubagentCapable(resolved, opts.tier, 'models.default'), source: 'models_default' };
}
// 5. Tier override (v0.31.12)
@@ -178,7 +393,7 @@ export async function resolveModel(
const tierVal = await engine.getConfig(`models.tier.${opts.tier}`);
if (tierVal && tierVal.trim()) {
const resolved = await resolveAlias(engine, tierVal.trim());
- return enforceSubagentCapable(resolved, opts.tier, `models.tier.${opts.tier}`);
+ return { model: enforceSubagentCapable(resolved, opts.tier, `models.tier.${opts.tier}`), source: 'tier_config' };
}
}
}
@@ -187,17 +402,30 @@ export async function resolveModel(
const env = process.env[envVar];
if (env && env.trim()) {
const resolved = await resolveAlias(engine, env.trim());
- return enforceSubagentCapable(resolved, opts.tier, `env:${envVar}`);
+ return { model: enforceSubagentCapable(resolved, opts.tier, `env:${envVar}`), source: 'env' };
}
- // 7. Tier default (v0.31.12 — when no override beats us, the tier's
- // canonical model wins over caller-supplied fallback)
+ // 7. Key-aware tier default — when no override beats us, the tier's
+ // canonical model for the first env-ready provider wins over the
+ // caller-supplied fallback.
if (opts.tier && TIER_DEFAULTS[opts.tier]) {
- return await resolveAlias(engine, TIER_DEFAULTS[opts.tier]);
+ const resolved = await resolveAlias(engine, resolveTierDefault(opts.tier));
+ return { model: enforceSubagentCapable(resolved, opts.tier, 'tier-default'), source: 'tier_default' };
}
// 8. Hardcoded fallback (caller-supplied)
- return await resolveAlias(engine, opts.fallback);
+ return { model: await resolveAlias(engine, opts.fallback), source: 'fallback' };
+}
+
+/**
+ * Resolve a model name through the precedence chain. Thin wrapper over
+ * `resolveModelDetailed` for the ~30 callers that don't care which step won.
+ */
+export async function resolveModel(
+ engine: BrainEngine | null,
+ opts: ResolveModelOpts,
+): Promise<string> {
+ return (await resolveModelDetailed(engine, opts)).model;
}
/**
@@ -315,7 +543,9 @@ export async function resolveAlias(
}
}
if (name in DEFAULT_ALIASES) {
- const next = DEFAULT_ALIASES[name];
+ // `gpt` tracks the CURRENT OpenAI flagship (discovered from the account,
+ // recipe-ranked static floor) instead of a pinned id that goes stale.
+ const next = name === 'gpt' ? discoveredOrStaticOpenAITier('deep') : DEFAULT_ALIASES[name];
if (next && next !== name) return await resolveAlias(engine, next, depth + 1);
}
return name;
@@ -325,4 +555,5 @@ export async function resolveAlias(
export function _resetDeprecationWarningsForTest(): void {
_deprecationWarningsEmitted.clear();
_subagentTierWarningsEmitted.clear();
+ _unservablePinWarningsEmitted.clear();
}
diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.ts
index b060f20124..b86a546183 100644
--- a/src/core/model-pricing.ts
+++ b/src/core/model-pricing.ts
@@ -82,6 +82,16 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {
// slot A from the --max-usd pre-flight and est_cost_usd audit rows.
'openai:gpt-5.2': { input: 1.25, output: 10.00 },
'openai:gpt-5.5': { input: 4.00, output: 16.00 },
+ // gpt-5.6 family (GA 2026-07-09; rates cross-checked 2026-08-17 across
+ // aggregator trackers — re-verify against platform.openai.com/pricing at
+ // next release). The bare `gpt-5.6` id is OpenAI's rolling alias for the
+ // family flagship (sol). These rows are LOAD-BEARING for latest-model
+ // discovery (src/core/ai/openai-latest.ts): only priced ids are eligible
+ // as defaults, so budget caps never fail closed on a discovered model.
+ 'openai:gpt-5.6': { input: 5.00, output: 30.00 },
+ 'openai:gpt-5.6-sol': { input: 5.00, output: 30.00 },
+ 'openai:gpt-5.6-terra': { input: 2.50, output: 15.00 },
+ 'openai:gpt-5.6-luna': { input: 1.00, output: 6.00 },
// ── Google ─────────────────────────────────────────────────────────────
// `gemini-1.5-pro` was retired by Google (#3510); kept so historical
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index c1dab84bba..b052a83e25 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -30,7 +30,7 @@ import type { SearchResult } from '../types.ts';
const extract_facts: Operation = {
name: 'extract_facts',
description:
- 'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls Haiku to extract structured claims, runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',
+ 'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls the configured extraction model (key-aware: any servable provider — OpenAI or Anthropic key both work), runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. With NO servable chat model, returns skipped: extraction_unavailable + an agent_action telling YOU to extract and write via `remember` (visibility: "private"). Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',
params: {
turn_text: { type: 'string', required: true, description: 'The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call.' },
session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface.' },
@@ -78,6 +78,46 @@ const extract_facts: Operation = {
mode: 'inline', // declarative; runFactsPipeline always inline
});
+ // Reason-specific envelopes — never collapse distinct failures into one
+ // message. `chat_unavailable` means no servable chat model: the calling
+ // agent IS an LLM, so hand it the keyless self-extract path (the
+ // `remember` verb + `## Facts` fences work with zero keys). The
+ // visibility pin in the instruction is mandatory copy: `remember`
+ // defaults to 'world' while extract_facts facts default 'private' —
+ // omitting it would silently widen private data to every connected agent.
+ // The visibility instruction names the RESOLVED visibility for THIS call
+ // (caller param > facts.default_visibility config > private): a caller who
+ // asked for world must not be steered to private, and an unpinned
+ // instruction would silently widen private-default extractions because
+ // `remember` hard-defaults to 'world'.
+ const visibilityPin = `visibility: "${visibility}"` +
+ (visibility === 'private' ? ' (remember defaults to world — omitting it would widen these facts)' : '');
+ if (r.skipped_reason === 'chat_unavailable') {
+ return {
+ inserted: 0, duplicate: 0, superseded: 0, fact_ids: [],
+ skipped: 'extraction_unavailable',
+ agent_action:
+ 'No server-side chat model is available. You are an LLM: extract the facts ' +
+ 'yourself (up to ~10 per turn) and write each one with the `remember` verb: ' +
+ 'one claim per call, provenance required, set `kind` (event | preference | ' +
+ 'commitment | belief — it defaults to plain "fact" otherwise), set `entity` ' +
+ `when the fact is about a person/company/project, and ${visibilityPin}. ` +
+ 'Or author a `## Facts` fence on the entity page. To enable automatic ' +
+ 'extraction, add an OpenAI or Anthropic API key.',
+ };
+ }
+ if (r.skipped_reason) {
+ return {
+ inserted: 0, duplicate: 0, superseded: 0, fact_ids: [],
+ skipped: 'extraction_failed',
+ reason: r.skipped_reason,
+ agent_action:
+ `The extractor failed on this turn (${r.skipped_reason}). You may extract the ` +
+ 'facts manually via the `remember` verb (one claim per call, provenance ' +
+ `required, ${visibilityPin}).`,
+ };
+ }
+
return {
inserted: r.inserted,
duplicate: r.duplicate,
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 96f8da499a..0b96982dbd 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.46.20.0 -->
+<!-- gbrain-template-stamp: 0.46.21.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/capabilities.test.ts b/test/ai/capabilities.test.ts
index 0c03973aff..6b07e1693b 100644
--- a/test/ai/capabilities.test.ts
+++ b/test/ai/capabilities.test.ts
@@ -14,7 +14,7 @@ describe('getProviderCapabilities (v0.38 Slice 1 — D6/D7 recipe-driven capabil
const caps = getProviderCapabilities('openai:gpt-5.2');
expect(caps.supportsToolCalling).toBe(true);
expect(caps.supportsPromptCaching).toBe(false); // OpenAI implicit caching doesn't get marked
- expect(caps.maxContext).toBe(200000);
+ expect(caps.maxContext).toBe(1_050_000); // gpt-5.6 family window (recipe-driven)
});
it('returns capabilities for Google Gemini', () => {
diff --git a/test/capability.test.ts b/test/capability.test.ts
index e00fd0b22d..767f07f607 100644
--- a/test/capability.test.ts
+++ b/test/capability.test.ts
@@ -78,7 +78,11 @@ describe('detectCapabilities — matrix', () => {
expect(caps.extraction).toEqual({ available: true, provider: 'google' });
});
- test('unknown provider in model string → unavailable, not a throw', () => {
+ test('unknown provider in model string → no throw; extraction falls back key-aware', () => {
+ // Availability-aware fallback: an unknown chat pin is unservable, so the
+ // effective-model resolution falls through to the key-aware tier default —
+ // with an OpenAI key present, extraction is honestly AVAILABLE via openai
+ // (an openai-only install with a garbage pin must still extract).
const caps = detectCapabilities({
config: cfg({
embedding_model: 'not-a-provider:some-model',
@@ -87,9 +91,50 @@ describe('detectCapabilities — matrix', () => {
env: { OPENAI_API_KEY: 'sk-test' },
});
expect(caps.embeddings.available).toBe(false);
+ expect(caps.extraction).toEqual({ available: true, provider: 'openai' });
+ expect(caps.mode).toBe('keyed');
+ });
+
+ test('unknown provider pin + NO key → unavailable, not a throw', () => {
+ const caps = detectCapabilities({
+ config: cfg({
+ embedding_model: 'not-a-provider:some-model',
+ chat_model: 'also-not-real:x',
+ }),
+ env: {},
+ });
+ expect(caps.embeddings.available).toBe(false);
expect(caps.extraction.available).toBe(false);
expect(caps.mode).toBe('keyless');
});
+
+ test('openai-key-only, no config → extraction available via openai (key-aware default)', () => {
+ const caps = detectCapabilities({ config: null, env: { OPENAI_API_KEY: 'sk-test' } });
+ expect(caps.extraction).toEqual({ available: true, provider: 'openai' });
+ });
+
+ test('voyage key + voyage embedding pin → embeddings yes, extraction no, mode keyed', () => {
+ // Init writes the voyage embedding pin to config; the Voyage key powers
+ // semantic search but NOT extraction (no chat touchpoint).
+ const caps = detectCapabilities({
+ config: cfg({ embedding_model: 'voyage:voyage-4' }),
+ env: { VOYAGE_API_KEY: 'pa-test' },
+ });
+ expect(caps.embeddings).toEqual({ available: true, provider: 'voyage' });
+ expect(caps.extraction.available).toBe(false);
+ expect(caps.mode).toBe('keyed');
+ });
+
+ test('GBRAIN_MODEL honored by the extraction probe (engine-free env override)', () => {
+ // GBRAIN_MODEL names an openai model; only the OpenAI key is present →
+ // available via openai even though the anthropic-first default would
+ // otherwise win when both keys exist.
+ const caps = detectCapabilities({
+ config: null,
+ env: { GBRAIN_MODEL: 'openai:gpt-4o-mini', OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test' },
+ });
+ expect(caps.extraction).toEqual({ available: true, provider: 'openai' });
+ });
});
describe('renderCapabilityReport', () => {
@@ -100,7 +145,8 @@ describe('renderCapabilityReport', () => {
expect(text).toContain('keyless mode');
expect(text).toContain('keyword-only');
expect(text).toContain('agent-authored');
- expect(text).toContain('add ONE key');
+ expect(text).toContain('one optional key upgrades capabilities');
+ expect(text).toContain('OpenAI: semantic search + auto-extraction');
});
test('keyed report names the providers and drops the upsell', () => {
@@ -116,6 +162,6 @@ describe('renderCapabilityReport', () => {
);
expect(text).toContain('keyed mode');
expect(text).toContain('openai');
- expect(text).not.toContain('add ONE key');
+ expect(text).not.toContain('one optional key upgrades capabilities');
});
});
diff --git a/test/facts-absorb-log.test.ts b/test/facts-absorb-log.test.ts
index 3ce94a9a5e..fe7c6405fb 100644
--- a/test/facts-absorb-log.test.ts
+++ b/test/facts-absorb-log.test.ts
@@ -118,7 +118,14 @@ describe('writeFactsAbsorbLog — ingest_log row shape', () => {
expect(FACTS_ABSORB_REASONS).toContain('queue_shutdown');
expect(FACTS_ABSORB_REASONS).toContain('embed_failure');
expect(FACTS_ABSORB_REASONS).toContain('pipeline_error');
- expect(FACTS_ABSORB_REASONS.length).toBe(6);
+ // Extraction-outcome codes (keyed-but-failing states; keyless writes no row).
+ expect(FACTS_ABSORB_REASONS).toContain('chat_unavailable');
+ expect(FACTS_ABSORB_REASONS).toContain('refusal');
+ expect(FACTS_ABSORB_REASONS).toContain('content_filter');
+ expect(FACTS_ABSORB_REASONS).toContain('malformed_output');
+ expect(FACTS_ABSORB_REASONS).toContain('non_terminal_stop');
+ expect(FACTS_ABSORB_REASONS).toContain('truncated_output');
+ expect(FACTS_ABSORB_REASONS.length).toBe(12);
});
});
diff --git a/test/facts-backstop-gating.test.ts b/test/facts-backstop-gating.test.ts
index e9f3dbe5b9..bff76158eb 100644
--- a/test/facts-backstop-gating.test.ts
+++ b/test/facts-backstop-gating.test.ts
@@ -10,7 +10,7 @@
import { describe, test, expect, beforeAll, beforeEach, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { resetGateway } from '../src/core/ai/gateway.ts';
+import { resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
let engine: PGLiteEngine;
@@ -29,7 +29,24 @@ beforeAll(async () => {
// 401. Reset the gateway before each test so isAvailable('embedding') is
// deterministically false → put_page uses noEmbed → the import never embeds →
// we exercise only the backstop gating the suite is about.
-beforeEach(() => { resetGateway(); });
+//
+// Chat transport stub: the backstop now gates on extraction availability
+// BEFORE enqueueing (keyless installs skip instead of minting doomed work).
+// This suite asserts eligibility/kill-switch/enqueue behavior, not
+// availability — install the transport seam so the availability gate passes
+// deterministically regardless of shard env keys.
+beforeEach(() => {
+ resetGateway();
+ __setChatTransportForTests(async () => ({
+ text: '[]',
+ blocks: [{ type: 'text', text: '[]' }],
+ stopReason: 'end' as const,
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ }));
+});
+afterAll(() => { __setChatTransportForTests(null); });
afterAll(async () => {
await engine.disconnect();
diff --git a/test/facts-backstop-integration.test.ts b/test/facts-backstop-integration.test.ts
index bf97e570d2..02b31cc954 100644
--- a/test/facts-backstop-integration.test.ts
+++ b/test/facts-backstop-integration.test.ts
@@ -223,42 +223,41 @@ describe('queue-mode → drains successfully on happy path', () => {
expect(counters.failed).toBe(0);
});
- test('extract.ts absorbs gateway errors silently — net effect is empty extraction', async () => {
- // The contract: extract.ts catches gateway errors and returns [] without
- // re-throwing (only AbortError re-throws). Backstop's catch only sees
- // errors from layers ABOVE extract — resolver, dedup, insert. Document
- // this here so future work that wants chat-error visibility knows to
- // rewire extract.ts itself rather than the backstop catch.
+ test('gateway errors PROPAGATE as typed FactsExtractionError in inline mode (silent-absorb contract retired)', async () => {
+ // The old contract deliberately swallowed gateway errors into empty
+ // extraction ("net effect is empty extraction") and left a note that
+ // future visibility work should rewire extract.ts. That work landed:
+ // transport-class failures (provider_error / truncated_output) now throw
+ // a typed FactsExtractionError — the queue-mode catch maps it to precise
+ // absorb-log codes, the durable minion retries, and the inline
+ // extract_facts op surfaces a real error instead of lying `inserted: 0`.
__setChatTransportForTests(async () => {
throw new Error('429 rate limit');
});
- const slug = 'meetings/silent-absorb-' + Math.random().toString(36).slice(2, 8);
- const r = await runFactsBackstop(
- {
- slug,
- type: 'meeting',
- compiled_truth: LONG_BODY,
- frontmatter: {},
- },
- {
- engine,
- sourceId: 'silent-source',
- sessionId: 'silent-session',
- source: 'mcp:put_page',
- mode: 'inline',
- },
- );
-
- // Inline-mode envelope returns zero counts; no error thrown.
- expect(r.mode).toBe('inline');
- if (r.mode === 'inline') {
- expect(r.inserted).toBe(0);
- expect(r.duplicate).toBe(0);
+ const slug = 'meetings/typed-throw-' + Math.random().toString(36).slice(2, 8);
+ let thrown: unknown;
+ try {
+ await runFactsBackstop(
+ {
+ slug,
+ type: 'meeting',
+ compiled_truth: LONG_BODY,
+ frontmatter: {},
+ },
+ {
+ engine,
+ sourceId: 'silent-source',
+ sessionId: 'silent-session',
+ source: 'mcp:put_page',
+ mode: 'inline',
+ },
+ );
+ } catch (e) {
+ thrown = e;
}
-
- // Note for future work: writeFactsAbsorbLog from extract.ts itself
- // would close this visibility gap — surface gateway errors via
- // ingest_log without changing extract's "best-effort" return contract.
+ expect(thrown).toBeInstanceOf(Error);
+ expect((thrown as Error).name).toBe('FactsExtractionError');
+ expect((thrown as { reason?: string }).reason).toBe('provider_error');
});
});
diff --git a/test/facts-backstop-outcome.serial.test.ts b/test/facts-backstop-outcome.serial.test.ts
new file mode 100644
index 0000000000..9f6169f981
--- /dev/null
+++ b/test/facts-backstop-outcome.serial.test.ts
@@ -0,0 +1,355 @@
+/**
+ * Facts extraction outcome honesty — the silent-[] bug-class regression suite.
+ *
+ * Pins the D4/D6 contract:
+ * - keyless-expected chat_unavailable: NO ingest_log row, ONE calm stderr
+ * note (keyless is an expected state, not a failure)
+ * - keyed-but-failing: one ingest_log row (doctor reads it) + fix hint
+ * - transport-class failures (provider_error/truncated_output) THROW a
+ * typed FactsExtractionError; the queue-mode classifier maps it to
+ * precise absorb codes
+ * - the pre-enqueue gate consults the RESOLVED extraction model (a servable
+ * DB-plane override must never be skipped — the CX1 false-skip class)
+ * - durable facts-absorb jobs carry the slow-retry policy (max_attempts 5,
+ * 60s backoff) and the handler retry-decision converts execution-time
+ * unavailability into a throw, never a silent consume
+ * - extract_facts returns reason-specific envelopes; the keyless one pins
+ * visibility: "private" (remember defaults to world)
+ * - put_page NEVER fails because its facts backstop threw (E1 invariant)
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __setChatTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import {
+ runFactsBackstop,
+ runFactsPipeline,
+ __resetBackstopWarningsForTests,
+} from '../src/core/facts/backstop.ts';
+import {
+ FactsExtractionError,
+ _resetExtractWrapperWarningsForTests,
+ extractFactsFromTurn,
+} from '../src/core/facts/extract.ts';
+import {
+ classifyFactsAbsorbError,
+ _resetFactsAbsorbDisconnectedFlagForTests,
+} from '../src/core/facts/absorb-log.ts';
+import { factsAbsorbShouldRetry } from '../src/commands/jobs.ts';
+import { markShortLivedCliProcess, __resetShortLivedCliForTests } from '../src/core/facts/cli-process-mode.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let engine: PGLiteEngine;
+const PINNED = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GBRAIN_MODEL', 'GBRAIN_HOME'] as const;
+let saved: Record<string, string | undefined>;
+let tmpHome: string;
+let stderrCapture: string;
+const origWrite = process.stderr.write.bind(process.stderr);
+// backstop's warnOnce writes via console.warn (not process.stderr.write) —
+// capture both channels into one buffer.
+const origConsoleWarn = console.warn.bind(console);
+
+function unwrap(r: { isError?: boolean; content: Array<{ text?: string }> }): Record<string, unknown> {
+ expect(r.isError).toBeFalsy();
+ return JSON.parse(r.content[0].text ?? '{}') as Record<string, unknown>;
+}
+
+const ELIGIBLE_BODY =
+ 'An eligible substantive note body. ' +
+ 'Enough prose to clear the minimum body length gate for the backstop. '.repeat(3);
+
+async function absorbRows(): Promise<Array<{ summary: string }>> {
+ return engine.executeRaw<{ summary: string }>(
+ `SELECT summary FROM ingest_log WHERE source_type = 'facts:absorb' ORDER BY created_at`,
+ );
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+beforeEach(async () => {
+ saved = {};
+ for (const k of PINNED) { saved[k] = process.env[k]; delete process.env[k]; }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-outcome-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ resetGateway();
+ __setChatTransportForTests(null);
+ __resetBackstopWarningsForTests();
+ __resetShortLivedCliForTests();
+ _resetExtractWrapperWarningsForTests();
+ _resetFactsAbsorbDisconnectedFlagForTests();
+ await engine.executeRaw(`DELETE FROM ingest_log WHERE source_type = 'facts:absorb'`).catch(() => {});
+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE name = 'facts-absorb'`).catch(() => {});
+ await engine.unsetConfig('facts.extraction_model').catch(() => {});
+ stderrCapture = '';
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ stderrCapture += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();
+ return true;
+ }) as typeof process.stderr.write;
+ console.warn = ((...args: unknown[]) => { stderrCapture += args.map(String).join(' ') + '\n'; }) as typeof console.warn;
+});
+
+const restoreEnv = () => {
+ process.stderr.write = origWrite;
+ console.warn = origConsoleWarn;
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const k of PINNED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+};
+afterEach(restoreEnv);
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ await engine.disconnect();
+ // Shard hygiene: restore the legacy embedding pin (see
+ // facts-extract-silent-no-op.test.ts for the poisoning story).
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+});
+
+describe('keyless vs keyed chat_unavailable', () => {
+ test('keyless: NO ingest_log row + one calm stderr note', async () => {
+ configureGateway({ env: {} }); // keyless gateway
+ const r = await runFactsBackstop(
+ { slug: 'outcome-keyless', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'queue' },
+ );
+ expect(r.mode).toBe('queue');
+ expect((r as { skipped?: string }).skipped).toBe('extraction_unavailable');
+ expect(await absorbRows()).toHaveLength(0);
+ expect(stderrCapture).toContain('keyless');
+ // Calm: the note fires once per process, not per write.
+ const before = stderrCapture.length;
+ await runFactsBackstop(
+ { slug: 'outcome-keyless-2', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'queue' },
+ );
+ expect(stderrCapture.length).toBe(before);
+ });
+
+ test('keyed-but-misrouted: one ingest_log row + fix hint', async () => {
+ // An OpenAI key exists but the pinned extraction model is Anthropic with
+ // no Anthropic key — a keyed problem the operator must see.
+ process.env.OPENAI_API_KEY = 'sk-test';
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-test' } });
+ const r = await runFactsBackstop(
+ { slug: 'outcome-misroute', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'queue' },
+ );
+ expect((r as { skipped?: string }).skipped).toBe('extraction_unavailable');
+ const rows = await absorbRows();
+ expect(rows).toHaveLength(1);
+ expect(rows[0].summary).toContain('chat_unavailable');
+ expect(rows[0].summary).toContain('anthropic:claude-sonnet-4-6');
+ expect(stderrCapture).toContain('facts.extraction_model');
+ });
+
+ test('pre-enqueue gate does NOT skip a servable DB-plane override (CX1 false-skip class)', async () => {
+ // Global default would be Anthropic (unservable), but the DB-plane
+ // extraction override IS servable with the OpenAI key — the engine-aware
+ // gate must admit the work. Short-lived mode routes to the durable minion
+ // (no LLM call executes in-test) so we can also pin the retry policy.
+ process.env.OPENAI_API_KEY = 'sk-test';
+ await engine.setConfig('facts.extraction_model', 'openai:gpt-4o-mini');
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-test' } });
+ markShortLivedCliProcess();
+ const r = await runFactsBackstop(
+ { slug: 'outcome-servable-override', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'queue' },
+ );
+ expect(r.mode).toBe('queue');
+ expect((r as { enqueued: boolean }).enqueued).toBe(true);
+ expect((r as { skipped?: string }).skipped).toBeUndefined();
+ const jobs = await engine.executeRaw<{ max_attempts: number; backoff_delay: number }>(
+ `SELECT max_attempts, backoff_delay FROM minion_jobs WHERE name = 'facts-absorb'`,
+ );
+ expect(jobs).toHaveLength(1);
+ // Slow-retry policy (R2-5): config drift is fixed on human timescales.
+ expect(Number(jobs[0].max_attempts)).toBe(5);
+ expect(Number(jobs[0].backoff_delay)).toBe(60_000);
+ });
+});
+
+describe('transport-class failures throw typed', () => {
+ test('provider_error propagates as FactsExtractionError in inline mode', async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ __setChatTransportForTests(async () => { throw new Error('simulated 500 from provider'); });
+ let thrown: unknown;
+ try {
+ await runFactsPipeline('alice-example founded acme-example in 2010 with charlie-example.', {
+ engine: engine as BrainEngine, sourceId: 'default', sessionId: null,
+ source: 'mcp:extract_facts', mode: 'inline',
+ });
+ } catch (e) { thrown = e; }
+ expect(thrown).toBeInstanceOf(FactsExtractionError);
+ expect((thrown as FactsExtractionError).reason).toBe('provider_error');
+ expect((thrown as FactsExtractionError).model).toBeTruthy();
+ });
+
+ test('classifier maps typed reasons precisely (queue-mode absorb codes)', () => {
+ expect(classifyFactsAbsorbError(new FactsExtractionError('provider_error', 'openai:gpt-5.2', new Error('401')))).toBe('gateway_error');
+ expect(classifyFactsAbsorbError(new FactsExtractionError('truncated_output', 'openai:gpt-5.2'))).toBe('truncated_output');
+ expect(classifyFactsAbsorbError(new FactsExtractionError('chat_unavailable'))).toBe('chat_unavailable');
+ });
+
+ test('durable-job retry decision: KEYED unavailable throws, keyless completes calm, real results return (CX9)', () => {
+ const unavailable: import('../src/core/facts/backstop.ts').FactsBackstopResult =
+ { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_unavailable' };
+ // Keyed worker + execution-time unavailability = config drift → retry.
+ expect(factsAbsorbShouldRetry(unavailable, 'keyed')).toBe(true);
+ expect(factsAbsorbShouldRetry({ mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped_reason: 'chat_unavailable' }, 'keyed')).toBe(true);
+ // Keyless worker = expected steady state → calm skip-success, never a
+ // failed-retry loop on every page write.
+ expect(factsAbsorbShouldRetry(unavailable, 'keyless')).toBe(false);
+ expect(factsAbsorbShouldRetry({ mode: 'inline', inserted: 2, duplicate: 0, superseded: 0, fact_ids: [1, 2] }, 'keyed')).toBe(false);
+ // refusal/malformed are NOT retryable drift — they logged and returned.
+ expect(factsAbsorbShouldRetry({ mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped_reason: 'malformed_output' }, 'keyed')).toBe(false);
+ expect(factsAbsorbShouldRetry({ mode: 'queue', enqueued: true, queueDepth: 0 }, 'keyed')).toBe(false);
+ });
+
+ test('classifyUnavailable: keyed when any chat key or servable model exists; keyless otherwise', async () => {
+ const { classifyUnavailable } = await import('../src/core/facts/backstop.ts');
+ // Pinned env (beforeEach) + tmp GBRAIN_HOME → no keys anywhere → keyless.
+ expect(await classifyUnavailable('anthropic:claude-sonnet-4-6')).toBe('keyless');
+ process.env.OPENAI_API_KEY = 'sk-test';
+ try {
+ // A chat-capable key exists → a failure is a KEYED problem (visible).
+ expect(await classifyUnavailable('anthropic:claude-sonnet-4-6')).toBe('keyed');
+ } finally {
+ delete process.env.OPENAI_API_KEY;
+ }
+ });
+});
+
+describe('extract_facts reason-specific envelopes', () => {
+ test('keyless → skipped: extraction_unavailable + agent_action pinning visibility private (CX4)', async () => {
+ configureGateway({ env: {} });
+ const res = unwrap(await dispatchToolCall(engine, 'extract_facts', { turn_text: ELIGIBLE_BODY }, { remote: false }));
+ expect(res.skipped).toBe('extraction_unavailable');
+ expect(res.inserted).toBe(0);
+ const action = String(res.agent_action);
+ expect(action).toContain('remember');
+ expect(action).toContain('visibility: "private"');
+ expect(action).toContain('kind');
+ expect(action).not.toContain('session id'); // remember has no session_id param (R2-8)
+ });
+
+ test('malformed extractor output → skipped: extraction_failed + reason (CX5 — never "unavailable")', async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ __setChatTransportForTests(async () => ({
+ text: 'this is not json at all {{{',
+ blocks: [{ type: 'text', text: 'this is not json at all {{{' }],
+ stopReason: 'end' as const,
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ }));
+ const res = unwrap(await dispatchToolCall(engine, 'extract_facts', { turn_text: ELIGIBLE_BODY }, { remote: false }));
+ expect(res.skipped).toBe('extraction_failed');
+ expect(res.reason).toBe('malformed_output');
+ expect(String(res.agent_action)).toContain('remember');
+ // keyed-but-failing → visible to doctor
+ const rows = await absorbRows();
+ expect(rows.some((r) => r.summary.startsWith('malformed_output'))).toBe(true);
+ });
+});
+
+describe('put_page never fails on extraction errors (E1 invariant)', () => {
+ test('page write succeeds while the extraction transport throws', async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ __setChatTransportForTests(async () => { throw new Error('simulated provider outage'); });
+ const res = await dispatchToolCall(engine, 'put_page', {
+ slug: 'e1-invariant-page',
+ content: `---\ntype: note\ntitle: E1 invariant\n---\n${ELIGIBLE_BODY}`,
+ }, { remote: false });
+ expect(res.isError).toBeFalsy();
+ const page = await engine.getPage('e1-invariant-page', { sourceId: 'default' });
+ expect(page).toBeTruthy();
+ expect(page?.slug).toBe('e1-invariant-page');
+ // Drain the in-process facts queue so the async failure lands, then
+ // confirm it was absorbed as a LOG ROW, not a thrown write failure.
+ const { getFactsQueue } = await import('../src/core/facts/queue.ts');
+ await getFactsQueue().drainPending({ timeout: 10_000 });
+ const rows = await absorbRows();
+ expect(rows.some((r) => r.summary.startsWith('gateway_error'))).toBe(true);
+ });
+});
+
+describe('legacy wrapper visibility (eng F3)', () => {
+ test('extractFactsFromTurn warns once per reason instead of silent []', async () => {
+ configureGateway({ env: {} }); // keyless → chat_unavailable
+ const facts = await extractFactsFromTurn({ turnText: 'Some turn text.', source: 'test:wrapper' });
+ expect(facts).toEqual([]);
+ expect(stderrCapture).toContain('extraction skipped (chat_unavailable');
+ const before = stderrCapture.length;
+ await extractFactsFromTurn({ turnText: 'Another turn.', source: 'test:wrapper' });
+ expect(stderrCapture.length).toBe(before); // once per reason per process
+ });
+});
+
+describe('caller-resolved visibility pin (review-army addition)', () => {
+ test('keyless envelope pins the CALLER visibility (world), not hardcoded private', async () => {
+ configureGateway({ env: {} });
+ const res = unwrap(await dispatchToolCall(engine, 'extract_facts', {
+ turn_text: ELIGIBLE_BODY, visibility: 'world',
+ }, { remote: false }));
+ expect(res.skipped).toBe('extraction_unavailable');
+ const action = String(res.agent_action);
+ expect(action).toContain('visibility: "world"');
+ expect(action).not.toContain('omitting it would widen');
+ });
+});
+
+describe('coverage-gap additions (ship review)', () => {
+ test('inline-lane keyless gate returns the skip envelope (the worker-consumed shape)', async () => {
+ configureGateway({ env: {} });
+ const r = await runFactsBackstop(
+ { slug: 'outcome-inline-keyless', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline' },
+ );
+ expect(r.mode).toBe('inline');
+ expect((r as { skipped?: string }).skipped).toBe('extraction_unavailable');
+ expect((r as { inserted: number }).inserted).toBe(0);
+ });
+
+ test('CRITICAL placement rule: keyless SUBMITTER still enqueues the durable job (worker may be keyed)', async () => {
+ configureGateway({ env: {} }); // keyless in the submitting process
+ markShortLivedCliProcess(); // durable-submit lane
+ const r = await runFactsBackstop(
+ { slug: 'outcome-keyless-submit', type: 'note', compiled_truth: ELIGIBLE_BODY, frontmatter: {} },
+ { engine: engine as BrainEngine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'queue' },
+ );
+ expect(r.mode).toBe('queue');
+ expect((r as { enqueued: boolean }).enqueued).toBe(true); // NOT gated at submit time
+ const jobs = await engine.executeRaw<{ name: string }>(
+ `SELECT name FROM minion_jobs WHERE name = 'facts-absorb'`,
+ );
+ expect(jobs).toHaveLength(1);
+ });
+
+ test('FactsExtractionError redaction: JSON.stringify and spread omit the provider body', () => {
+ const err = new FactsExtractionError('provider_error', 'openai:gpt-5.6-terra',
+ new Error('401 Incorrect API key provided: sk-proj-****xyz'));
+ expect(JSON.stringify(err)).not.toContain('sk-proj');
+ expect(JSON.stringify({ ...err })).not.toContain('sk-proj');
+ expect(err.message).not.toContain('sk-proj');
+ // The cause stays reachable for local debugging.
+ expect(String((err as { cause?: unknown }).cause)).toContain('401');
+ });
+});
diff --git a/test/facts-classify.test.ts b/test/facts-classify.test.ts
index 8294c01474..dd244f6601 100644
--- a/test/facts-classify.test.ts
+++ b/test/facts-classify.test.ts
@@ -112,3 +112,34 @@ describe('classifyAgainstCandidates', () => {
expect((result as { reason: string }).reason).toBe('cosine_fallback');
});
});
+
+describe('classify gate — key-aware, engine-free (CX10)', () => {
+ test('unservable classifier model degrades to cosine fallback, never throws', async () => {
+ const { withEnv } = await import('./helpers/with-env.ts');
+ // Deterministic gate: clear any gateway/transport state a sibling file in
+ // this shard's process left behind — the test must exercise the
+ // unavailability gate, not a leftover stub or a network failure.
+ const { resetGateway, __setChatTransportForTests } = await import('../src/core/ai/gateway.ts');
+ resetGateway();
+ __setChatTransportForTests(null);
+ await withEnv({
+ ANTHROPIC_API_KEY: undefined,
+ OPENAI_API_KEY: undefined,
+ GBRAIN_MODEL: undefined,
+ GBRAIN_HOME: '/nonexistent-gbrain-home-classify-test',
+ }, async () => {
+ const existing = makeFact({ id: 1, embedding: vec(1, 0, 0) });
+ // Keyless env → resolveTierDefault('utility') yields the Anthropic
+ // default whose key is absent → gate fails (or, if a sibling test file
+ // left a transport stub, the call itself fails) → cosine fallback at
+ // ≥0.92 → duplicate. Either path must land on cosine_fallback.
+ const r = await classifyAgainstCandidates(
+ { fact: 'x', kind: 'fact', embedding: vec(0.93, Math.sqrt(1 - 0.93 * 0.93), 0) },
+ [existing],
+ );
+ expect(r.reason).toBe('cosine_fallback');
+ expect(r.decision).toBe('duplicate');
+ if (r.decision === 'duplicate') expect(r.matched_id).toBe(1);
+ });
+ });
+});
diff --git a/test/facts-extract-salvage.test.ts b/test/facts-extract-salvage.test.ts
index e372b06e65..c4542a9b6c 100644
--- a/test/facts-extract-salvage.test.ts
+++ b/test/facts-extract-salvage.test.ts
@@ -64,7 +64,14 @@ describe('facts extractor candidate salvage (#3866)', () => {
{ fact: null, kind: 'fact' },
]);
- expect(await extract()).toEqual({ ok: false, reason: 'malformed_output' });
+ const outcome = await extract();
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) {
+ expect(outcome.reason).toBe('malformed_output');
+ // The outcome names the resolved model so failure surfaces (absorb log,
+ // warn lines) can tell the operator WHICH model misbehaved.
+ expect(typeof outcome.model).toBe('string');
+ }
});
test('keeps an explicitly empty array as a successful empty result', async () => {
diff --git a/test/facts-extract-silent-no-op.test.ts b/test/facts-extract-silent-no-op.test.ts
index 4272bb5d6d..ed85911e6d 100644
--- a/test/facts-extract-silent-no-op.test.ts
+++ b/test/facts-extract-silent-no-op.test.ts
@@ -110,7 +110,7 @@ describe('facts extract — silent-no-op regression (v0.31.6 bug class)', () =>
});
expect(isAvailable('chat')).toBe(false);
const facts = await extractFactsFromTurn({
- turnText: 'Garry founded Initialized in 2010 with Alexis.',
+ turnText: 'alice-example founded acme-example in 2010 with charlie-example.',
source: 'test:no-op-regression',
});
expect(facts).toEqual([]);
@@ -141,9 +141,43 @@ describe('facts extract — silent-no-op regression (v0.31.6 bug class)', () =>
};
});
await extractFactsFromTurn({
- turnText: 'Garry founded Initialized in 2010 with Alexis.',
+ turnText: 'alice-example founded acme-example in 2010 with charlie-example.',
source: 'test:smoking-gun',
});
expect(chatCalled).toBe(true); // ← THE bug-class assertion
});
});
+
+describe('gate-vs-model split (the wrong-model gate bug class)', () => {
+ test('global chat unservable but extraction override servable → override gate passes', () => {
+ // Global chat_model is Anthropic with no Anthropic key; the only live key
+ // is OpenAI. The bare probe must say NO while the model-override probe
+ // says YES — extraction gates on the model it will actually call.
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ expect(isAvailable('chat')).toBe(false);
+ expect(isAvailable('chat', 'openai:gpt-4o-mini')).toBe(true);
+ });
+
+ test('reverse split: global servable but extraction model unservable → chat_unavailable carries the model', async () => {
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test' },
+ });
+ expect(isAvailable('chat')).toBe(true);
+ expect(isAvailable('chat', 'openai:gpt-4o-mini')).toBe(false);
+ const { extractFactsFromTurnWithOutcome } = await import('../src/core/facts/extract.ts');
+ const outcome = await extractFactsFromTurnWithOutcome({
+ turnText: 'Some turn text worth extracting.',
+ source: 'test:gate-split',
+ model: 'openai:gpt-4o-mini',
+ });
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) {
+ expect(outcome.reason).toBe('chat_unavailable');
+ expect(outcome.model).toBe('openai:gpt-4o-mini'); // outcome names the ACTUAL model
+ }
+ });
+});
diff --git a/test/facts-visibility.test.ts b/test/facts-visibility.test.ts
index 5ffbe43ea5..1f0f9c455e 100644
--- a/test/facts-visibility.test.ts
+++ b/test/facts-visibility.test.ts
@@ -14,6 +14,7 @@ import {
FACTS_DEFAULT_VISIBILITY_KEY,
} from '../src/core/facts/visibility.ts';
import { runFactsBackstop } from '../src/core/facts/backstop.ts';
+import { __setChatTransportForTests } from '../src/core/ai/gateway.ts';
import {
markShortLivedCliProcess,
__resetShortLivedCliForTests,
@@ -191,6 +192,20 @@ describe('ontology_propose visibility site (operations.ts ~:5812) [ENG-8]', () =
});
describe('backstop minion-payload visibility site (backstop.ts queue mode) [ENG-8]', () => {
+ // The backstop gates on extraction availability before enqueueing; this
+ // block asserts the minion PAYLOAD, not availability — stub the chat
+ // transport so the gate passes regardless of shard env keys.
+ beforeAll(() => {
+ __setChatTransportForTests(async () => ({
+ text: '[]',
+ blocks: [{ type: 'text', text: '[]' }],
+ stopReason: 'end' as const,
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ }));
+ });
+ afterAll(() => { __setChatTransportForTests(null); });
afterEach(async () => {
__resetShortLivedCliForTests();
await engine.unsetConfig(FACTS_DEFAULT_VISIBILITY_KEY);
diff --git a/test/gateway-reconfigure-clobber.serial.test.ts b/test/gateway-reconfigure-clobber.serial.test.ts
new file mode 100644
index 0000000000..8f6ea3821e
--- /dev/null
+++ b/test/gateway-reconfigure-clobber.serial.test.ts
@@ -0,0 +1,142 @@
+/**
+ * reconfigureGatewayWithEngine — the clobber regression suite.
+ *
+ * The historical bug: reconfigure resolved `models.chat` with tier
+ * 'reasoning', and the key-blind tier default beat the caller fallback — an
+ * explicit `chat_model: "openai:gpt-5.2"` in ~/.gbrain/config.json was
+ * silently replaced with the Anthropic default on every engine connect.
+ *
+ * Post-fix contract: DB-plane overrides win as before; when resolution falls
+ * to the tier default, the SHARED effective-model resolver consults the RAW
+ * file config — a SERVABLE pin survives, an unservable pin (provider switch)
+ * falls to the key-aware default with one warn.
+ *
+ * Hermetic: GBRAIN_HOME points at a temp dir (the file-plane read), provider
+ * key envs are pinned, gateway env is injected via configureGateway.
+ */
+import { describe, test, expect, beforeEach, afterEach, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ configureGateway,
+ reconfigureGatewayWithEngine,
+ getChatModel,
+ resetGateway,
+} from '../src/core/ai/gateway.ts';
+import { TIER_DEFAULTS, _resetDeprecationWarningsForTest, openaiStaticTierFallback } from '../src/core/model-config.ts';
+
+class StubEngine {
+ readonly kind = 'pglite' as const;
+ private cfg = new Map<string, string>();
+ set(key: string, value: string) { this.cfg.set(key, value); }
+ async getConfig(key: string) { return this.cfg.get(key) ?? null; }
+ async setConfig() {}
+}
+
+const PINNED = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GBRAIN_MODEL', 'GBRAIN_CHAT_MODEL', 'GBRAIN_HOME'] as const;
+let saved: Record<string, string | undefined>;
+let tmpHome: string;
+let stub: StubEngine;
+let stderrCapture: string;
+const origWrite = process.stderr.write.bind(process.stderr);
+
+function writeFileConfig(cfg: Record<string, unknown>): void {
+ // GBRAIN_HOME is a PARENT dir — configDir() appends '.gbrain' itself.
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...cfg }));
+}
+
+beforeEach(() => {
+ saved = {};
+ for (const k of PINNED) { saved[k] = process.env[k]; delete process.env[k]; }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-reconf-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ stub = new StubEngine();
+ resetGateway();
+ _resetDeprecationWarningsForTest();
+ stderrCapture = '';
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ stderrCapture += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();
+ return true;
+ }) as typeof process.stderr.write;
+});
+
+afterEach(() => {
+ process.stderr.write = origWrite;
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const k of PINNED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+// Shard hygiene (same pattern as facts-extract-silent-no-op.test.ts): restore
+// the legacy embedding pin so later fresh-schema files in this shard's
+// process don't size vector columns from this file's leftover gateway state.
+afterAll(() => {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+});
+
+describe('reconfigureGatewayWithEngine — no-clobber', () => {
+ test('servable file pin survives reconnect (THE regression)', async () => {
+ writeFileConfig({ chat_model: 'openai:gpt-5.2' });
+ configureGateway({ chat_model: 'openai:gpt-5.2', env: { OPENAI_API_KEY: 'sk-test' } });
+ await reconfigureGatewayWithEngine(stub as never);
+ expect(getChatModel()).toBe('openai:gpt-5.2');
+ });
+
+ test('DB-plane models.chat still wins over everything', async () => {
+ writeFileConfig({ chat_model: 'openai:gpt-5.2' });
+ configureGateway({ chat_model: 'openai:gpt-5.2', env: { OPENAI_API_KEY: 'sk-test' } });
+ stub.set('models.chat', 'anthropic:claude-opus-4-7');
+ await reconfigureGatewayWithEngine(stub as never);
+ expect(getChatModel()).toBe('anthropic:claude-opus-4-7');
+ });
+
+ test('provider switch: unservable openai pin + anthropic-only key → key-aware default + one warn', async () => {
+ writeFileConfig({ chat_model: 'openai:gpt-5.2' });
+ configureGateway({ chat_model: 'openai:gpt-5.2', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ await reconfigureGatewayWithEngine(stub as never);
+ expect(getChatModel()).toBe(TIER_DEFAULTS.reasoning);
+ expect(stderrCapture).toContain('openai:gpt-5.2');
+ expect(stderrCapture).toContain('no usable');
+ });
+
+ test('keyless + no pin → tier default (today\'s shape, honest downstream)', async () => {
+ writeFileConfig({});
+ configureGateway({ env: {} });
+ await reconfigureGatewayWithEngine(stub as never);
+ expect(getChatModel()).toBe(TIER_DEFAULTS.reasoning);
+ });
+
+ test('openai-only, no pin → key-aware tier default routes chat to openai', async () => {
+ writeFileConfig({ openai_api_key: 'sk-file-plane' });
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-test' } });
+ await reconfigureGatewayWithEngine(stub as never);
+ expect(getChatModel()).toBe(openaiStaticTierFallback().reasoning);
+ });
+});
+
+describe('expansion-side effective resolution (review-army addition)', () => {
+ test('servable expansion_model file pin survives reconnect', async () => {
+ writeFileConfig({ expansion_model: 'openai:gpt-4o-mini' });
+ configureGateway({ expansion_model: 'openai:gpt-4o-mini', env: { OPENAI_API_KEY: 'sk-test' } });
+ await reconfigureGatewayWithEngine(stub as never);
+ const { getExpansionModel } = await import('../src/core/ai/gateway.ts');
+ expect(getExpansionModel()).toBe('openai:gpt-4o-mini');
+ });
+
+ test('unservable expansion pin falls to the key-aware utility default + warn', async () => {
+ writeFileConfig({ expansion_model: 'openai:gpt-4o-mini' });
+ configureGateway({ expansion_model: 'openai:gpt-4o-mini', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ await reconfigureGatewayWithEngine(stub as never);
+ const { getExpansionModel } = await import('../src/core/ai/gateway.ts');
+ expect(getExpansionModel()).toBe(TIER_DEFAULTS.utility);
+ expect(stderrCapture).toContain('expansion_model');
+ });
+});
diff --git a/test/helpers/provider-keys-preload.ts b/test/helpers/provider-keys-preload.ts
new file mode 100644
index 0000000000..88145f0697
--- /dev/null
+++ b/test/helpers/provider-keys-preload.ts
@@ -0,0 +1,61 @@
+/**
+ * provider-keys-preload — strip ambient chat-provider API keys so the unit
+ * lane is hermetic-keyless by definition (parity with keyless CI).
+ *
+ * Why: key-aware model routing (src/core/model-config.ts
+ * PROVIDER_TIER_DEFAULTS / resolveTierDefault) resolves tier defaults from
+ * whichever provider keys are present. That is the PRODUCT contract — an
+ * OPENAI_API_KEY-only install routes chat/extraction to OpenAI — but it means
+ * a dev shell exporting a chat key flips every default-model assertion and,
+ * worse, turns previously-gated code paths into REAL network calls with the
+ * shell's key (observed: 183 unit failures and 15-minute retry hangs on an
+ * OPENAI_API_KEY-exporting shell, the TODOS "env-sensitive LLM-availability
+ * tests" class at full scale). CI is keyless; local unit runs must match.
+ *
+ * Tests that WANT keys inject them explicitly (configureGateway({env}),
+ * detectCapabilities({env}), withEnv, or process.env in serial files) — this
+ * preload only removes ambient shell state, never test-set state (it runs
+ * once, before any test file loads).
+ *
+ * Escape hatch: GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 preserves the ambient keys.
+ * The e2e wrapper (scripts/run-e2e.sh) sets it at its own subprocess boundary
+ * so keyed e2e runs (live embed parity tests skip-gated on real keys) keep
+ * today's behavior — same pattern as GBRAIN_TEST_ALLOW_DATABASE_URL.
+ */
+
+// Every provider credential/endpoint the canonical fold recognizes
+// (src/core/ai/provider-env.ts mergedProviderEnv) — an ambient GEMINI,
+// VOYAGE, ZEROENTROPY, or Azure endpoint flips capability/embedding
+// assertions the same way a chat key flips model routing. Keep this list in
+// sync with mergedProviderEnv's output names.
+const STRIPPED_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'OPENAI_API_KEY',
+ 'GEMINI_API_KEY',
+ 'GOOGLE_GENERATIVE_AI_API_KEY',
+ 'VOYAGE_API_KEY',
+ 'OPENROUTER_API_KEY',
+ 'ZEROENTROPY_API_KEY',
+ 'DASHSCOPE_API_KEY',
+ 'AZURE_OPENAI_ENDPOINT',
+ 'AZURE_OPENAI_DEPLOYMENT',
+ 'AZURE_OPENAI_USE_ENTRA',
+] as const;
+
+if (process.env.GBRAIN_TEST_KEEP_PROVIDER_KEYS !== '1') {
+ for (const key of STRIPPED_KEYS) {
+ if (process.env[key] !== undefined) {
+ delete process.env[key];
+ }
+ }
+}
+
+// Latest-model discovery (src/core/ai/openai-latest.ts) fetches the
+// account's /v1/models at gateway connect. Tests configure fake keys and
+// call reconfigureGatewayWithEngine constantly — without this switch every
+// such test would attempt a real network call. Off in ALL test lanes
+// (respecting an explicit operator override); unit tests for discovery
+// inject fetchImpl + force instead.
+if (process.env.GBRAIN_MODEL_DISCOVERY === undefined) {
+ process.env.GBRAIN_MODEL_DISCOVERY = 'off';
+}
diff --git a/test/jobs-gateway-refresh.serial.test.ts b/test/jobs-gateway-refresh.serial.test.ts
new file mode 100644
index 0000000000..f62e65ab6c
--- /dev/null
+++ b/test/jobs-gateway-refresh.serial.test.ts
@@ -0,0 +1,143 @@
+/**
+ * refreshGatewayForJob + init no-persist — the worker key-staleness seam and
+ * the install-time pin removal.
+ *
+ * refreshGatewayForJob's contract (three staleness tiers): a key added to the
+ * FILE plane (~/.gbrain/config.json) reaches a long-lived worker at the next
+ * gateway-refresh job — the refresh re-folds mergedProviderEnv(loadConfig(),
+ * process.env) into the LIVE gateway env only (never through
+ * buildGatewayConfig, which would clobber DB-plane-merged fields), then
+ * re-resolves models. (DB-plane `config set *_api_key` is deliberately
+ * unmerged — filed TODO; true env vars need a restart.)
+ *
+ * Serial: mutates GBRAIN_HOME + process env + global gateway state.
+ */
+import { describe, test, expect, beforeEach, afterEach, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { configureGateway, resetGateway, isAvailable, getChatModel } from '../src/core/ai/gateway.ts';
+import { refreshGatewayForJob } from '../src/commands/jobs.ts';
+import { resolveChatByEnv } from '../src/commands/init.ts';
+import { _resetDeprecationWarningsForTest, openaiStaticTierFallback } from '../src/core/model-config.ts';
+
+class StubEngine {
+ readonly kind = 'pglite' as const;
+ async getConfig() { return null; }
+ async setConfig() {}
+}
+
+const PINNED = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GBRAIN_MODEL', 'GBRAIN_CHAT_MODEL', 'GBRAIN_HOME'] as const;
+let saved: Record<string, string | undefined>;
+let tmpHome: string;
+
+beforeEach(() => {
+ saved = {};
+ for (const k of PINNED) { saved[k] = process.env[k]; delete process.env[k]; }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-refresh-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ resetGateway();
+ _resetDeprecationWarningsForTest();
+});
+
+afterEach(() => {
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const k of PINNED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+afterAll(() => {
+ // Shard hygiene: restore the legacy embedding pin.
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+});
+
+describe('refreshGatewayForJob (worker key staleness)', () => {
+ test('file-plane key added after boot reaches the gateway at the next job', async () => {
+ // Boot: keyless gateway (worker started before the operator had a key).
+ configureGateway({ env: {} });
+ const expected = openaiStaticTierFallback().reasoning;
+ expect(isAvailable('chat', expected)).toBe(false);
+ // Operator edits ~/.gbrain/config.json while the worker runs.
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(
+ join(tmpHome, '.gbrain', 'config.json'),
+ JSON.stringify({ engine: 'pglite', openai_api_key: 'sk-added-later' }),
+ );
+ await refreshGatewayForJob(new StubEngine() as never);
+ // The re-fold picked the key up AND key-aware re-resolution routed chat
+ // to the recipe-ranked default (no discovery cache in this hermetic env).
+ expect(isAvailable('chat', expected)).toBe(true);
+ expect(getChatModel()).toBe(expected);
+ });
+
+ test('unreadable config: env re-fold falls back to process env, refresh never throws', async () => {
+ // The env-only refresh recomputes mergedProviderEnv(fileCfg, process.env);
+ // with no config.json the process env is the whole fold — a worker whose
+ // key lives in its process env keeps it across refreshes.
+ process.env.ANTHROPIC_API_KEY = 'sk-ant';
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ...process.env } });
+ await refreshGatewayForJob(new StubEngine() as never);
+ expect(isAvailable('chat', 'anthropic:claude-sonnet-4-6')).toBe(true);
+ });
+
+ test('env-only refresh preserves non-env gateway fields (no file-plane clobber)', async () => {
+ // The worker's boot fold can carry DB-plane-merged fields (base_urls,
+ // chat options). refreshGatewayForJob must re-fold ONLY env — a full
+ // configureGateway(buildGatewayConfig(loadConfig())) here would reset
+ // those fields to file-plane-only values.
+ // The chat pin lives in the FILE config (only file pins survive
+ // reconfigure — gateway state can't distinguish an explicit pin from the
+ // boot-stamped default).
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(
+ join(tmpHome, '.gbrain', 'config.json'),
+ JSON.stringify({ engine: 'pglite', openai_api_key: 'sk-file', chat_model: 'openai:gpt-5.2' }),
+ );
+ configureGateway({
+ chat_model: 'openai:gpt-5.2',
+ base_urls: { openai: 'http://localhost:9999/db-plane-merged' },
+ env: {},
+ });
+ await refreshGatewayForJob(new StubEngine() as never);
+ expect(isAvailable('chat', 'openai:gpt-5.2')).toBe(true);
+ expect(getChatModel()).toBe('openai:gpt-5.2');
+ // Read the live config back through reconfigure's return value: the
+ // boot-installed base_urls must have survived the env-only refresh.
+ const { reconfigureGatewayWithEngine } = await import('../src/core/ai/gateway.ts');
+ const live = await reconfigureGatewayWithEngine(new StubEngine() as never);
+ expect(live.base_urls?.openai).toBe('http://localhost:9999/db-plane-merged');
+ });
+});
+
+describe('init resolveChatByEnv (no-persist contract, CX2)', () => {
+ test('detection never writes a chat_model pin', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ const out: { chat_model?: string } = {};
+ await resolveChatByEnv(out as never);
+ // Key-aware runtime resolution replaced install-time pins — the resolved
+ // options object must stay unpinned regardless of what was detected.
+ expect(out.chat_model).toBeUndefined();
+ });
+});
+
+describe('refreshGatewayEnvFromFilePlane guards (review-army addition)', () => {
+ test('safe no-op before configure; corrupt config still folds process env', async () => {
+ const { refreshGatewayEnvFromFilePlane } = await import('../src/core/ai/gateway.ts');
+ resetGateway();
+ expect(() => refreshGatewayEnvFromFilePlane()).not.toThrow();
+ expect(isAvailable('chat', 'anthropic:claude-sonnet-4-6')).toBe(false); // still unconfigured
+ // Corrupt config.json: loadConfig throws inside → cfg=null → process-env fold.
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), '{not json');
+ process.env.ANTHROPIC_API_KEY = 'sk-ant';
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: {} });
+ expect(() => refreshGatewayEnvFromFilePlane()).not.toThrow();
+ expect(isAvailable('chat', 'anthropic:claude-sonnet-4-6')).toBe(true);
+ });
+});
diff --git a/test/model-config.serial.test.ts b/test/model-config.serial.test.ts
index 94f28bc191..4692f0d2c9 100644
--- a/test/model-config.serial.test.ts
+++ b/test/model-config.serial.test.ts
@@ -5,12 +5,19 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import {
resolveModel,
+ resolveModelDetailed,
resolveAlias,
+ resolveTierDefault,
+ resolveEffectiveChatModel,
+ providerKeyReady,
+ openaiStaticTierFallback,
DEFAULT_ALIASES,
TIER_DEFAULTS,
+ PROVIDER_TIER_DEFAULTS,
isAnthropicProvider,
_resetDeprecationWarningsForTest,
} from '../src/core/model-config.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
class StubEngine {
readonly kind = 'pglite' as const;
@@ -25,6 +32,15 @@ let stub: StubEngine;
let stderrCapture: string;
const origWrite = process.stderr.write.bind(process.stderr);
+// Hermetic-env pinning (TODOS:1200 class): the key-aware tier default reads
+// provider keys from process.env AND ~/.gbrain/config.json. Without pinning,
+// every default-path assertion below would flip on a dev shell that exports
+// only OPENAI_API_KEY (or carries keys in config.json). Save/delete the key
+// envs and point GBRAIN_HOME at a nonexistent dir so the config read misses —
+// local runs then match keyless CI byte-for-byte.
+const PINNED_ENV_KEYS = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GBRAIN_HOME'] as const;
+let savedEnv: Record<string, string | undefined>;
+
beforeEach(() => {
stub = new StubEngine();
stderrCapture = '';
@@ -33,11 +49,21 @@ beforeEach(() => {
return true;
}) as typeof process.stderr.write;
delete process.env.GBRAIN_MODEL;
+ savedEnv = {};
+ for (const k of PINNED_ENV_KEYS) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.GBRAIN_HOME = '/nonexistent-gbrain-home-for-model-config-tests';
_resetDeprecationWarningsForTest();
});
afterEach(() => {
process.stderr.write = origWrite;
+ for (const k of PINNED_ENV_KEYS) {
+ if (savedEnv[k] === undefined) delete process.env[k];
+ else process.env[k] = savedEnv[k];
+ }
});
describe('resolveAlias', () => {
@@ -244,3 +270,167 @@ describe('resolveModel — v0.31.12 tier system', () => {
expect(result.length).toBeGreaterThan(0);
});
});
+
+describe('resolveTierDefault — key-aware matrix (injected env used exclusively)', () => {
+ test('anthropic-only → anthropic tier defaults (unchanged behavior)', () => {
+ const env = { ANTHROPIC_API_KEY: 'sk-ant-test' };
+ expect(resolveTierDefault('reasoning', env)).toBe(TIER_DEFAULTS.reasoning);
+ expect(resolveTierDefault('utility', env)).toBe(TIER_DEFAULTS.utility);
+ expect(resolveTierDefault('deep', env)).toBe(TIER_DEFAULTS.deep);
+ expect(resolveTierDefault('subagent', env)).toBe(TIER_DEFAULTS.subagent);
+ });
+
+ test('openai-only → recipe-ranked openai tier defaults (no literal pins anywhere)', () => {
+ const env = { OPENAI_API_KEY: 'sk-test' };
+ const fallback = openaiStaticTierFallback();
+ // Behavioral, not literal: the expected ids derive from the openai
+ // recipe's chat list through the shared ranking grammar — updating the
+ // recipe at a release updates this test's expectations automatically.
+ expect(resolveTierDefault('reasoning', env)).toBe(fallback.reasoning);
+ expect(resolveTierDefault('utility', env)).toBe(fallback.utility);
+ expect(resolveTierDefault('deep', env)).toBe(fallback.deep);
+ expect(resolveTierDefault('subagent', env)).toBe(fallback.subagent);
+ // Shape sanity: all openai-prefixed, cheap ≠ top unless the recipe list
+ // collapses to one family member.
+ for (const id of Object.values(fallback)) expect(id.startsWith('openai:')).toBe(true);
+ });
+
+ test('both keys → anthropic wins (first table entry; zero change for keyed installs)', () => {
+ const env = { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' };
+ expect(resolveTierDefault('reasoning', env)).toBe(TIER_DEFAULTS.reasoning);
+ });
+
+ test('no keys → TIER_DEFAULTS unchanged (keyless shape preserved)', () => {
+ expect(resolveTierDefault('reasoning', {})).toBe(TIER_DEFAULTS.reasoning);
+ });
+
+ test('empty-string keys treated absent (#1249 posture)', () => {
+ const env = { ANTHROPIC_API_KEY: '', OPENAI_API_KEY: '' };
+ expect(resolveTierDefault('reasoning', env)).toBe(TIER_DEFAULTS.reasoning);
+ const openaiOnly = { ANTHROPIC_API_KEY: '', OPENAI_API_KEY: 'sk-test' };
+ expect(resolveTierDefault('reasoning', openaiOnly)).toBe(openaiStaticTierFallback().reasoning);
+ });
+
+ test('table order is the precedence contract: anthropic first, openai second', () => {
+ expect(PROVIDER_TIER_DEFAULTS[0].provider).toBe('anthropic');
+ expect(PROVIDER_TIER_DEFAULTS[1].provider).toBe('openai');
+ });
+});
+
+describe('resolveModelDetailed — sources + key-aware step 7', () => {
+ test('tier default resolves key-aware with source tier_default (openai-only env)', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ try {
+ const r = await resolveModelDetailed(null, { tier: 'reasoning', fallback: 'sonnet' });
+ expect(r.model).toBe(openaiStaticTierFallback().reasoning);
+ expect(r.source).toBe('tier_default');
+ } finally {
+ delete process.env.OPENAI_API_KEY;
+ }
+ });
+
+ test('GBRAIN_MODEL env still beats the key-aware tier default (source env)', async () => {
+ process.env.GBRAIN_MODEL = 'haiku';
+ process.env.OPENAI_API_KEY = 'sk-test';
+ try {
+ const r = await resolveModelDetailed(null, { tier: 'reasoning', fallback: 'sonnet' });
+ expect(r.model).toBe(DEFAULT_ALIASES.haiku);
+ expect(r.source).toBe('env');
+ } finally {
+ delete process.env.GBRAIN_MODEL;
+ delete process.env.OPENAI_API_KEY;
+ }
+ });
+
+ test('models.tier.<tier> config still beats the key-aware default (source tier_config)', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ try {
+ stub.set('models.tier.reasoning', 'opus');
+ const r = await resolveModelDetailed(stub as never, { tier: 'reasoning', fallback: 'sonnet' });
+ expect(r.model).toBe(DEFAULT_ALIASES.opus);
+ expect(r.source).toBe('tier_config');
+ } finally {
+ delete process.env.OPENAI_API_KEY;
+ }
+ });
+
+ test('config key wins with source config_key; fallback labels fallback', async () => {
+ stub.set('facts.extraction_model', 'openai:gpt-4o-mini');
+ const withKey = await resolveModelDetailed(stub as never, {
+ configKey: 'facts.extraction_model', tier: 'reasoning', fallback: 'sonnet',
+ });
+ expect(withKey).toEqual({ model: 'openai:gpt-4o-mini', source: 'config_key' });
+ const noTier = await resolveModelDetailed(null, { fallback: 'sonnet' });
+ expect(noTier.source).toBe('fallback');
+ expect(noTier.model).toBe(DEFAULT_ALIASES.sonnet);
+ });
+
+ test('subagent + openai-only: returns openai with once-per-process no-caching warn', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ try {
+ const r = await resolveModelDetailed(null, { tier: 'subagent', fallback: 'sonnet' });
+ expect(r.model).toBe(openaiStaticTierFallback().subagent);
+ expect(stderrCapture).toContain('caching');
+ const before = stderrCapture.length;
+ await resolveModelDetailed(null, { tier: 'subagent', fallback: 'sonnet' });
+ expect(stderrCapture.length).toBe(before); // warned once
+ } finally {
+ delete process.env.OPENAI_API_KEY;
+ }
+ });
+});
+
+describe('providerKeyReady + resolveEffectiveChatModel (shared runtime/report resolution)', () => {
+ const fileCfg = (partial: Partial<GBrainConfig>): GBrainConfig =>
+ ({ engine: 'pglite', ...partial }) as GBrainConfig;
+
+ test('providerKeyReady: recipe auth_env drives readiness; bare/unknown ids are not servable', () => {
+ expect(providerKeyReady('openai:gpt-5.2', { OPENAI_API_KEY: 'sk-test' })).toBe(true);
+ expect(providerKeyReady('openai:gpt-5.2', {})).toBe(false);
+ expect(providerKeyReady('claude-sonnet-4-6', { ANTHROPIC_API_KEY: 'x' })).toBe(false); // bare id
+ expect(providerKeyReady('not-a-provider:x', { OPENAI_API_KEY: 'sk-test' })).toBe(false);
+ // No required keys + a chat touchpoint (the CLI owns auth) → ready.
+ expect(providerKeyReady('claude-cli:claude-sonnet-4-6', {})).toBe(true);
+ // A keyed/keyless but CHAT-LESS recipe is NOT ready: honoring an
+ // embedding-only pin as chat_model would install a model
+ // isAvailable('chat') rejects instead of falling back to the key-aware
+ // default. (ollama is embedding-only in this repo's recipe, hence false
+ // despite requiring no keys.)
+ expect(providerKeyReady('voyage:voyage-4-large', { VOYAGE_API_KEY: 'x' })).toBe(false);
+ expect(providerKeyReady('ollama:llama3', {})).toBe(false);
+ });
+
+ test('servable file pin wins (init-era openai pin + live key)', () => {
+ const r = resolveEffectiveChatModel(
+ fileCfg({ chat_model: 'openai:gpt-5.2', openai_api_key: 'sk-file' }), {});
+ expect(r).toEqual({ model: 'openai:gpt-5.2', source: 'file_pin' });
+ });
+
+ test('unservable pin falls through to key-aware default with one warn (provider switch)', () => {
+ // Stale init-era openai pin, but the only live key is Anthropic.
+ const cfg = fileCfg({ chat_model: 'openai:gpt-5.2' });
+ const env = { ANTHROPIC_API_KEY: 'sk-ant-test' };
+ const r = resolveEffectiveChatModel(cfg, env);
+ expect(r).toEqual({ model: TIER_DEFAULTS.reasoning, source: 'tier_default' });
+ expect(stderrCapture).toContain('openai:gpt-5.2');
+ const before = stderrCapture.length;
+ resolveEffectiveChatModel(cfg, env);
+ expect(stderrCapture.length).toBe(before); // warned once per pin per process
+ });
+
+ test('GBRAIN_MODEL beats the file pin (env_model source)', () => {
+ const r = resolveEffectiveChatModel(
+ fileCfg({ chat_model: 'openai:gpt-5.2', openai_api_key: 'sk-file' }),
+ { GBRAIN_MODEL: 'anthropic:claude-sonnet-4-6' });
+ expect(r).toEqual({ model: 'anthropic:claude-sonnet-4-6', source: 'env_model' });
+ });
+
+ test('no pin, no env model → key-aware tier default (keyless → anthropic shape)', () => {
+ expect(resolveEffectiveChatModel(null, {})).toEqual({
+ model: TIER_DEFAULTS.reasoning, source: 'tier_default',
+ });
+ expect(resolveEffectiveChatModel(null, { OPENAI_API_KEY: 'sk-test' })).toEqual({
+ model: openaiStaticTierFallback().reasoning, source: 'tier_default',
+ });
+ });
+});
diff --git a/test/openai-latest.serial.test.ts b/test/openai-latest.serial.test.ts
new file mode 100644
index 0000000000..e23ab01b2c
--- /dev/null
+++ b/test/openai-latest.serial.test.ts
@@ -0,0 +1,318 @@
+/**
+ * openai-latest — latest-model discovery: id grammar, priced-only ranking,
+ * cache round-trip, TTL throttle, fail-open refresh. Serial: mutates
+ * GBRAIN_HOME + process env + module memo state.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ parseOpenAIChatId,
+ rankOpenAIChatModels,
+ latestOpenAITiers,
+ refreshLatestOpenAIModels,
+ _resetOpenAILatestForTests,
+} from '../src/core/ai/openai-latest.ts';
+import { resolveTierDefault, openaiStaticTierFallback } from '../src/core/model-config.ts';
+
+const PINNED = ['GBRAIN_HOME', 'GBRAIN_MODEL_DISCOVERY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY'] as const;
+let saved: Record<string, string | undefined>;
+let tmpHome: string;
+
+beforeEach(() => {
+ saved = {};
+ for (const k of PINNED) { saved[k] = process.env[k]; delete process.env[k]; }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-latest-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ _resetOpenAILatestForTests();
+});
+
+afterEach(() => {
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const k of PINNED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+function fetchReturning(ids: string[]): typeof fetch {
+ return (async () =>
+ new Response(JSON.stringify({ data: ids.map((id) => ({ id })) }), { status: 200 })
+ ) as unknown as typeof fetch;
+}
+
+describe('parseOpenAIChatId — conservative grammar', () => {
+ test('bare family aliases and known tier suffixes parse', () => {
+ expect(parseOpenAIChatId('gpt-5.6')).toEqual({ id: 'gpt-5.6', family: [5, 6], suffix: '' });
+ expect(parseOpenAIChatId('gpt-5.6-sol')?.suffix).toBe('sol');
+ expect(parseOpenAIChatId('gpt-5.6-terra')?.suffix).toBe('terra');
+ expect(parseOpenAIChatId('gpt-5.6-luna')?.suffix).toBe('luna');
+ expect(parseOpenAIChatId('gpt-4o-mini')).toBeNull(); // 4o is not \d.\d grammar
+ expect(parseOpenAIChatId('gpt-5-mini')?.suffix).toBe('mini');
+ });
+
+ test('non-chat, snapshot, and unknown-suffix ids are ignored (fail-safe rot)', () => {
+ for (const id of [
+ 'gpt-5.6-cyber', // unknown future suffix → ignored, never mis-tiered
+ 'gpt-5.5-2026-04-24', // dated snapshot
+ 'gpt-5-chat-latest', // ChatGPT-Instant class (weak strict-JSON)
+ 'chat-latest',
+ 'gpt-realtime-2.1',
+ 'gpt-image-2',
+ 'text-embedding-3-large',
+ 'o4-mini',
+ ]) {
+ expect(parseOpenAIChatId(id)).toBeNull();
+ }
+ });
+});
+
+describe('rankOpenAIChatModels — newest PRICED family, tier ladder', () => {
+ const allPriced = () => true;
+
+ test('named tiers map to the ladder (5.6 family shape)', () => {
+ const { tiers } = rankOpenAIChatModels(
+ ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.6', 'gpt-5.5', 'gpt-4o'],
+ allPriced,
+ );
+ expect(tiers).toEqual({
+ utility: 'openai:gpt-5.6-luna',
+ reasoning: 'openai:gpt-5.6-terra',
+ deep: 'openai:gpt-5.6-sol',
+ subagent: 'openai:gpt-5.6-terra',
+ });
+ });
+
+ test('bare-alias-only family serves every tier (5.2-era shape)', () => {
+ const { tiers } = rankOpenAIChatModels(['gpt-5.2', 'gpt-5-mini'], allPriced);
+ expect(tiers).toEqual({
+ utility: 'openai:gpt-5.2', // no cheap tier in the newest family → mid
+ reasoning: 'openai:gpt-5.2',
+ deep: 'openai:gpt-5.2',
+ subagent: 'openai:gpt-5.2',
+ });
+ });
+
+ test('unpriced newer family is skipped (budget caps must not fail closed) and reported', () => {
+ const priced = (id: string) => !id.startsWith('gpt-5.7');
+ const { tiers, newestUnpriced } = rankOpenAIChatModels(
+ ['gpt-5.7', 'gpt-5.7-luna', 'gpt-5.6', 'gpt-5.6-luna'],
+ priced,
+ );
+ expect(tiers?.deep).toBe('openai:gpt-5.6');
+ expect(tiers?.utility).toBe('openai:gpt-5.6-luna');
+ expect(newestUnpriced).toBe('gpt-5.7');
+ });
+
+ test('partial family (no top tier, no bare alias) still serves every tier', () => {
+ // An account entitled to only terra/luna of the newest family must get
+ // usable tiers, not tiers:null + a static fallback it may not serve.
+ const { tiers } = rankOpenAIChatModels(['gpt-5.6-terra', 'gpt-5.6-luna'], allPriced);
+ expect(tiers).toEqual({
+ utility: 'openai:gpt-5.6-luna',
+ reasoning: 'openai:gpt-5.6-terra',
+ deep: 'openai:gpt-5.6-terra',
+ subagent: 'openai:gpt-5.6-terra',
+ });
+ // Cheap-only family: everything degrades to the one available model.
+ const only = rankOpenAIChatModels(['gpt-5.6-luna'], allPriced).tiers;
+ expect(only?.deep).toBe('openai:gpt-5.6-luna');
+ });
+
+ test('OLDER unpriced families are not reported (no obsolete-model pricing nags)', () => {
+ // Accounts still list legacy unpriced ids; warning about them would tell
+ // a release engineer to price a model nobody should adopt.
+ const priced = (id: string) => id.startsWith('gpt-5.6');
+ const { tiers, newestUnpriced } = rankOpenAIChatModels(
+ ['gpt-5', 'gpt-5.1', 'gpt-5.6', 'gpt-5.6-luna'],
+ priced,
+ );
+ expect(tiers?.deep).toBe('openai:gpt-5.6');
+ expect(newestUnpriced).toBeUndefined();
+ });
+
+ test('nothing usable → null tiers', () => {
+ expect(rankOpenAIChatModels(['gpt-realtime-2.1', 'davinci'], allPriced).tiers).toBeNull();
+ expect(rankOpenAIChatModels([], allPriced).tiers).toBeNull();
+ });
+
+ test('default priced-filter uses the canonical pricing table', () => {
+ // gpt-5.6 has a pricing row (load-bearing for discovery); a made-up
+ // family does not and must lose eligibility.
+ const { tiers } = rankOpenAIChatModels(['gpt-9.9', 'gpt-5.6']);
+ expect(tiers?.deep).toBe('openai:gpt-5.6');
+ });
+});
+
+describe('refresh + cache + resolution overlay', () => {
+ test('discovered tiers overlay the static fallback in resolveTierDefault', async () => {
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-test' },
+ fetchImpl: fetchReturning(['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna']),
+ force: true,
+ });
+ expect(latestOpenAITiers('reasoning')).toBe('openai:gpt-5.6-terra');
+ expect(resolveTierDefault('reasoning', { OPENAI_API_KEY: 'sk-test' })).toBe('openai:gpt-5.6-terra');
+ expect(resolveTierDefault('deep', { OPENAI_API_KEY: 'sk-test' })).toBe('openai:gpt-5.6-sol');
+ // Anthropic-first is untouched by the overlay.
+ expect(resolveTierDefault('reasoning', { ANTHROPIC_API_KEY: 'sk-ant', OPENAI_API_KEY: 'sk-test' }))
+ .toBe('anthropic:claude-sonnet-4-6');
+ });
+
+ test('no cache → static recipe-ranked fallback', () => {
+ expect(latestOpenAITiers('reasoning')).toBeNull();
+ expect(resolveTierDefault('reasoning', { OPENAI_API_KEY: 'sk-test' }))
+ .toBe(openaiStaticTierFallback().reasoning);
+ });
+
+ test('TTL throttle: a fresh cache suppresses refetch; force bypasses', async () => {
+ let calls = 0;
+ const counting = (async () => {
+ calls++;
+ return new Response(JSON.stringify({ data: [{ id: 'gpt-5.6' }] }), { status: 200 });
+ }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: counting, force: true });
+ expect(calls).toBe(1);
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: counting });
+ expect(calls).toBe(1); // fresh cache → throttled
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: counting, force: true });
+ expect(calls).toBe(2);
+ });
+
+ test('fail-open: keyless, disabled, HTTP error, and throwing fetch never write or throw', async () => {
+ const boom = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: {}, fetchImpl: boom, force: true }); // keyless → no-op
+ process.env.GBRAIN_MODEL_DISCOVERY = 'off';
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: boom, force: true });
+ delete process.env.GBRAIN_MODEL_DISCOVERY;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: boom, force: true }); // throws inside → absorbed
+ const err401 = (async () => new Response('{}', { status: 401 })) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: err401, force: true });
+ // Failures persist ONLY the attempt stamp (durable backoff) — never
+ // tiers. The overlay must still see nothing.
+ expect(latestOpenAITiers()).toBeNull();
+ const raw = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'model-cache.json'), 'utf8'));
+ expect(raw.openai).toBeUndefined();
+ expect(typeof raw.last_attempt_at).toBe('string');
+ });
+
+ test('unpriced-newer warning fires once and cache still lands on the priced family', async () => {
+ let stderrCapture = '';
+ const origWrite = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ stderrCapture += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();
+ return true;
+ }) as typeof process.stderr.write;
+ try {
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'k' },
+ fetchImpl: fetchReturning(['gpt-9.9', 'gpt-5.6', 'gpt-5.6-luna']),
+ force: true,
+ });
+ expect(stderrCapture).toContain('gpt-9.9');
+ expect(stderrCapture).toContain('model-pricing');
+ expect(latestOpenAITiers('deep')).toBe('openai:gpt-5.6');
+ const before = stderrCapture.length;
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'k' },
+ fetchImpl: fetchReturning(['gpt-9.9', 'gpt-5.6']),
+ force: true,
+ });
+ expect(stderrCapture.length).toBe(before); // warned once per id per process
+ } finally {
+ process.stderr.write = origWrite;
+ }
+ });
+});
+
+describe('review-army additions', () => {
+ test('numeric family compare: gpt-10 beats gpt-9.9 (no lexicographic rot)', () => {
+ const { tiers } = rankOpenAIChatModels(['gpt-9.9', 'gpt-10'], () => true);
+ expect(tiers?.deep).toBe('openai:gpt-10');
+ const minors = rankOpenAIChatModels(['gpt-5.9', 'gpt-5.10'], () => true);
+ expect(minors.tiers?.deep).toBe('openai:gpt-5.10');
+ });
+
+ test('gpt alias tracks the discovered flagship; recipe-ranked floor otherwise', async () => {
+ const { resolveAlias } = await import('../src/core/model-config.ts');
+ // No cache in this hermetic tmp home → static floor.
+ expect(await resolveAlias(null, 'gpt')).toBe(openaiStaticTierFallback().deep);
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'k' },
+ fetchImpl: fetchReturning(['gpt-5.6-sol', 'gpt-5.6', 'gpt-5.6-luna']),
+ force: true,
+ });
+ expect(await resolveAlias(null, 'gpt')).toBe('openai:gpt-5.6-sol');
+ });
+});
+
+describe('coverage-gap additions (ship review)', () => {
+ test('failure backoff: a failed non-force refresh suppresses refetch within the window', async () => {
+ let calls = 0;
+ const failing = (async () => { calls++; throw new Error('offline'); }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: failing });
+ expect(calls).toBe(1);
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: failing });
+ expect(calls).toBe(1); // within FAILURE_BACKOFF_MS → no second attempt
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: failing, force: true });
+ expect(calls).toBe(2); // force bypasses the backoff
+ });
+
+ test('identity switch (key/endpoint) bypasses TTL and replaces the cache', async () => {
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-account-a' },
+ fetchImpl: fetchReturning(['gpt-5.6', 'gpt-5.6-luna']),
+ });
+ expect(latestOpenAITiers('deep')).toBe('openai:gpt-5.6');
+ // Same identity, fresh cache → TTL suppresses (no force).
+ let calls = 0;
+ const counting = (async () => {
+ calls++;
+ return new Response(JSON.stringify({ data: [{ id: 'gpt-5.5' }] }), { status: 200 });
+ }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'sk-account-a' }, fetchImpl: counting });
+ expect(calls).toBe(0);
+ // DIFFERENT key → the cached tiers belong to another account; the TTL
+ // must not serve them. Refresh fires and overwrites.
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'sk-account-b' }, fetchImpl: counting });
+ expect(calls).toBe(1);
+ expect(latestOpenAITiers('deep')).toBe('openai:gpt-5.5');
+ });
+
+ test('identity switch + failed refresh drops the other account\'s tiers (static floor)', async () => {
+ await refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-account-a' },
+ fetchImpl: fetchReturning(['gpt-5.6']),
+ });
+ expect(latestOpenAITiers('deep')).toBe('openai:gpt-5.6');
+ const failing = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'sk-account-b' }, fetchImpl: failing });
+ // Account A's tiers must not serve account B — honest state is the
+ // static floor until B's own discovery succeeds.
+ expect(latestOpenAITiers()).toBeNull();
+ });
+
+ test('failure backoff survives a process boundary (persisted attempt stamp)', async () => {
+ let calls = 0;
+ const failing = (async () => { calls++; throw new Error('offline'); }) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: failing });
+ expect(calls).toBe(1);
+ // Simulate a fresh process: module state cleared, cache file intact
+ // (the reset touches only module state, never the file). Short-lived CLI
+ // invocations on a blackholed network must not each re-pay the fetch
+ // timeout — the stamp in model-cache.json carries the backoff across
+ // processes.
+ _resetOpenAILatestForTests();
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: failing });
+ expect(calls).toBe(1);
+ });
+
+ test('empty/malformed bodies never write the cache', async () => {
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: fetchReturning([]), force: true });
+ expect(latestOpenAITiers()).toBeNull();
+ const noData = (async () => new Response('{}', { status: 200 })) as unknown as typeof fetch;
+ await refreshLatestOpenAIModels({ env: { OPENAI_API_KEY: 'k' }, fetchImpl: noData, force: true });
+ expect(latestOpenAITiers()).toBeNull();
+ });
+});
diff --git a/test/provider-env.test.ts b/test/provider-env.test.ts
new file mode 100644
index 0000000000..b130b2ee92
--- /dev/null
+++ b/test/provider-env.test.ts
@@ -0,0 +1,66 @@
+/**
+ * mergedProviderEnv — the canonical provider-key/env fold (one mapping shared
+ * by buildGatewayConfig, detectCapabilities, and key-aware model resolution).
+ * Pins the unification deltas: Azure fields present (the old capability copy
+ * omitted them), GEMINI alias present (both copies had it), #1249 empty-drop.
+ */
+import { describe, test, expect } from 'bun:test';
+import { mergedProviderEnv } from '../src/core/ai/provider-env.ts';
+import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+const cfg = (partial: Partial<GBrainConfig>): GBrainConfig =>
+ ({ engine: 'pglite', ...partial }) as GBrainConfig;
+
+describe('mergedProviderEnv', () => {
+ test('folds every file-plane key incl. the Azure fields (unification delta)', () => {
+ const env = mergedProviderEnv(cfg({
+ openai_api_key: 'sk-o', anthropic_api_key: 'sk-a', voyage_api_key: 'pa-v',
+ zeroentropy_api_key: 'ze', openrouter_api_key: 'or', dashscope_api_key: 'ds',
+ google_api_key: 'gg',
+ azure_openai_endpoint: 'https://x.openai.azure.com',
+ azure_openai_deployment: 'gpt-5',
+ azure_openai_use_entra: '1',
+ }), {});
+ expect(env.OPENAI_API_KEY).toBe('sk-o');
+ expect(env.ANTHROPIC_API_KEY).toBe('sk-a');
+ expect(env.VOYAGE_API_KEY).toBe('pa-v');
+ expect(env.ZEROENTROPY_API_KEY).toBe('ze');
+ expect(env.OPENROUTER_API_KEY).toBe('or');
+ expect(env.DASHSCOPE_API_KEY).toBe('ds');
+ expect(env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('gg');
+ expect(env.AZURE_OPENAI_ENDPOINT).toBe('https://x.openai.azure.com');
+ expect(env.AZURE_OPENAI_DEPLOYMENT).toBe('gpt-5');
+ expect(env.AZURE_OPENAI_USE_ENTRA).toBe('1');
+ });
+
+ test('env wins over config ONLY for real values; empty strings dropped (#1249)', () => {
+ const env = mergedProviderEnv(
+ cfg({ anthropic_api_key: 'sk-config' }),
+ { ANTHROPIC_API_KEY: '', OPENAI_API_KEY: 'sk-env', UNRELATED: undefined },
+ );
+ expect(env.ANTHROPIC_API_KEY).toBe('sk-config'); // '' must not clobber
+ expect(env.OPENAI_API_KEY).toBe('sk-env');
+ expect('UNRELATED' in env).toBe(false);
+ });
+
+ test('GEMINI_API_KEY alias: canonical env name > alias > config fallback', () => {
+ expect(mergedProviderEnv(null, { GEMINI_API_KEY: 'g-alias' }).GOOGLE_GENERATIVE_AI_API_KEY).toBe('g-alias');
+ expect(mergedProviderEnv(null, {
+ GEMINI_API_KEY: 'g-alias', GOOGLE_GENERATIVE_AI_API_KEY: 'g-canonical',
+ }).GOOGLE_GENERATIVE_AI_API_KEY).toBe('g-canonical');
+ expect(mergedProviderEnv(cfg({ google_api_key: 'g-config' }), { GEMINI_API_KEY: 'g-alias' })
+ .GOOGLE_GENERATIVE_AI_API_KEY).toBe('g-alias'); // alias is still process-env: beats config
+ });
+
+ test('buildGatewayConfig consumes the shared fold (no drift possible)', async () => {
+ // The gateway env must carry the same fold — assert a config-plane key
+ // reaches the recipes' env name through buildGatewayConfig. Pin the real
+ // env var (dev shells export it; env legitimately wins over config).
+ await withEnv({ VOYAGE_API_KEY: undefined }, () => {
+ const gw = buildGatewayConfig(cfg({ voyage_api_key: 'pa-through-gateway' }));
+ expect(gw.env?.VOYAGE_API_KEY).toBe('pa-through-gateway');
+ });
+ });
+});