Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(config): refuse an unregistered search.* or content_sanity.* key at config set (#5956)

time-attackfd87d1940b4e
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 40bb9640ba..70e1b79df1 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -379,6 +379,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
const err = validateDecideConfigValue(key, value);
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
+ (await import('./config/enumerated-keys.ts')).refuseUnregisteredEnumeratedKey(key, force);
if (key === 'auto_chronicle' || key.startsWith('chronicle.')) await refuseInvalidChronicleValue(key, value, force);
if (key.startsWith('facts.drain_')) {
const { validateFactsDrainConfigValue } = await import('../core/facts/drain-config.ts');
diff --git a/src/commands/config/enumerated-keys.ts b/src/commands/config/enumerated-keys.ts
new file mode 100644
index 0000000000..8ac2c191b3
--- /dev/null
+++ b/src/commands/config/enumerated-keys.ts
@@ -0,0 +1,60 @@
+/**
+ * `config set` refusal for an unregistered leaf under an enumerated prefix.
+ *
+ * A prefix in KNOWN_CONFIG_KEY_PREFIXES admits any sub-key, so a misspelled
+ * or retired `search.token_budget` (the reader is `search.tokenBudget`) used
+ * to be written and never read. Under these prefixes every key gbrain reads
+ * is registered in KNOWN_CONFIG_KEYS: `search.*` is pinned key by key in
+ * test/config-search-registry.test.ts, and `content_sanity.*` has one reader,
+ * the DB-plane merge in loadConfigWithEngine. Other prefixes hold per-phase,
+ * per-provider or per-name sub-keys; `chronicle.*` has its own list.
+ *
+ * The refusal is a usage error (exit 2) naming the nearest registered
+ * spelling; nothing is written. `--force` writes the key anyway (one a newer
+ * gbrain reads) with a warning.
+ */
+import { KNOWN_CONFIG_KEYS } from '../../core/config.ts';
+import { suggestNearest } from '../../core/levenshtein.ts';
+import { inertText } from '../../core/agent-output.ts';
+import { exitCliError, usageError } from '../../cli/cli-error.ts';
+
+const ENUMERATED_CONFIG_KEY_PREFIXES: readonly string[] = ['search.', 'content_sanity.'];
+
+export function refuseUnregisteredEnumeratedKey(key: string, force: boolean): void {
+ const prefix = ENUMERATED_CONFIG_KEY_PREFIXES.find((p) => key.startsWith(p));
+ if (!prefix || KNOWN_CONFIG_KEYS.includes(key)) return;
+ // Case- and underscore-blind: the usual miss is a camelCase reader under a
+ // snake_case write (or the reverse), not a typo.
+ const fold = (k: string) => k.toLowerCase().replaceAll('_', '');
+ const registered = KNOWN_CONFIG_KEYS.filter((k) => k.startsWith(prefix));
+ const nearest = suggestNearest(fold(key), registered.map(fold), 3);
+ const suggestion = registered.find((k) => fold(k) === nearest);
+ const shown = inertText(key, 80);
+ const didYouMean = suggestion ? ` Did you mean "${suggestion}"?` : '';
+ if (force) {
+ console.error(`[config] WARN: writing unregistered ${prefix}* key "${shown}" with --force. Nothing in gbrain reads it.${didYouMean}`);
+ return;
+ }
+ const target = suggestion ?? '<KEY>';
+ exitCliError(usageError(
+ `Unknown config key "${shown}".${didYouMean} Nothing was written.`,
+ suggestion
+ ? `Set the registered key instead: gbrain config set ${suggestion} <value>. To write "${shown}" anyway (a key a newer gbrain reads), re-run with --force.`
+ : `Set a registered ${prefix}* key instead. To write "${shown}" anyway (a key a newer gbrain reads), re-run with --force.`,
+ {
+ why: `Every ${prefix}* key gbrain reads is registered, so nothing would read this one.`,
+ fix: {
+ argv: ['gbrain', 'config', 'set', target, '<VALUE>'],
+ inputs: [
+ ...(suggestion ? [] : [{ name: 'KEY', how: `Ask the user which registered ${prefix}* key they meant; gbrain reads no other ${prefix}* key.` }]),
+ { name: 'VALUE', how: 'The value the refused command carried.' },
+ ],
+ consent: [],
+ actor: suggestion ? 'agent' : 'user',
+ why: `Writes the value under the ${prefix}* key gbrain reads.`,
+ verify: { argv: ['gbrain', 'config', 'get', target] },
+ requires_exclusive: false,
+ },
+ },
+ ), 'config');
+}
diff --git a/src/core/config.ts b/src/core/config.ts
index 54e7ca687f..da2bbbeb41 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1694,7 +1694,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
* Levenshtein suggestion in `gbrain config set`.
*/
export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = [
- 'search.', // search.* (mode, cache.*, etc.)
+ 'search.', // search.* (mode, cache.*, etc.); config set refuses unregistered leaves (commands/config/enumerated-keys.ts)
'graph.', // graph.edge_validity (temporal typed-edge read policy, src/core/link-validity.ts)
'models.', // models.* (tier, aliases, per-task)
'dream.', // dream.synthesize.*, dream.patterns.*
@@ -1702,7 +1702,7 @@ export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = [
'embedding_columns.', // per-column overrides
'provider_base_urls.', // per-provider base URL overrides
'provider_chat_options.', // per-provider / per-model chat providerOptions
- 'content_sanity.', // v0.41 content-sanity tunables
+ 'content_sanity.', // v0.41 content-sanity tunables; enumerated like search.
'mcp.', // mcp.publish_skills, mcp.skills_dir (PR1 skill catalog)
'autopilot.', // autopilot.nightly_quality_probe.*, autopilot.auto_drain.* (#1685)
'chronicle.', // Life Chronicle knobs; config set refuses leaves outside CHRONICLE_CONFIG_KEYS (#5876)
diff --git a/test/config-set-unread-prefixed-key.test.ts b/test/config-set-unread-prefixed-key.test.ts
new file mode 100644
index 0000000000..8d6567ce07
--- /dev/null
+++ b/test/config-set-unread-prefixed-key.test.ts
@@ -0,0 +1,137 @@
+/**
+ * `config set` refuses an unregistered key under an enumerated prefix
+ * (`search.`, `content_sanity.`), as it refuses an unknown chronicle.* leaf.
+ *
+ * A prefix in KNOWN_CONFIG_KEY_PREFIXES admits any sub-key, so before this a
+ * retired or misspelled `search.token_budget` (the reader is
+ * `search.tokenBudget`) or `search.reranker.topN` (the reader is
+ * `search.reranker.top_n_in`) was written silently and then never read. Now
+ * it is a usage error (exit 2, agent contract) naming the nearest registered
+ * spelling, and nothing is written; --force still writes it (a key a newer
+ * gbrain reads), with a warning. Registered keys and keys under the open
+ * prefixes (`cycle.`, `models.`, ...) behave as before.
+ */
+import { describe, expect, spyOn, test } from 'bun:test';
+import { KNOWN_CONFIG_KEYS, loadConfigWithEngine } from '../src/core/config.ts';
+import { runConfig } from '../src/commands/config.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+function stubEngine(): { engine: BrainEngine; setCalls: Array<[string, string]>; unsetCalls: string[] } {
+ const setCalls: Array<[string, string]> = [];
+ const unsetCalls: string[] = [];
+ const engine = {
+ getConfig: async () => null,
+ setConfig: async (key: string, value: string) => { setCalls.push([key, value]); },
+ unsetConfig: async (key: string) => { unsetCalls.push(key); return 1; },
+ } as unknown as BrainEngine;
+ return { engine, setCalls, unsetCalls };
+}
+
+async function runConfigCapture(engine: BrainEngine, args: string[]): Promise<{ errs: string; exit: number | null }> {
+ const errs: string[] = [];
+ let exit: number | null = null;
+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const writeSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { errs.push(String(chunk)); return true; }) as never);
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ exit = code ?? 0;
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ try {
+ await runConfig(engine, args);
+ } catch (e) {
+ if (!(e as Error).message.startsWith('EXIT:')) throw e;
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ writeSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ return { errs: errs.join('\n'), exit };
+}
+
+describe('config set: unregistered key under an enumerated prefix', () => {
+ const cases: Array<[string, string]> = [
+ ['search.token_budget', 'search.tokenBudget'],
+ ['search.reranker.topN', 'search.reranker.top_n_in'],
+ ['search.keyword_or_fallback', 'search.keywordOrFallback'],
+ ['content_sanity.bytes_warnn', 'content_sanity.bytes_warn'],
+ ];
+ for (const [key, registered] of cases) {
+ test(`${key}: refused (exit 2), nothing written, naming ${registered}`, async () => {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', key, '100']);
+ expect(exit).toBe(2);
+ expect(setCalls).toEqual([]);
+ expect(errs).toContain(`Error [invalid_params]: Unknown config key "${key}". Did you mean "${registered}"? Nothing was written.`);
+ expect(errs).toContain(`Fix: gbrain config set ${registered} '<VALUE>'`);
+ expect(errs).toContain(`Why: Every ${key.split('.')[0]}.* key gbrain reads is registered, so nothing would read this one.`);
+ expect(errs).not.toContain('100');
+ });
+ }
+
+ test('a key with no near registered spelling is refused without a suggestion', async () => {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'search.zzzzzzzzzzzz', '1']);
+ expect(exit).toBe(2);
+ expect(setCalls).toEqual([]);
+ expect(errs).toContain('Error [invalid_params]: Unknown config key "search.zzzzzzzzzzzz". Nothing was written.');
+ expect(errs).toContain(`Fix: gbrain config set '<KEY>' '<VALUE>'`);
+ expect(errs).not.toContain('Did you mean');
+ });
+
+ test('a control character in the key is rendered inert', async () => {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'search.zz\nError [fake]: injected', '1']);
+ expect(exit).toBe(2);
+ expect(setCalls).toEqual([]);
+ expect(errs).not.toContain('\nError [fake]');
+ });
+
+ test('--force writes it, with a warning naming the registered spelling', async () => {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'search.token_budget', '100', '--force']);
+ expect(exit).toBeNull();
+ expect(setCalls).toEqual([['search.token_budget', '100']]);
+ expect(errs).toContain('WARN: writing unregistered search.* key "search.token_budget" with --force.');
+ expect(errs).toContain('Did you mean "search.tokenBudget"?');
+ });
+
+ test('a registered key under an enumerated prefix is written with no message', async () => {
+ for (const key of ['search.tokenBudget', 'search.reranker.top_n_in', 'content_sanity.bytes_warn']) {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', key, '100']);
+ expect(exit).toBeNull();
+ expect(setCalls).toEqual([[key, '100']]);
+ expect(errs).not.toContain('Unknown config key');
+ expect(errs).not.toContain('unregistered');
+ }
+ });
+
+ test('a key under an open prefix is unchanged: written, no message', async () => {
+ const { engine, setCalls } = stubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'cycle.some_phase.enabled', 'true']);
+ expect(exit).toBeNull();
+ expect(setCalls).toEqual([['cycle.some_phase.enabled', 'true']]);
+ expect(errs).not.toContain('Unknown config key');
+ });
+
+ test('a key written before this change can still be unset', async () => {
+ const { engine, unsetCalls } = stubEngine();
+ const { exit } = await runConfigCapture(engine, ['unset', 'search.token_budget']);
+ expect(exit).toBeNull();
+ expect(unsetCalls).toEqual(['search.token_budget']);
+ });
+});
+
+// The refusal is only safe while every key read under these prefixes is
+// registered. search.* is pinned key by key in config-search-registry.test.ts;
+// this pins the DB-plane merge, the one reader of content_sanity.*.
+test('every key loadConfigWithEngine reads under search.* or content_sanity.* is registered', async () => {
+ const read = new Set<string>();
+ const engine = { getConfig: async (key: string) => { read.add(key); return null; } };
+ await loadConfigWithEngine(engine as never, { engine: 'pglite' } as never);
+ const underPrefix = [...read].filter((k) => k.startsWith('search.') || k.startsWith('content_sanity.'));
+ expect(underPrefix.some((k) => k.startsWith('content_sanity.'))).toBe(true);
+ expect(underPrefix.filter((k) => !KNOWN_CONFIG_KEYS.includes(k))).toEqual([]);
+});