Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(chronicle): auto_chronicle defaults on; validate chronicle.* rails at config set (#5876)
garrytan838e96262edc
diff --git a/src/commands/config.ts b/src/commands/config.tsindex 9534a0df99..8dbec73faa 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -294,6 +294,21 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:} catch { /* the value already persisted */ }}+/**+ * #5876: an explicit `config set auto_chronicle` answers the default-on change, which clears the+ * durable doctor/advisor `auto_chronicle_default_on` notice. Best-effort: the value already persisted.+ */+async function acknowledgeAutoChronicle(engine: BrainEngine, value: string): Promise<void> {+ const { CHRONICLE_ACK_KEY, parseAutoChronicle } = await import('../core/chronicle/config.ts');+ try { await engine.setConfig(CHRONICLE_ACK_KEY, new Date().toISOString()); } catch { /* the notice stays; harmless */ }+ if (parseAutoChronicle(value).enabled) {+ console.log('Automatic event extraction is on: each eligible new or changed meeting, conversation or calendar page gets one paid chat call, bounded by chronicle.job_budget_usd per page and chronicle.auto_daily_limit per day.');+ console.log('To turn it off: gbrain config set auto_chronicle false');+ } else {+ console.log('Automatic event extraction is off. To extract history on request (paid; ask the user first): gbrain chronicle-backfill --dry-run');+ }+}+/** #5232: the CLI write wait is file-plane so the engine-free CLI reads it before choosing a transport. */async function setFileWriteWait(cfg: GBrainConfig, value: string, saveConfig: (cfg: GBrainConfig) => void): Promise<void> {const { MAX_WRITE_WAIT_MS, WRITE_WAIT_CONFIG_KEY, WRITE_WAIT_ENV } = await import('../core/persistence/write-wait.ts');@@ -667,6 +682,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {if (n > 0) {console.log(`Unset ${key}`);if (key === 'facts.default_visibility') await restampVisibilityPosture(null);+ if (key === 'auto_chronicle') {+ console.log('auto_chronicle now uses its default, which is ON: eligible new or changed meeting, conversation and calendar pages each get one paid extraction call.');+ console.log('To turn automatic extraction off, run: gbrain config set auto_chronicle false');+ }} else {console.error(`Config key not found: ${key}`);process.exit(1);@@ -1090,6 +1109,21 @@ export async function runConfig(engine: BrainEngine, args: string[]) {}}+ // #5876: auto_chronicle and chronicle.* knobs gate paid extraction, so a+ // typo is refused here instead of silently falling back at run time.+ if (key === 'auto_chronicle' || key.startsWith('chronicle.')) {+ const { validateChronicleConfigValue, CHRONICLE_CONFIG_KEYS } = await import('../core/chronicle/config.ts');+ if (key.startsWith('chronicle.') && !CHRONICLE_CONFIG_KEYS.includes(key) && !forceFlag) {+ const { suggestNearest } = await import('../core/levenshtein.ts');+ const suggestion = suggestNearest(key, [...CHRONICLE_CONFIG_KEYS], 3);+ console.error(`[config] Unknown config key "${key}".${suggestion ? ` Did you mean "${suggestion}"?` : ''}`);+ console.error(`[config] chronicle keys: ${CHRONICLE_CONFIG_KEYS.join(', ')}. Nothing was written.`);+ process.exit(1);+ }+ const err = validateChronicleConfigValue(key, value);+ if (err) { console.error(`[config] ${err}`); process.exit(1); }+ }+if (key === 'embedding_columns') {try {const parsed = JSON.parse(value);@@ -1207,6 +1241,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {// scrollback; echoing the raw value to stderr leaks the secret.console.log(`Set ${key} = ${redactConfigValue(key, value)}`);if (key === 'facts.default_visibility') await restampVisibilityPosture(value);+ if (key === 'auto_chronicle') await acknowledgeAutoChronicle(engine, value);// v0.40.3.0 (D3 + Phase 2B): mode-switch UX. Fires only on// search.mode writes. Honors GBRAIN_NO_MODE_SWITCH_UX=1 + non-TTY.diff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.tsindex 1df538efa7..a79d0af4f1 100644--- a/src/core/chronicle/config.ts+++ b/src/core/chronicle/config.ts@@ -1,15 +1,155 @@-// v0.42.x — Life Chronicle (#2390) config flags.+// Life Chronicle (#2390, #5876) config: the auto_chronicle switch and the chronicle.* knobs.import type { BrainEngine } from '../engine.ts';+export const AUTO_CHRONICLE_KEY = 'auto_chronicle';+/** The one documented opt-out. Unsetting the key restores the default, which is on. */+export const AUTO_CHRONICLE_OPT_OUT_ARGV = ['gbrain', 'config', 'set', 'auto_chronicle', 'false'] as const;+export const AUTO_CHRONICLE_KEEP_ARGV = ['gbrain', 'config', 'set', 'auto_chronicle', 'true'] as const;+/** Stamped by `gbrain config set auto_chronicle <value>`: the operator has seen the default-on change. */+export const CHRONICLE_ACK_KEY = 'chronicle.default_on_acknowledged';+/** Stamped when the one-shot post-upgrade notice prints. */+export const CHRONICLE_NOTICE_SHOWN_KEY = 'chronicle.default_on_notice_shown';++const TRUE_WORDS = ['true', '1', 'yes', 'on'];+const FALSE_WORDS = ['false', '0', 'no', 'off'];+/**- * Auto-emit is OFF by default (plan D5.5: spend posture — extraction spends LLM- * tokens per eligible write). The only caller is the unwired backstop, so the- * setting currently has no effect; advisor and doctor `auto_chronicle` say so (#5876).+ * `default`: unset, so on. `explicit`: a recognized true/false word.+ * `invalid`: any other value, read as off (fail closed on spend) and reported by doctor.+ */+export interface AutoChronicleSetting {+ enabled: boolean;+ source: 'default' | 'explicit' | 'invalid';+ raw: string | null;+}++export function parseAutoChronicle(raw: string | null | undefined): AutoChronicleSetting {+ if (raw == null || raw.trim() === '') return { enabled: true, source: 'default', raw: raw ?? null };+ const word = raw.trim().toLowerCase();+ if (TRUE_WORDS.includes(word)) return { enabled: true, source: 'explicit', raw };+ if (FALSE_WORDS.includes(word)) return { enabled: false, source: 'explicit', raw };+ return { enabled: false, source: 'invalid', raw };+}++export async function readAutoChronicle(engine: BrainEngine): Promise<AutoChronicleSetting> {+ return parseAutoChronicle(await engine.getConfig(AUTO_CHRONICLE_KEY));+}++/**+ * Automatic extraction is ON by default (the default-on rule for new features); the opt-out is+ * `gbrain config set auto_chronicle false`. Each eligible new or changed page costs one chat call,+ * bounded by `chronicle.job_budget_usd` per page and `chronicle.auto_daily_limit` per rolling day.*/export async function isAutoChronicleEnabled(engine: BrainEngine): Promise<boolean> {- const val = await engine.getConfig('auto_chronicle');- if (val == null) return false; // default OFF- return ['true', '1', 'yes', 'on'].includes(val.trim().toLowerCase());+ return (await readAutoChronicle(engine)).enabled;+}++/**+ * True while the operator has not answered the default-on change: the feature is on and nobody ran+ * `gbrain config set auto_chronicle ...` since this release (an explicit `true` written before it+ * was a no-op, so it does not count as an answer).+ */+export async function autoChronicleNeedsAcknowledgement(engine: BrainEngine): Promise<boolean> {+ const setting = await readAutoChronicle(engine);+ if (!setting.enabled) return false;+ const ack = await engine.getConfig(CHRONICLE_ACK_KEY);+ return ack == null || ack.trim() === '';+}++interface NumericKeySpec {+ fallback: number;+ min: number;+ max: number;+ integer: boolean;+ meaning: string;+}++export const CHRONICLE_NUMERIC_KEYS = {+ 'chronicle.job_budget_usd': { fallback: 0.25, min: 0.01, max: 10, integer: false,+ meaning: 'USD cap for one page extraction (a per-call cap, not a daily budget)' },+ 'chronicle.auto_daily_limit': { fallback: 200, min: 1, max: 10_000, integer: true,+ meaning: 'automatic extraction calls per rolling 24 hours; to stop them, set auto_chronicle false' },+ 'chronicle.auto_recent_days': { fallback: 30, min: 1, max: 3650, integer: true,+ meaning: 'days back a page date may be for automatic extraction; older pages are left to chronicle-backfill' },+ 'chronicle.auto_settle_seconds': { fallback: 180, min: 0, max: 86_400, integer: true,+ meaning: 'seconds a page must stay unchanged before automatic extraction' },+ 'chronicle.judge_max_tokens': { fallback: 4000, min: 1, max: 128_000, integer: true,+ meaning: 'output-token cap for one extraction call' },+} as const satisfies Record<string, NumericKeySpec>;++export type ChronicleNumericKey = keyof typeof CHRONICLE_NUMERIC_KEYS;++/** Every chronicle.* key gbrain reads or writes. `config set` refuses other chronicle.* leaves. */+export const CHRONICLE_CONFIG_KEYS: readonly string[] = [+ ...Object.keys(CHRONICLE_NUMERIC_KEYS),+ 'chronicle.tz',+ CHRONICLE_ACK_KEY,+ CHRONICLE_NOTICE_SHOWN_KEY,+];++function describeRange(key: ChronicleNumericKey): string {+ const spec: NumericKeySpec = CHRONICLE_NUMERIC_KEYS[key];+ return `${spec.integer ? 'a whole number' : 'a number'} from ${spec.min} to ${spec.max} (${spec.meaning}; default ${spec.fallback})`;+}++function parseNumeric(key: ChronicleNumericKey, raw: string): number | null {+ const spec: NumericKeySpec = CHRONICLE_NUMERIC_KEYS[key];+ const text = raw.trim();+ if (!/^\d+(\.\d+)?$/.test(text)) return null;+ const n = Number(text);+ if (spec.integer && !Number.isInteger(n)) return null;+ return n >= spec.min && n <= spec.max ? n : null;+}++/** `config set` validation for auto_chronicle and chronicle.*; returns the refusal text or null. */+export function validateChronicleConfigValue(key: string, value: string): string | null {+ if (key === AUTO_CHRONICLE_KEY) {+ return parseAutoChronicle(value).source === 'explicit' ? null+ : `auto_chronicle must be true or false (got '${value}'). Nothing was written. ` ++ 'To turn automatic event extraction off: gbrain config set auto_chronicle false';+ }+ if (key in CHRONICLE_NUMERIC_KEYS) {+ const k = key as ChronicleNumericKey;+ return parseNumeric(k, value) === null ? `${key} must be ${describeRange(k)} (got '${value}'). Nothing was written.` : null;+ }+ return null;+}++export interface ChronicleSettings {+ jobBudgetUsd: number;+ /** True when the operator set the cap: an unpriced model then refuses with no_pricing instead of warn-and-run. */+ jobBudgetExplicit: boolean;+ autoDailyLimit: number;+ autoRecentDays: number;+ autoSettleSeconds: number;+ judgeMaxTokens: number;+ /** Stored values outside the valid range; each fell back to its default. */+ invalid: Array<{ key: ChronicleNumericKey; raw: string; fallback: number }>;+}++/** Reads every chronicle.* knob; a malformed or unreadable row falls back to its default. */+export async function readChronicleSettings(engine: BrainEngine): Promise<ChronicleSettings> {+ const invalid: ChronicleSettings['invalid'] = [];+ const values = {} as Record<ChronicleNumericKey, number>;+ let budgetExplicit = false;+ for (const key of Object.keys(CHRONICLE_NUMERIC_KEYS) as ChronicleNumericKey[]) {+ const fallback = CHRONICLE_NUMERIC_KEYS[key].fallback;+ const raw = await engine.getConfig(key).catch(() => null);+ if (raw == null || raw.trim() === '') { values[key] = fallback; continue; }+ const parsed = parseNumeric(key, raw);+ if (parsed === null) { invalid.push({ key, raw, fallback }); values[key] = fallback; continue; }+ values[key] = parsed;+ if (key === 'chronicle.job_budget_usd') budgetExplicit = true;+ }+ return {+ jobBudgetUsd: values['chronicle.job_budget_usd'],+ jobBudgetExplicit: budgetExplicit,+ autoDailyLimit: values['chronicle.auto_daily_limit'],+ autoRecentDays: values['chronicle.auto_recent_days'],+ autoSettleSeconds: values['chronicle.auto_settle_seconds'],+ judgeMaxTokens: values['chronicle.judge_max_tokens'],+ invalid,+ };}/** Pinned timezone for the when→date projection cast (plan: default UTC). */diff --git a/src/core/config.ts b/src/core/config.tsindex 12ef0346a2..0263b9508c 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1552,11 +1552,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// set` accepts them directly. See docs/operations/spend-controls.md.'spend.posture','pricing.overrides',- // Life Chronicle (v0.42.56.0, #2390). The release notes' enable command is- // `gbrain config set auto_chronicle true`, but the key was never registered- // — so the documented command failed with "Unknown config key" and the- // operator had to discover --force by reading source. Same class as the- // spend-controls registration above.+ // Life Chronicle (#2390, #5876): automatic event extraction, on by default+ // (unset = on). The documented opt-out is `gbrain config set auto_chronicle+ // false`; read by core/chronicle/config.ts.'auto_chronicle',// Auto-link toggle read by the put_page post-hook (link-extraction.ts),// reconcile-links, and sweep. The documented off-switch is `gbrain config@@ -1574,6 +1572,12 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// pages overflowed the old hardcoded 1500 and were misrecorded as// no_events; the cap is now configurable and truncation is surfaced.'chronicle.judge_max_tokens',+ // #5876: automatic extraction rails, validated at `config set` by+ // core/chronicle/config.ts (CHRONICLE_NUMERIC_KEYS).+ 'chronicle.job_budget_usd',+ 'chronicle.auto_daily_limit',+ 'chronicle.auto_recent_days',+ 'chronicle.auto_settle_seconds',// Takes bootstrap (v0.41.18.0, A12). The onboard remediation's two-gate// consent reads this key, and enabling it is the documented path to// `gbrain takes extract --from-pages` — same unregistered-key class.@@ -1650,7 +1654,7 @@ export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = ['content_sanity.', // v0.41 content-sanity tunables'mcp.', // mcp.publish_skills, mcp.skills_dir (PR1 skill catalog)'autopilot.', // autopilot.nightly_quality_probe.*, autopilot.auto_drain.* (#1685)- 'chronicle.', // chronicle.tz + future Life Chronicle knobs (#2390)+ 'chronicle.', // Life Chronicle knobs; config set refuses leaves outside CHRONICLE_CONFIG_KEYS (#5876)'self_upgrade.', // v0.42 self-upgrade (mode, quiet_hours, state)// Queue admission control (per-name sub-keys):// minions.coalesce_params.<name>, minions.ttl_waiting_hours.<name>,diff --git a/test/chronicle-config-5876.test.ts b/test/chronicle-config-5876.test.tsnew file mode 100644index 0000000000..f228a0844b--- /dev/null+++ b/test/chronicle-config-5876.test.ts@@ -0,0 +1,111 @@+/**+ * #5876 (T10): auto_chronicle defaults on and the chronicle.* rails are validated.+ *+ * Protects: unset auto_chronicle reads as on; true/false words parse; any other word reads as off+ * and is reported as invalid; a malformed stored chronicle.* value falls back to its default;+ * `gbrain config set` refuses out-of-range chronicle.* values, unknown chronicle.* leaves and+ * non-boolean auto_chronicle values, and an explicit set records the operator's answer.+ * Fails when: the default reverts to off, a typo silently becomes a cap, or `config set+ * auto_chronicle` stops clearing the default-on notice.+ * Seams: none; in-memory PGLite, console/process.exit spies around runConfig.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runConfig } from '../src/commands/config.ts';+import {+ CHRONICLE_ACK_KEY, autoChronicleNeedsAcknowledgement, isAutoChronicleEnabled, parseAutoChronicle, readChronicleSettings,+ validateChronicleConfigValue,+} from '../src/core/chronicle/config.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';++let engine: PGLiteEngine;+const KEYS = ['auto_chronicle', CHRONICLE_ACK_KEY, 'chronicle.auto_daily_limit', 'chronicle.job_budget_usd',+ 'chronicle.auto_recent_days', 'chronicle.auto_settle_seconds', 'chronicle.judge_max_tokens'];++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { for (const k of KEYS) await engine.unsetConfig(k); });++async function runConfigCapture(args: string[]) {+ const logs: string[] = [];+ const errs: string[] = [];+ let exit: number | null = null;+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });+ 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(); exitSpy.mockRestore(); }+ return { out: logs.join('\n'), err: errs.join('\n'), exit: exit as number | null };+}++describe('auto_chronicle parsing', () => {+ test('unset is on by default; true/false words parse; anything else reads as off and invalid', async () => {+ expect(await isAutoChronicleEnabled(engine)).toBe(true);+ expect(parseAutoChronicle(null)).toEqual({ enabled: true, source: 'default', raw: null });+ for (const v of ['true', 'YES', ' on ', '1']) expect(parseAutoChronicle(v)).toMatchObject({ enabled: true, source: 'explicit' });+ for (const v of ['false', 'No', 'off', '0']) expect(parseAutoChronicle(v)).toMatchObject({ enabled: false, source: 'explicit' });+ expect(parseAutoChronicle('flase')).toEqual({ enabled: false, source: 'invalid', raw: 'flase' });+ await engine.setConfig('auto_chronicle', 'false');+ expect(await isAutoChronicleEnabled(engine)).toBe(false);+ });++ test('chronicle.* rails: defaults, explicit budget flag, malformed rows fall back', async () => {+ expect(await readChronicleSettings(engine)).toMatchObject({ jobBudgetUsd: 0.25, jobBudgetExplicit: false, autoDailyLimit: 200,+ autoRecentDays: 30, autoSettleSeconds: 180, judgeMaxTokens: 4000, invalid: [] });+ await engine.setConfig('chronicle.job_budget_usd', '0.4');+ await engine.setConfig('chronicle.auto_daily_limit', 'lots');+ const s = await readChronicleSettings(engine);+ expect(s).toMatchObject({ jobBudgetUsd: 0.4, jobBudgetExplicit: true, autoDailyLimit: 200 });+ expect(s.invalid).toEqual([{ key: 'chronicle.auto_daily_limit', raw: 'lots', fallback: 200 }]);+ });++ test('the new keys are registered', () => {+ for (const k of ['auto_chronicle', 'chronicle.job_budget_usd', 'chronicle.auto_daily_limit', 'chronicle.auto_recent_days', 'chronicle.auto_settle_seconds']) {+ expect(KNOWN_CONFIG_KEYS).toContain(k);+ }+ expect(validateChronicleConfigValue('chronicle.auto_settle_seconds', '0')).toBeNull();+ expect(validateChronicleConfigValue('chronicle.job_budget_usd', '0')).toContain('from 0.01 to 10');+ });+});++describe('gbrain config set', () => {+ test('refuses chronicle.auto_daily_limit 0 with the valid range and writes nothing', async () => {+ const r = await runConfigCapture(['set', 'chronicle.auto_daily_limit', '0']);+ expect(r.exit).toBe(1);+ expect(r.err).toContain('chronicle.auto_daily_limit must be a whole number from 1 to 10000');+ expect(r.err).toContain('auto_chronicle false');+ expect(await engine.getConfig('chronicle.auto_daily_limit')).toBeNull();+ });++ test('refuses an unknown chronicle.* leaf with a suggestion', async () => {+ const r = await runConfigCapture(['set', 'chronicle.auto_daily_limt', '50']);+ expect(r.exit).toBe(1);+ expect(r.err).toContain('Did you mean "chronicle.auto_daily_limit"?');+ expect(await engine.getConfig('chronicle.auto_daily_limt')).toBeNull();+ });++ test('refuses auto_chronicle flase and names the opt-out', async () => {+ const r = await runConfigCapture(['set', 'auto_chronicle', 'flase']);+ expect(r.exit).toBe(1);+ expect(r.err).toContain('gbrain config set auto_chronicle false');+ expect(await engine.getConfig('auto_chronicle')).toBeNull();+ });++ test('an explicit set acknowledges the default-on change; true names the cost and the opt-out', async () => {+ await engine.setConfig('auto_chronicle', 'true'); // written before this release: still unanswered+ expect(await autoChronicleNeedsAcknowledgement(engine)).toBe(true);+ const r = await runConfigCapture(['set', 'auto_chronicle', 'true']);+ expect(r.exit).toBeNull();+ expect(r.out).toContain('gbrain config set auto_chronicle false');+ expect(await engine.getConfig(CHRONICLE_ACK_KEY)).not.toBeNull();+ expect(await autoChronicleNeedsAcknowledgement(engine)).toBe(false);+ });++ test('unset explains the default is on and names the set-false opt-out', async () => {+ await engine.setConfig('auto_chronicle', 'false');+ const r = await runConfigCapture(['unset', 'auto_chronicle']);+ expect(r.out).toContain('default, which is ON');+ expect(r.out).toContain('gbrain config set auto_chronicle false');+ });+});diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.tsindex 32266824a9..90910647a7 100644--- a/test/chronicle-extract.test.ts+++ b/test/chronicle-extract.test.ts@@ -179,7 +179,8 @@ describe('runChronicleBackstop gating', () => {await engine.putPage('meetings/bs', { type: 'meeting', title: 'bs', compiled_truth: LONG_BODY });});- test('skips when auto_chronicle is off (default)', async () => {+ test('skips when auto_chronicle is set false (the opt-out; unset is on since #5876)', async () => {+ await engine.setConfig('auto_chronicle', 'false');const r = await runChronicleBackstop({ slug: 'meetings/bs', type: 'meeting', compiled_truth: LONG_BODY }, { engine, sourceId: 'default' });expect(r).toEqual({ enqueued: false, skipped: 'auto_chronicle_off' });});