Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(config): register runtime reader keys and guard every getConfig read (#6780)

garrytanc58cb64337fb
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index af9aee6aea..b03707c8dd 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -23,6 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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-snapshot.ts` — one-round-trip config reads. `loadConfigSnapshot`/`snapshotConfigReader` read the whole config table once (`getAllConfig`) for a resolution pass and fall back to per-key reads when the engine lacks the bulk read or it fails. `withRequestConfigSnapshot(engine, fn)` holds one snapshot of that engine object for the life of `fn` (AsyncLocalStorage; an enclosing snapshot of the same engine is reused); MCP dispatch of a read op and `POST /mcp` (`serve-http-mcp.ts`) open it. Both engines' `getConfig`/`getAllConfig` answer from it (`requestConfigValue`/`requestConfigRows`) and `setConfig`/`unsetConfig` keep it current (`noteRequestConfigWrite`). `withoutRequestConfigSnapshot` runs a write op with live reads and drops the snapshot when it settles, so a later read in the request retakes it. Reads after `fn` settles, on another engine object (a transaction's) or after a failed bulk read go to the database per key. Pinned by `test/config-request-snapshot.test.ts`.
+- `src/core/config-runtime-keys.ts` — `RUNTIME_READER_CONFIG_KEYS`, the runtime knobs read with `engine.getConfig()` (doctor budgets, `embed.max_usd_per_page`, image-OCR caps, `skillopt.allowed_skills`, ...), spread into `KNOWN_CONFIG_KEYS` so `gbrain config set` accepts them. `test/config-reader-keys-registered.test.ts` scans every `getConfig()` under `src/` and fails on a key that is neither registered nor recorded as internal state (`test/helpers/config-reader-registry.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/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
new file mode 100644
index 0000000000..19f3ff3dde
--- /dev/null
+++ b/src/core/config-runtime-keys.ts
@@ -0,0 +1,20 @@
+/**
+ * Runtime knobs read directly with `engine.getConfig()` (#6780), registered
+ * so `gbrain config set` accepts them without --force. Spread into
+ * KNOWN_CONFIG_KEYS (config.ts); test/config-reader-keys-registered.test.ts
+ * fails when a src/ reader names a key that is neither registered nor
+ * recorded as internal state.
+ */
+export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
+ 'doctor.entry_budget_ms', // doctor/budget.ts ENTRY_BUDGET_KEY: per-check budget, default 15000 ms
+ 'doctor.orphan_ratio.full_scan_max_pages', // doctor/checks/orphan-estimate.ts: exact orphan scan up to N pages, default 50000
+ 'embed.max_usd_per_page', // page-embedding-budget.ts: large-page embedding cap, default $2 (unlimited under spend.posture tokenmax)
+ 'facts.absorb_warn_threshold', // doctor facts_extraction_health absorb-refusal warn threshold, default 10 per 24 h
+ 'think.trajectory_enabled', // think/index.ts: trajectory substrate on temporal intents, default on
+ 'embedding_image_ocr_max_images', 'embedding_image_ocr_max_usd', // import-file.ts image-OCR per-run caps, default 200 images / $1
+ 'agent.search_snippet_chars', // ops/search.ts subagent snippet cap, default 300 (0 = full text)
+ 'skillopt.allowed_skills', // JSON array of skills remote callers may optimize (ops/skillopt.ts, shared-skills/optimizer.ts); default deny-all
+ 'skillopt.capture_enabled', // skillopt/held-out.ts production rollout capture, default off
+ 'entity_identity.union', // entity-identity.ts: links/backlinks union across identity co-members, default off
+ 'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off
+];
diff --git a/src/core/config.ts b/src/core/config.ts
index 50bfceb191..2d1483bcdb 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -7,6 +7,7 @@ import { loadConfigSnapshot } from './config-snapshot.ts';
import { loadGbrainEnvFile } from './gbrain-env-file.ts';
import { dotenvValuesForKey } from './env-trust.ts';
import { REMOTE_PRIVATE_PAGES_KEY } from './search/private-visibility.ts';
+import { RUNTIME_READER_CONFIG_KEYS } from './config-runtime-keys.ts';
/**
* Where is the active DB URL coming from? Pure introspection, no connection
@@ -1788,6 +1789,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'planner.auto_analyze', 'planner.first_read_budget_ms', 'import.analyze_every_pages', 'health.cache_ttl_ms',
// Wave B segmented page storage (src/core/page-body/limits.ts PAGE_BODY_CONFIG_KEYS; switch defaults off).
'pages.segmented_storage', 'pages.max_bytes', 'pages.flip_retire_max_rows', 'versions.segmented_max_per_page', 'versions.segmented_max_pinned_bytes',
+ ...RUNTIME_READER_CONFIG_KEYS, // #6780: getConfig() runtime knobs (config-runtime-keys.ts)
];
/**
diff --git a/test/config-reader-keys-registered.test.ts b/test/config-reader-keys-registered.test.ts
new file mode 100644
index 0000000000..f1ae6c36aa
--- /dev/null
+++ b/test/config-reader-keys-registered.test.ts
@@ -0,0 +1,129 @@
+/**
+ * #6780: runtime readers name config keys `gbrain config set` refuses.
+ *
+ * Protects: every key gbrain reads with getConfig() is either a registered
+ * knob (KNOWN_CONFIG_KEYS / KNOWN_CONFIG_KEY_PREFIXES, so `config set`
+ * accepts it without --force) or recorded as internal state with a reason.
+ * Regression it catches: a new reader of a new key, or a key constant moved
+ * without its registration (doctor.entry_budget_ms, the orphan full-scan cap
+ * and the per-page embedding spend cap all shipped unregistered).
+ * Existing coverage: per-feature tests pin their own keys; nothing scans
+ * readers, so an unregistered reader was invisible until a user hit it.
+ * Seam: none (a source scan plus the exported key constants).
+ */
+import { describe, expect, test } from 'bun:test';
+import { join } from 'path';
+import { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES } from '../src/core/config.ts';
+import { ENTRY_BUDGET_KEY } from '../src/commands/doctor/budget.ts';
+import { ORPHAN_FULL_SCAN_KEY } from '../src/commands/doctor/checks/orphan-estimate.ts';
+import { PAGE_EMBED_CAP_KEY } from '../src/core/page-embedding-budget.ts';
+import { ENTITY_IDENTITY_UNION_CONFIG_KEY } from '../src/core/entity-identity.ts';
+import { scanConfigReads, type ConfigRead } from './helpers/config-reader-scan.ts';
+import {
+ ENUMERATED_TEMPLATE_PREFIXES,
+ INTERNAL_CONFIG_STATE,
+ UNRESOLVED_CONFIG_READS,
+} from './helpers/config-reader-registry.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const REMEDY = 'Register a user-facing knob in src/core/config-runtime-keys.ts (or its home list in src/core/config.ts KNOWN_CONFIG_KEYS / KNOWN_CONFIG_KEY_PREFIXES); '
+ + 'record state gbrain writes itself in INTERNAL_CONFIG_STATE in test/helpers/config-reader-registry.ts with a reason.';
+
+const isRegistered = (key: string) => KNOWN_CONFIG_KEYS.includes(key) || KNOWN_CONFIG_KEY_PREFIXES.some((p) => key.startsWith(p));
+const internalKey = (key: string) => INTERNAL_CONFIG_STATE.find((s) => (s.prefix ? key.startsWith(s.key) : key === s.key));
+const where = (r: ConfigRead) => `${r.file}:${r.line} getConfig(${r.expr})`;
+
+describe('#6780 runtime config keys are registered', () => {
+ test.each([
+ ['doctor.entry_budget_ms', ENTRY_BUDGET_KEY],
+ ['doctor.orphan_ratio.full_scan_max_pages', ORPHAN_FULL_SCAN_KEY],
+ ['embed.max_usd_per_page', PAGE_EMBED_CAP_KEY],
+ ['entity_identity.union', ENTITY_IDENTITY_UNION_CONFIG_KEY],
+ ])('%s (the reader constant) is in KNOWN_CONFIG_KEYS', (name, constant) => {
+ expect(constant).toBe(name);
+ expect(KNOWN_CONFIG_KEYS).toContain(constant);
+ });
+
+ test.each([
+ 'facts.absorb_warn_threshold',
+ 'think.trajectory_enabled',
+ 'embedding_image_ocr_max_images',
+ 'embedding_image_ocr_max_usd',
+ 'agent.search_snippet_chars',
+ 'skillopt.allowed_skills',
+ 'skillopt.capture_enabled',
+ 'writer.lint_on_put_page',
+ ])('%s is in KNOWN_CONFIG_KEYS', (key) => {
+ expect(KNOWN_CONFIG_KEYS).toContain(key);
+ });
+});
+
+describe('#6780 guard: every getConfig() key under src/ is registered or recorded', () => {
+ const reads = scanConfigReads(ROOT);
+ const literal = reads.filter((r) => r.target.kind === 'keys');
+ const templates = reads.filter((r) => r.target.kind === 'template');
+ const unresolved = reads.filter((r) => r.target.kind === 'unresolved');
+ console.log(`[config-reader guard] ${reads.length} getConfig reads: ${literal.length} resolved keys, ${templates.length} templates, ${unresolved.length} unresolved`);
+
+ test('the scan sees the reader population (not a vacuous pass)', () => {
+ expect(reads.length).toBeGreaterThan(400);
+ expect(literal.some((r) => r.file === 'src/commands/doctor/registry.ts' && r.target.kind === 'keys' && r.target.keys.includes('doctor.entry_budget_ms'))).toBe(true);
+ });
+
+ test('resolved keys are registered or internal state', () => {
+ const bad: string[] = [];
+ for (const r of literal) {
+ if (r.target.kind !== 'keys') continue;
+ for (const key of r.target.keys) {
+ if (!isRegistered(key) && !internalKey(key)) bad.push(`${where(r)} reads "${key}", which gbrain config set refuses.`);
+ }
+ }
+ expect(bad, `${bad.length} unregistered config reads:\n${bad.join('\n')}\n${REMEDY}`).toEqual([]);
+ });
+
+ test('template keys match a registered prefix, an enumerated prefix or an internal prefix', () => {
+ const bad = templates.filter((r) => {
+ if (r.target.kind !== 'template') return false;
+ const prefix = r.target.prefix;
+ return !KNOWN_CONFIG_KEY_PREFIXES.some((p) => prefix.startsWith(p))
+ && !ENUMERATED_TEMPLATE_PREFIXES.some((e) => e.prefix === prefix)
+ && !INTERNAL_CONFIG_STATE.some((s) => s.prefix && prefix.startsWith(s.key));
+ }).map((r) => `${where(r)} builds keys under "${(r.target as { prefix: string }).prefix}".`);
+ expect(bad, `${bad.join('\n')}\n${REMEDY}`).toEqual([]);
+ });
+
+ test('enumerated template prefixes still have registered leaves', () => {
+ for (const e of ENUMERATED_TEMPLATE_PREFIXES) {
+ expect(KNOWN_CONFIG_KEYS.some((k) => k.startsWith(e.prefix)), `no registered key under ${e.prefix}`).toBe(true);
+ }
+ });
+
+ test('unresolved keys are allowlisted, and parameter entries are still parameters', () => {
+ const remaining = [...UNRESOLVED_CONFIG_READS];
+ const bad: string[] = [];
+ for (const r of unresolved) {
+ if (r.target.kind !== 'unresolved') continue;
+ const via = r.target.via;
+ const i = remaining.findIndex((u) => u.file === r.file && u.expr === r.expr && (u.why === 'parameter') === (via === 'parameter'));
+ if (i === -1) {
+ bad.push(`${where(r)}: the key is not statically resolvable (${via}). Pass a string literal or a const (same file or a named import), `
+ + 'or add { file, expr, why } to UNRESOLVED_CONFIG_READS in test/helpers/config-reader-registry.ts.');
+ continue;
+ }
+ remaining.splice(i, 1);
+ }
+ expect(bad, bad.join('\n')).toEqual([]);
+ expect(remaining.map((u) => `stale UNRESOLVED_CONFIG_READS entry (no matching read): ${u.file} getConfig(${u.expr}); remove it`)).toEqual([]);
+ });
+
+ test('every internal-state entry is still read and is not also registered', () => {
+ const stale: string[] = [];
+ for (const s of INTERNAL_CONFIG_STATE) {
+ const read = reads.some((r) => (r.target.kind === 'keys' && r.target.keys.some((k) => (s.prefix ? k.startsWith(s.key) : k === s.key)))
+ || (r.target.kind === 'template' && s.prefix && r.target.prefix.startsWith(s.key)));
+ if (!read) stale.push(`${s.key}: no getConfig reader left; remove it from INTERNAL_CONFIG_STATE`);
+ if (!s.prefix && isRegistered(s.key)) stale.push(`${s.key}: registered as a knob and listed as internal state; keep one`);
+ }
+ expect(stale).toEqual([]);
+ });
+});
diff --git a/test/config-set-runtime-keys.test.ts b/test/config-set-runtime-keys.test.ts
new file mode 100644
index 0000000000..3606182023
--- /dev/null
+++ b/test/config-set-runtime-keys.test.ts
@@ -0,0 +1,60 @@
+/**
+ * #6780: `gbrain config set` accepts each runtime knob registered in
+ * src/core/config-runtime-keys.ts without --force.
+ *
+ * Protects the user-visible contract the registry exists for: before the
+ * fix, every key below exited 1 with `Unknown config key` (the doctor's own
+ * facts_extraction_health message told operators to run one of them).
+ * Spawns the real CLI against a throwaway PGLite brain; asserts the exit
+ * code, the confirmation line and the value `config get` reads back.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const CASES: Array<[string, string]> = [
+ ['doctor.entry_budget_ms', '20000'],
+ ['doctor.orphan_ratio.full_scan_max_pages', '100000'],
+ ['embed.max_usd_per_page', '5'],
+ ['facts.absorb_warn_threshold', '25'],
+ ['think.trajectory_enabled', 'false'],
+ ['embedding_image_ocr_max_images', '50'],
+ ['embedding_image_ocr_max_usd', '0.5'],
+ ['agent.search_snippet_chars', '500'],
+ ['skillopt.allowed_skills', '["brain-ops"]'],
+ ['skillopt.capture_enabled', 'true'],
+ ['entity_identity.union', 'true'],
+ ['writer.lint_on_put_page', 'true'],
+];
+
+let home: string;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-config-runtime-keys-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const dbPath = join(home, '.gbrain', 'brain.pglite');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath, embedding_dimensions: 1536 }) + '\n');
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: dbPath });
+ await engine.initSchema();
+ await engine.disconnect();
+}, 240_000);
+
+afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('#6780 config set accepts the runtime reader keys', () => {
+ test.each(CASES)('config set %s %s succeeds and reads back', async (key, value) => {
+ const env = { GBRAIN_BRAIN_ID: '', GBRAIN_SOURCE: '' };
+ const set = await runCli(['config', 'set', key, value], { home, env, timeoutMs: 120_000 });
+ expect(set.stderr).not.toContain('Unknown config key');
+ expect(set.exitCode).toBe(0);
+ const get = await runCli(['config', 'get', key], { home, env, timeoutMs: 120_000 });
+ expect(get.exitCode).toBe(0);
+ expect(get.stdout.trim()).toBe(value);
+ }, 240_000);
+});
diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.ts
new file mode 100644
index 0000000000..62daee8c3e
--- /dev/null
+++ b/test/helpers/config-reader-registry.ts
@@ -0,0 +1,146 @@
+/**
+ * Typed registry for test/config-reader-keys-registered.test.ts (#6780).
+ *
+ * The guard requires every `getConfig(<key>)` under src/ to name a key
+ * `gbrain config set` accepts (KNOWN_CONFIG_KEYS or KNOWN_CONFIG_KEY_PREFIXES).
+ * This file holds the two exceptions, each with a reason a reviewer can check:
+ *
+ * - INTERNAL_CONFIG_STATE: keys and key prefixes gbrain writes itself
+ * (markers, cursors, caches, receipts, counters). Operators do not set them
+ * with `config set`; registering them would advertise a knob that is not one.
+ * - UNRESOLVED_CONFIG_READS: call sites whose key is not statically resolvable.
+ * `why: 'parameter'` is verified by the guard (the argument still resolves to
+ * a function parameter); any other reason names where the keys come from.
+ *
+ * A user-facing knob never belongs here: register it in
+ * src/core/config-runtime-keys.ts (or its home list in src/core/config.ts).
+ */
+
+export interface InternalConfigState {
+ /** An exact key, or a key prefix when `prefix` is true. */
+ key: string;
+ prefix?: true;
+ reason: string;
+}
+
+export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [
+ { key: 'version', reason: 'schema version stamp written by migrate.ts' },
+ { key: '_internal.link_extraction_generation', reason: 'link-extraction watermark generation (link-extraction-watermark.ts)' },
+ { key: 'code.cluster_generation', reason: 'code-intel traversal cache generation counter' },
+ { key: 'embedding_migration.state', reason: 'gbrain migrate-embeddings resume state' },
+ { key: 'embedding_migration.completed', reason: 'gbrain migrate-embeddings completion marker' },
+ { key: 'facts.drain_state', reason: 'facts drain scheduler state (facts/drain.ts)' },
+ { key: 'google.file_modes_notice', reason: 'one-time upgrade notice marker (v0.60.31 migration)' },
+ { key: 'notices.behavior_changes.http', reason: 'behavior-change notice shown-marker for serve --http' },
+ { key: 'ocr_attempted', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
+ { key: 'ocr_succeeded', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
+ { key: 'ocr_failed_no_key', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
+ { key: 'ocr_failed_other', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
+ { key: 'ocr_skipped_budget', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
+ { key: 'page_state.revision_backfill', reason: 'page-state revision backfill progress marker' },
+ { key: 'persistence.database_only_sources', reason: 'list maintained by gbrain sources writer activate/deactivate; config unset (which takes any key) is the documented escape hatch' },
+ { key: 'persistence.maintenance.last_compaction', reason: 'receipt compaction pass cursor (compaction-pass.ts)' },
+ { key: 'persistence.true_up.compacted_through', reason: 'receipt true-up cursor (receipt-true-up.ts)' },
+ { key: 'sync.slug_root_mode', reason: 'legacy unsourced slug-root mode stamped by sync (sync-anchor.ts); sourced brains keep it on the sources row' },
+ { key: 'transcripts.secret_audit', reason: 'cached transcript secret-audit result (transcripts/secret-audit.ts)' },
+ { key: 'trust.backfill_completed_at', reason: 'memory-trust backfill completion marker' },
+ { key: 'trust.kill_switch', reason: 'receipt written by gbrain trust disable/enable --all' },
+ { key: 'schema_pack.source.', prefix: true, reason: 'per-source schema pack binding written by gbrain schema commands' },
+ { key: 'brainstorm.domain_bank.prefixes:', prefix: true, reason: 'brainstorm domain-bank prefix cache' },
+ { key: 'backfill.', prefix: true, reason: 'resumable backfill checkpoints (backfill-base.ts checkpointKey)' },
+ { key: 'shared_skills.export.v1.', prefix: true, reason: 'shared-skills migration export receipts' },
+ { key: 'shared_skills.content.v1.', prefix: true, reason: 'shared-skills content setup state per source incarnation' },
+ { key: 'shared_skills.migration.v1.', prefix: true, reason: 'shared-skills migration checkpoints per source incarnation' },
+ { key: 'shared_skills.bridge_owner.v1.', prefix: true, reason: 'shared-brain bridge ownership claims' },
+];
+
+/**
+ * A template-built key whose leaves are each registered in KNOWN_CONFIG_KEYS
+ * (the guard checks that at least one registered key carries the prefix).
+ */
+export const ENUMERATED_TEMPLATE_PREFIXES: readonly { prefix: string; reason: string }[] = [
+ { prefix: 'shared_skills.inventory.', reason: 'inventoryLimitKey(name): the four shared_skills.inventory.* leaves are registered' },
+];
+
+export interface UnresolvedConfigRead {
+ file: string;
+ /** The getConfig argument's source text, whitespace-collapsed. */
+ expr: string;
+ why: 'parameter' | string;
+}
+
+const P = 'parameter' as const;
+
+export const UNRESOLVED_CONFIG_READS: readonly UnresolvedConfigRead[] = [
+ { file: 'src/commands/autopilot/install-consent.ts', expr: 'k', why: P },
+ { file: 'src/commands/config.ts', expr: 'key', why: 'gbrain config get <key>: the operator names the key' },
+ { file: 'src/commands/decide/probe-query.ts', expr: 'key', why: P },
+ { file: 'src/commands/doctor/checks/keyword-plan.ts', expr: 'key', why: P },
+ { file: 'src/commands/doctor/checks/sync-config-keys.ts', expr: 'key', why: P },
+ { file: 'src/commands/doctor/checks/timeline-history.ts', expr: 'key', why: P },
+ { file: 'src/commands/doctor/probe-consent.ts', expr: 'key', why: P },
+ { file: 'src/commands/doctor/skill-checks.ts', expr: 'key', why: P },
+ { file: 'src/commands/init-mode-picker.ts', expr: 'k', why: P },
+ { file: 'src/commands/models.ts', expr: 'overrideKey', why: 'per-task model override key from the model-tier table (models.* prefix)' },
+ { file: 'src/commands/skillpack/harness.ts', expr: 'key', why: P },
+ { file: 'src/core/advisor/collect-setup-smells.ts', expr: 'key', why: P },
+ { file: 'src/core/config-db-merge.ts', expr: 'key', why: 'listConfigKeys walk filtered to the cycle. and provider_chat_options. prefixes' },
+ { file: 'src/core/config.ts', expr: 'key', why: P },
+ { file: 'src/core/connectors/sync.ts', expr: 'key', why: P },
+ { file: 'src/core/connectors/sync.ts', expr: 'key', why: P },
+ { file: 'src/core/consent-cli.ts', expr: 'key', why: P },
+ { file: 'src/core/content-repair/llm.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/auto-think.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/extract-atoms-cost-gate.ts', expr: 'key', why: 'listConfigKeys walk over ATOMS_NO_PRICING_KEY_PREFIX (cycle. prefix)' },
+ { file: 'src/core/cycle/nightly-probe-routes.ts', expr: 'key', why: 'Object.entries walk over NIGHTLY_PROBE_SLOT_KEYS' },
+ { file: 'src/core/cycle/nightly-probe-search-config.ts', expr: 'key', why: 'walk over NIGHTLY_PROBE_SEARCH_CONFIG_KEYS (search. prefix)' },
+ { file: 'src/core/cycle/patterns-plan.ts', expr: 'cadenceKey', why: P },
+ { file: 'src/core/cycle/patterns.ts', expr: 'keys.evidence', why: 'patterns cooldown stamp key from its keys bag (dream. prefix)' },
+ { file: 'src/core/cycle/patterns.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/patterns.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/phase-config-values.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/propose-takes.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/synthesize.ts', expr: 'key', why: P },
+ { file: 'src/core/cycle/synthesize.ts', expr: 'key', why: P },
+ { file: 'src/core/eligibility/policy.ts', expr: 'key', why: P },
+ { file: 'src/core/embed-backfill-submit.ts', expr: 'key', why: P },
+ { file: 'src/core/embed-consent.ts', expr: 'key', why: P },
+ { file: 'src/core/facts/extract.ts', expr: 'key', why: P },
+ { file: 'src/core/feedback/settings.ts', expr: 'key', why: P },
+ { file: 'src/core/fence-repair/config.ts', expr: 'key', why: P },
+ { file: 'src/core/fence-repair/config.ts', expr: 'key', why: P },
+ { file: 'src/core/import-file.ts', expr: 'key', why: P },
+ { file: 'src/core/import-screen.ts', expr: 'key', why: P },
+ { file: 'src/core/line-grammar.ts', expr: 'key', why: P },
+ { file: 'src/core/line-grammar.ts', expr: 'key', why: P },
+ { file: 'src/core/line-grammar.ts', expr: 'key', why: P },
+ { file: 'src/core/mentions/policy.ts', expr: 'k', why: P },
+ { file: 'src/core/migration-ledger.ts', expr: 'key', why: 'Object.entries walk over MIGRATION_OPT_OUT_KEYS' },
+ { file: 'src/core/minions/admission.ts', expr: 'key', why: 'listConfigKeys walk under the minions. prefix' },
+ { file: 'src/core/model-config.ts', expr: 'opts.configKey', why: 'model-tier resolver option; callers pass models.* keys' },
+ { file: 'src/core/model-config.ts', expr: 'opts.deprecatedConfigKey', why: 'model-tier resolver option; callers pass legacy model keys' },
+ { file: 'src/core/model-config.ts', expr: 'opts.deprecatedConfigKey', why: 'model-tier resolver option; callers pass legacy model keys' },
+ { file: 'src/core/pace-mode.ts', expr: 'k', why: P },
+ { file: 'src/core/page-body/limits.ts', expr: 'key', why: P },
+ { file: 'src/core/persistence/group-publish.ts', expr: 'name', why: P },
+ { file: 'src/core/persistence/page-mutations.ts', expr: 'name', why: P },
+ { file: 'src/core/persistence/sync-drain.ts', expr: 'key', why: P },
+ { file: 'src/core/persistence/sync-group.ts', expr: 'key', why: P },
+ { file: 'src/core/persistence/worktree-refresh.ts', expr: 'key', why: P },
+ { file: 'src/core/pglite-engine.ts', expr: 'key', why: P },
+ { file: 'src/core/planner-stats.ts', expr: 'key', why: P },
+ { file: 'src/core/postgres-engine.ts', expr: 'key', why: P },
+ { file: 'src/core/questions/auto-think-migration.ts', expr: 'key', why: P },
+ { file: 'src/core/questions/auto-think-migration.ts', expr: 'key', why: P },
+ { file: 'src/core/questions/phase.ts', expr: 'key', why: P },
+ { file: 'src/core/reindex-consent.ts', expr: 'key', why: P },
+ { file: 'src/core/search/evidence-delivery.ts', expr: 'key', why: P },
+ { file: 'src/core/search/evidence-delivery.ts', expr: 'input.configKey ?? RETURN_UNIT_CONFIG_KEY', why: 'per-op return-unit key option (search. prefix), else the registered default' },
+ { file: 'src/core/search/mode.ts', expr: 'k', why: P },
+ { file: 'src/core/search/page-rank-cut.ts', expr: 'key', why: P },
+ { file: 'src/core/skillopt/cycle-phase.ts', expr: 'key', why: P },
+ { file: 'src/core/skillpack/preconditions.ts', expr: 'key', why: 'skillpack precondition config:<key>: the skill names the key' },
+ { file: 'src/core/sync-config-keys.ts', expr: 'key', why: P },
+ { file: 'src/core/think/pages-budget.ts', expr: 'key', why: P },
+ { file: 'src/mcp/publish-gates.ts', expr: 'key', why: P },
+];
diff --git a/test/helpers/config-reader-scan.ts b/test/helpers/config-reader-scan.ts
new file mode 100644
index 0000000000..278b426f17
--- /dev/null
+++ b/test/helpers/config-reader-scan.ts
@@ -0,0 +1,292 @@
+/**
+ * Source scan behind test/config-reader-keys-registered.test.ts (#6780).
+ *
+ * Finds every `getConfig(<arg>)` call under a root and resolves its argument
+ * syntactically: a string literal, a template literal (to its static prefix),
+ * a const in scope (same file, named import, or a destructured dynamic
+ * import), a const object's property, both arms of `?:`/`??`/`||`, or a
+ * key-builder function whose returns resolve. Anything else (a parameter, a
+ * `let`, a computed call) is reported unresolved with its source text.
+ */
+import ts from 'typescript';
+import { readdirSync, readFileSync, statSync } from 'fs';
+import { dirname, join, relative, resolve } from 'path';
+
+export type ConfigReadTarget =
+ | { kind: 'keys'; keys: string[] }
+ | { kind: 'template'; prefix: string }
+ | { kind: 'unresolved'; via: 'parameter' | 'other' };
+
+export interface ConfigRead { file: string; line: number; expr: string; target: ConfigReadTarget }
+
+const MAX_DEPTH = 8;
+
+function walk(dir: string, out: string[]): string[] {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path, out);
+ else if (path.endsWith('.ts') && !path.endsWith('.d.ts')) out.push(path);
+ }
+ return out;
+}
+
+export function scanConfigReads(root: string, subdir = 'src'): ConfigRead[] {
+ const sources = new Map<string, ts.SourceFile>();
+ const source = (path: string): ts.SourceFile => {
+ let sf = sources.get(path);
+ if (!sf) {
+ sf = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true);
+ sources.set(path, sf);
+ }
+ return sf;
+ };
+ const moduleFile = (from: string, spec: string): string | null => {
+ if (!spec.startsWith('.')) return null;
+ const base = resolve(dirname(from), spec);
+ for (const candidate of [base, base.replace(/\.js$/, '.ts'), `${base}.ts`, join(base, 'index.ts')]) {
+ try { if (statSync(candidate).isFile()) return candidate; } catch { /* next candidate */ }
+ }
+ return null;
+ };
+
+ type Decl = ts.Expression | ts.FunctionLikeDeclaration | ts.ParameterDeclaration | ts.ForOfStatement | null;
+
+ const exported = (file: string, name: string, depth: number): Decl => {
+ if (depth > MAX_DEPTH) return null;
+ for (const stmt of source(file).statements) {
+ const found = declaredIn(stmt, name, file, depth);
+ if (found !== undefined) return found;
+ if (ts.isExportDeclaration(stmt) && stmt.moduleSpecifier && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
+ for (const el of stmt.exportClause.elements) {
+ if (el.name.text !== name) continue;
+ const target = moduleFile(file, (stmt.moduleSpecifier as ts.StringLiteral).text);
+ return target ? exported(target, (el.propertyName ?? el.name).text, depth + 1) : null;
+ }
+ }
+ }
+ return null;
+ };
+
+ const importedDecl = (file: string, spec: string, name: string, depth: number): Decl => {
+ const target = moduleFile(file, spec);
+ return target ? exported(target, name, depth + 1) : null;
+ };
+
+ const dynamicImportSpec = (init: ts.Expression | undefined): string | null => {
+ let e = init;
+ while (e && (ts.isAwaitExpression(e) || ts.isParenthesizedExpression(e))) e = e.expression;
+ if (e && ts.isCallExpression(e) && e.expression.kind === ts.SyntaxKind.ImportKeyword && e.arguments[0] && ts.isStringLiteralLike(e.arguments[0])) {
+ return e.arguments[0].text;
+ }
+ return null;
+ };
+
+ /** undefined = not declared by this statement; null = declared but not a const value. */
+ const declaredIn = (stmt: ts.Node, name: string, file: string, depth: number): Decl | undefined => {
+ if (ts.isVariableStatement(stmt)) {
+ const isConst = (stmt.declarationList.flags & ts.NodeFlags.Const) !== 0;
+ for (const d of stmt.declarationList.declarations) {
+ if (ts.isIdentifier(d.name) && d.name.text === name) {
+ if (!isConst || !d.initializer) return null;
+ return d.initializer;
+ }
+ if (ts.isObjectBindingPattern(d.name)) {
+ for (const el of d.name.elements) {
+ if (!ts.isIdentifier(el.name) || el.name.text !== name) continue;
+ const spec = isConst ? dynamicImportSpec(d.initializer) : null;
+ const prop = el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : name;
+ return spec ? importedDecl(file, spec, prop, depth) : null;
+ }
+ }
+ }
+ return undefined;
+ }
+ if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === name) return stmt;
+ if (ts.isImportDeclaration(stmt) && stmt.importClause?.namedBindings && ts.isNamedImports(stmt.importClause.namedBindings)) {
+ for (const el of stmt.importClause.namedBindings.elements) {
+ if (el.name.text === name) return importedDecl(file, (stmt.moduleSpecifier as ts.StringLiteral).text, (el.propertyName ?? el.name).text, depth);
+ }
+ }
+ return undefined;
+ };
+
+ const bindsName = (b: ts.BindingName, name: string): boolean => ts.isIdentifier(b)
+ ? b.text === name
+ : b.elements.some((el) => !ts.isOmittedExpression(el) && bindsName(el.name, name));
+
+ /** Lexical lookup from a use site outward to the file's top level. */
+ const lookup = (id: ts.Identifier, file: string, depth: number): Decl => {
+ for (let node: ts.Node | undefined = id.parent; node; node = node.parent) {
+ if (ts.isFunctionLike(node)) {
+ const param = node.parameters.find((p) => bindsName(p.name, id.text));
+ if (param) return param;
+ }
+ if ((ts.isForOfStatement(node) || ts.isForInStatement(node) || ts.isForStatement(node)) && node.initializer && ts.isVariableDeclarationList(node.initializer)
+ && node.initializer.declarations.some((d) => bindsName(d.name, id.text))) {
+ return ts.isForOfStatement(node) && ts.isIdentifier(node.initializer.declarations[0].name) ? node : null;
+ }
+ if (ts.isCatchClause(node) && node.variableDeclaration && bindsName(node.variableDeclaration.name, id.text)) return null;
+ if (ts.isBlock(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isCaseClause(node) || ts.isDefaultClause(node)) {
+ for (const stmt of node.statements) {
+ const found = declaredIn(stmt, id.text, file, depth);
+ if (found !== undefined) return found;
+ }
+ }
+ }
+ return null;
+ };
+
+ const strip = (e: ts.Expression): ts.Expression => {
+ while (ts.isAsExpression(e) || ts.isParenthesizedExpression(e) || ts.isSatisfiesExpression(e) || ts.isNonNullExpression(e) || ts.isTypeAssertionExpression(e)) e = e.expression;
+ return e;
+ };
+
+ const fileOf = (n: ts.Node): string => n.getSourceFile().fileName;
+
+ const OTHER: ConfigReadTarget = { kind: 'unresolved', via: 'other' };
+
+ /** A parameter typed as a union of string literals resolves to those literals. */
+ const literalUnion = (type: ts.TypeNode | undefined): string[] | null => {
+ if (!type) return null;
+ const members = ts.isUnionTypeNode(type) ? type.types : [type];
+ const out: string[] = [];
+ for (const m of members) {
+ if (!ts.isLiteralTypeNode(m) || !ts.isStringLiteral(m.literal)) return null;
+ out.push(m.literal.text);
+ }
+ return out;
+ };
+
+ const resolveDecl = (decl: Decl, depth: number): ConfigReadTarget => {
+ if (!decl) return OTHER;
+ if (ts.isParameter(decl as ts.Node)) {
+ const keys = literalUnion((decl as ts.ParameterDeclaration).type);
+ return keys ? { kind: 'keys', keys } : { kind: 'unresolved', via: 'parameter' };
+ }
+ if (ts.isForOfStatement(decl as ts.Node)) return elementsOf((decl as ts.ForOfStatement).expression, depth + 1);
+ if (ts.isFunctionLike(decl as ts.Node)) return OTHER;
+ return resolveExpr(decl as ts.Expression, depth + 1);
+ };
+
+ /** `for (const k of X)`: X a const array literal, or Object.keys/values of a const object literal. */
+ const elementsOf = (raw: ts.Expression, depth: number): ConfigReadTarget => {
+ if (depth > MAX_DEPTH) return OTHER;
+ const e = strip(raw);
+ if (ts.isArrayLiteralExpression(e)) {
+ const parts = e.elements.map((el) => ts.isSpreadElement(el) ? elementsOf(el.expression, depth + 1) : resolveExpr(el, depth + 1));
+ return parts.length > 0 ? merge(parts) : OTHER;
+ }
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && ts.isIdentifier(e.expression.expression)
+ && e.expression.expression.text === 'Object' && e.arguments[0]) {
+ const obj = objectLiteral(e.arguments[0], depth + 1);
+ const assignments = obj?.properties.filter(ts.isPropertyAssignment) ?? [];
+ if (assignments.length === 0) return OTHER;
+ if (e.expression.name.text === 'keys') {
+ return { kind: 'keys', keys: assignments.map((p) => ts.isStringLiteral(p.name) || ts.isIdentifier(p.name) ? p.name.text : p.name.getText()) };
+ }
+ if (e.expression.name.text === 'values') return merge(assignments.map((p) => resolveExpr(p.initializer, depth + 1)));
+ return OTHER;
+ }
+ if (ts.isIdentifier(e)) {
+ const decl = lookup(e, fileOf(e), depth);
+ return decl && !ts.isParameter(decl as ts.Node) && !ts.isFunctionLike(decl as ts.Node) && !ts.isForOfStatement(decl as ts.Node)
+ ? elementsOf(decl as ts.Expression, depth + 1) : OTHER;
+ }
+ return OTHER;
+ };
+
+ const objectLiteral = (e: ts.Expression, depth: number): ts.ObjectLiteralExpression | null => {
+ const s = strip(e);
+ if (ts.isObjectLiteralExpression(s)) return s;
+ if (ts.isCallExpression(s) && ts.isPropertyAccessExpression(s.expression) && s.expression.name.text === 'freeze' && s.arguments[0]) return objectLiteral(s.arguments[0], depth);
+ if (ts.isIdentifier(s) && depth <= MAX_DEPTH) {
+ const decl = lookup(s, fileOf(s), depth);
+ if (decl && !ts.isFunctionLike(decl as ts.Node) && !ts.isParameter(decl as ts.Node) && !ts.isForOfStatement(decl as ts.Node)) return objectLiteral(decl as ts.Expression, depth + 1);
+ }
+ return null;
+ };
+
+ const merge = (targets: ConfigReadTarget[]): ConfigReadTarget => {
+ if (targets.some((t) => t.kind !== 'keys')) {
+ return targets.length === 1 ? targets[0] : (targets.find((t) => t.kind === 'unresolved') ?? targets.find((t) => t.kind === 'template')!);
+ }
+ return { kind: 'keys', keys: [...new Set(targets.flatMap((t) => (t as { keys: string[] }).keys))] };
+ };
+
+ const returnsOf = (fn: ts.FunctionLikeDeclaration): ts.Expression[] => {
+ if (!fn.body) return [];
+ if (!ts.isBlock(fn.body)) return [fn.body as ts.Expression];
+ const out: ts.Expression[] = [];
+ const visit = (n: ts.Node) => {
+ if (n !== fn.body && ts.isFunctionLike(n)) return;
+ if (ts.isReturnStatement(n) && n.expression) out.push(n.expression);
+ ts.forEachChild(n, visit);
+ };
+ visit(fn.body);
+ return out;
+ };
+
+ const resolveExpr = (raw: ts.Expression, depth: number): ConfigReadTarget => {
+ if (depth > MAX_DEPTH) return OTHER;
+ const e = strip(raw);
+ if (ts.isStringLiteralLike(e)) return { kind: 'keys', keys: [e.text] };
+ if (ts.isTemplateExpression(e)) {
+ let keys = [e.head.text];
+ for (const span of e.templateSpans) {
+ const part = resolveExpr(span.expression, depth + 1);
+ if (part.kind !== 'keys' || keys.length * part.keys.length > 16) {
+ return keys.length === 1 ? { kind: 'template', prefix: keys[0] } : OTHER;
+ }
+ keys = keys.flatMap((k) => part.keys.map((p) => k + p + span.literal.text));
+ }
+ return { kind: 'keys', keys };
+ }
+ if (ts.isConditionalExpression(e)) return merge([resolveExpr(e.whenTrue, depth + 1), resolveExpr(e.whenFalse, depth + 1)]);
+ if (ts.isBinaryExpression(e) && (e.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || e.operatorToken.kind === ts.SyntaxKind.BarBarToken)) {
+ return merge([resolveExpr(e.left, depth + 1), resolveExpr(e.right, depth + 1)]);
+ }
+ if (ts.isIdentifier(e)) return resolveDecl(lookup(e, fileOf(e), depth), depth);
+ if (ts.isPropertyAccessExpression(e)) {
+ const obj = objectLiteral(e.expression, depth + 1);
+ const prop = obj?.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === e.name.text) as ts.PropertyAssignment | undefined;
+ return prop ? resolveExpr(prop.initializer, depth + 1) : OTHER;
+ }
+ if (ts.isElementAccessExpression(e)) {
+ const obj = objectLiteral(e.expression, depth + 1);
+ const values = obj?.properties.filter(ts.isPropertyAssignment).map((p) => resolveExpr(p.initializer, depth + 1)) ?? [];
+ return values.length > 0 ? merge(values) : OTHER;
+ }
+ if (ts.isCallExpression(e) && ts.isIdentifier(e.expression)) {
+ const decl = lookup(e.expression, fileOf(e), depth);
+ let fn: ts.FunctionLikeDeclaration | null = null;
+ if (decl && ts.isFunctionLike(decl as ts.Node)) fn = decl as ts.FunctionLikeDeclaration;
+ else if (decl && !ts.isParameter(decl as ts.Node) && !ts.isForOfStatement(decl as ts.Node) && (ts.isArrowFunction(strip(decl as ts.Expression)) || ts.isFunctionExpression(strip(decl as ts.Expression)))) fn = strip(decl as ts.Expression) as ts.ArrowFunction;
+ const returns = fn ? returnsOf(fn) : [];
+ return returns.length > 0 ? merge(returns.map((r) => resolveExpr(r, depth + 1))) : OTHER;
+ }
+ return OTHER;
+ };
+
+ const reads: ConfigRead[] = [];
+ for (const path of walk(join(root, subdir), [])) {
+ const sf = source(path);
+ const visit = (n: ts.Node) => {
+ if (ts.isCallExpression(n) && n.arguments.length > 0) {
+ const callee = n.expression;
+ const name = ts.isPropertyAccessExpression(callee) ? callee.name.text : ts.isIdentifier(callee) ? callee.text : '';
+ if (name === 'getConfig') {
+ const arg = n.arguments[0];
+ reads.push({
+ file: relative(root, path),
+ line: sf.getLineAndCharacterOfPosition(n.getStart()).line + 1,
+ expr: arg.getText().replace(/\s+/g, ' '),
+ target: resolveExpr(arg, 0),
+ });
+ }
+ }
+ ts.forEachChild(n, visit);
+ };
+ visit(sf);
+ }
+ return reads;
+}