Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(models): DB-plane chat_model reaches the gateway; config set warns only when shadowed (#6795)

time-attack640d5da6ad32
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 18e3b06066..bd4b60e425 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -19,6 +19,7 @@
| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
| A write (`add_timeline_entry`, `put_page`, `remember`, any `mutating` tool) refused `invalid_params` "unknown parameter … write operations always reject unknown parameters; nothing was written" | the call named a parameter the tool does not declare (for example `content` instead of `detail`); the `suggestion` names the submitted key and the declared one; resend with the declared name. Reads keep the `mcp.strict_params` warn grace period | agent | none | the resent call returns no `invalid_params` and no `unknown_param` warning |
+| `gbrain config set chat_model` (or `expansion_model`) printed `[config] WARN: … outranks it, so the model in use does not change`, or its `--json` says `effective: false` | the value is stored in the database, but `shadowed_by` names what wins at runtime (never its value): a `models.*` key (`gbrain config unset <that key>`, after asking: it may select other models too), an environment variable (`GBRAIN_MODEL`, `GBRAIN_CHAT_MODEL`, `GBRAIN_EXPANSION_MODEL`: the user removes it from their shell profile or service environment), or the `config.json` pin (`gbrain config unset chat_model --file` removes only the pin) | agent for the config changes, after the user agrees; user for an environment variable | none | `gbrain config get chat_model` reports `source: db plane`, and a repeat `config set … --json` says `effective: true` |
| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): the fix text names the config key that selected the model when the gateway knows it ("Selected via models.tier.reasoning. Fix: gbrain config set …"; an env var or config.json pin says what to clear); otherwise check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` |
| Doctor `links_extraction_lag` or sync says "N page(s) have un-extracted edges" | `gbrain extract --stale --dry-run --json`, then on the host `gbrain extract --stale --catch-up [--source-id <id>]` | user above 120 s, else agent | none | dry run: `actionable: 0` |
| Doctor `links_extraction_lag` says "N page(s) failed link extraction 3 runs in a row and are held", or `extract --stale` lists failed pages | Read each page's code (`unknown_source`: the page's source row is gone; restore the source or delete the page), fix the cause, then `gbrain extract --stale [--source-id <id>] --retry-held` | agent | none | `gbrain extract --stale --dry-run --json`: `held: 0` |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index dce9a9de2b..70abe14e58 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -45,5 +45,5 @@ src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1499 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge)
src/core/search/evidence-delivery.ts 1712 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page
-src/commands/config.ts 1512 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts)
+src/commands/config.ts 1514 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 14e7589c37..ea1ac1c402 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1,6 +1,7 @@
import type { GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import { loadConfig, loadConfigWithEngine } from '../core/config.ts';
+import { isLegacyModelKey, reportLegacyModelWrite, unsetModelFilePin } from './config/model-pin-shadow.ts';
import {
getEmbeddingColumnRegistry,
validateColumnKey,
@@ -680,8 +681,9 @@ Subcommands:
get <key> [--raw] Print one value (--raw: no secret redaction)
set <key> <value> Write a value. --force accepts an unknown key;
--coverage-override (or --yes) passes the embedding
- coverage gate; --yes accepts a disclosure prompt
- unset <key> Remove one key
+ coverage gate; --yes accepts a disclosure prompt;
+ chat_model/expansion_model warn when outranked (--json)
+ unset <key> Remove one key (a model key with --file: its config.json pin)
unset --pattern <prefix> Remove every key under a prefix`;
export function printUsage(): void {
@@ -769,6 +771,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
await unsetEmbeddingDisabled(engine);
return;
}
+ if (isLegacyModelKey(key) && args.includes('--file')) return unsetModelFilePin(key);
if (MEMORY_DUAL_PLANE_KEYS.has(key) || key === BRAIN_AUDIENCE_KEY) {
// Dual-plane delete, mirroring the dual-plane set: file mirror AND the
// authoritative DB row both go. "Not found" only when neither had it.
@@ -971,7 +974,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
// sitting in the value slot can't slip through as literal config
// content.
const tail = args.slice(2);
- const unknownFlags = tail.filter(a => a.startsWith('-') && !CONFIG_SET_KNOWN_FLAGS.includes(a));
+ const unknownFlags = tail.filter(a => a.startsWith('-') && !CONFIG_SET_KNOWN_FLAGS.includes(a) && !(a === '--json' && isLegacyModelKey(key)));
if (unknownFlags.length > 0) {
for (const flag of unknownFlags) {
console.error(`[config] unknown flag: ${flag}`);
@@ -1438,10 +1441,9 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
await setConfigWithDecideHooks(engine, key, value, forceFlag);
- // v0.36.x #892: redact sensitive values in confirmation output. API
- // keys / tokens / passwords are commonly set from terminals with
- // scrollback; echoing the raw value to stderr leaks the secret.
- console.log(`Set ${key} = ${redactConfigValue(key, value)}`);
+ // #892: keep credentials out of confirmation output and scrollback. #6795: a model pin says whether it took effect.
+ if (isLegacyModelKey(key)) await reportLegacyModelWrite(engine, key, value, tail.includes('--json'));
+ else console.log(`Set ${key} = ${redactConfigValue(key, value)}`);
if (key === 'facts.default_visibility') await restampVisibilityPosture(value);
// v0.40.3.0 (D3 + Phase 2B): mode-switch UX. Fires only on
diff --git a/src/commands/config/model-pin-shadow.ts b/src/commands/config/model-pin-shadow.ts
new file mode 100644
index 0000000000..9993e81004
--- /dev/null
+++ b/src/commands/config/model-pin-shadow.ts
@@ -0,0 +1,65 @@
+/**
+ * #6795: `gbrain config set chat_model|expansion_model` writes a DB-plane
+ * default. A `models.*` key, `GBRAIN_MODEL`, the per-key env var or a
+ * config.json pin outranks it at runtime (gateway.ts resolveGatewayModels +
+ * ai/legacy-model-pin.ts). This names the one that actually wins, by key,
+ * variable or file path, never its value, with the fix that clears it.
+ */
+import { cliRenderContext, renderNotice, type Action, type Notice } from '../../core/agent-output.ts';
+import { configPath, loadConfigFileOnly, saveConfig } from '../../core/config.ts';
+import type { ConfigReader } from '../../core/config-snapshot.ts';
+
+export type LegacyModelKey = 'chat_model' | 'expansion_model';
+export const isLegacyModelKey = (key: string): key is LegacyModelKey => key === 'chat_model' || key === 'expansion_model';
+
+export interface ModelPinShadow { kind: 'config_key' | 'env' | 'file'; name: string }
+
+export async function modelPinShadow(engine: ConfigReader, key: LegacyModelKey): Promise<ModelPinShadow | null> {
+ const chat = key === 'chat_model';
+ for (const name of [chat ? 'models.chat' : 'models.expansion', chat ? 'models.tier.reasoning' : 'models.tier.utility', 'models.default']) {
+ if ((await engine.getConfig(name))?.trim()) return { kind: 'config_key', name };
+ }
+ for (const name of ['GBRAIN_MODEL', chat ? 'GBRAIN_CHAT_MODEL' : 'GBRAIN_EXPANSION_MODEL']) {
+ if (process.env[name]?.trim()) return { kind: 'env', name };
+ }
+ return loadConfigFileOnly()?.[key] !== undefined ? { kind: 'file', name: configPath() } : null;
+}
+
+export function modelPinShadowNotice(key: LegacyModelKey, shadow: ModelPinShadow): Notice {
+ const by = shadow.kind === 'config_key' ? `the config key ${shadow.name}`
+ : shadow.kind === 'env' ? `the environment variable ${shadow.name}` : `the ${key} pin in ${shadow.name}`;
+ const verify = { argv: ['gbrain', 'config', 'get', shadow.kind === 'config_key' ? shadow.name : key] };
+ const fix: Action = shadow.kind === 'config_key'
+ ? { argv: ['gbrain', 'config', 'unset', shadow.name], ask_user: true, consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Removes ${shadow.name} so the ${key} just written takes effect; it may also select other models, so ask first.` }
+ : shadow.kind === 'env'
+ ? { argv: ['unset', shadow.name], consent: [], actor: 'user', requires_exclusive: false, verify,
+ why: `${shadow.name} is set in the environment gbrain runs in; only the user can remove it (shell profile or service environment).` }
+ : { argv: ['gbrain', 'config', 'unset', key, '--file'], ask_user: true, consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Removes the ${key} pin from ${shadow.name} so the database value just written takes effect.` };
+ return { code: 'config_write_shadowed', kind: 'degraded', why: `${key} was stored in the database, but ${by} outranks it, so the model in use does not change.`, fix };
+}
+
+/** The confirmation of a DB write to a legacy model key: `effective` says whether it takes effect, `shadowed_by` what outranks it. */
+export async function reportLegacyModelWrite(engine: ConfigReader, key: LegacyModelKey, value: string, json: boolean): Promise<void> {
+ const shadow = await modelPinShadow(engine, key);
+ const notice = shadow ? modelPinShadowNotice(key, shadow) : null;
+ if (json) {
+ console.log(JSON.stringify({ key, value, written: true, effective: shadow === null, ...(shadow ? { shadowed_by: shadow, notices: [renderNotice(notice!, cliRenderContext())] } : {}) }));
+ return;
+ }
+ console.log(`Set ${key} = ${value}`);
+ if (notice) console.error(`[config] WARN: ${notice.why} Fix: ${notice.fix!.argv!.join(' ')} (${notice.fix!.why})`);
+}
+
+/** `gbrain config unset chat_model|expansion_model --file`: drop only the config.json pin; the database value stays. */
+export function unsetModelFilePin(key: LegacyModelKey): void {
+ const cfg = loadConfigFileOnly();
+ if (!cfg || cfg[key] === undefined) {
+ console.error(`Config key not found in ${configPath()}: ${key}`);
+ process.exit(1);
+ }
+ delete cfg[key];
+ saveConfig(cfg);
+ console.log(`Unset ${key} (file plane: ${configPath()})`);
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index fecd2bda5d..ebc7808bc0 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -57,6 +57,7 @@ import {
openrouterRequiresExplicitPromptCache,
} from './recipes/openrouter.ts';
import { resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';
+import { readLegacyModelPin } from './legacy-model-pin.ts';
import { snapshotConfigReader } from '../config-snapshot.ts';
import { clearGatewayModelSources, gatewayModelSource, setGatewayModelSource } from './gateway-model-sources.ts';
import { parseLlmJson } from '../llm-json.ts';
@@ -572,13 +573,9 @@ async function discoverBeforeOpenAICall(modelStr: string | undefined): Promise<v
async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConfig> {
const cfg = requireConfig();
- // The two resolutions below each walk a 5-tier precedence chain that reads
- // up to 4 config keys, plus alias expansion. Against the engine that is
- // many sequential round trips before the CLI does any work — seconds of
- // `gbrain stats`'s wall clock on a hosted brain, for reads the server
- // answered in microseconds. Take one snapshot of the config table and
- // resolve every model against it. Same keys, same precedence, one round
- // trip.
+ // Resolve every model (each walks a 5-tier chain plus alias expansion, and
+ // the legacy DB pins below) against ONE config snapshot: per-key reads add
+ // seconds of sequential round trips on a hosted brain.
const reader = await snapshotConfigReader(engine);
// Resolve expansion (utility tier) and chat (reasoning tier). Embedding is
@@ -604,6 +601,7 @@ async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConfi
// 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.
+ // Only with no pin does a DB-plane chat_model/expansion_model (#6795) apply.
const needsFileCfg = (s: string) => s === 'tier_default' || s === 'fallback';
let fileCfg: GBrainConfig | null = null;
if (needsFileCfg(chatDetailed.source) || needsFileCfg(expansionDetailed.source)) {
@@ -616,8 +614,10 @@ async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConfi
const env = cfg.env ?? process.env;
const chatEffective = needsFileCfg(chatDetailed.source) ? resolveEffectiveChatModel(fileCfg, env) : null;
const expansionEffective = needsFileCfg(expansionDetailed.source) ? resolveEffectiveExpansionModel(fileCfg, env) : null;
- const newChat = chatEffective?.model ?? chatDetailed.model;
- const newExpansion = expansionEffective?.model ?? expansionDetailed.model;
+ const dbChat = await readLegacyModelPin(reader, 'chat_model', chatEffective, fileCfg, env);
+ const dbExpansion = await readLegacyModelPin(reader, 'expansion_model', expansionEffective, fileCfg, env);
+ const newChat = dbChat ?? chatEffective?.model ?? chatDetailed.model;
+ const newExpansion = dbExpansion ?? expansionEffective?.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
@@ -627,8 +627,8 @@ async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConfi
const chatFull = newChat.includes(':') ? newChat : prefixWithProviderFrom(cfg.chat_model ?? DEFAULT_CHAT_MODEL, newChat);
_config = { ...cfg, expansion_model: expansionFull, chat_model: chatFull };
- setGatewayModelSource('expansion', expansionFull, gatewayModelSource('expansion', expansionDetailed, expansionEffective));
- setGatewayModelSource('chat', chatFull, gatewayModelSource('chat', chatDetailed, chatEffective));
+ setGatewayModelSource('expansion', expansionFull, dbExpansion ? { source: 'config_key', origin: 'expansion_model' } : gatewayModelSource('expansion', expansionDetailed, expansionEffective));
+ setGatewayModelSource('chat', chatFull, dbChat ? { source: 'config_key', origin: 'chat_model' } : gatewayModelSource('chat', chatDetailed, chatEffective));
_modelCache.clear();
clearQueryEmbedCache();
_shrinkState.clear();
diff --git a/src/core/ai/legacy-model-pin.ts b/src/core/ai/legacy-model-pin.ts
new file mode 100644
index 0000000000..b60f9e358a
--- /dev/null
+++ b/src/core/ai/legacy-model-pin.ts
@@ -0,0 +1,32 @@
+/**
+ * #6795: a DB-plane `chat_model` / `expansion_model` (`gbrain config set`)
+ * is a default below every `models.*` key, `GBRAIN_MODEL` and an explicit
+ * file or env pin. The gateway consults it only when its resolution fell to
+ * the tier default with no pin, reading the same config snapshot, never gateway
+ * state (which holds fabricated defaults and the previous job's model).
+ */
+import type { GBrainConfig } from '../config.ts';
+import type { ConfigReader } from '../config-snapshot.ts';
+import { providerKeyReady, resolveModelDetailed, type EffectiveModelSource } from '../model-config.ts';
+import { mergedProviderEnv } from './provider-env.ts';
+
+const unservableWarned = new Set<string>();
+
+export async function readLegacyModelPin(
+ reader: ConfigReader | null,
+ key: 'chat_model' | 'expansion_model',
+ effective: { source: EffectiveModelSource } | null,
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined>,
+): Promise<string | null> {
+ if (!reader || effective?.source !== 'tier_default' || fileCfg?.[key] !== undefined) return null;
+ const raw = await reader.getConfig(key);
+ if (!raw?.trim()) return null;
+ const resolved = await resolveModelDetailed(reader, { configKey: key, fallback: raw });
+ if (providerKeyReady(resolved.model, mergedProviderEnv(fileCfg, env))) return resolved.model;
+ if (!unservableWarned.has(`${key}=${resolved.model}`)) {
+ unservableWarned.add(`${key}=${resolved.model}`);
+ process.stderr.write(`[models] DB-plane ${key} has no usable provider key or provider prefix; falling back to the key-aware default. Set the provider's key, or gbrain config unset ${key}.\n`);
+ }
+ return null;
+}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index a544b2f0f2..65b4b55adb 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -918,6 +918,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: '`gbrain apply-migrations --list` now shows v0.53.0 as `applied_pending_host_work` instead of `applied` while its stored shared-skills report still names host work (a source\'s inventory, writer, projection or publication-policy stage, or a brain-level pending action), and no longer prints "All migrations up to date" for it; `--list --json` rows carry that status and an `applied_pending_host_work` array whose fix is the read-only `gbrain apply-migrations --migration 0.53.0 --dry-run --json` inventory. Scripts that match `applied` should accept both. `gbrain doctor` warns on `minions_migration` (`details.code: migration_host_work_pending`) until a later `gbrain apply-migrations --yes` re-check finds the work done. Unenrolled members (every new brain), sources that opted out and a declined migration are never reported.' },
{ since: '0.60.307.0', text: 'A queued job under a cost cap you set that calls a model with a registered price but no known context-token ceiling (OpenRouter models) now stops with `no_context_ceiling` instead of `no_pricing`. The message says the price is already known; the fix asks before rerunning without your cap (`--yes` in place of `--max-usd`), or asks for the model\'s context size for the brain-host operator. Under a default or derived cap the warning names the missing ceiling. Nothing else changed: no provider call is made either way.' },
{ since: '0.60.307.0', text: 'A `claude-cli:` chat call capped at 1024 output tokens or fewer (the `gbrain models doctor` probe, query intent, fact classification, decisions, calibration and grading calls) now runs with Claude Code\'s thinking turned off (`MAX_THINKING_TOKENS=0`), because the API needs a thinking budget of at least 1024 tokens below the cap; those calls failed with a 400 before. The call reports `thinking: \'disabled_below_floor\'` in its claude-cli provider metadata. Calls with a larger cap are unchanged.' },
+ { since: '0.60.307.0', text: 'A database-plane `chat_model` or `expansion_model` (`gbrain config set chat_model …`) now selects the model when no `models.*` key, `GBRAIN_MODEL`, `GBRAIN_CHAT_MODEL` / `GBRAIN_EXPANSION_MODEL` or config.json pin outranks it; before, the gateway ignored it and used the built-in default. Its provenance reads `config_key` / `chat_model`. When one of those does outrank the write, `config set` still stores it but warns, naming the key, variable or file (never its value) and the fix (`gbrain config unset <models key>`, the new `gbrain config unset chat_model --file`, or unsetting the variable); `config set chat_model|expansion_model … --json` reports `effective` and `shadowed_by`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 26ac58e526..268a7433ff 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -745,6 +745,7 @@ export const NOTICE_CODES = {
sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
+ config_write_shadowed: { kind: 'degraded', summary: '`gbrain config set chat_model|expansion_model` stored the value in the database, but a models.* config key, an environment variable (GBRAIN_MODEL, GBRAIN_CHAT_MODEL, GBRAIN_EXPANSION_MODEL) or the config.json pin outranks it, so the model in use does not change; `shadowed_by` names it (never its value) and the fix clears it (`gbrain config unset <models key>`, `gbrain config unset <key> --file`, or the user unsets the variable).' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },
references_unavailable: { kind: 'degraded', summary: 'The reference count and records on entity rows did not finish (deadline or read failure); rows marked references_unavailable are unread, not empty.' },
diff --git a/test/ai/gateway-model-sources.serial.test.ts b/test/ai/gateway-model-sources.serial.test.ts
index fb82ed82d4..14024ff4ae 100644
--- a/test/ai/gateway-model-sources.serial.test.ts
+++ b/test/ai/gateway-model-sources.serial.test.ts
@@ -6,8 +6,8 @@
*
* Serial lane: mutates gateway module state and provider/home env vars.
*/
-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -19,6 +19,7 @@ import {
} from '../../src/core/ai/gateway.ts';
import { getGatewayModelSource } from '../../src/core/ai/gateway-model-sources.ts';
import { _resetDeprecationWarningsForTest } from '../../src/core/model-config.ts';
+import { runConfig } from '../../src/commands/config.ts';
import { withEnv } from '../helpers/with-env.ts';
class StubEngine {
@@ -26,7 +27,7 @@ class StubEngine {
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() {}
+ async setConfig(key: string, value: string) { this.cfg.set(key, value); }
}
let tmpHome: string;
@@ -62,6 +63,134 @@ afterEach(() => {
rmSync(tmpHome, { recursive: true, force: true });
});
+/** Run `gbrain config` against the stub; returns stdout and stderr lines. */
+async function config(args: string[], extra: Record<string, string | undefined> = {}): Promise<{ out: string[]; err: string[] }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });
+ const error = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });
+ try {
+ await withEnv(env(extra), () => runConfig(stub as never, args));
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ }
+ return { out, err };
+}
+
+function pinFile(key: string, value: string): string {
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ const path = join(tmpHome, '.gbrain', 'config.json');
+ writeFileSync(path, JSON.stringify({ engine: 'pglite', [key]: value }));
+ return path;
+}
+
+for (const [key, touchpoint, model] of [
+ ['chat_model', 'chat', 'anthropic:claude-opus-4-7'],
+ ['expansion_model', 'expansion', 'anthropic:claude-sonnet-4-6'],
+] as const) {
+ const selected = () => touchpoint === 'chat' ? getChatModel() : getExpansionModel();
+ const pinEnv = touchpoint === 'chat' ? 'GBRAIN_CHAT_MODEL' : 'GBRAIN_EXPANSION_MODEL';
+ const OTHER = 'anthropic:claude-haiku-4-5-20251001';
+
+ describe(`#6795: DB-plane ${key}`, () => {
+ test('config set reaches the gateway and is attributed to the key', async () => {
+ const { out, err } = await config(['set', key, model]);
+ expect(out).toEqual([`Set ${key} = ${model}`]);
+ expect(err.join('\n')).not.toContain('WARN');
+ await reconfigure();
+ expect(selected()).toBe(model);
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'config_key', origin: key });
+ stub.set(key, OTHER);
+ await reconfigure();
+ expect(selected()).toBe(OTHER);
+ stub.set(key, '');
+ await reconfigure();
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'tier_default', origin: 'built-in default' });
+ });
+
+ test('a file pin, its env var, GBRAIN_MODEL and models.* keys all outrank it', async () => {
+ stub.set(key, model);
+ pinFile(key, OTHER);
+ await reconfigure();
+ expect(selected()).toBe(OTHER);
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'file_config', origin: `${key} (config.json)` });
+ await reconfigure({ [pinEnv]: 'anthropic:claude-sonnet-4-6' });
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'env', origin: pinEnv });
+ rmSync(join(tmpHome, '.gbrain', 'config.json'));
+ await reconfigure({ GBRAIN_MODEL: OTHER });
+ expect(selected()).toBe(OTHER);
+ stub.set(`models.${touchpoint}`, 'anthropic:claude-sonnet-4-6');
+ await reconfigure();
+ expect(selected()).toBe('anthropic:claude-sonnet-4-6');
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'config_key', origin: `models.${touchpoint}` });
+ });
+
+ test('a DB value whose provider has no key falls back to the default', async () => {
+ stub.set(key, 'openai:gpt-5.2');
+ await reconfigure();
+ expect(selected()).not.toBe('openai:gpt-5.2');
+ expect(getGatewayModelSource(touchpoint, selected())).toEqual({ source: 'tier_default', origin: 'built-in default' });
+ });
+
+ test('config set --json reports effective:true when nothing outranks the write', async () => {
+ const { out } = await config(['set', key, model, '--json']);
+ expect(JSON.parse(out.join(''))).toEqual({ key, value: model, written: true, effective: true });
+ });
+
+ test('a shadowing config.json pin: warning names the file, never its value; the fix clears only the pin', async () => {
+ const path = pinFile(key, OTHER);
+ const before = readFileSync(path, 'utf8');
+ const text = await config(['set', key, model]);
+ expect(await stub.getConfig(key)).toBe(model);
+ expect(readFileSync(path, 'utf8')).toBe(before);
+ expect(text.err.join('\n')).toContain(`[config] WARN: ${key} was stored in the database, but the ${key} pin in ${path} outranks it`);
+ expect(text.err.join('\n')).toContain(`gbrain config unset ${key} --file`);
+ expect(text.err.join('\n')).not.toContain(OTHER);
+ const { out } = await config(['set', key, model, '--json']);
+ const doc = JSON.parse(out.join(''));
+ expect(doc).toMatchObject({ key, written: true, effective: false, shadowed_by: { kind: 'file', name: path } });
+ expect(doc.notices[0]).toMatchObject({ code: 'config_write_shadowed', kind: 'degraded',
+ fix: { argv: ['gbrain', 'config', 'unset', key, '--file'], next: 'ask_user', verify: { argv: ['gbrain', 'config', 'get', key] } } });
+ expect(JSON.stringify(doc)).not.toContain(OTHER);
+ const unset = await config(['unset', key, '--file']);
+ expect(unset.out).toEqual([`Unset ${key} (file plane: ${path})`]);
+ expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual({ engine: 'pglite' });
+ expect(await stub.getConfig(key)).toBe(model);
+ await reconfigure();
+ expect(selected()).toBe(model);
+ });
+
+ test('a shadowing env var is named by variable; the user unsets it', async () => {
+ const { out } = await config(['set', key, model, '--json'], { [pinEnv]: OTHER });
+ const doc = JSON.parse(out.join(''));
+ expect(doc).toMatchObject({ effective: false, shadowed_by: { kind: 'env', name: pinEnv } });
+ expect(doc.notices[0].fix).toMatchObject({ argv: ['unset', pinEnv], actor: 'user', next: 'tell_user_to_run' });
+ expect(JSON.stringify(doc)).not.toContain(OTHER);
+ const generic = JSON.parse((await config(['set', key, model, '--json'], { GBRAIN_MODEL: OTHER })).out.join(''));
+ expect(generic.shadowed_by).toEqual({ kind: 'env', name: 'GBRAIN_MODEL' });
+ });
+
+ test('a shadowing models.* key is named; the fix unsets that key after asking', async () => {
+ for (const name of [`models.${touchpoint}`, `models.tier.${touchpoint === 'chat' ? 'reasoning' : 'utility'}`, 'models.default']) {
+ stub = new StubEngine();
+ stub.set(name, OTHER);
+ const doc = JSON.parse((await config(['set', key, model, '--json'])).out.join(''));
+ expect(doc).toMatchObject({ effective: false, shadowed_by: { kind: 'config_key', name } });
+ expect(doc.notices[0].fix).toMatchObject({ argv: ['gbrain', 'config', 'unset', name], next: 'ask_user' });
+ }
+ });
+
+ test('--json is refused for every other key, before any write', async () => {
+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit ${code}`); }) as never);
+ try {
+ await expect(config(['set', 'search.mode', 'balanced', '--json'])).rejects.toThrow('exit 1');
+ } finally { exit.mockRestore(); }
+ expect(await stub.getConfig('search.mode')).toBeNull();
+ });
+ });
+}
+
describe('gateway model provenance', () => {
test('tier config and models.default are attributed to their keys', async () => {
stub.set('models.tier.utility', 'anthropic:claude-haiku-4-5-20251001');