Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(config): merge DB-plane provider_chat_options rows; refuse dotted leaves at config set (#6290)

time-attack309e9ea1c0c4
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 27afb294b1..a57a2705ad 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -21,6 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the resolver backfill watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.
- `src/core/config.ts` (cwd `.env` boundary) — the #427 cwd-.env parser (`CWD_DOTENV_FILES`, `dotenvValuesForKey`) lives in `env-trust.ts`; config.ts re-exports both (façade rule — `test/config-env-hijack.test.ts` keeps importing from config) and `effectiveEnvDatabaseUrl` / `envShadowDetected` keep VALUE-match semantics for `DATABASE_URL` (a deliberate export equal to the cwd value would have selected the same database anyway; the value guard never touches `GBRAIN_DATABASE_URL` — the key-presence quarantine in env-trust.ts drops that one when a cwd `.env` assigns it). `loadConfig()` calls `loadGbrainEnvFile(getConfigDir)` (`~/.gbrain/.env`, operator-owned, never overrides a shell export) — `cli-preflight.ts` loads the same file earlier so the guardrails loader sees it.
+- `src/core/config-db-merge.ts` — the DB-plane read-side merge `loadConfigWithEngine` applies after its per-key merges (env > file > DB): provider API keys, `chat_model`/`expansion_model`, `chat_fallback_chain`/`chat_fallback_on_refusal`, flat `cycle.*`, and (#6290) `provider_chat_options.<selector>` rows, all from one batched, ~30 s memoized read. A chat-options row is one JSON object per selector (`<provider>` or `<provider>:<model>`, model ids may carry dots); the file plane wins per leaf and `__proto__`/`constructor`/`prototype` keys are dropped. A legacy dotted-leaf row is read only when `splitChatOptionsKey` (the path starts at the first dot followed by a non-digit) leaves a dot-free selector, otherwise ignored with a value-free warning. `assertProviderChatOptionsSetValue` backs `gbrain config set`, refusing a dotted leaf or non-object value with the exact JSON-form command. Pinned by `test/loadConfig-merge.test.ts` and `test/config-chat-options-db.test.ts`.
- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.
diff --git a/src/commands/config.ts b/src/commands/config.ts
index ca8ce2fbb5..8a615ffe55 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1201,6 +1201,13 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
const coverageOverride =
args.includes('--coverage-override') || args.includes('--yes');
+ // #6290: provider_chat_options rows are one JSON object per selector; a dotted leaf would be inert.
+ if (key.startsWith('provider_chat_options.')) {
+ const { assertProviderChatOptionsSetValue } = await import('../core/config-db-merge.ts');
+ try { assertProviderChatOptionsSetValue(key, value); }
+ catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }
+ }
+
// #5470: every admission parses the journal caps; a malformed value
// would refuse all managed writes, so reject it here.
const { JOURNAL_CONFIG_KEYS, parseJournalConfigValue } = await import('../core/persistence/limits.ts');
diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.ts
index cdc6334155..c64c344701 100644
--- a/src/core/config-db-merge.ts
+++ b/src/core/config-db-merge.ts
@@ -96,6 +96,65 @@ const DB_MERGED_SCALAR_KEYS: readonly string[] = [
];
const CYCLE_PREFIX = 'cycle.';
+const CHAT_OPTIONS_PREFIX = 'provider_chat_options.';
+const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+
+function isPlainRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+/** A copy of a parsed JSON value with prototype-polluting keys dropped at every depth. */
+function withoutUnsafeKeys(v: unknown): unknown {
+ if (Array.isArray(v)) return v.map(withoutUnsafeKeys);
+ if (!isPlainRecord(v)) return v;
+ const out: Record<string, unknown> = {};
+ for (const [k, child] of Object.entries(v)) if (!UNSAFE_KEYS.has(k)) out[k] = withoutUnsafeKeys(child);
+ return out;
+}
+
+/** Per-leaf merge: values already in `over` win; `under` fills the gaps. */
+function fillLeaves(over: Record<string, unknown>, under: Record<string, unknown>): Record<string, unknown> {
+ const out: Record<string, unknown> = { ...over };
+ for (const [k, v] of Object.entries(under)) {
+ if (out[k] === undefined) out[k] = v;
+ else if (isPlainRecord(out[k]) && isPlainRecord(v)) out[k] = fillLeaves(out[k] as Record<string, unknown>, v);
+ }
+ return out;
+}
+
+/**
+ * #6290: split a dotted `provider_chat_options.<selector>.<path>` remainder.
+ * Model ids carry dots (`openai:gpt-5.4`), so the path starts at the first
+ * dot followed by a non-digit; `path` is empty when there is none.
+ */
+export function splitChatOptionsKey(rest: string): { selector: string; path: string[] } {
+ const m = /\.(?=[^0-9.])/.exec(rest);
+ if (!m) return { selector: rest, path: [] };
+ return { selector: rest.slice(0, m.index), path: rest.slice(m.index + 1).split('.') };
+}
+
+function parseJsonOrString(raw: string): unknown {
+ try { return JSON.parse(raw); } catch { return raw; }
+}
+
+/**
+ * `gbrain config set provider_chat_options.<selector> <value>` takes one JSON
+ * object per selector. A dotted leaf (`...<selector>.thinking.type disabled`)
+ * or a non-object value is refused with the exact JSON-form command.
+ */
+export function assertProviderChatOptionsSetValue(key: string, value: string): void {
+ const rest = key.slice(CHAT_OPTIONS_PREFIX.length);
+ const { selector, path } = splitChatOptionsKey(rest);
+ const parsed = parseJsonOrString(value);
+ if (selector && path.length === 0 && isPlainRecord(parsed)) return;
+ let leaf: unknown = parsed;
+ for (const segment of [...path].reverse()) leaf = { [segment]: leaf };
+ const example = isPlainRecord(leaf) ? JSON.stringify(leaf) : '{"thinking":{"type":"disabled"}}';
+ throw new Error(
+ `${key} takes one JSON object per selector (provider_chat_options.<provider> or provider_chat_options.<provider>:<model>); nothing was written. ` +
+ `Run: gbrain config set ${CHAT_OPTIONS_PREFIX}${selector || '<provider>'} '${example.replace(/'/g, `'\\''`)}'`,
+ );
+}
/**
* D2 remediation: this merge used to issue ~12 sequential `engine.getConfig`
@@ -138,7 +197,7 @@ async function readDbPlaneMergeValues(
if (typeof engine.executeRaw === 'function') {
try {
const rows = await engine.executeRaw<{ key: string; value: string | null }>(
- `SELECT key, value FROM config WHERE key = ANY($1) OR key LIKE 'cycle.%'`,
+ `SELECT key, value FROM config WHERE key = ANY($1) OR key LIKE 'cycle.%' OR key LIKE 'provider\\_chat\\_options.%'`,
[[...DB_MERGED_SCALAR_KEYS]],
);
for (const row of rows) {
@@ -160,13 +219,15 @@ async function readDbPlaneMergeValues(
}
if (typeof engine.listConfigKeys === 'function') {
try {
- for (const key of await engine.listConfigKeys(CYCLE_PREFIX)) {
- if (!key.startsWith(CYCLE_PREFIX)) continue;
- const v = await engine.getConfig(key).catch(() => undefined);
- if (v !== undefined && v !== null && v !== '') values.set(key, v);
+ for (const prefix of [CYCLE_PREFIX, CHAT_OPTIONS_PREFIX]) {
+ for (const key of await engine.listConfigKeys(prefix)) {
+ if (!key.startsWith(prefix)) continue;
+ const v = await engine.getConfig(key).catch(() => undefined);
+ if (v !== undefined && v !== null && v !== '') values.set(key, v);
+ }
}
} catch {
- // quiet failure — no cycle merge this load
+ // quiet failure — no cycle / chat-options merge this load
}
}
}
@@ -236,4 +297,36 @@ export async function applyDbPlaneReadSideMerge(
}
merged.cycle = nextCycle;
}
+
+ // #6290: provider_chat_options rows. Canonical form: one JSON object per
+ // selector. A legacy dotted-leaf row is read only when its selector has no
+ // dot (the split is then unambiguous); otherwise it is ignored with a
+ // value-free warning. File plane wins per leaf; prototype keys are dropped.
+ const dbChatOptions: Record<string, Record<string, unknown>> = {};
+ for (const key of [...values.keys()].sort()) {
+ if (!key.startsWith(CHAT_OPTIONS_PREFIX)) continue;
+ const rest = key.slice(CHAT_OPTIONS_PREFIX.length);
+ const parsed = withoutUnsafeKeys(parseJsonOrString(values.get(key)!));
+ let selector = rest;
+ let entry: unknown = parsed;
+ const split = splitChatOptionsKey(rest);
+ if (split.path.length > 0 || !isPlainRecord(parsed)) {
+ if (split.path.length === 0 || split.selector.includes('.') || !split.selector) {
+ console.warn(`[gbrain] config: ${key} is not a JSON object per selector; ignoring. Store it as gbrain config set ${CHAT_OPTIONS_PREFIX}<selector> '<json object>'.`);
+ continue;
+ }
+ if (split.path.some((segment) => UNSAFE_KEYS.has(segment))) continue;
+ selector = split.selector;
+ for (const segment of [...split.path].reverse()) entry = { [segment]: entry };
+ }
+ if (!selector || UNSAFE_KEYS.has(selector) || !isPlainRecord(entry)) continue;
+ dbChatOptions[selector] = fillLeaves(dbChatOptions[selector] ?? {}, entry);
+ }
+ if (Object.keys(dbChatOptions).length > 0) {
+ const next: Record<string, Record<string, unknown>> = { ...(merged.provider_chat_options ?? {}) };
+ for (const [selector, options] of Object.entries(dbChatOptions)) {
+ next[selector] = fillLeaves(isPlainRecord(next[selector]) ? next[selector] : {}, options);
+ }
+ merged.provider_chat_options = next;
+ }
}
diff --git a/test/config-chat-options-db.test.ts b/test/config-chat-options-db.test.ts
new file mode 100644
index 0000000000..aca73a477f
--- /dev/null
+++ b/test/config-chat-options-db.test.ts
@@ -0,0 +1,95 @@
+// #6290: DB-plane provider_chat_options rows reach the gateway. One JSON
+// object per selector (model ids carry dots, so a dotted leaf is ambiguous);
+// the file plane wins per leaf; prototype keys are dropped; `config set`
+// refuses a dotted leaf with the exact JSON-form command.
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
+import { _resetDbPlaneMergeMemoForTests, assertProviderChatOptionsSetValue } from '../src/core/config-db-merge.ts';
+import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';
+import { __setGenerateTextTransportForTests, chat, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+function fakeEngine(map: Record<string, string>) {
+ return {
+ async getConfig(key: string) { return map[key]; },
+ async listConfigKeys(prefix: string) { return Object.keys(map).filter(k => k.startsWith(prefix)); },
+ };
+}
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ _resetDbPlaneMergeMemoForTests();
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'provider_chat_options.%'");
+});
+afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+});
+
+describe('DB-plane provider_chat_options merge', () => {
+ test('a JSON object row per selector reaches the gateway request (batched read, real PGLite)', async () => {
+ await engine.setConfig('provider_chat_options.anthropic:claude-sonnet-4-6', '{"thinking":{"type":"disabled"}}');
+ const merged = await loadConfigWithEngine(engine, { engine: 'pglite', chat_model: 'anthropic:claude-sonnet-4-6', anthropic_api_key: 'fake' } as GBrainConfig);
+ expect(merged?.provider_chat_options?.['anthropic:claude-sonnet-4-6']).toEqual({ thinking: { type: 'disabled' } });
+ let captured: Record<string, unknown> | undefined;
+ __setGenerateTextTransportForTests(async (args: any) => {
+ captured = args.providerOptions;
+ return { content: [{ type: 'text', text: 'ok' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+ configureGateway({ ...buildGatewayConfig(merged!), env: { ANTHROPIC_API_KEY: 'fake' } });
+ await chat({ model: 'anthropic:claude-sonnet-4-6', messages: [{ role: 'user', content: 'hello' }] });
+ expect((captured?.anthropic as Record<string, unknown>)?.thinking).toEqual({ type: 'disabled' });
+ });
+
+ test('the file plane wins per leaf; the DB fills siblings', async () => {
+ const base = { engine: 'pglite', provider_chat_options: { anthropic: { thinking: { type: 'enabled', budget_tokens: 1024 } } } } as GBrainConfig;
+ const merged = await loadConfigWithEngine(fakeEngine({
+ 'provider_chat_options.anthropic': '{"thinking":{"type":"disabled"},"temperature":0.2}',
+ }), base);
+ expect(merged?.provider_chat_options?.anthropic).toEqual({ thinking: { type: 'enabled', budget_tokens: 1024 }, temperature: 0.2 });
+ });
+
+ test('prototype keys are dropped at every depth', async () => {
+ const merged = await loadConfigWithEngine(fakeEngine({
+ 'provider_chat_options.anthropic': '{"__proto__":{"polluted":true},"thinking":{"constructor":{"x":1},"type":"disabled"}}',
+ 'provider_chat_options.__proto__': '{"polluted":true}',
+ }), { engine: 'pglite' } as GBrainConfig);
+ expect(merged?.provider_chat_options?.anthropic).toEqual({ thinking: { type: 'disabled' } });
+ expect(Object.keys(merged?.provider_chat_options ?? {})).toEqual(['anthropic']);
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ test('a legacy dotted row is read only when its selector has no dot', async () => {
+ const merged = await loadConfigWithEngine(fakeEngine({
+ 'provider_chat_options.deepseek:deepseek-v4.thinking.type': 'disabled',
+ 'provider_chat_options.openai:gpt-5.4.reasoningEffort': 'low',
+ }), { engine: 'pglite' } as GBrainConfig);
+ expect(merged?.provider_chat_options?.['deepseek:deepseek-v4']).toEqual({ thinking: { type: 'disabled' } });
+ expect(merged?.provider_chat_options?.['openai:gpt-5.4']).toBeUndefined();
+ expect(merged?.provider_chat_options?.['openai:gpt-5']).toBeUndefined();
+ });
+});
+
+describe('config set provider_chat_options validation', () => {
+ test('a JSON object per selector is accepted, dotted model ids included', () => {
+ expect(() => assertProviderChatOptionsSetValue('provider_chat_options.openai:gpt-5.4', '{"reasoningEffort":"low"}')).not.toThrow();
+ expect(() => assertProviderChatOptionsSetValue('provider_chat_options.anthropic', '{"thinking":{"type":"disabled"}}')).not.toThrow();
+ });
+
+ test('a dotted leaf is refused with the exact JSON-form command', () => {
+ expect(() => assertProviderChatOptionsSetValue('provider_chat_options.deepseek:deepseek-v4.thinking.type', 'disabled'))
+ .toThrow(`gbrain config set provider_chat_options.deepseek:deepseek-v4 '{"thinking":{"type":"disabled"}}'`);
+ });
+
+ test('a non-object value is refused', () => {
+ expect(() => assertProviderChatOptionsSetValue('provider_chat_options.anthropic', 'disabled')).toThrow('takes one JSON object per selector');
+ expect(() => assertProviderChatOptionsSetValue('provider_chat_options.anthropic', '[1]')).toThrow('nothing was written');
+ });
+});