Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(chronicle): align surfaces with the lane-core ledger contract (#5876)
garrytanb3cdec1cbee4
diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.mdindex a3f38b250b..3370c7842c 100644--- a/docs/guides/life-chronicle.md+++ b/docs/guides/life-chronicle.md@@ -138,18 +138,22 @@ brackets are filled in with real values on each surface.| `not_yet_happened` | decision | The calendar event has not ended yet; it is picked up automatically after its end time, with no edit needed. | — | — | — || `too_short` | decision | The page body is under 80 characters, too short to hold events. | — | — | — || `dream_generated` | decision | Dream-generated pages are never mined for events. | — | — | — |-| `decision_error` | decision | The extraction decision failed for this write; the write itself committed. | `gbrain doctor --json` | agent | — |-| `no_write_decision` | execution | This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid |+| `no_write_decision` | discovery | This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid |+| `not_chronicle_shaped` | decision | The page is no longer a meeting, conversation or calendar page, so the events extracted from it were retired. | — | — | — || `superseded` | execution | A newer revision replaced this content before extraction ran; the newer revision carries its own decision. | — | — | — |-| `daily_limit` | execution | The automatic daily limit (chronicle.auto_daily_limit = 200 calls per rolling 24 hours) was used up. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid |+| `daily_limit` | execution | The automatic daily limit (chronicle.auto_daily_limit = 200 calls per rolling 24 hours) is used up; pending pages wait for a free slot. | `gbrain config set chronicle.auto_daily_limit 400` | agent | paid || `judge_llm_unavailable` | execution | No chat provider is configured on the brain host, so extraction cannot run. | — | user | credentials || `no_pricing` | execution | chronicle.job_budget_usd was set explicitly, and gbrain has no price for <provider:model>, so the cap cannot be enforced. | `gbrain pricing set <provider:model> --input <usd-per-1M-input-tokens> --output <usd-per-1M-output-tokens> --source <pricing-page-url>` | agent | — |-| `job_budget_exceeded` | execution | The extraction call cost more than chronicle.job_budget_usd allows for one page. | `gbrain config set chronicle.job_budget_usd 0.50` | agent | paid |-| `chat_error` | execution | The chat provider returned an error; the page retries with backoff. | — | provider | — |+| `budget_exhausted` | execution | The extraction call cost more than chronicle.job_budget_usd allows for one page. | `gbrain config set chronicle.job_budget_usd 0.50` | agent | paid |+| `judge_chat_error` | execution | The chat provider returned an error; the page retries with backoff. | — | provider | — || `judge_truncated` | execution | The extraction output hit chronicle.judge_max_tokens and was cut off, so nothing was written. | `gbrain config set chronicle.judge_max_tokens 8000` | agent | paid |-| `malformed_proposal` | execution | The extraction output was not valid event JSON, so nothing was written; the page is tried again when its content changes. | — | — | — |+| `judge_parse_failed` | execution | The extraction output had no parseable JSON array, so nothing was written; the page retries on a later run. | — | — | — |+| `malformed_proposal` | execution | A proposed event failed validation, so the whole batch was rejected and nothing was written; the page retries on a later run. | — | — | — |+| `publish_error` | execution | Publishing the events failed; nothing from this attempt replaced the previous events, and the page retries on a later run. | — | — | — || `judge_refused` | execution | The chat model refused or filtered the page; no events were written. | — | — | — |-| `page_not_found` | execution | The page was deleted or renamed before extraction ran. | — | — | — |+| `page_missing` | execution | The page was deleted before extraction ran. | — | — | — |+| `no_events` | execution | Extraction read the page and found no events. | — | — | — |+| `no_chat_provider` | phase | No chat provider is configured on the brain host, so the chronicle phase made no calls. | — | user | credentials |<!-- chronicle-reasons:end -->Don't hand-write `life/events/` pages: extraction owns them and retires eventsdiff --git a/src/commands/doctor/checks/auto-chronicle.ts b/src/commands/doctor/checks/auto-chronicle.tsindex de55353ae8..c86eb19832 100644--- a/src/commands/doctor/checks/auto-chronicle.ts+++ b/src/commands/doctor/checks/auto-chronicle.ts@@ -12,12 +12,11 @@ import {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 { CHRONICLE_REASONS, CHRONICLE_RUN_NOW_ARGV, 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/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);@@ -60,9 +59,8 @@ async function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {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');+ chat_available: chat, run_now: [...CHRONICLE_RUN_NOW_ARGV] };+ const failures = Object.entries(stats.last7d.failedReasons).filter(([reason]) => reason in CHRONICLE_REASONS);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} ` +@@ -78,7 +76,10 @@ async function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {`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 limited = stats.pending > 0 && stats.autoCalls24h >= settings.autoDailyLimit+ ? ' The daily limit is used up, so pending pages wait for a free slot; raising chronicle.auto_daily_limit needs the user\'s agreement.' : '';+ const runNow = stats.pending > 0 && !limited+ ? ` Pending pages run in the next autopilot cycle; to run them now: \`${command(CHRONICLE_RUN_NOW_ARGV)}\` (paid).` : limited;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}`,diff --git a/src/core/advisor/collect-chronicle.ts b/src/core/advisor/collect-chronicle.tsindex 7ef4a75104..cd084425a5 100644--- a/src/core/advisor/collect-chronicle.ts+++ b/src/core/advisor/collect-chronicle.ts@@ -68,8 +68,7 @@ async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFindingask_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');+ const failed = Object.entries(stats.last7d.failedReasons).find(([reason]) => reason in CHRONICLE_REASONS);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];@@ -84,14 +83,14 @@ async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFindingask_user: fix ? fix.consent.length > 0 || fix.actor !== 'agent' : false,});}- const limited = stats.last7d.reasons.daily_limit ?? 0;- if (limited > 0) {+ if (stats.pending > 0 && stats.autoCalls24h >= settings.autoDailyLimit) {+ const fix = CHRONICLE_REASONS.daily_limit.fix({ dailyLimit: settings.autoDailyLimit, since: daysAgo(ctx.now ?? new Date(), 7) });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 }) },+ title: `The automatic daily limit (${settings.autoDailyLimit} calls) is used up; ${stats.pending} page(s) wait for a free slot`,+ detail: `${fix.why} ${activity}`,+ fix: { command_argv: fix.argv ?? null },collector: 'chronicle',ask_user: true,});diff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.tsindex a79d0af4f1..800a105ab6 100644--- a/src/core/chronicle/config.ts+++ b/src/core/chronicle/config.ts@@ -9,6 +9,8 @@ export const AUTO_CHRONICLE_KEEP_ARGV = ['gbrain', 'config', 'set', 'auto_chroniexport 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';+/** Written by the ledger migration: automatic extraction covers revisions decided after it. */+export const CHRONICLE_ACTIVATED_AT_KEY = 'chronicle.activated_at';const TRUE_WORDS = ['true', '1', 'yes', 'on'];const FALSE_WORDS = ['false', '0', 'no', 'off'];@@ -83,6 +85,7 @@ export type ChronicleNumericKey = keyof typeof CHRONICLE_NUMERIC_KEYS;export const CHRONICLE_CONFIG_KEYS: readonly string[] = [...Object.keys(CHRONICLE_NUMERIC_KEYS),'chronicle.tz',+ CHRONICLE_ACTIVATED_AT_KEY,CHRONICLE_ACK_KEY,CHRONICLE_NOTICE_SHOWN_KEY,];diff --git a/src/core/chronicle/ledger-stats.ts b/src/core/chronicle/ledger-stats.tsindex 5b723435d0..f4c0322f67 100644--- a/src/core/chronicle/ledger-stats.ts+++ b/src/core/chronicle/ledger-stats.ts@@ -11,53 +11,62 @@ export interface ChronicleLedgerStats {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 rows decided in the last 7 days: by state, by skip/failure reason, and failure reasons alone. */+ last7d: { extracted: number; failed: number; skipped: number; reasons: Record<string, number>; failedReasons: 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: {} },+ last7d: { extracted: 0, failed: 0, skipped: 0, reasons: {}, failedReasons: {} },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;+ const [counts] = await engine.executeRaw<{ pending: number; extracted: number; failed: number; skipped: number;known_usd: number | null; unpriced: number; incomplete: number }>(`SELECTcount(*) 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')+ count(*) FILTER (WHERE NOT unpriced AND cost_usd IS NULL AND state IN ('extracted','failed') AND attempts > 0AND updated_at > now() - interval '7 days')::int AS incompleteFROM 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+ const reasons = await engine.executeRaw<{ state: string; reason: string; n: number }>(+ `SELECT state, reason, count(*)::int AS n FROM chronicle_page_stateWHERE 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`,+ GROUP BY state, reason ORDER BY n DESC, reason`,+ );+ const tally = (rows: typeof reasons) => rows.reduce<Record<string, number>>((acc, r) => {+ acc[r.reason] = (acc[r.reason] ?? 0) + Number(r.n);+ return acc;+ }, {});+ // One reservation row per automatic judge call (retries included): the daily limit's own count.+ const [calls] = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM chronicle_judge_reservations WHERE reserved_at > now() - interval '24 hours'`,);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'+ `SELECT coalesce(l.principal_kind, 'unattributed') || coalesce(':' || l.principal_id, '') AS principal, count(*)::int AS calls+ FROM chronicle_judge_reservations r+ LEFT JOIN chronicle_page_state l ON l.source_id = r.source_id AND l.page_id = r.page_id+ AND l.content_hash = r.content_hash AND l.trigger = 'auto'+ WHERE r.reserved_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),+ autoCalls24h: Number(calls?.n ?? 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)])) },+ reasons: tally(reasons), failedReasons: tally(reasons.filter((r) => r.state === 'failed')) },spend7d: { knownUsd: Number(counts?.known_usd ?? 0), unpricedCalls: Number(counts?.unpriced ?? 0),incompleteRecords: Number(counts?.incomplete ?? 0) },};diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 8286130b12..0adfba190c 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -18,8 +18,12 @@ export interface ChronicleAction {inputs?: Array<{ name: string; how: string }>;}-/** `decision`: decided when the page was written (receipt). `execution`: decided when the chronicle phase ran. */-export type ChronicleStage = 'decision' | 'execution';+/**+ * Where a code is decided (same stages as Lane 1's `src/core/chronicle/contract.ts`): `decision` when+ * the page is written (receipt), `discovery` when the phase finds the page, `execution` when it judges+ * the page, `phase` for a whole run.+ */+export type ChronicleStage = 'decision' | 'discovery' | 'execution' | 'phase';export interface ChronicleReasonContext {/** Omitted on brain-wide surfaces (doctor, advisor): the pointer then covers every source. */@@ -44,6 +48,9 @@ export function chronicleBackfillArgv(opts: { sourceId?: string; since: string;'--since', opts.since, '--limit', String(opts.limit ?? 50), ...(opts.dryRun ? ['--dry-run'] : [])];}+/** The run-now pointer: the chronicle phase in the foreground (paid). */+export const CHRONICLE_RUN_NOW_ARGV = ['gbrain', 'dream', '--phase', 'chronicle'] as const;+const backfill = (actor: ChronicleActor, why: string) => (ctx: ChronicleReasonContext): ChronicleAction => ({argv: chronicleBackfillArgv({ sourceId: ctx.sourceId, since: ctx.since, dryRun: false }),preview_argv: chronicleBackfillArgv({ sourceId: ctx.sourceId, since: ctx.since, dryRun: true }),@@ -79,18 +86,18 @@ export const CHRONICLE_REASONS = {meaning: () => 'The page body is under 80 characters, too short to hold events.' },dream_generated: { stage: 'decision',meaning: () => 'Dream-generated pages are never mined for events.' },- decision_error: { stage: 'decision',- meaning: () => 'The extraction decision failed for this write; the write itself committed.',- fix: () => ({ argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent',- why: 'Read the auto_chronicle check for the cause, then backfill the page if the user agrees.', requires_exclusive: false }) },- no_write_decision: { stage: 'execution',+ no_write_decision: { stage: 'discovery',meaning: () => 'This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it.',fix: backfill('agent', FIX_BY_BACKFILL) },+ not_chronicle_shaped: { stage: 'decision',+ meaning: () => 'The page is no longer a meeting, conversation or calendar page, so the events extracted from it were retired.' },superseded: { stage: 'execution',meaning: () => 'A newer revision replaced this content before extraction ran; the newer revision carries its own decision.' },daily_limit: { stage: 'execution',- meaning: (ctx) => `The automatic daily limit (chronicle.auto_daily_limit = ${ctx.dailyLimit ?? 200} calls per rolling 24 hours) was used up.`,- fix: backfill('agent', FIX_BY_BACKFILL) },+ meaning: (ctx) => `The automatic daily limit (chronicle.auto_daily_limit = ${ctx.dailyLimit ?? 200} calls per rolling 24 hours) is used up; pending pages wait for a free slot.`,+ fix: (ctx) => ({ argv: ['gbrain', 'config', 'set', 'chronicle.auto_daily_limit', String((ctx.dailyLimit ?? 200) * 2)],+ consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: 'Pending pages run on their own as slots free up. Raise the limit only if the user agrees to more paid calls per day.' }) },judge_llm_unavailable: { stage: 'execution',meaning: () => 'No chat provider is configured on the brain host, so extraction cannot run.',fix: () => ({ consent: ['credentials'], actor: 'user', requires_exclusive: false,@@ -103,11 +110,11 @@ export const CHRONICLE_REASONS = {inputs: [{ name: 'usd-per-1M-input-tokens', how: 'the provider pricing page' },{ name: 'usd-per-1M-output-tokens', how: 'the provider pricing page' },{ name: 'pricing-page-url', how: 'the URL you read the price from' }] }) },- job_budget_exceeded: { stage: 'execution',+ budget_exhausted: { stage: 'execution',meaning: () => 'The extraction call cost more than chronicle.job_budget_usd allows for one page.',fix: () => ({ argv: ['gbrain', 'config', 'set', 'chronicle.job_budget_usd', '0.50'], consent: ['paid'], actor: 'agent',requires_exclusive: false, why: 'Raising the per-page cap lets long pages finish; ask the user before raising spend.' }) },- chat_error: { stage: 'execution',+ judge_chat_error: { stage: 'execution',meaning: () => 'The chat provider returned an error; the page retries with backoff.',fix: () => ({ consent: [], actor: 'provider', requires_exclusive: false,why: 'Wait for the retry; if it keeps failing, check the provider status and key.' }) },@@ -115,12 +122,22 @@ export const CHRONICLE_REASONS = {meaning: () => 'The extraction output hit chronicle.judge_max_tokens and was cut off, so nothing was written.',fix: () => ({ argv: ['gbrain', 'config', 'set', 'chronicle.judge_max_tokens', '8000'], consent: ['paid'], actor: 'agent',requires_exclusive: false, why: 'A higher output cap lets event-dense pages finish; ask the user before raising spend.' }) },+ judge_parse_failed: { stage: 'execution',+ meaning: () => 'The extraction output had no parseable JSON array, so nothing was written; the page retries on a later run.' },malformed_proposal: { stage: 'execution',- meaning: () => 'The extraction output was not valid event JSON, so nothing was written; the page is tried again when its content changes.' },+ meaning: () => 'A proposed event failed validation, so the whole batch was rejected and nothing was written; the page retries on a later run.' },+ publish_error: { stage: 'execution',+ meaning: () => 'Publishing the events failed; nothing from this attempt replaced the previous events, and the page retries on a later run.' },judge_refused: { stage: 'execution',meaning: () => 'The chat model refused or filtered the page; no events were written.' },- page_not_found: { stage: 'execution',- meaning: () => 'The page was deleted or renamed before extraction ran.' },+ page_missing: { stage: 'execution',+ meaning: () => 'The page was deleted before extraction ran.' },+ no_events: { stage: 'execution',+ meaning: () => 'Extraction read the page and found no events.' },+ no_chat_provider: { stage: 'phase',+ meaning: () => 'No chat provider is configured on the brain host, so the chronicle phase made no calls.',+ fix: () => ({ consent: ['credentials'], actor: 'user', requires_exclusive: false,+ why: 'Ask the user to configure a chat provider key on the brain host (see docs/ai-providers/); pending pages run on the next cycle.' }) },} as const satisfies Record<string, ChronicleReason>;export type ChronicleReasonCode = keyof typeof CHRONICLE_REASONS;diff --git a/test/auto-chronicle-surfaces-5876.test.ts b/test/auto-chronicle-surfaces-5876.test.tsindex d8bb0ce306..4e06253a33 100644--- a/test/auto-chronicle-surfaces-5876.test.ts+++ b/test/auto-chronicle-surfaces-5876.test.ts@@ -43,6 +43,7 @@ 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');+ await engine.executeRaw('DELETE FROM chronicle_judge_reservations');__unconfigureGatewayForTests();});afterEach(() => { __setChatTransportForTests(null); resetGateway(); });@@ -151,15 +152,29 @@ describe('advisor', () => {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 () => {+ test('a used-up daily limit with pages waiting asks before raising it; the coverage gap points at a scoped preview', async () => {+ withChat();await engine.setConfig(CHRONICLE_ACK_KEY, 'x');+ await engine.setConfig('chronicle.auto_daily_limit', '2');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' });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'extracted', cost: 0.01 });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/b', state: 'extracted', cost: 0.01 });+ await insertChronicleLedgerRow(engine, { slug: 'meetings/c', state: 'pending' });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'] } });+ fix: { command_argv: ['gbrain', 'config', 'set', 'chronicle.auto_daily_limit', '4'] } });expect(findings.find((f) => f.id === 'chronicle_coverage_gap')?.fix.command_argv).toEqual(['gbrain', 'chronicle-backfill', '--since', '2026-09-04', '--limit', '50', '--dry-run']);+ const main = byName(await doctor(), 'auto_chronicle');+ expect(main.message).toContain('The daily limit is used up, so pending pages wait');+ expect(main.message).not.toContain('to run them now');+ });++ test('a skipped execution reason alone is not reported as a failure', async () => {+ withChat();+ await insertChronicleLedgerRow(engine, { slug: 'meetings/a', state: 'skipped', reason: 'superseded' });+ expect((await collectChronicle.collect(advisorCtx())).some((f) => f.id === 'chronicle_extraction_failing')).toBe(false);+ expect(byName(await doctor(), 'auto_chronicle').status).toBe('ok');});test('pending pages with no chat provider warn', async () => {diff --git a/test/helpers/chronicle-ledger-stub.ts b/test/helpers/chronicle-ledger-stub.tsindex bbdb7c9aa4..fff2799833 100644--- a/test/helpers/chronicle-ledger-stub.ts+++ b/test/helpers/chronicle-ledger-stub.ts@@ -1,30 +1,45 @@/**- * 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.+ * TEMPORARY (Lane 2 of the #5876 wave): Lane 1's `chronicle_page_state` and+ * `chronicle_judge_reservations` DDL (capy/chronicle-lane-core 95e8d6d04, migration+ * `chronicle_page_state`) minus the foreign keys, so the surface tests run before that migration+ * merges. The integrator deletes this helper once the migration is on the branch.*/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(),+ source_id TEXT NOT NULL, page_id INTEGER NOT NULL, content_hash TEXT NOT NULL, extractor_version INTEGER NOT NULL,+ slug TEXT NOT NULL, state TEXT NOT NULL CHECK (state IN ('pending','skipped','extracted','failed')), reason TEXT,+ trigger TEXT NOT NULL CHECK (trigger IN ('auto','backfill')), principal_kind TEXT, principal_id TEXT, request_id UUID,+ no_extract BOOLEAN NOT NULL DEFAULT false, attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), next_attempt_at TIMESTAMPTZ,+ cost_usd NUMERIC, unpriced BOOLEAN NOT NULL DEFAULT false, event_slugs TEXT[] NOT NULL DEFAULT '{}',+ decided_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (source_id, page_id, content_hash, extractor_version))`);+ await engine.executeRaw(`CREATE TABLE IF NOT EXISTS chronicle_judge_reservations (+ id BIGSERIAL PRIMARY KEY, reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(), source_id TEXT NOT NULL,+ page_id INTEGER NOT NULL, content_hash TEXT NOT NULL)`);}export interface LedgerRowStub {- slug: string; state: string; reason?: string; trigger?: string; principal?: [string, string];- cost?: number | null; unpriced?: boolean; hoursAgo?: number;+ slug: string; state: 'pending' | 'skipped' | 'extracted' | 'failed'; reason?: string; trigger?: 'auto' | 'backfill';+ principal?: [string, string]; cost?: number | null; unpriced?: boolean; hoursAgo?: number;}let pageSeq = 1;+/** Judged automatic rows (extracted/failed) also get the reservation the phase takes before each call. */export async function insertChronicleLedgerRow(engine: BrainEngine, row: LedgerRowStub): Promise<void> {+ const pageId = pageSeq++;+ const hash = `h${pageId}`;+ const hoursAgo = String(row.hoursAgo ?? 1);+ const judged = row.state === 'extracted' || row.state === 'failed';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)]);+ (source_id, page_id, content_hash, extractor_version, slug, state, reason, trigger, principal_kind, principal_id,+ attempts, cost_usd, unpriced, updated_at)+ VALUES ('default', $1, $2, 1, $3, $4, $5, $6, $7, $8, $9, $10, $11, now() - ($12 || ' hours')::interval)`,+ [pageId, hash, row.slug, row.state, row.reason ?? null, row.trigger ?? 'auto', row.principal?.[0] ?? null,+ row.principal?.[1] ?? null, judged ? 1 : 0, row.cost ?? null, row.unpriced ?? false, hoursAgo]);+ if (judged && (row.trigger ?? 'auto') === 'auto') {+ await engine.executeRaw(`INSERT INTO chronicle_judge_reservations (reserved_at, source_id, page_id, content_hash)+ VALUES (now() - ($1 || ' hours')::interval, 'default', $2, $3)`, [hoursAgo, pageId, hash]);+ }}