Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(chronicle): doctor and advisor report automatic extraction (#5876)
garrytan88612c702c8c
diff --git a/src/commands/doctor/checks/auto-chronicle.ts b/src/commands/doctor/checks/auto-chronicle.tsindex 67bb3f1145..de55353ae8 100644--- a/src/commands/doctor/checks/auto-chronicle.ts+++ b/src/commands/doctor/checks/auto-chronicle.ts@@ -1,29 +1,126 @@/**- * auto_chronicle (#5876): the `auto_chronicle` config key has no reader in this- * version (the put_page chronicle backstop was dropped and nothing else enqueues- * `chronicle_extract`), so a brain with it set to true silently gets no events.- * Warns when the key is on, naming the manual sweep and the unset command.+ * auto_chronicle (#5876): automatic event extraction health. On by default; the chronicle cycle+ * phase extracts pending meeting/conversation/calendar pages recorded in `chronicle_page_state`.+ * Reports the setting, 24 h use of the daily limit with the largest writer's share, 7-day outcomes+ * and spend (priced dollars, unpriced calls and missing cost records apart), and the command that+ * runs pending pages now. `auto_chronicle_default_on` stays visible (info) until the operator+ * answers the default-on change with `gbrain config set auto_chronicle true|false`.+ * Config-plane only: no provider calls.*/-import { isAutoChronicleEnabled } from '../../../core/chronicle/config.ts';+import {+ AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, CHRONICLE_NUMERIC_KEYS, autoChronicleNeedsAcknowledgement,+ readAutoChronicle, readChronicleSettings,+} from '../../../core/chronicle/config.ts';+import { describeChronicleActivity, readChronicleLedgerStats } from '../../../core/chronicle/ledger-stats.ts';+import { CHRONICLE_REASONS, chronicleBackfillArgv, type ChronicleAction } from '../../../core/chronicle/reasons.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-export const AUTO_CHRONICLE_DOCS = 'docs/guides/troubleshooting.md#auto_chronicle-has-no-effect';+export const AUTO_CHRONICLE_DOCS = 'docs/guides/life-chronicle.md';+const RUN_NOW_ARGV = ['gbrain', 'dream', '--phase', 'chronicle'];++const command = (argv: readonly string[]) => argv.join(' ');+const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);++async function chatAvailable(): Promise<boolean> {+ try {+ const { isAvailable } = await import('../../../core/ai/gateway.ts');+ return isAvailable('chat');+ } catch {+ return false;+ }+}++function warn(code: string, message: string, fix: ChronicleAction, extra: Record<string, unknown> = {}): Omit<Check, 'name'> {+ return { status: 'warn', message,+ details: { code, ...extra, fix, ...(fix.argv ? { fix_hint: command(fix.argv) } : {}), docs: AUTO_CHRONICLE_DOCS } };+}async function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const setting = await readAutoChronicle(engine);+ const settings = await readChronicleSettings(engine);const checks: Check[] = [];- const enabled = await isAutoChronicleEnabled(connectedEngine(ctx));- checks.push(enabled- ? {- name: 'auto_chronicle',- status: 'warn',- message: 'auto_chronicle=true currently has no effect: no write or cycle step enqueues chronicle extraction, so new meetings are not swept into events. ' +- 'Fix: run `gbrain chronicle-backfill --dry-run`, then `gbrain chronicle-backfill`; `gbrain config unset auto_chronicle` clears the setting.',- details: { code: 'auto_chronicle_no_effect', enabled: true, cause: 'auto_chronicle has no reader in this version',- fix: 'gbrain chronicle-backfill --dry-run', docs: AUTO_CHRONICLE_DOCS },+ const backfillPreview = command(chronicleBackfillArgv({ since: daysAgo(30), dryRun: true }));++ if (setting.source === 'invalid') {+ checks.push({ name: 'auto_chronicle', ...warn('auto_chronicle_invalid',+ `auto_chronicle is '${setting.raw}', which is neither true nor false, so automatic event extraction is off. ` ++ `Ask the user which they want, then run \`${command(AUTO_CHRONICLE_KEEP_ARGV)}\` or \`${command(AUTO_CHRONICLE_OPT_OUT_ARGV)}\`.`,+ CHRONICLE_REASONS.auto_chronicle_invalid.fix(), { enabled: false, readiness: 'degraded' }) });+ } else if (!setting.enabled) {+ checks.push({ name: 'auto_chronicle', status: 'ok',+ message: `auto_chronicle is off by choice. History stays available on request (paid; ask the user first): \`${backfillPreview}\`.`,+ details: { enabled: false, severity: 'info', readiness: 'disabled_by_choice', docs: AUTO_CHRONICLE_DOCS } });+ } else {+ const stats = await readChronicleLedgerStats(engine);+ const chat = await chatAvailable();+ const activity = stats.available ? describeChronicleActivity(stats, settings.autoDailyLimit)+ : 'The chronicle ledger is not created yet; run `gbrain apply-migrations --yes --no-autopilot-install`.';+ const summary = { enabled: true, source: setting.source, daily_limit: settings.autoDailyLimit,+ job_budget_usd: settings.jobBudgetUsd, ledger_available: stats.available, pending: stats.pending,+ auto_calls_24h: stats.autoCalls24h, principals_24h: stats.principals24h, last_7d: stats.last7d, spend_7d: stats.spend7d,+ chat_available: chat, run_now: RUN_NOW_ARGV };+ const failures = Object.entries(stats.last7d.reasons)+ .filter(([reason]) => reason in CHRONICLE_REASONS && CHRONICLE_REASONS[reason as keyof typeof CHRONICLE_REASONS].stage === 'execution');+ if (!chat && stats.pending > 0) {+ checks.push({ name: 'auto_chronicle', ...warn('judge_llm_unavailable',+ `auto_chronicle is on, but no chat provider is configured, so ${stats.pending} pending page(s) cannot be extracted. ${activity} ` ++ 'Ask the user to configure a chat provider key on the brain host; pending pages run on the next cycle.',+ CHRONICLE_REASONS.judge_llm_unavailable.fix(), { ...summary, readiness: 'missing' }) });+ } else if (stats.last7d.failed > 0 && failures.length > 0) {+ const [reason] = failures[0];+ const entry = CHRONICLE_REASONS[reason as keyof typeof CHRONICLE_REASONS];+ const ctxFix = { since: daysAgo(7), dailyLimit: settings.autoDailyLimit, recentDays: settings.autoRecentDays };+ const fix: ChronicleAction = ('fix' in entry ? entry.fix(ctxFix) : undefined)+ ?? { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-check after the next cycle.' };+ checks.push({ name: 'auto_chronicle', ...warn(reason,+ `auto_chronicle is on; ${stats.last7d.failed} automatic extraction(s) failed in 7 days, most often ${reason}: ${entry.meaning(ctxFix)} ${activity}`,+ fix, { ...summary, readiness: 'degraded' }) });+ } else {+ const runNow = stats.pending > 0 ? ` Pending pages run in the next autopilot cycle; to run them now: \`${command(RUN_NOW_ARGV)}\` (paid).` : '';+ const noChat = chat ? '' : ' No chat provider is configured, so nothing will be extracted until one is.';+ checks.push({ name: 'auto_chronicle', status: 'ok',+ message: `auto_chronicle is on${setting.source === 'default' ? ' (default)' : ''}. ${activity}${runNow}${noChat}`,+ details: { ...summary, severity: 'info', readiness: chat ? 'ok' : 'missing', docs: AUTO_CHRONICLE_DOCS } });}- : { name: 'auto_chronicle', status: 'ok', message: 'auto_chronicle is off.', details: { enabled: false } });+ }++ if (settings.invalid.length > 0) {+ const first = settings.invalid[0];+ checks.push({ name: 'chronicle_config_invalid', ...warn('chronicle_config_invalid',+ `${settings.invalid.map((i) => `${i.key}='${i.raw}'`).join(', ')} ${settings.invalid.length === 1 ? 'is' : 'are'} out of range, so the default ` ++ `${settings.invalid.length === 1 ? 'applies' : 'apply'} (${settings.invalid.map((i) => `${i.key}=${i.fallback}`).join(', ')}). ` ++ `Set a valid value, for example \`gbrain config set ${first.key} ${first.fallback}\`.`,+ { argv: ['gbrain', 'config', 'set', first.key, String(first.fallback)], consent: [], actor: 'agent', requires_exclusive: false,+ why: `${first.key}: ${CHRONICLE_NUMERIC_KEYS[first.key].meaning}.` },+ { invalid: settings.invalid }) });+ } else {+ checks.push({ name: 'chronicle_config_invalid', status: 'ok', message: 'chronicle.* settings are valid.' });+ }++ if (await autoChronicleNeedsAcknowledgement(engine)) {+ const ceiling = settings.autoDailyLimit * settings.jobBudgetUsd;+ checks.push({ name: 'auto_chronicle_default_on', status: 'ok',+ message: 'Automatic event extraction is on by default and the user has not confirmed it yet. ' ++ `Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $${settings.jobBudgetUsd.toFixed(2)} per page; ` ++ `at most ${settings.autoDailyLimit} calls per day, so at most $${ceiling.toFixed(2)} per day for a priced model; an unpriced model has no cap), ` ++ 'and page text goes to the configured chat provider. Relay this to the user, then run ' ++ `\`${command(AUTO_CHRONICLE_KEEP_ARGV)}\` to keep it or \`${command(AUTO_CHRONICLE_OPT_OUT_ARGV)}\` to opt out.`,+ details: { code: 'auto_chronicle_default_on', severity: 'info', ask_user: true, docs: AUTO_CHRONICLE_DOCS,+ fix: { argv: [...AUTO_CHRONICLE_KEEP_ARGV], consent: ['paid', 'egress'], actor: 'agent', requires_exclusive: false,+ why: 'Keeping the default records that the user accepted the per-page cost; the alternative is the opt-out.' } satisfies ChronicleAction,+ decisions: [{ id: 'keep', label: 'Keep automatic extraction on', argv: [...AUTO_CHRONICLE_KEEP_ARGV] },+ { id: 'opt_out', label: 'Turn automatic extraction off', argv: [...AUTO_CHRONICLE_OPT_OUT_ARGV] }],+ default: 'keep' } });+ } else {+ checks.push({ name: 'auto_chronicle_default_on', status: 'ok', message: 'The auto_chronicle setting is confirmed.' });+ }return checks;}-export const autoChronicleEntry: DoctorEntry = { name: 'auto_chronicle', emits: ['auto_chronicle'], run: runAutoChronicle };+export const autoChronicleEntry: DoctorEntry = {+ name: 'auto_chronicle',+ emits: ['auto_chronicle', 'chronicle_config_invalid', 'auto_chronicle_default_on'],+ run: runAutoChronicle,+};diff --git a/src/core/advisor/collect-chronicle.ts b/src/core/advisor/collect-chronicle.tsindex ecf935a64c..7ef4a75104 100644--- a/src/core/advisor/collect-chronicle.ts+++ b/src/core/advisor/collect-chronicle.ts@@ -2,10 +2,102 @@// Brain-state (not workspace-dependent), so it runs over MCP too. Two signals:// - unresolved ontology conflicts (genuine disagreement, not supersession)// - recent meetings not yet swept into the timeline (coverage gap)-// - auto_chronicle=true, which has no effect in this version (#5876)+// - automatic extraction (#5876): the unconfirmed default-on change, an invalid setting,+// pending pages with no chat provider, failures, and 7-day spend with the largest writer's share// Advisory display only (no dispatch_id) — the user runs the shown command.import type { AdvisorCollector, AdvisorContext, AdvisorFinding } from './types.ts';-import { isAutoChronicleEnabled } from '../chronicle/config.ts';+import {+ AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, autoChronicleNeedsAcknowledgement, readAutoChronicle, readChronicleSettings,+} from '../chronicle/config.ts';+import { describeChronicleActivity, readChronicleLedgerStats } from '../chronicle/ledger-stats.ts';+import { CHRONICLE_REASONS, chronicleBackfillArgv, type ChronicleAction } from '../chronicle/reasons.ts';++const daysAgo = (now: Date, days: number) => new Date(now.getTime() - days * 86_400_000).toISOString().slice(0, 10);++async function chatAvailable(): Promise<boolean> {+ try {+ const { isAvailable } = await import('../ai/gateway.ts');+ return isAvailable('chat');+ } catch {+ return false;+ }+}++async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFinding[]> {+ const setting = await readAutoChronicle(ctx.engine);+ if (setting.source === 'invalid') {+ return [{+ id: 'auto_chronicle_invalid',+ severity: 'warn',+ title: `auto_chronicle is '${setting.raw}', which reads as off`,+ detail: 'Ask the user whether automatic event extraction should be on (one paid chat call per eligible page) or off, ' ++ `then run \`${AUTO_CHRONICLE_KEEP_ARGV.join(' ')}\` or \`${AUTO_CHRONICLE_OPT_OUT_ARGV.join(' ')}\`.`,+ fix: { command_argv: [...AUTO_CHRONICLE_KEEP_ARGV] },+ collector: 'chronicle',+ ask_user: true,+ }];+ }+ if (!setting.enabled) return [];+ const findings: AdvisorFinding[] = [];+ const settings = await readChronicleSettings(ctx.engine);+ const stats = await readChronicleLedgerStats(ctx.engine);+ const activity = stats.available ? describeChronicleActivity(stats, settings.autoDailyLimit) : '';+ if (await autoChronicleNeedsAcknowledgement(ctx.engine)) {+ findings.push({+ id: 'auto_chronicle_default_on',+ severity: 'info',+ title: 'Automatic event extraction is on by default; confirm it with the user',+ detail: `Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $${settings.jobBudgetUsd.toFixed(2)} per page, ` ++ `at most ${settings.autoDailyLimit} calls per day: $${(settings.autoDailyLimit * settings.jobBudgetUsd).toFixed(2)} per day at most for a priced model; ` ++ 'an unpriced model has no cap). Page text goes to the configured chat provider. ' ++ `Keep it: \`${AUTO_CHRONICLE_KEEP_ARGV.join(' ')}\`. Opt out: \`${AUTO_CHRONICLE_OPT_OUT_ARGV.join(' ')}\`.` ++ (activity ? ` ${activity}` : ''),+ fix: { command_argv: [...AUTO_CHRONICLE_KEEP_ARGV] },+ collector: 'chronicle',+ ask_user: true,+ });+ }+ if (stats.pending > 0 && !(await chatAvailable())) {+ findings.push({+ id: 'chronicle_chat_unavailable',+ severity: 'warn',+ title: `${stats.pending} page(s) wait for event extraction, but no chat provider is configured`,+ detail: CHRONICLE_REASONS.judge_llm_unavailable.fix().why,+ fix: { command_argv: null },+ collector: 'chronicle',+ ask_user: true,+ });+ }+ const failed = Object.entries(stats.last7d.reasons)+ .find(([reason]) => reason in CHRONICLE_REASONS && CHRONICLE_REASONS[reason as keyof typeof CHRONICLE_REASONS].stage === 'execution');+ if (stats.last7d.failed > 0 && failed) {+ const reasonCtx = { since: daysAgo(ctx.now ?? new Date(), 7), dailyLimit: settings.autoDailyLimit, recentDays: settings.autoRecentDays };+ const entry = CHRONICLE_REASONS[failed[0] as keyof typeof CHRONICLE_REASONS];+ const fix: ChronicleAction | undefined = 'fix' in entry ? entry.fix(reasonCtx) : undefined;+ findings.push({+ id: 'chronicle_extraction_failing',+ severity: 'warn',+ title: `${stats.last7d.failed} automatic event extraction(s) failed in 7 days (most often ${failed[0]})`,+ detail: `${entry.meaning(reasonCtx)}${fix ? ` ${fix.why}` : ''} ${activity}`,+ fix: { command_argv: fix?.argv ?? null },+ collector: 'chronicle',+ ask_user: fix ? fix.consent.length > 0 || fix.actor !== 'agent' : false,+ });+ }+ const limited = stats.last7d.reasons.daily_limit ?? 0;+ if (limited > 0) {+ findings.push({+ id: 'chronicle_daily_limit',+ severity: 'info',+ title: `${limited} page(s) hit the automatic daily limit (${settings.autoDailyLimit} calls) in 7 days`,+ detail: `They are not lost: preview them, then backfill if the user agrees to the cost. ${activity}`,+ fix: { command_argv: chronicleBackfillArgv({ since: daysAgo(ctx.now ?? new Date(), 7), dryRun: true }) },+ collector: 'chronicle',+ ask_user: true,+ });+ }+ return findings;+}export const collectChronicle: AdvisorCollector = {id: 'chronicle',@@ -47,8 +139,8 @@ export const collectChronicle: AdvisorCollector = {id: 'chronicle_coverage_gap',severity: 'info',title: `${gap} recent meeting(s) aren't in the timeline yet`,- detail: 'Sweep them into events with `gbrain chronicle-backfill`.',- fix: { command_argv: ['gbrain', 'chronicle-backfill'] },+ detail: 'Preview them, then sweep them into events if the user agrees to one paid chat call per page.',+ fix: { command_argv: chronicleBackfillArgv({ since: daysAgo(ctx.now ?? new Date(), 30), dryRun: true }) },collector: 'chronicle',ask_user: true,});@@ -57,22 +149,11 @@ export const collectChronicle: AdvisorCollector = {// timeline_entries.event_page_id may be absent pre-migration; ignore.}- // 3. #5876: the setting is accepted but nothing reads it.+ // 3. #5876: automatic extraction (on by default). Brain state only; no provider calls.try {- if (await isAutoChronicleEnabled(ctx.engine)) {- findings.push({- id: 'auto_chronicle_no_effect',- severity: 'warn',- title: 'auto_chronicle=true currently has no effect',- detail: 'No write or cycle step enqueues chronicle extraction in this version, so new meetings are not swept into events. ' +- 'Run `gbrain chronicle-backfill` to sweep them; `gbrain config unset auto_chronicle` clears the setting.',- fix: { command_argv: ['gbrain', 'chronicle-backfill', '--dry-run'] },- collector: 'chronicle',- ask_user: true,- });- }+ findings.push(...await collectAutoChronicle(ctx));} catch {- // Config read failures leave the other findings intact.+ // Config/ledger read failures leave the other findings intact.}return findings;diff --git a/src/core/chronicle/ledger-stats.ts b/src/core/chronicle/ledger-stats.tsnew file mode 100644index 0000000000..5b723435d0--- /dev/null+++ b/src/core/chronicle/ledger-stats.ts@@ -0,0 +1,81 @@+// Life Chronicle (#5876): read-only rollups of the `chronicle_page_state` ledger for doctor and+// the advisor. One query module so the surfaces cannot drift from the ledger's columns.+import type { BrainEngine } from '../engine.ts';+import { isUndefinedTableError } from '../utils.ts';++export interface ChronicleLedgerStats {+ /** False when the ledger table is absent (migration not applied yet). */+ available: boolean;+ pending: number;+ /** Automatic extraction calls in the last rolling 24 hours (each counts against the daily limit). */+ autoCalls24h: number;+ /** Automatic calls per writer principal in the last 24 hours, largest first. */+ principals24h: Array<{ principal: string; calls: number }>;+ /** Automatic rows decided in the last 7 days, by state and by skip/failure reason. */+ last7d: { extracted: number; failed: number; skipped: number; reasons: Record<string, number> };+ /** Automatic spend in the last 7 days: priced dollars, unpriced calls and calls with no cost record, kept apart. */+ spend7d: { knownUsd: number; unpricedCalls: number; incompleteRecords: number };+}++const EMPTY: ChronicleLedgerStats = {+ available: false, pending: 0, autoCalls24h: 0, principals24h: [],+ last7d: { extracted: 0, failed: 0, skipped: 0, reasons: {} },+ spend7d: { knownUsd: 0, unpricedCalls: 0, incompleteRecords: 0 },+};++/** Automatic (trigger='auto') rows only: backfill is manual and bounded by its own --limit. */+export async function readChronicleLedgerStats(engine: BrainEngine): Promise<ChronicleLedgerStats> {+ try {+ const [counts] = await engine.executeRaw<{ pending: number; calls: number; extracted: number; failed: number; skipped: number;+ known_usd: number | null; unpriced: number; incomplete: number }>(+ `SELECT+ count(*) FILTER (WHERE state = 'pending')::int AS pending,+ count(*) FILTER (WHERE state IN ('extracted','failed') AND updated_at > now() - interval '24 hours')::int AS calls,+ count(*) FILTER (WHERE state = 'extracted' AND updated_at > now() - interval '7 days')::int AS extracted,+ count(*) FILTER (WHERE state = 'failed' AND updated_at > now() - interval '7 days')::int AS failed,+ count(*) FILTER (WHERE state = 'skipped' AND updated_at > now() - interval '7 days')::int AS skipped,+ sum(cost_usd) FILTER (WHERE NOT unpriced AND updated_at > now() - interval '7 days')::float8 AS known_usd,+ count(*) FILTER (WHERE unpriced AND state IN ('extracted','failed') AND updated_at > now() - interval '7 days')::int AS unpriced,+ count(*) FILTER (WHERE NOT unpriced AND cost_usd IS NULL AND state IN ('extracted','failed')+ AND updated_at > now() - interval '7 days')::int AS incomplete+ FROM chronicle_page_state WHERE trigger = 'auto'`,+ );+ const reasons = await engine.executeRaw<{ reason: string; n: number }>(+ `SELECT reason, count(*)::int AS n FROM chronicle_page_state+ WHERE trigger = 'auto' AND state IN ('skipped','failed') AND reason IS NOT NULL AND updated_at > now() - interval '7 days'+ GROUP BY reason ORDER BY n DESC, reason`,+ );+ const principals = await engine.executeRaw<{ principal: string; calls: number }>(+ `SELECT coalesce(principal_kind, 'unknown') || coalesce(':' || principal_id, '') AS principal, count(*)::int AS calls+ FROM chronicle_page_state+ WHERE trigger = 'auto' AND state IN ('extracted','failed') AND updated_at > now() - interval '24 hours'+ GROUP BY 1 ORDER BY calls DESC, principal LIMIT 5`,+ );+ return {+ available: true,+ pending: Number(counts?.pending ?? 0),+ autoCalls24h: Number(counts?.calls ?? 0),+ principals24h: principals.map((p) => ({ principal: p.principal, calls: Number(p.calls) })),+ last7d: { extracted: Number(counts?.extracted ?? 0), failed: Number(counts?.failed ?? 0), skipped: Number(counts?.skipped ?? 0),+ reasons: Object.fromEntries(reasons.map((r) => [r.reason, Number(r.n)])) },+ spend7d: { knownUsd: Number(counts?.known_usd ?? 0), unpricedCalls: Number(counts?.unpriced ?? 0),+ incompleteRecords: Number(counts?.incomplete ?? 0) },+ };+ } catch (error) {+ if (isUndefinedTableError(error)) return EMPTY;+ throw error;+ }+}++/** One line for doctor/advisor: 24 h usage against the limit, the largest writer's share, 7-day outcomes and spend. */+export function describeChronicleActivity(stats: ChronicleLedgerStats, dailyLimit: number): string {+ const top = stats.principals24h[0];+ const share = top ? `; largest writer ${top.principal} used ${Math.round((top.calls / dailyLimit) * 100)}% of the daily limit` : '';+ const reasons = Object.entries(stats.last7d.reasons).slice(0, 4).map(([r, n]) => `${r} ${n}`).join(', ');+ const usd = `$${stats.spend7d.knownUsd.toFixed(2)} known spend`;+ const unpriced = stats.spend7d.unpricedCalls > 0 ? ` + ${stats.spend7d.unpricedCalls} unpriced call(s)` : '';+ const incomplete = stats.spend7d.incompleteRecords > 0 ? ` + ${stats.spend7d.incompleteRecords} call(s) with no cost record` : '';+ return `Last 24 h: ${stats.autoCalls24h} of ${dailyLimit} automatic extraction calls${share}. ` ++ `Last 7 days: ${stats.last7d.extracted} extracted, ${stats.last7d.failed} failed, ${stats.last7d.skipped} skipped` ++ `${reasons ? ` (${reasons})` : ''}; ${usd}${unpriced}${incomplete}. ${stats.pending} page(s) pending.`;+}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex d1d979ea06..c009777886 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -72,6 +72,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['child_table_orphans','chronicle_projection_health','auto_chronicle',+ 'auto_chronicle_default_on',+ 'chronicle_config_invalid','fact_take_vectors','code_chunk_metadata','content_hash_duplicates',diff --git a/test/auto-chronicle-no-effect-5876.test.ts b/test/auto-chronicle-no-effect-5876.test.tsdeleted file mode 100644index a3c5203b4a..0000000000--- a/test/auto-chronicle-no-effect-5876.test.ts+++ /dev/null@@ -1,55 +0,0 @@-/**- * #5876 (honest half): `auto_chronicle=true` has no reader in this version.- *- * Protects: the chronicle advisor no longer tells users to enable- * auto_chronicle, and both the advisor and doctor say plainly that- * `auto_chronicle=true` currently has no effect, naming the manual sweep.- * Fails when: the coverage-gap finding recommends enabling the dead setting,- * or a brain with it on gets no advisor/doctor signal.- * Seams: none; in-memory PGLite.- */-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { collectChronicle } from '../src/core/advisor/collect-chronicle.ts';-import type { AdvisorContext } from '../src/core/advisor/types.ts';-import { autoChronicleEntry } from '../src/commands/doctor/checks/auto-chronicle.ts';-import type { DoctorContext } from '../src/commands/doctor/context.ts';-import { categorizeCheck } from '../src/core/doctor-categories.ts';-import type { Check } from '../src/commands/doctor.ts';--let engine: PGLiteEngine;-const advisorCtx = () => ({ engine, remote: false } as unknown as AdvisorContext);-const doctorCtx = () => ({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext);--beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);-afterAll(async () => { await engine.disconnect(); });-beforeEach(async () => { await engine.unsetConfig('auto_chronicle'); });--describe('advisor', () => {- test('the coverage gap names only the sweep, never the dead setting', async () => {- await engine.putPage('meetings/2026-04-03', { type: 'meeting', title: 'Weekly sync', compiled_truth: 'x'.repeat(120) });- const gap = (await collectChronicle.collect(advisorCtx())).find(f => f.id === 'chronicle_coverage_gap')!;- expect(gap.detail).not.toContain('auto_chronicle');- });-- test('auto_chronicle=true is reported as having no effect', async () => {- expect((await collectChronicle.collect(advisorCtx())).some(f => f.id === 'auto_chronicle_no_effect')).toBe(false);- await engine.setConfig('auto_chronicle', 'true');- const finding = (await collectChronicle.collect(advisorCtx())).find(f => f.id === 'auto_chronicle_no_effect')!;- expect(finding).toMatchObject({ severity: 'warn', title: 'auto_chronicle=true currently has no effect' });- expect(finding.fix.command_argv).toEqual(['gbrain', 'chronicle-backfill', '--dry-run']);- });-});--describe('doctor', () => {- test('auto_chronicle check: ok when off, warn with code and fix when on', async () => {- expect(categorizeCheck('auto_chronicle')).toBe('brain');- const [off] = await autoChronicleEntry.run(doctorCtx()) as Check[];- expect(off).toMatchObject({ name: 'auto_chronicle', status: 'ok' });- await engine.setConfig('auto_chronicle', 'true');- const [on] = await autoChronicleEntry.run(doctorCtx()) as Check[];- expect(on).toMatchObject({ name: 'auto_chronicle', status: 'warn', details: { code: 'auto_chronicle_no_effect',- fix: 'gbrain chronicle-backfill --dry-run', docs: 'docs/guides/troubleshooting.md#auto_chronicle-has-no-effect' } });- expect(on.message).toContain('currently has no effect');- });-});diff --git a/test/auto-chronicle-surfaces-5876.test.ts b/test/auto-chronicle-surfaces-5876.test.tsnew file mode 100644index 0000000000..d8bb0ce306--- /dev/null+++ b/test/auto-chronicle-surfaces-5876.test.ts@@ -0,0 +1,170 @@+/**+ * #5876 (T11): doctor `auto_chronicle` and the chronicle advisor report automatic extraction.+ *+ * Protects: the wave-8 "has no effect" text is gone; off-by-choice is ok/info (disabled_by_choice);+ * an invalid setting or chronicle.* value warns with a fix; pending pages with no chat provider warn;+ * failures warn with the reason's fix; otherwise the check reports 24 h use of the daily limit, the+ * largest writer's share and 7-day spend (priced dollars and unpriced calls apart); the default-on+ * notice stays visible (doctor info + advisor ask_user) until `config set auto_chronicle` answers it,+ * even after the post-upgrade banner was stamped (swap-only upgrade).+ * Fails when: a surface reverts to the no-op text, mislabels a by-choice state as a problem, loses+ * the spend/share numbers, or the default-on notice clears without an explicit answer.+ * Seams: gateway chat transport/unconfigure test seams; TEMPORARY ledger stub (Lane 1 owns the table).+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { collectChronicle } from '../src/core/advisor/collect-chronicle.ts';+import type { AdvisorContext } from '../src/core/advisor/types.ts';+import { autoChronicleEntry } from '../src/commands/doctor/checks/auto-chronicle.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import type { Check } from '../src/commands/doctor.ts';+import { CHRONICLE_ACK_KEY, CHRONICLE_NOTICE_SHOWN_KEY } from '../src/core/chronicle/config.ts';+import { __setChatTransportForTests, __unconfigureGatewayForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { createChronicleLedgerStub, insertChronicleLedgerRow } from './helpers/chronicle-ledger-stub.ts';++let engine: PGLiteEngine;+const advisorCtx = () => ({ engine, remote: false, now: new Date('2026-10-04T12:00:00Z') } as unknown as AdvisorContext);+const doctorCtx = () => ({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext);+const doctor = async () => (await autoChronicleEntry.run(doctorCtx())) as Check[];+const byName = (checks: Check[], name: string) => checks.find((c) => c.name === name)!;+const withChat = () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } } as never);+ __setChatTransportForTests(async () => { throw new Error('doctor and advisor must not call the provider'); });+};++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await createChronicleLedgerStub(engine);+}, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ for (const k of ['auto_chronicle', CHRONICLE_ACK_KEY, CHRONICLE_NOTICE_SHOWN_KEY, 'chronicle.auto_daily_limit']) await engine.unsetConfig(k);+ await engine.executeRaw('DELETE FROM chronicle_page_state');+ __unconfigureGatewayForTests();+});+afterEach(() => { __setChatTransportForTests(null); resetGateway(); });++describe('doctor auto_chronicle', () => {+ test('default on, fresh brain, no provider: ok/info, no stale no-op text, default-on notice with both answers', async () => {+ const checks = await doctor();+ const main = byName(checks, 'auto_chronicle');+ expect(main.status).toBe('ok');+ expect(main.message).toContain('auto_chronicle is on (default)');+ expect(main.message).toContain('No chat provider is configured');+ expect(main.message).not.toContain('no effect');+ expect(main.details).toMatchObject({ severity: 'info', readiness: 'missing', daily_limit: 200, ledger_available: true });+ const notice = byName(checks, 'auto_chronicle_default_on');+ expect(notice).toMatchObject({ status: 'ok', details: { code: 'auto_chronicle_default_on', severity: 'info', ask_user: true } });+ expect(notice.message).toContain('gbrain config set auto_chronicle false');+ expect(notice.message).toContain('$50.00 per day');+ for (const c of checks) expect(categorizeCheck(c.name)).toBe('brain');+ });++ test('off by choice is ok + info + disabled_by_choice, with no default-on notice', async () => {+ await engine.setConfig('auto_chronicle', 'false');+ const checks = await doctor();+ expect(byName(checks, 'auto_chronicle')).toMatchObject({ status: 'ok',+ details: { enabled: false, severity: 'info', readiness: 'disabled_by_choice' } });+ expect(byName(checks, 'auto_chronicle_default_on').details).toBeUndefined();+ });++ test('an invalid word reads as off and warns with a fix', async () => {+ await engine.setConfig('auto_chronicle', 'flase');+ const main = byName(await doctor(), 'auto_chronicle');+ expect(main).toMatchObject({ status: 'warn', details: { code: 'auto_chronicle_invalid', enabled: false,+ fix: { argv: ['gbrain', 'config', 'set', 'auto_chronicle', 'true'], consent: ['paid'] } } });+ });++ test('a malformed chronicle.* row falls back and warns with the set command', async () => {+ await engine.setConfig('chronicle.auto_daily_limit', '-3');+ const check = byName(await doctor(), 'chronicle_config_invalid');+ expect(check).toMatchObject({ status: 'warn', details: { code: 'chronicle_config_invalid',+ fix: { argv: ['gbrain', 'config', 'set', 'chronicle.auto_daily_limit', '200'] } } });+ });++ test('pending pages and no chat provider warn with the credentials fix', async () => {+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'pending' });+ const main = byName(await doctor(), 'auto_chronicle');+ expect(main).toMatchObject({ status: 'warn', details: { code: 'judge_llm_unavailable', pending: 1,+ fix: { actor: 'user', consent: ['credentials'] } } });+ });++ test('activity: 24 h use, largest writer share, 7-day spend with unpriced calls apart, run-now command', async () => {+ withChat();+ await engine.setConfig('chronicle.auto_daily_limit', '10');+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'extracted', principal: ['oauth_client', 'client-a'], cost: 0.01 });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/b', state: 'extracted', principal: ['oauth_client', 'client-a'], cost: 0.02 });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/c', state: 'extracted', principal: ['local_cli', 'w1'], unpriced: true });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/old', state: 'extracted', cost: 5, hoursAgo: 24 * 9 });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/d', state: 'skipped', reason: 'history' });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/e', state: 'pending' });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/f', state: 'extracted', trigger: 'backfill', cost: 1 });+ const main = byName(await doctor(), 'auto_chronicle');+ expect(main.status).toBe('ok');+ expect(main.message).toContain('Last 24 h: 3 of 10 automatic extraction calls; largest writer oauth_client:client-a used 20% of the daily limit');+ expect(main.message).toContain('3 extracted, 0 failed, 1 skipped (history 1); $0.03 known spend + 1 unpriced call(s)');+ expect(main.message).toContain('gbrain dream --phase chronicle');+ expect(main.details).toMatchObject({ readiness: 'ok', auto_calls_24h: 3,+ spend_7d: { knownUsd: 0.03, unpricedCalls: 1, incompleteRecords: 0 } });+ });++ test('failures warn with the reason fix (no_pricing names the pricing command)', async () => {+ withChat();+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'failed', reason: 'no_pricing' });+ const main = byName(await doctor(), 'auto_chronicle');+ expect(main).toMatchObject({ status: 'warn', details: { code: 'no_pricing', fix: { actor: 'agent' } } });+ expect((main.details!.fix as { argv: string[] }).argv.slice(0, 3)).toEqual(['gbrain', 'pricing', 'set']);+ });++ test('the default-on notice survives a stamped banner and clears on an explicit answer', async () => {+ await engine.setConfig('auto_chronicle', 'true');+ await engine.setConfig(CHRONICLE_NOTICE_SHOWN_KEY, '2026-10-04T00:00:00Z');+ expect(byName(await doctor(), 'auto_chronicle_default_on').details).toMatchObject({ code: 'auto_chronicle_default_on' });+ await engine.setConfig(CHRONICLE_ACK_KEY, '2026-10-04T00:00:00Z');+ expect(byName(await doctor(), 'auto_chronicle_default_on').details).toBeUndefined();+ });+});++describe('advisor', () => {+ test('default on: ask_user default-on finding with the keep command and no stale no-op finding', async () => {+ const findings = await collectChronicle.collect(advisorCtx());+ expect(findings.some((f) => f.id === 'auto_chronicle_no_effect')).toBe(false);+ const f = findings.find((x) => x.id === 'auto_chronicle_default_on')!;+ expect(f).toMatchObject({ severity: 'info', ask_user: true, fix: { command_argv: ['gbrain', 'config', 'set', 'auto_chronicle', 'true'] } });+ expect(f.detail).toContain('gbrain config set auto_chronicle false');+ });++ test('swap-only upgrade: the stamped banner does not clear the finding; an explicit set does', async () => {+ await engine.setConfig(CHRONICLE_NOTICE_SHOWN_KEY, '2026-10-04T00:00:00Z');+ expect((await collectChronicle.collect(advisorCtx())).some((f) => f.id === 'auto_chronicle_default_on')).toBe(true);+ await engine.setConfig('auto_chronicle', 'true');+ await engine.setConfig(CHRONICLE_ACK_KEY, '2026-10-04T00:00:00Z');+ expect((await collectChronicle.collect(advisorCtx())).some((f) => f.id === 'auto_chronicle_default_on')).toBe(false);+ });++ test('off by choice: no automatic-extraction findings', async () => {+ await engine.setConfig('auto_chronicle', 'false');+ const ids = (await collectChronicle.collect(advisorCtx())).map((f) => f.id);+ expect(ids.filter((id) => id.startsWith('auto_chronicle') || id.startsWith('chronicle_') && id !== 'chronicle_coverage_gap')).toEqual([]);+ });++ test('daily-limit skips point at a scoped, previewed backfill; the coverage gap is scoped too', async () => {+ await engine.setConfig(CHRONICLE_ACK_KEY, 'x');+ await engine.putPage('meetings/2026-10-01', { type: 'meeting', title: 'Weekly sync', compiled_truth: 'x'.repeat(120) });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'skipped', reason: 'daily_limit' });+ const findings = await collectChronicle.collect(advisorCtx());+ expect(findings.find((f) => f.id === 'chronicle_daily_limit')).toMatchObject({ ask_user: true,+ fix: { command_argv: ['gbrain', 'chronicle-backfill', '--since', '2026-09-27', '--limit', '50', '--dry-run'] } });+ expect(findings.find((f) => f.id === 'chronicle_coverage_gap')?.fix.command_argv).toEqual(+ ['gbrain', 'chronicle-backfill', '--since', '2026-09-04', '--limit', '50', '--dry-run']);+ });++ test('pending pages with no chat provider warn', async () => {+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'pending' });+ expect((await collectChronicle.collect(advisorCtx())).find((f) => f.id === 'chronicle_chat_unavailable'))+ .toMatchObject({ severity: 'warn', ask_user: true });+ });+});diff --git a/test/helpers/chronicle-ledger-stub.ts b/test/helpers/chronicle-ledger-stub.tsnew file mode 100644index 0000000000..bbdb7c9aa4--- /dev/null+++ b/test/helpers/chronicle-ledger-stub.ts@@ -0,0 +1,30 @@+/**+ * TEMPORARY (Lane 2 of the #5876 wave): a stand-in for Lane 1's `chronicle_page_state` migration,+ * with the columns E1 of the plan names. The integrator deletes this helper once the real+ * migration lands and the surface tests run against it.+ */+import type { BrainEngine } from '../../src/core/engine.ts';++export async function createChronicleLedgerStub(engine: BrainEngine): Promise<void> {+ await engine.executeRaw(`CREATE TABLE IF NOT EXISTS chronicle_page_state (+ source_id text NOT NULL, page_id integer NOT NULL, content_hash text NOT NULL, extractor_version integer NOT NULL DEFAULT 1,+ slug text NOT NULL, state text NOT NULL, reason text, trigger text NOT NULL,+ principal_kind text, principal_id text, request_id uuid, no_extract boolean NOT NULL DEFAULT false,+ attempts integer NOT NULL DEFAULT 0, next_attempt_at timestamptz, cost_usd numeric, unpriced boolean NOT NULL DEFAULT false,+ event_slugs text[] NOT NULL DEFAULT '{}', created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, page_id, content_hash, extractor_version))`);+}++export interface LedgerRowStub {+ slug: string; state: string; reason?: string; trigger?: string; principal?: [string, string];+ cost?: number | null; unpriced?: boolean; hoursAgo?: number;+}++let pageSeq = 1;+export async function insertChronicleLedgerRow(engine: BrainEngine, row: LedgerRowStub): Promise<void> {+ await engine.executeRaw(`INSERT INTO chronicle_page_state+ (source_id, page_id, content_hash, slug, state, reason, trigger, principal_kind, principal_id, cost_usd, unpriced, updated_at)+ VALUES ('default', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now() - ($11 || ' hours')::interval)`,+ [pageSeq++, `h${pageSeq}`, row.slug, row.state, row.reason ?? null, row.trigger ?? 'auto', row.principal?.[0] ?? null,+ row.principal?.[1] ?? null, row.cost ?? null, row.unpriced ?? false, String(row.hoursAgo ?? 1)]);+}