Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(config): route self_upgrade.* keys to the file plane (#5489, #5518)

garrytan5e68244fda3c
diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.md
index f416b2889a..25890b25a1 100644
--- a/docs/guides/upgrades-auto-update.md
+++ b/docs/guides/upgrades-auto-update.md
@@ -57,6 +57,15 @@ action on the user's local sleep window — is owned by
[quiet-hours.md](quiet-hours.md); this doc only covers the self-upgrade
hook into it.
+`gbrain config set self_upgrade.<key>` writes `~/.gbrain/config.json` (the
+file plane every self-upgrade reader uses) and refuses a value the readers
+would ignore: an unknown key or mode, a quiet-hours window with an hour
+outside 0-23, equal bounds, or an unknown timezone. Versions are stored in the
+four-segment form (`0.57.1` becomes `0.57.1.0`). The keys are machine-local,
+so they work on a thin client too. Older versions wrote these keys to the
+database, where nothing reads them; the next `config set` or `config unset` of
+the key removes that row.
+
## Implementation
### The Check (cron-initiated)
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 043119188a..5ed2a493a6 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -8,7 +8,7 @@
path name lines justification
src/commands/bootstrap.ts runHooks 597 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/bootstrap.ts runHooks>withLock(#1) 449 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/config.ts runConfig 852 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/config.ts runConfig 765 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/report-remote.ts doctorReportRemote 416 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/src/cli.ts b/src/cli.ts
index eb4667548c..36693b5721 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1895,7 +1895,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
'code-callers': '`code-callers` has no MCP op yet. Run on the host.',
'code-callees': '`code-callees` has no MCP op yet. Run on the host.',
// scratch-DB audit additions
- config: "config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set.",
+ config: "config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",
jobs: '`jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.',
// Gap-closure wave [OV6]: routable subcommands are intercepted before this
// hint fires — these fire only for the host-bound remainder.
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index f6f8140121..2856d3c9ec 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -37,6 +37,7 @@ import {
isCacheFresh,
readUpdateCache,
reconcileBreadcrumb,
+ resolveQuietHoursWindow,
resolveSelfUpgradeMode,
} from '../core/self-upgrade.ts';
import { logSelfUpgrade } from '../core/audit/self-upgrade-audit.ts';
@@ -440,9 +441,7 @@ export async function attemptAutopilotSelfUpgrade(
const latestVersion = entry.marker.latest;
const idle = await computeAutopilotIdle(engine, engineType);
- const qh = cfg.self_upgrade?.quiet_hours;
- const tz = qh?.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
- const verdict = evaluateQuietHours({ start: qh?.start ?? 23, end: qh?.end ?? 8, tz }, new Date());
+ const verdict = evaluateQuietHours(resolveQuietHoursWindow(cfg.self_upgrade?.quiet_hours), new Date());
const installMethod = detectInstallMethod();
const decision = decideSelfUpgrade({
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 979fa6e7d2..898d1d24d0 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -11,6 +11,12 @@ import {
import { redactPgUrl } from '../core/url-redact.ts';
import { WRITER_ADMIN_LOCK_KEY } from '../core/persistence/admin-contract.ts';
+import {
+ SELF_UPGRADE_CONFIG_LEAVES,
+ isSelfUpgradeConfigLeaf,
+ parseSelfUpgradeConfigValue,
+ selfUpgradeModeEnvOverride,
+} from '../core/self-upgrade.ts';
// v0.36.x #892: sensitive config-key allowlist. The `show` path used a
// loose `.includes('key')` check that also redacts (works); the `set` path
@@ -55,6 +61,53 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([
'mcp.instructions',
]);
+/** #5489: every self_upgrade.* reader (cli.ts startup check, autopilot,
+ * doctor) reads the file plane, so the whole prefix is file-plane: a
+ * registered leaf is written there and an unregistered one is refused,
+ * never written to a DB row nothing reads. */
+const SELF_UPGRADE_KEY_PREFIX = 'self_upgrade.';
+
+/** The single membership test the get/set/unset lanes share. */
+function isFilePlaneDottedKey(key: string): boolean {
+ return FILE_PLANE_DOTTED_KEYS.has(key) || key.startsWith(SELF_UPGRADE_KEY_PREFIX);
+}
+
+/** Delete the DB-plane row of a file-plane key: a `config set` from before
+ * the key was routed (#5489, #4748) wrote it there and nothing reads it.
+ * Best-effort: the file-plane write already succeeded, so a DB failure warns
+ * and the command still succeeds. */
+async function dropStaleDbRow(engine: BrainEngine, key: string): Promise<number> {
+ try {
+ return await engine.unsetConfig(key);
+ } catch (e) {
+ console.error(`[config] WARN: could not check for a stale DB-plane row for ${key} (${e instanceof Error ? e.message : String(e)}); nothing reads one.`);
+ return 0;
+ }
+}
+
+function warnSelfUpgradeModeEnvOverride(): void {
+ const env = selfUpgradeModeEnvOverride();
+ if (env) {
+ console.error(`[config] note: GBRAIN_SELF_UPGRADE_MODE=${env} is set and overrides the file; the effective mode stays ${env} while it is set.`);
+ }
+}
+
+/** Remove a file-plane dotted key from ~/.gbrain/config.json; true when the
+ * file held it. Splits at the FIRST dot, so `self_upgrade.quiet_hours.start`
+ * never deletes `quiet_hours`. */
+async function unsetFilePlaneKey(key: string): Promise<boolean> {
+ const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
+ const cfg = loadConfigFileOnly();
+ const dot = key.indexOf('.');
+ const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade';
+ const leaf = key.slice(dot + 1);
+ const branch = cfg?.[top] as Record<string, unknown> | undefined;
+ if (!cfg || !branch || !(leaf in branch)) return false;
+ delete branch[leaf];
+ saveConfig(cfg);
+ return true;
+}
+
/** Ambient-writeback keys are DUAL-PLANE (OV2-5): the DB plane is
* authoritative (the serve-side harvest gate re-checks it before any
* extraction) while the file plane mirrors it for the engine-free readers
@@ -238,6 +291,167 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
} catch { /* the value already persisted */ }
}
+/** `config set` for the FILE_PLANE_DOTTED_KEYS and the memorable consent
+ * gate: every one of these is read from ~/.gbrain/config.json by an
+ * engine-free reader, so the write never touches the engine. */
+async function setFilePlaneKey(key: string, value: string, tail: string[]): Promise<void> {
+ const { loadConfigFileOnly, saveConfig, isConfigTruthy } = await import('../core/config.ts');
+ const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as Parameters<typeof saveConfig>[0];
+ if (key === 'integrations.memorable.enabled') {
+ // Same file-plane rule as the other hook-lane keys: the session-end
+ // relay gate is read by engine-free hook children via loadConfig.
+ //
+ // Enabling is a CONSENT event, not just a config write: the relay
+ // hands session tool-call traces to a closed-source third-party CLI
+ // that sends them off-machine. The gate requires a gbrain-authored
+ // consent stamp that ONLY this flow writes (the memorable CLI flips
+ // the boolean out-of-band on `memorable enable`, but it can never
+ // write the stamp — see hook-heartbeat.ts's consent-stamp section).
+ const hb = await import('../core/context/hook-heartbeat.ts');
+ const on = isConfigTruthy(value);
+ if (!on) {
+ cfg.integrations = { ...(cfg.integrations ?? {}), memorable: { ...(cfg.integrations?.memorable ?? {}), enabled: false } };
+ saveConfig(cfg);
+ await hb.clearMemorableConsent();
+ console.log(`Set ${key} = false (file plane: ~/.gbrain/config.json)`);
+ console.log('Relay disabled and the disclosure consent was revoked — re-enabling shows the disclosure again.');
+ return;
+ }
+ if (!(await hb.memorableConsentValid())) {
+ console.log(hb.MEMORABLE_DISCLOSURE_TEXT);
+ const preConsented = tail.includes('--yes');
+ if (!preConsented) {
+ if (!process.stdin.isTTY) {
+ // Skillpack trust-prompt posture: a non-interactive session
+ // cannot consent on the operator's behalf. Nothing was written.
+ console.error('[config] non-interactive session and no --yes: refusing to enable a third-party relay without explicit consent. Nothing was written.');
+ // Deliberately does NOT mention --yes: this line is printed INTO
+ // agent sessions (the very sessions whose tool calls the relay
+ // egresses), and advertising the non-interactive bypass here
+ // hands a prompt-injected agent the exact string that flips the
+ // gate. Operators find --yes in the docs.
+ console.error('[AGENT] Relay this to your operator: run `gbrain config set integrations.memorable.enabled true` in a terminal and answer the prompt.');
+ process.exit(1);
+ }
+ const { promptYesNo } = await import('../core/confirm-prompt.ts');
+ const accepted = await promptYesNo('[gbrain] Enable the Memorable session-end relay? [y/N] ');
+ if (!accepted) {
+ console.log('Declined. Nothing was written.');
+ return;
+ }
+ }
+ const stampPath = await hb.writeMemorableConsent();
+ console.log(`Consent recorded: ${stampPath}`);
+ }
+ cfg.integrations = { ...(cfg.integrations ?? {}), memorable: { ...(cfg.integrations?.memorable ?? {}), enabled: true } };
+ saveConfig(cfg);
+ console.log(`Set ${key} = true (file plane: ~/.gbrain/config.json)`);
+ console.log(
+ 'Session-end traces will now be offered to the locally-installed `memorable` CLI, ' +
+ 'which sends redacted tool calls off-machine to its extraction API. ' +
+ 'Turn off: gbrain config set integrations.memorable.enabled false (or GBRAIN_MEMORABLE=0)',
+ );
+ } else if (key === 'push.allow_unverified_remote') {
+ const on = isConfigTruthy(value);
+ cfg.push = { ...(cfg.push ?? {}), allow_unverified_remote: on };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
+ if (on) {
+ console.log(
+ 'WARNING: workspace pushes now SKIP repo-visibility verification. ' +
+ 'This trusts the remote on your word — unset it once verification works: ' +
+ 'gbrain config set push.allow_unverified_remote false',
+ );
+ }
+ } else if (key === 'backup.check_enabled') {
+ const on = isConfigTruthy(value);
+ cfg.backup = { ...(cfg.backup ?? {}), check_enabled: on };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
+ } else if (key === 'backup.check_interval_days') {
+ const n = Number.parseInt(value, 10);
+ if (!Number.isFinite(n) || n < 1) {
+ console.error(`[config] ${key} must be an integer >= 1 (days between automatic backup checks)`);
+ process.exit(1);
+ }
+ cfg.backup = { ...(cfg.backup ?? {}), check_interval_days: n };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json)`);
+ } else if (key === 'mcp.instructions') {
+ // #4748: deployment identity appended to the MCP initialize contract.
+ // Takes effect on the next `gbrain serve` start (the response is
+ // built once per process from loadConfig()).
+ cfg.mcp = { ...(cfg.mcp ?? {}), instructions: value };
+ saveConfig(cfg);
+ console.log(`Set ${key} (file plane: ~/.gbrain/config.json) — restart \`gbrain serve\` to apply`);
+ } else if (key.startsWith(SELF_UPGRADE_KEY_PREFIX)) {
+ const leaf = key.slice(SELF_UPGRADE_KEY_PREFIX.length);
+ if (!isSelfUpgradeConfigLeaf(leaf)) {
+ const { suggestNearest } = await import('../core/levenshtein.ts');
+ const suggestion = suggestNearest(key, SELF_UPGRADE_CONFIG_LEAVES.map((l) => `${SELF_UPGRADE_KEY_PREFIX}${l}`), 3);
+ console.error(`[config] Unknown config key "${key}".${suggestion ? ` Did you mean "${suggestion}"?` : ''}`);
+ console.error(`[config] self_upgrade keys: ${SELF_UPGRADE_CONFIG_LEAVES.join(', ')}. Nothing was written.`);
+ process.exit(1);
+ }
+ const parsed = parseSelfUpgradeConfigValue(leaf, value);
+ if (!parsed.ok) {
+ console.error(`[config] ${key} ${parsed.error}`);
+ process.exit(1);
+ }
+ cfg.self_upgrade = { ...(cfg.self_upgrade ?? {}), [leaf]: parsed.value };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${JSON.stringify(parsed.value)} (file plane: ~/.gbrain/config.json)`);
+ if (leaf === 'mode') warnSelfUpgradeModeEnvOverride();
+ } else {
+ const n = Number.parseInt(value, 10);
+ if (!Number.isFinite(n) || n < 0) {
+ console.error(`[config] ${key} must be an integer >= 0 (minutes; 0 = push every turn)`);
+ process.exit(1);
+ }
+ cfg.hooks = { ...(cfg.hooks ?? {}), stop_push_debounce_min: n };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json)`);
+ }
+}
+
+/**
+ * Thin-client `config` dispatch. `self_upgrade.*` is machine-local:
+ * self-upgrade runs engine-free on every install shape, a thin client
+ * included, so `config set|unset|get self_upgrade.<key>` edit this machine's
+ * ~/.gbrain/config.json. Every other key, and any flag, keeps the host-plane
+ * refusal. Returns true when handled.
+ */
+export async function tryRunConfigThinClient(args: string[]): Promise<boolean> {
+ const [action, key, ...rest] = args;
+ if (!key || !key.startsWith(SELF_UPGRADE_KEY_PREFIX) || rest.some((a) => a.startsWith('-'))) return false;
+ if (action === 'set' && rest.length === 1) {
+ await setFilePlaneKey(key, rest[0], rest);
+ return true;
+ }
+ if (action === 'unset' && rest.length === 0) {
+ if (!(await unsetFilePlaneKey(key))) {
+ console.error(`Config key not found: ${key}`);
+ process.exit(1);
+ }
+ console.log(`Unset ${key} (file plane)`);
+ if (key === `${SELF_UPGRADE_KEY_PREFIX}mode`) warnSelfUpgradeModeEnvOverride();
+ return true;
+ }
+ if (action === 'get' && rest.length === 0) {
+ const { loadConfigFileOnly } = await import('../core/config.ts');
+ const branch = loadConfigFileOnly()?.self_upgrade as Record<string, unknown> | undefined;
+ const val = branch?.[key.slice(SELF_UPGRADE_KEY_PREFIX.length)];
+ if (val === undefined || val === null) {
+ console.error(`Config key not found: ${key}`);
+ process.exit(1);
+ }
+ console.log(typeof val === 'string' ? val : JSON.stringify(val));
+ console.error('[config] source: file plane (~/.gbrain/config.json)');
+ return true;
+ }
+ return false;
+}
+
export async function runConfig(engine: BrainEngine, args: string[]) {
const action = args[0];
@@ -382,15 +596,12 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
return;
}
- if (FILE_PLANE_DOTTED_KEYS.has(key)) {
- const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
- const cfg = loadConfigFileOnly();
- const [top, leaf] = key.split('.') as ['push' | 'hooks' | 'backup' | 'mcp', string];
- const branch = cfg?.[top] as Record<string, unknown> | undefined;
- if (cfg && branch && leaf in branch) {
- delete branch[leaf];
- saveConfig(cfg);
- console.log(`Unset ${key} (file plane)`);
+ if (isFilePlaneDottedKey(key)) {
+ const fileHad = await unsetFilePlaneKey(key);
+ const dbDeleted = await dropStaleDbRow(engine, key);
+ if (fileHad || dbDeleted > 0) {
+ console.log(`Unset ${key} (${[fileHad ? 'file plane' : null, dbDeleted > 0 ? 'stale db-plane row' : null].filter(Boolean).join(' + ')})`);
+ if (key === `${SELF_UPGRADE_KEY_PREFIX}mode`) warnSelfUpgradeModeEnvOverride();
} else {
console.error(`Config key not found: ${key}`);
process.exit(1);
@@ -475,9 +686,15 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
// non-zero exit exists to prevent. Everything else keeps the #2120
// file/env-wins resolution.
const dbAuthoritative = MEMORY_DUAL_PLANE_KEYS.has(key) || key === BRAIN_AUDIENCE_KEY;
+ // File-plane keys have no DB reader: a DB row is a stale pre-routing
+ // write, never the answer (#5489).
+ const fileOnly = isFilePlaneDottedKey(key);
+ const hasStaleDbRow = fileOnly && dbVal !== null && dbVal !== undefined;
const val = dbAuthoritative
? (dbVal ?? fileVal)
- : (fileVal !== undefined && fileVal !== null ? fileVal : dbVal);
+ : fileOnly
+ ? fileVal
+ : (fileVal !== undefined && fileVal !== null ? fileVal : dbVal);
if (val !== null && val !== undefined) {
// #3943: redact by default like `show`/`set` — `get` output lands in
// agent transcripts and shell history; scripts opt out with the flag.
@@ -489,14 +706,19 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.error(`[config] WARN: file mirror disagrees ('${String(fileVal)}') — planes diverged; re-run: gbrain config set ${key} ${String(dbVal)}`);
}
} else if (fileVal !== undefined && fileVal !== null) {
- const shadow = dbVal !== null && dbVal !== undefined
- ? ' — a DB-plane value also exists and is shadowed at runtime'
- : '';
+ const shadow = hasStaleDbRow
+ ? ` — a stale DB-plane row also exists and nothing reads it (gbrain config unset ${key} removes it)`
+ : dbVal !== null && dbVal !== undefined
+ ? ' — a DB-plane value also exists and is shadowed at runtime'
+ : '';
console.error(`[config] source: file/env plane (~/.gbrain/config.json or env)${shadow}`);
} else {
console.error(`[config] source: db plane`);
}
} else {
+ if (hasStaleDbRow) {
+ console.error(`[config] a stale DB-plane row holds '${redactConfigValue(key, String(dbVal))}', but nothing reads it; the runtime default applies. Remove it: gbrain config unset ${key}`);
+ }
console.error(`Config key not found: ${key}`);
process.exit(1);
}
@@ -657,105 +879,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
return;
}
- if (FILE_PLANE_DOTTED_KEYS.has(key) || key === 'integrations.memorable.enabled') {
- const { loadConfigFileOnly, saveConfig, isConfigTruthy } = await import('../core/config.ts');
- const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as Parameters<typeof saveConfig>[0];
- if (key === 'integrations.memorable.enabled') {
- // Same file-plane rule as the other hook-lane keys: the session-end
- // relay gate is read by engine-free hook children via loadConfig.
- //
- // Enabling is a CONSENT event, not just a config write: the relay
- // hands session tool-call traces to a closed-source third-party CLI
- // that sends them off-machine. The gate requires a gbrain-authored
- // consent stamp that ONLY this flow writes (the memorable CLI flips
- // the boolean out-of-band on `memorable enable`, but it can never
- // write the stamp — see hook-heartbeat.ts's consent-stamp section).
- const hb = await import('../core/context/hook-heartbeat.ts');
- const on = isConfigTruthy(value);
- if (!on) {
- cfg.integrations = { ...(cfg.integrations ?? {}), memorable: { ...(cfg.integrations?.memorable ?? {}), enabled: false } };
- saveConfig(cfg);
- await hb.clearMemorableConsent();
- console.log(`Set ${key} = false (file plane: ~/.gbrain/config.json)`);
- console.log('Relay disabled and the disclosure consent was revoked — re-enabling shows the disclosure again.');
- return;
- }
- if (!(await hb.memorableConsentValid())) {
- console.log(hb.MEMORABLE_DISCLOSURE_TEXT);
- const preConsented = tail.includes('--yes');
- if (!preConsented) {
- if (!process.stdin.isTTY) {
- // Skillpack trust-prompt posture: a non-interactive session
- // cannot consent on the operator's behalf. Nothing was written.
- console.error('[config] non-interactive session and no --yes: refusing to enable a third-party relay without explicit consent. Nothing was written.');
- // Deliberately does NOT mention --yes: this line is printed INTO
- // agent sessions (the very sessions whose tool calls the relay
- // egresses), and advertising the non-interactive bypass here
- // hands a prompt-injected agent the exact string that flips the
- // gate. Operators find --yes in the docs.
- console.error('[AGENT] Relay this to your operator: run `gbrain config set integrations.memorable.enabled true` in a terminal and answer the prompt.');
- process.exit(1);
- }
- const { promptYesNo } = await import('../core/confirm-prompt.ts');
- const accepted = await promptYesNo('[gbrain] Enable the Memorable session-end relay? [y/N] ');
- if (!accepted) {
- console.log('Declined. Nothing was written.');
- return;
- }
- }
- const stampPath = await hb.writeMemorableConsent();
- console.log(`Consent recorded: ${stampPath}`);
- }
- cfg.integrations = { ...(cfg.integrations ?? {}), memorable: { ...(cfg.integrations?.memorable ?? {}), enabled: true } };
- saveConfig(cfg);
- console.log(`Set ${key} = true (file plane: ~/.gbrain/config.json)`);
- console.log(
- 'Session-end traces will now be offered to the locally-installed `memorable` CLI, ' +
- 'which sends redacted tool calls off-machine to its extraction API. ' +
- 'Turn off: gbrain config set integrations.memorable.enabled false (or GBRAIN_MEMORABLE=0)',
- );
- } else if (key === 'push.allow_unverified_remote') {
- const on = isConfigTruthy(value);
- cfg.push = { ...(cfg.push ?? {}), allow_unverified_remote: on };
- saveConfig(cfg);
- console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
- if (on) {
- console.log(
- 'WARNING: workspace pushes now SKIP repo-visibility verification. ' +
- 'This trusts the remote on your word — unset it once verification works: ' +
- 'gbrain config set push.allow_unverified_remote false',
- );
- }
- } else if (key === 'backup.check_enabled') {
- const on = isConfigTruthy(value);
- cfg.backup = { ...(cfg.backup ?? {}), check_enabled: on };
- saveConfig(cfg);
- console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
- } else if (key === 'backup.check_interval_days') {
- const n = Number.parseInt(value, 10);
- if (!Number.isFinite(n) || n < 1) {
- console.error(`[config] ${key} must be an integer >= 1 (days between automatic backup checks)`);
- process.exit(1);
- }
- cfg.backup = { ...(cfg.backup ?? {}), check_interval_days: n };
- saveConfig(cfg);
- console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json)`);
- } else if (key === 'mcp.instructions') {
- // #4748: deployment identity appended to the MCP initialize contract.
- // Takes effect on the next `gbrain serve` start (the response is
- // built once per process from loadConfig()).
- cfg.mcp = { ...(cfg.mcp ?? {}), instructions: value };
- saveConfig(cfg);
- console.log(`Set ${key} (file plane: ~/.gbrain/config.json) — restart \`gbrain serve\` to apply`);
- } else {
- const n = Number.parseInt(value, 10);
- if (!Number.isFinite(n) || n < 0) {
- console.error(`[config] ${key} must be an integer >= 0 (minutes; 0 = push every turn)`);
- process.exit(1);
- }
- cfg.hooks = { ...(cfg.hooks ?? {}), stop_push_debounce_min: n };
- saveConfig(cfg);
- console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json)`);
+ if (isFilePlaneDottedKey(key) || key === 'integrations.memorable.enabled') {
+ await setFilePlaneKey(key, value, tail);
+ if (isFilePlaneDottedKey(key) && (await dropStaleDbRow(engine, key)) > 0) {
+ console.log(`Removed a stale DB-plane row for ${key} (an earlier \`config set\` wrote it there; nothing reads it).`);
}
return;
}
diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.ts
index 8d4a4af03b..6487575ba9 100644
--- a/src/commands/thin-client-routing.ts
+++ b/src/commands/thin-client-routing.ts
@@ -62,6 +62,11 @@ export async function routeThinClientCommand(
const sub = args[0];
const rest = args.slice(1);
+ if (command === 'config') {
+ const { tryRunConfigThinClient } = await import('./config.ts');
+ return tryRunConfigThinClient(args);
+ }
+
if (command === 'takes') {
switch (sub) {
case 'list': {
diff --git a/src/core/minions/quiet-hours.ts b/src/core/minions/quiet-hours.ts
index d072ec5c83..854ae46ef4 100644
--- a/src/core/minions/quiet-hours.ts
+++ b/src/core/minions/quiet-hours.ts
@@ -67,7 +67,7 @@ export function evaluateQuietHours(
// Helpers
// ---------------------------------------------------------------------------
-function isValidConfig(cfg: QuietHoursConfig): boolean {
+export function isValidConfig(cfg: QuietHoursConfig): boolean {
if (!Number.isInteger(cfg.start) || cfg.start < 0 || cfg.start > 23) return false;
if (!Number.isInteger(cfg.end) || cfg.end < 0 || cfg.end > 23) return false;
if (cfg.start === cfg.end) return false; // zero-width window is ambiguous
diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.ts
index d8c53301ba..65a48c7975 100644
--- a/src/core/self-upgrade.ts
+++ b/src/core/self-upgrade.ts
@@ -28,7 +28,9 @@
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
-import { gbrainPath } from './config.ts';
+import { gbrainPath, isConfigTruthy } from './config.ts';
+import { isValidTimeZone } from './cycle/cycle-date.ts';
+import { isValidConfig as isValidQuietHoursWindow } from './minions/quiet-hours.ts';
import { acquirePackLock, type PackLockOpts } from './schema-pack/pack-lock.ts';
import { isNewerVersion, isValidVersionString, parseSemver, semverGt, semverLte } from './semver.ts';
@@ -511,12 +513,166 @@ function normalizeMode(raw: unknown): SelfUpgradeMode | null {
* onto the hot path. Env (`GBRAIN_SELF_UPGRADE_MODE`) is the operator / CI
* escape hatch.
*/
+/** The `GBRAIN_SELF_UPGRADE_MODE` override, when it names a valid mode. */
+export function selfUpgradeModeEnvOverride(): SelfUpgradeMode | null {
+ return normalizeMode(process.env.GBRAIN_SELF_UPGRADE_MODE);
+}
+
export function resolveSelfUpgradeMode(
cfg: { self_upgrade?: { mode?: string } } | null | undefined,
): SelfUpgradeMode {
- const env = normalizeMode(process.env.GBRAIN_SELF_UPGRADE_MODE);
+ const env = selfUpgradeModeEnvOverride();
if (env) return env;
const fromCfg = normalizeMode(cfg?.self_upgrade?.mode);
if (fromCfg) return fromCfg;
return 'notify';
}
+
+// ── `gbrain config set self_upgrade.<leaf>` (file plane) ─────────────────────
+
+const QUIET_HOURS_DEFAULT_START = 23;
+const QUIET_HOURS_DEFAULT_END = 8;
+
+/** The autopilot silent channel's quiet-hours window: configured bounds, else
+ * 23:00-08:00 in the system timezone. `config set self_upgrade.quiet_hours`
+ * validates against the same resolution. */
+export function resolveQuietHoursWindow(
+ qh: SelfUpgradeState['quiet_hours'],
+): { start: number; end: number; tz: string } {
+ return {
+ start: qh?.start ?? QUIET_HOURS_DEFAULT_START,
+ end: qh?.end ?? QUIET_HOURS_DEFAULT_END,
+ tz: qh?.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',
+ };
+}
+
+/** Every `self_upgrade.*` leaf `gbrain config set` accepts. All of them route
+ * to ~/.gbrain/config.json: each reader (the cli.ts startup check, the
+ * autopilot channel, doctor) reads the file plane only, so a DB-plane write
+ * would be accepted and never read (#5489). */
+export const SELF_UPGRADE_CONFIG_LEAVES = [
+ 'mode',
+ 'mode_prompted',
+ 'quiet_hours',
+ 'failed_versions',
+ 'attempting_version',
+ 'last_check_ts',
+ 'last_applied_version',
+] as const satisfies readonly (keyof SelfUpgradeState)[];
+
+export type SelfUpgradeConfigLeaf = (typeof SELF_UPGRADE_CONFIG_LEAVES)[number];
+
+export type SelfUpgradeConfigParse =
+ | { ok: true; value: SelfUpgradeState[SelfUpgradeConfigLeaf] }
+ | { ok: false; error: string };
+
+export function isSelfUpgradeConfigLeaf(leaf: string): leaf is SelfUpgradeConfigLeaf {
+ return (SELF_UPGRADE_CONFIG_LEAVES as readonly string[]).includes(leaf);
+}
+
+/** Normalize to the 4-segment form (`0.57.1` -> `0.57.1.0`): the upgrade
+ * machinery compares stored versions to the 4-segment latest by string, so a
+ * shorter spelling would be stored and never match. */
+function parseVersionLeaf(raw: string): string | null {
+ const tuple = parseSemver(raw.trim());
+ return tuple ? tuple.join('.') : null;
+}
+
+function isHour(n: unknown): n is number {
+ return Number.isInteger(n) && (n as number) >= 0 && (n as number) <= 23;
+}
+
+function parseQuietHours(raw: string): SelfUpgradeConfigParse {
+ const shape = 'a JSON object like {"start":23,"end":8,"tz":"America/New_York"}';
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return { ok: false, error: `must be ${shape}` };
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return { ok: false, error: `must be ${shape}` };
+ }
+ const obj = parsed as Record<string, unknown>;
+ const unknownKeys = Object.keys(obj).filter((k) => k !== 'start' && k !== 'end' && k !== 'tz');
+ if (unknownKeys.length > 0) {
+ return { ok: false, error: `accepts only start, end and tz (got ${unknownKeys.join(', ')})` };
+ }
+ const out: { start?: number; end?: number; tz?: string } = {};
+ for (const k of ['start', 'end'] as const) {
+ if (obj[k] === undefined) continue;
+ if (!isHour(obj[k])) return { ok: false, error: `${k} must be an integer hour 0-23 (got ${JSON.stringify(obj[k])})` };
+ out[k] = obj[k];
+ }
+ if (obj.tz !== undefined) {
+ if (typeof obj.tz !== 'string' || !isValidTimeZone(obj.tz)) {
+ return { ok: false, error: `tz must be a valid IANA timezone (got ${JSON.stringify(obj.tz)})` };
+ }
+ out.tz = obj.tz;
+ }
+ // Validate what the autopilot reader will evaluate (defaults filled in) with
+ // the reader's own rule: a window evaluateQuietHours rejects is no window at
+ // all, so auto mode would never find a quiet hour to upgrade in.
+ if (!isValidQuietHoursWindow(resolveQuietHoursWindow(out))) {
+ return { ok: false, error: `start and end must differ (missing bounds default to ${QUIET_HOURS_DEFAULT_START} and ${QUIET_HOURS_DEFAULT_END})` };
+ }
+ return { ok: true, value: out };
+}
+
+function parseFailedVersions(raw: string): SelfUpgradeConfigParse {
+ const trimmed = raw.trim();
+ let items: unknown[];
+ if (trimmed.startsWith('[')) {
+ try {
+ const parsed = JSON.parse(trimmed);
+ if (!Array.isArray(parsed)) throw new Error('not an array');
+ items = parsed;
+ } catch {
+ return { ok: false, error: 'must be a JSON array of versions or a comma-separated list' };
+ }
+ } else {
+ items = trimmed === '' ? [] : trimmed.split(',');
+ }
+ const versions: string[] = [];
+ for (const item of items) {
+ const v = typeof item === 'string' ? parseVersionLeaf(item) : null;
+ if (!v) return { ok: false, error: `entries must be versions like 0.57.1.0 (got ${JSON.stringify(item)})` };
+ if (!versions.includes(v)) versions.push(v);
+ }
+ return { ok: true, value: versions };
+}
+
+/**
+ * Parse the raw `gbrain config set self_upgrade.<leaf> <value>` string into
+ * the typed value the file-plane readers expect. Refuses anything a reader
+ * would silently ignore (an unknown mode reads as `notify`).
+ */
+export function parseSelfUpgradeConfigValue(leaf: SelfUpgradeConfigLeaf, raw: string): SelfUpgradeConfigParse {
+ switch (leaf) {
+ case 'mode': {
+ const mode = normalizeMode(raw.trim());
+ return mode ? { ok: true, value: mode } : { ok: false, error: `must be auto, notify or off (got '${raw}')` };
+ }
+ case 'mode_prompted': {
+ if (isConfigTruthy(raw)) return { ok: true, value: true };
+ if (['false', '0', 'no', 'off'].includes(raw.trim().toLowerCase())) return { ok: true, value: false };
+ return { ok: false, error: `must be true or false (got '${raw}')` };
+ }
+ case 'quiet_hours':
+ return parseQuietHours(raw);
+ case 'failed_versions':
+ return parseFailedVersions(raw);
+ case 'attempting_version':
+ case 'last_applied_version': {
+ const v = parseVersionLeaf(raw);
+ return v ? { ok: true, value: v } : { ok: false, error: `must be a version like 0.57.1.0 (got '${raw}')` };
+ }
+ case 'last_check_ts': {
+ const t = raw.trim();
+ const n = /^\d+$/.test(t) ? Number(t) : NaN;
+ return Number.isSafeInteger(n)
+ ? { ok: true, value: n }
+ : { ok: false, error: `must be epoch milliseconds, an integer >= 0 (got '${raw}')` };
+ }
+ }
+}
diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.ts
index 59ea92c908..3b8a6886fd 100644
--- a/test/config-file-plane-keys.test.ts
+++ b/test/config-file-plane-keys.test.ts
@@ -22,7 +22,8 @@ import {
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
-// The file-plane branch returns before any engine access — a null stub proves it.
+// The file-plane write never depends on the engine — a null stub proves it.
+// (Its best-effort stale-DB-row cleanup warns on the null stub and continues.)
const noEngine = null as unknown as BrainEngine;
async function captureLog(fn: () => Promise<void>): Promise<string> {
@@ -379,3 +380,211 @@ describe('config set integrations.memorable.enabled — the disclosure consent g
});
});
});
+
+/**
+ * #5489: every `self_upgrade.*` reader is file-plane — the cli.ts startup
+ * check (loadConfigFileOnly, before any DB connect), the autopilot silent
+ * channel and doctor's self_upgrade_health (loadConfig). `config set
+ * self_upgrade.mode auto` used to write the DB plane, print "Set ... = auto"
+ * and change nothing. The null engine is the discriminator again: the write
+ * must land in config.json without reaching the engine.
+ */
+import {
+ parseSelfUpgradeConfigValue,
+ resolveQuietHoursWindow,
+ resolveSelfUpgradeMode,
+} from '../src/core/self-upgrade.ts';
+import { checkSelfUpgradeHealth } from '../src/commands/doctor.ts';
+import { tryRunConfigThinClient } from '../src/commands/config.ts';
+import { routeThinClientCommand } from '../src/commands/thin-client-routing.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+/** A DB plane holding rows an earlier, pre-routing `config set` wrote. */
+function staleRowEngine(rows: Record<string, string>): { engine: BrainEngine; rows: Map<string, string> } {
+ const map = new Map(Object.entries(rows));
+ const engine = {
+ getConfig: async (k: string) => map.get(k) ?? null,
+ unsetConfig: async (k: string) => (map.delete(k) ? 1 : 0),
+ } as unknown as BrainEngine;
+ return { engine, rows: map };
+}
+
+describe('config set — self_upgrade.* keys are FILE-plane canonical (#5489)', () => {
+ const VALID_CASES: ReadonlyArray<{ leaf: string; raw: string; stored: unknown }> = [
+ { leaf: 'mode', raw: 'auto', stored: 'auto' },
+ { leaf: 'mode', raw: 'off', stored: 'off' },
+ { leaf: 'mode_prompted', raw: 'false', stored: false },
+ { leaf: 'mode_prompted', raw: 'yes', stored: true },
+ { leaf: 'quiet_hours', raw: '{"start":1,"end":5,"tz":"UTC"}', stored: { start: 1, end: 5, tz: 'UTC' } },
+ { leaf: 'failed_versions', raw: '0.57.0.0, 0.57.1.0', stored: ['0.57.0.0', '0.57.1.0'] },
+ { leaf: 'failed_versions', raw: '["0.57.0.0"]', stored: ['0.57.0.0'] },
+ { leaf: 'failed_versions', raw: '[]', stored: [] },
+ { leaf: 'attempting_version', raw: '0.57.2.0', stored: '0.57.2.0' },
+ // stored in the 4-segment form the upgrade check compares by string
+ { leaf: 'attempting_version', raw: 'v0.57.2', stored: '0.57.2.0' },
+ { leaf: 'failed_versions', raw: '0.57.1, v0.57.1.0', stored: ['0.57.1.0'] },
+ { leaf: 'last_check_ts', raw: '1790000000000', stored: 1790000000000 },
+ { leaf: 'last_applied_version', raw: '0.57.1.0', stored: '0.57.1.0' },
+ ];
+
+ test('the cases cover every registered self_upgrade.* key', async () => {
+ const { KNOWN_CONFIG_KEYS } = await import('../src/core/config.ts');
+ const registered = KNOWN_CONFIG_KEYS.filter((k) => k.startsWith('self_upgrade.')).sort();
+ const covered = [...new Set(VALID_CASES.map((c) => `self_upgrade.${c.leaf}`))].sort();
+ expect(covered).toEqual(registered);
+ });
+
+ for (const c of VALID_CASES) {
+ test(`self_upgrade.${c.leaf} ${c.raw} lands nested in config.json`, async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-'));
+ await withEnv({ GBRAIN_HOME: parent }, async () => {
+ const r = await captureAll(() => runConfig(noEngine, ['set', `self_upgrade.${c.leaf}`, c.raw]));
+ expect(r.exitCode).toBeNull();
+ expect(r.out).toContain('file plane');
+ const cfg = JSON.parse(readFileSync(join(parent, '.gbrain', 'config.json'), 'utf8')) as {
+ self_upgrade?: Record<string, unknown>;
+ };
+ expect(cfg.self_upgrade?.[c.leaf]).toEqual(c.stored);
+ });
+ });
+ }
+
+ test('the readers see the new mode: startup check, doctor, and unset restores the notify default', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-read-'));
+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_SELF_UPGRADE_MODE: undefined }, async () => {
+ const { loadConfigFileOnly } = await import('../src/core/config.ts');
+ await captureAll(() => runConfig(noEngine, ['set', 'self_upgrade.mode', 'auto']));
+ expect(resolveSelfUpgradeMode(loadConfigFileOnly())).toBe('auto');
+ expect(checkSelfUpgradeHealth().message).toContain('mode=auto');
+
+ const r = await captureAll(() => runConfig(noEngine, ['unset', 'self_upgrade.mode']));
+ expect(r.out).toContain('Unset self_upgrade.mode (file plane)');
+ expect(resolveSelfUpgradeMode(loadConfigFileOnly())).toBe('notify');
+ });
+ });
+
+ test('an empty failed_versions list clears the known-bad set', () => {
+ expect(parseSelfUpgradeConfigValue('failed_versions', '')).toEqual({ ok: true, value: [] });
+ });
+
+ test('resolveQuietHoursWindow fills 23:00-08:00 in the system timezone, keeping configured bounds', () => {
+ const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ expect(resolveQuietHoursWindow(undefined)).toEqual({ start: 23, end: 8, tz: systemTz });
+ expect(resolveQuietHoursWindow({ end: 5, tz: 'UTC' })).toEqual({ start: 23, end: 5, tz: 'UTC' });
+ });
+
+ test('a stale DB-plane row is never reported as the value, and set/unset remove it', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-stale-'));
+ await withEnv({ GBRAIN_HOME: parent }, async () => {
+ const { engine, rows } = staleRowEngine({ 'self_upgrade.mode': 'auto', 'self_upgrade.quiet_hours': '{"start":1,"end":5}' });
+
+ // get: the file has no mode, so the answer is not-found plus a pointer at the stale row.
+ const got = await captureAll(() => runConfig(engine, ['get', 'self_upgrade.mode']));
+ expect(got.exitCode).toBe(1);
+ expect(got.out).toBe('');
+ expect(got.err).toContain('stale DB-plane row');
+
+ // set writes the file and deletes the stale row.
+ const set = await captureAll(() => runConfig(engine, ['set', 'self_upgrade.mode', 'off']));
+ expect(set.out).toContain('Removed a stale DB-plane row for self_upgrade.mode');
+ expect(rows.has('self_upgrade.mode')).toBe(false);
+
+ // unset with no file value still removes the stale row instead of "not found".
+ const unset = await captureAll(() => runConfig(engine, ['unset', 'self_upgrade.quiet_hours']));
+ expect(unset.exitCode).toBeNull();
+ expect(unset.out).toContain('Unset self_upgrade.quiet_hours (stale db-plane row)');
+ expect(rows.size).toBe(0);
+ });
+ });
+
+ test('set/unset self_upgrade.mode say when GBRAIN_SELF_UPGRADE_MODE overrides the file', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-env-'));
+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_SELF_UPGRADE_MODE: 'off' }, async () => {
+ const set = await captureAll(() => runConfig(noEngine, ['set', 'self_upgrade.mode', 'auto']));
+ expect(set.err).toContain('GBRAIN_SELF_UPGRADE_MODE=off is set and overrides the file');
+ const unset = await captureAll(() => runConfig(noEngine, ['unset', 'self_upgrade.mode']));
+ expect(unset.err).toContain('GBRAIN_SELF_UPGRADE_MODE=off');
+ });
+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_SELF_UPGRADE_MODE: undefined }, async () => {
+ const set = await captureAll(() => runConfig(noEngine, ['set', 'self_upgrade.mode', 'auto']));
+ expect(set.err).not.toContain('GBRAIN_SELF_UPGRADE_MODE');
+ });
+ });
+
+ test('a thin client sets, reads and unsets self_upgrade.* on its own file plane', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-thin-'));
+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_SELF_UPGRADE_MODE: undefined }, async () => {
+ const thinCfg = { engine: 'pglite', remote_mcp: { mcp_url: 'https://brain.example.test/mcp' } } as unknown as GBrainConfig;
+ const set = await captureAll(async () => {
+ expect(await routeThinClientCommand(thinCfg, 'config', ['set', 'self_upgrade.mode', 'off'])).toBe(true);
+ });
+ expect(set.out).toContain('Set self_upgrade.mode = "off" (file plane');
+ const { loadConfigFileOnly } = await import('../src/core/config.ts');
+ expect(resolveSelfUpgradeMode(loadConfigFileOnly())).toBe('off');
+
+ const got = await captureAll(async () => { expect(await tryRunConfigThinClient(['get', 'self_upgrade.mode'])).toBe(true); });
+ expect(got.out.trim()).toBe('off');
+
+ const unset = await captureAll(async () => { expect(await tryRunConfigThinClient(['unset', 'self_upgrade.mode'])).toBe(true); });
+ expect(unset.out).toContain('Unset self_upgrade.mode (file plane)');
+ expect(resolveSelfUpgradeMode(loadConfigFileOnly())).toBe('notify');
+
+ // Host-plane keys and flags keep the thin-client refusal.
+ expect(await tryRunConfigThinClient(['set', 'search.mode', 'balanced'])).toBe(false);
+ expect(await tryRunConfigThinClient(['set', 'self_upgrade.mode', 'off', '--force'])).toBe(false);
+ });
+ });
+
+ test('set keeps the sibling self_upgrade state the upgrade machinery wrote', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-merge-'));
+ await withEnv({ GBRAIN_HOME: parent }, async () => {
+ const gb = join(parent, '.gbrain');
+ mkdirSync(gb, { recursive: true });
+ writeFileSync(join(gb, 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ self_upgrade: { mode: 'notify', mode_prompted: true, failed_versions: ['0.50.0.0'] },
+ }));
+ await captureAll(() => runConfig(noEngine, ['set', 'self_upgrade.mode', 'auto']));
+ const cfg = JSON.parse(readFileSync(join(gb, 'config.json'), 'utf8')) as { engine?: string; self_upgrade?: Record<string, unknown> };
+ expect(cfg.engine).toBe('pglite');
+ expect(cfg.self_upgrade).toEqual({ mode: 'auto', mode_prompted: true, failed_versions: ['0.50.0.0'] });
+ });
+ });
+
+ const INVALID_CASES: ReadonlyArray<{ leaf: string; raw: string }> = [
+ { leaf: 'mode', raw: 'yes' },
+ { leaf: 'mode', raw: 'Auto' },
+ { leaf: 'mode_prompted', raw: 'maybe' },
+ { leaf: 'quiet_hours', raw: 'not-json' },
+ { leaf: 'quiet_hours', raw: '[1,5]' },
+ { leaf: 'quiet_hours', raw: '{"start":24,"end":5}' },
+ { leaf: 'quiet_hours', raw: '{"start":2.5,"end":5}' },
+ // end defaults to 8 at the reader, so start 8 alone is a zero-width window
+ { leaf: 'quiet_hours', raw: '{"start":8}' },
+ { leaf: 'quiet_hours', raw: '{"start":1,"end":5,"tz":"Mars/Olympus_Mons"}' },
+ { leaf: 'quiet_hours', raw: '{"start":1,"end":5,"policy":"skip"}' },
+ { leaf: 'failed_versions', raw: 'latest' },
+ { leaf: 'failed_versions', raw: '[1]' },
+ { leaf: 'failed_versions', raw: '[0.57' },
+ { leaf: 'attempting_version', raw: 'v-next' },
+ { leaf: 'last_check_ts', raw: '1.5' },
+ { leaf: 'last_check_ts', raw: '12abc' },
+ { leaf: 'last_applied_version', raw: '0.57.x' },
+ { leaf: 'last_applied_version', raw: '0.57' },
+ // unregistered leaves are refused, never written to a DB row nothing reads
+ { leaf: 'modee', raw: 'auto' },
+ { leaf: 'quiet_hours.start', raw: '1' },
+ ];
+
+ for (const c of INVALID_CASES) {
+ test(`self_upgrade.${c.leaf} ${c.raw} is refused and nothing is written`, async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-selfup-bad-'));
+ await withEnv({ GBRAIN_HOME: parent }, async () => {
+ const r = await captureAll(() => runConfig(noEngine, ['set', `self_upgrade.${c.leaf}`, c.raw]));
+ expect(r.exitCode).toBe(1);
+ expect(r.err).toContain(`self_upgrade.${c.leaf}`);
+ expect(existsSync(join(parent, '.gbrain', 'config.json'))).toBe(false);
+ });
+ });
+ }
+});
diff --git a/test/config-set-mcp-instructions.test.ts b/test/config-set-mcp-instructions.test.ts
index faa41ad425..bb07a960bd 100644
--- a/test/config-set-mcp-instructions.test.ts
+++ b/test/config-set-mcp-instructions.test.ts
@@ -83,7 +83,10 @@ describe('#4748 config set mcp.instructions lands on the plane resolveMcpInstruc
const unset = await runConfigCapture(engine, ['unset', 'mcp.instructions']);
expect(unset.exit).toBeNull();
- expect(unsetCalls).toEqual([]);
+ // The DB plane is never written; set and unset each delete a stale
+ // pre-routing DB row (#5489), which the stub reports as absent.
+ expect(setCalls).toEqual([]);
+ expect(unsetCalls).toEqual(['mcp.instructions', 'mcp.instructions']);
expect(resolveMcpInstructions(loadConfig(), {})).toBe(GBRAIN_MCP_INSTRUCTIONS);
},
);
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index 5e98eecea6..df1dc2aa2b 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -1951,6 +1951,7 @@
"cache": [
"stats"
],
+ "config": [],
"jobs": [
"stats"
],
diff --git a/test/fixtures/goldens/cli/thin-client-cases.json b/test/fixtures/goldens/cli/thin-client-cases.json
index 1b87c7a35e..e4c57752e8 100644
--- a/test/fixtures/goldens/cli/thin-client-cases.json
+++ b/test/fixtures/goldens/cli/thin-client-cases.json
@@ -102,7 +102,7 @@
"argv": "config",
"exitCode": 1,
"stderr": [
- "`gbrain config` is not routable. config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set.",
+ "`gbrain config` is not routable. config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",
"(thin-client of http://127.0.0.1:1/mcp)"
],
"stdout": []