Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: one reason table; ledger receipt delegates to reasons.ts (#5876)
garrytan1ddfb76c002f
diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.mdindex 553ec37a7a..ad00d959df 100644--- a/docs/guides/life-chronicle.md+++ b/docs/guides/life-chronicle.md@@ -140,6 +140,7 @@ brackets are filled in with real values on each surface.| `dream_generated` | decision | Dream-generated pages are never mined for events. | — | — | — || `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 --yes` (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. | — | — | — |+| `already_extracted` | decision | This exact content was already extracted; its events are current, so no new call is made. | — | — | — || `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) 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 |diff --git a/skills/migrations/vNEXT-auto-chronicle.md b/skills/migrations/v0.60.43.0.mdsimilarity index 89%rename from skills/migrations/vNEXT-auto-chronicle.mdrename to skills/migrations/v0.60.43.0.mdindex fbb4cc0800..bc95a8761e 100644--- a/skills/migrations/vNEXT-auto-chronicle.md+++ b/skills/migrations/v0.60.43.0.md@@ -1,7 +1,4 @@-# Upgrade: automatic event extraction is on (auto_chronicle)--<!-- Integrator: rename to skills/migrations/v<this release>.md and add the- schema-migration numbers for the chronicle ledger in step 1. -->+# Upgrade to v0.60.43.0: automatic event extraction is on (auto_chronicle)This release turns automatic event extraction back on, and on by default. Whenthe user saves a meeting, conversation or calendar page, gbrain turns it into@@ -18,8 +15,9 @@ chronicle`, on the user's behalf without asking.```bashgbrain apply-migrations --yes --no-autopilot-install```- It creates the `chronicle_page_state` ledger, the record of which page- content was extracted. It rewrites no existing rows. Restart every+ Schema migration v199 creates the `chronicle_page_state` ledger (the record+ of which page content was extracted) and the `chronicle_judge_reservations`+ table behind the daily limit. It rewrites no existing rows. Restart every`gbrain serve`, autopilot and worker.2. **Relay the cost and ask.** Say to the user, with the real numbers fromdiff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.tsindex 4271e7b9d3..959d6d342f 100644--- a/src/core/chronicle/config.ts+++ b/src/core/chronicle/config.ts@@ -9,14 +9,14 @@ 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. */+/** Stamped by the first write decision or chronicle phase run: 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'];/**- * How a stored `auto_chronicle` value reads (same contract as capy/chronicle-lane-core): unset is on;+ * How a stored `auto_chronicle` value reads: unset is on;* a recognized true/false word is on/off; any other value reads as off and doctor warns* `auto_chronicle_invalid` (fail closed on spend).*/@@ -108,7 +108,6 @@ export function validateChronicleConfigValue(key: string, value: string): stringreturn null;}-/** Field names match capy/chronicle-lane-core's `chronicleSettings`, plus `judgeMaxTokens` and `invalid`. */export interface ChronicleSettings {jobBudgetUsd: number;/** The operator set chronicle.job_budget_usd: an unpriced model then refuses with no_pricing instead of warn-and-run. */@@ -117,7 +116,7 @@ export interface ChronicleSettings {recentDays: number;settleSeconds: number;judgeMaxTokens: number;- /** When the automatic path activated on this brain (written by the ledger migration); null when unset or unreadable. */+ /** When the automatic path activated on this brain (stamped by the first decision or phase run); null when unset or unreadable. */activatedAt: Date | null;/** Stored values outside the valid range; each fell back to its default. */invalid: Array<{ key: ChronicleNumericKey; raw: string; fallback: number }>;diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.tsindex 5f96752994..80b9c744fc 100644--- a/src/core/chronicle/contract.ts+++ b/src/core/chronicle/contract.ts@@ -1,8 +1,8 @@/*** Life Chronicle automatic extraction contract (#5876): the ledger columns,- * the decision and outcome reason codes, the write-receipt hint and the- * `chronicle` cycle-phase result. Doctor, advisor, receipts, docs and tests- * import these names; nothing else spells them.+ * the phase bounds and the `chronicle` cycle-phase result. The reason codes+ * and the `chronicle_backstop` receipt live in reasons.ts (the one table);+ * the config keys and defaults live in config.ts.** Lifecycle:* 1. A coordinated page publication (put_page, capture, edit_page,@@ -19,6 +19,7 @@* trigger='backfill' (exempt from the daily limit and recency rule);* the same phase executes them.*/+import { CHRONICLE_RUN_NOW_ARGV, type ChronicleAction, type ChronicleReasonCode } from './reasons.ts';/** Bump to re-extract every page once (the ledger key includes it). */export const CHRONICLE_EXTRACTOR_VERSION = 1;@@ -38,7 +39,7 @@ export interface ChronicleLedgerRow {extractor_version: number;slug: string;state: ChronicleLedgerState;- /** A `ChronicleReason` (or `no_events` on an extracted row); null on pending/extracted-with-events. */+ /** A `ChronicleReasonCode` from reasons.ts (or `no_events` on an extracted row); null on pending/extracted-with-events. */reason: string | null;trigger: ChronicleTrigger;/** Writer of the decided revision (`persistence_requests.principal_*`); null on unmanaged scans and backfill. */@@ -63,22 +64,8 @@ export interface ChronicleLedgerRow {updated_at: Date | string;}-/** Config keys this subsystem reads (registered under the `chronicle.` prefix). */-export const CHRONICLE_CONFIG = {- enabled: 'auto_chronicle',- jobBudgetUsd: 'chronicle.job_budget_usd',- dailyLimit: 'chronicle.auto_daily_limit',- recentDays: 'chronicle.auto_recent_days',- settleSeconds: 'chronicle.auto_settle_seconds',- /** ISO timestamp the automatic path activated on this brain (stamped by the first write decision or `chronicle` phase run). */- activatedAt: 'chronicle.activated_at',-} as const;-+/** Phase bounds. The config knobs and their defaults live in config.ts (`CHRONICLE_NUMERIC_KEYS`). */export const CHRONICLE_DEFAULTS = {- jobBudgetUsd: 0.25,- dailyLimit: 200,- recentDays: 30,- settleSeconds: 180,/** Items one phase run judges at most (automatic + backfill). */maxItemsPerRun: 50,/** Wall-time bound of one phase run. */@@ -87,52 +74,8 @@ export const CHRONICLE_DEFAULTS = {maxAttempts: 5,} as const;-export const OPT_OUT_COMMAND = 'gbrain config set auto_chronicle false';-export const RUN_NOW_COMMAND = 'gbrain dream --phase chronicle';--/**- * Every reason code a ledger row, receipt or phase result can carry. One- * table: meaning, the exact next command, and whether the agent must ask- * the user first (paid or destructive).- */-export const CHRONICLE_REASONS = {- // ── write-time / discovery skips (state 'skipped') ──- auto_chronicle_off: { stage: 'decision', meaning: 'Automatic extraction is turned off on this brain.', next: 'gbrain config set auto_chronicle true', ask_user: true },- no_extract: { stage: 'decision', meaning: 'The sync ran with --no-extract, so its pages are not extracted automatically.', next: 'gbrain chronicle-backfill --limit 50 --dry-run', ask_user: true },- slug_bound_client: { stage: 'decision', meaning: 'A confined writer (slug-bound, delegated or restricted namespace) cannot trigger paid extraction.', next: 'gbrain chronicle-backfill --limit 50 --dry-run', ask_user: true },- operation_bound_client: { stage: 'decision', meaning: 'The writer grant does not include extract_facts, which also covers automatic event extraction.', next: 'gbrain chronicle-backfill --limit 50 --dry-run', ask_user: true },- dream_generated: { stage: 'decision', meaning: 'Dream output is never mined for events.', next: null, ask_user: false },- too_short: { stage: 'decision', meaning: 'The page body is under 80 characters.', next: null, ask_user: false },- history: { stage: 'decision', meaning: 'The page is dated older than chronicle.auto_recent_days; history is left to the backfill.', next: 'gbrain chronicle-backfill --dated-since <date> --limit 50 --dry-run', ask_user: true },- not_yet_happened: { stage: 'decision', meaning: 'The meeting has not ended yet; the phase picks it up once its end time passes.', next: null, ask_user: false },- no_write_decision: { stage: 'discovery', meaning: 'A managed page revision has no write decision (written by an older binary or before activation).', next: 'gbrain chronicle-backfill --limit 50 --dry-run', ask_user: true },- not_chronicle_shaped: { stage: 'decision', meaning: 'The page is no longer a meeting, conversation or calendar page; its automatic events were retired.', next: null, ask_user: false },- already_extracted: { stage: 'decision', meaning: 'This exact content was already extracted; its events are current.', next: null, ask_user: false },- // ── execution outcomes ──- superseded: { stage: 'execution', meaning: 'The page, its source, its privacy or the writer grant changed before the events were published; the newer revision carries its own decision.', next: null, ask_user: false },- page_missing: { stage: 'execution', meaning: 'The page was deleted before extraction.', next: null, ask_user: false },- judge_refused: { stage: 'execution', meaning: 'The model refused or filtered the page.', next: null, ask_user: false },- no_events: { stage: 'execution', meaning: 'The judge read the page and found no events.', next: null, ask_user: false },- // ── failures (state 'failed') ──- judge_chat_error: { stage: 'execution', meaning: 'The chat provider call failed; the row retries with backoff.', next: RUN_NOW_COMMAND, ask_user: false },- judge_llm_unavailable: { stage: 'execution', meaning: 'No chat provider is configured, so nothing can be extracted until one is.', next: 'gbrain config set models.chat <provider:model>', ask_user: true },- no_pricing: { stage: 'execution', meaning: 'chronicle.job_budget_usd was set explicitly and the chat model has no price, so the cap cannot be enforced.', next: 'gbrain pricing set <model> --input <usd-per-1M-input-tokens> --output <usd-per-1M-output-tokens> --source <pricing-page-url>', ask_user: true },- budget_exhausted: { stage: 'execution', meaning: 'The page cost more than chronicle.job_budget_usd.', next: 'gbrain config set chronicle.job_budget_usd <usd>', ask_user: true },- judge_truncated: { stage: 'execution', meaning: 'The judge output hit its token cap.', next: 'gbrain config set chronicle.judge_max_tokens 8000', ask_user: false },- judge_parse_failed: { stage: 'execution', meaning: 'The judge returned no parseable JSON array.', next: RUN_NOW_COMMAND, ask_user: false },- malformed_proposal: { stage: 'execution', meaning: 'A proposed event failed validation, so the whole batch was rejected.', next: RUN_NOW_COMMAND, ask_user: false },- publish_error: { stage: 'execution', meaning: 'Publishing the events failed; nothing from this attempt was retired.', next: RUN_NOW_COMMAND, ask_user: false },- // ── phase-level ──- daily_limit: { stage: 'execution', meaning: 'The rolling 24 h automatic limit is used up; pending pages wait for a free slot.', next: 'gbrain config set chronicle.auto_daily_limit <n>', ask_user: true },- no_chat_provider: { stage: 'phase', meaning: 'No chat provider is configured; the phase made no calls.', next: 'gbrain config set models.chat <provider:model>', ask_user: true },-} as const satisfies Record<string, { stage: 'decision' | 'discovery' | 'execution' | 'phase'; meaning: string; next: string | null; ask_user: boolean }>;--export type ChronicleReason = keyof typeof CHRONICLE_REASONS;--/** Write-receipt hint (`chronicle_backstop`), omitted for pages that are not chronicle-shaped. */-export type ChronicleBackstopReceipt =- | { pending: 'next_cycle'; daily_remaining: number; next_command: string }- | { skipped: ChronicleReason; next_command: string | null; ask_user: boolean };+/** The run-now command line, rendered from the one argv in reasons.ts. */+export const RUN_NOW_COMMAND = CHRONICLE_RUN_NOW_ARGV.join(' ');/** `chronicle` cycle-phase result details. */export interface ChronicleRunDetails {@@ -147,7 +90,7 @@ export interface ChronicleRunDetails {no_events: number;failed: number;/** Count per reason of rows skipped or failed in this run. */- reasons: Partial<Record<ChronicleReason, number>>;+ reasons: Partial<Record<ChronicleReasonCode, number>>;events_written: number;events_retired: number;/** Pending automatic rows left for the next run because the daily limit is used up. */@@ -159,4 +102,6 @@ export interface ChronicleRunDetails {max_items: number;per_source: Record<string, { candidates: number; judged: number }>;next_command?: string;+ /** The reason table's fix when the phase could not run (no chat provider). */+ fix?: ChronicleAction;}diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex d5df6e9043..b4e4e102a2 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -16,7 +16,8 @@ import { recordOnTracker } from '../ai/budget-record.ts';import { getCurrentBudgetTracker, withBudgetTracker } from '../ai/gateway.ts';import type { ExtractAtomsCostGate } from '../cycle/extract-atoms-cost-gate.ts';import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';-import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow, type ChronicleReason } from './contract.ts';+import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow } from './contract.ts';+import type { ChronicleReasonCode } from './reasons.ts';import type { ChronicleSettings } from './config.ts';import { isChronicleEligible } from './eligibility.ts';import { buildChronicleEvents, chronicleJudgeContext, isValidProposal, type ChronicleJudge, type ChronicleJudgeResult } from './extract-events.ts';@@ -96,7 +97,7 @@ function propagateSpend(parent: BudgetTracker | null, child: BudgetTracker): voi}/** Classify a judge result or throw into the ledger vocabulary (E2/D5). */-function classifyJudge(result: ChronicleJudgeResult | null, thrown: unknown): { state: 'failed' | 'skipped'; reason: ChronicleReason } | null {+function classifyJudge(result: ChronicleJudgeResult | null, thrown: unknown): { state: 'failed' | 'skipped'; reason: ChronicleReasonCode } | null {if (thrown) {const budget = thrown as { tag?: string; reason?: string };if (budget.tag === 'BUDGET_EXHAUSTED') return { state: 'failed', reason: budget.reason === 'no_pricing' ? 'no_pricing' : 'budget_exhausted' };diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.tsindex fac7f9dceb..daf9be4955 100644--- a/src/core/chronicle/ledger.ts+++ b/src/core/chronicle/ledger.ts@@ -7,12 +7,10 @@ import type { BrainEngine } from '../engine.ts';import type { PageSnapshot } from '../page-state/types.ts';import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';import { derivedExtractionSkip } from '../persistence/derived-extraction-gate.ts';-import { autoChronicleSetting, chronicleSettings, type ChronicleSettings } from './config.ts';-import {- CHRONICLE_CONFIG, CHRONICLE_EXTRACTOR_VERSION, CHRONICLE_REASONS, RUN_NOW_COMMAND,- type ChronicleBackstopReceipt, type ChronicleLedgerRow, type ChronicleReason, type ChronicleTrigger,-} from './contract.ts';-import { chroniclePageDate, isChronicleEligible, isChronicleShaped } from './eligibility.ts';+import { CHRONICLE_ACTIVATED_AT_KEY, autoChronicleSetting, chronicleSettings, type ChronicleSettings } from './config.ts';+import { CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow, type ChronicleTrigger } from './contract.ts';+import { isChronicleEligible, isChronicleShaped } from './eligibility.ts';+import { chronicleBackstopReceipt, type ChronicleBackstopReceipt, type ChronicleReasonCode, type ChronicleReasonContext } from './reasons.ts';/** Publications that import page content and therefore carry a decision (C1). */const DECIDING_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'restore_page', 'revert_version']);@@ -32,7 +30,7 @@ export interface ChronicleDecisionPage {export type ChronicleDecision =| { state: 'pending'; reason: null; nextAttemptAt: Date }| { state: 'pending'; reason: 'not_yet_happened'; nextAttemptAt: Date }- | { state: 'skipped'; reason: ChronicleReason | string; nextAttemptAt: null };+ | { state: 'skipped'; reason: ChronicleReasonCode | string; nextAttemptAt: null };/*** The automatic-path decision for one revision of a chronicle-shaped page.@@ -43,9 +41,11 @@ export type ChronicleDecision =export function decideChronicle(input: {page: ChronicleDecisionPage; authority: Pick<WriteAuthority, 'restrictedNamespace' | 'delegated' | 'slugPrefixes' | 'operations'> | null;noExtract: boolean; enabled: boolean; settings: Pick<ChronicleSettings, 'recentDays' | 'settleSeconds'>; now: Date;+ /** The stored auto_chronicle word was neither true nor false (reads as off). */+ invalidSetting?: boolean;}): ChronicleDecision {const skip = (reason: string): ChronicleDecision => ({ state: 'skipped', reason, nextAttemptAt: null });- if (!input.enabled) return skip('auto_chronicle_off');+ if (!input.enabled) return skip(input.invalidSetting ? 'auto_chronicle_invalid' : 'auto_chronicle_off');if (input.noExtract) return skip('no_extract');const confined = input.authority ? derivedExtractionSkip(input.authority) : null;if (confined) return skip(confined);@@ -65,22 +65,13 @@ export function decideChronicle(input: {return { state: 'pending', reason: null, nextAttemptAt: new Date(input.now.getTime() + input.settings.settleSeconds * 1000) };}-/** The exact next command for a skip, with real values where the reason has them. */-export function chronicleNextCommand(reason: string, page?: ChronicleDecisionPage): string | null {- if (reason === 'history' && page) {- const dated = chroniclePageDate({ effectiveDate: page.effective_date, effectiveDateSource: page.effective_date_source, frontmatter: page.frontmatter });- if (dated) return `gbrain chronicle-backfill --dated-since ${dated.toISOString().slice(0, 10)} --limit 50 --dry-run`;- }- return (CHRONICLE_REASONS as Record<string, { next: string | null }>)[reason]?.next ?? null;-}--export function chronicleReceipt(decision: ChronicleDecision, dailyRemaining: number, page?: ChronicleDecisionPage): ChronicleBackstopReceipt {- if (decision.state === 'pending' && decision.reason === null) {- return { pending: 'next_cycle', daily_remaining: dailyRemaining, next_command: RUN_NOW_COMMAND };- }- const reason = (decision.reason ?? 'not_yet_happened') as ChronicleReason;- const known = (CHRONICLE_REASONS as Record<string, { ask_user: boolean }>)[reason];- return { skipped: reason, next_command: chronicleNextCommand(reason, page), ask_user: known?.ask_user ?? false };+/**+ * The `chronicle_backstop` receipt for a decision: built by reasons.ts from the one reason table+ * (stored fix Actions, rendered here with this page's source, today's date and the brain's limits).+ */+export function chronicleReceipt(decision: Pick<ChronicleDecision, 'state' | 'reason'>,+ ctx: ChronicleReasonContext & { dailyRemaining?: number }): ChronicleBackstopReceipt | undefined {+ return chronicleBackstopReceipt(decision, ctx);}/** Automatic judge calls left in the rolling 24 h window. */@@ -193,21 +184,25 @@ export async function recordChronicleDecision(tx: BrainEngine, row: DecidingRequconst [enabledRaw, settings] = await Promise.all([tx.getConfig('auto_chronicle').catch(() => null), chronicleSettings(tx)]);// The first decision after the upgrade activates the automatic path; earlier revisions stay history.if (!settings.activatedAt) {- await tx.executeRaw("INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING", [CHRONICLE_CONFIG.activatedAt, new Date().toISOString()]);+ await tx.executeRaw("INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING", [CHRONICLE_ACTIVATED_AT_KEY, new Date().toISOString()]);}+ const now = new Date();+ const setting = autoChronicleSetting(enabledRaw);const decision = decideChronicle({ page, authority: row.authority ?? null, noExtract,- enabled: autoChronicleSetting(enabledRaw) === 'on', settings, now: new Date() });+ enabled: setting === 'on', invalidSetting: setting === 'invalid', settings, now });+ const receiptCtx: ChronicleReasonContext = { sourceId: base.sourceId, since: now.toISOString().slice(0, 10),+ dailyLimit: settings.dailyLimit, recentDays: settings.recentDays };if (decision.state === 'skipped') await recordSkip(tx, { ...base, noExtract }, String(decision.reason));else if (!(await upsertChronicleRow(tx, { ...base, noExtract, state: 'pending', reason: decision.reason, nextAttemptAt: decision.nextAttemptAt }))) {// The content's current generation is already extracted (or queued by backfill): say so, not "pending".const kept = await readChronicleRow(tx, base);if (kept?.state === 'extracted') {- outcome.chronicle_backstop = { skipped: 'already_extracted', next_command: null, ask_user: false } satisfies ChronicleBackstopReceipt;+ outcome.chronicle_backstop = chronicleReceipt({ state: 'skipped', reason: 'already_extracted' }, receiptCtx);return;}}- const remaining = decision.state === 'pending' && decision.reason === null ? await chronicleDailyRemaining(tx, settings.dailyLimit) : 0;- outcome.chronicle_backstop = chronicleReceipt(decision, remaining, page);+ const dailyRemaining = decision.state === 'pending' && decision.reason === null ? await chronicleDailyRemaining(tx, settings.dailyLimit) : undefined;+ outcome.chronicle_backstop = chronicleReceipt(decision, { ...receiptCtx, dailyRemaining });}export async function readChronicleRow(engine: BrainEngine, key: { sourceId: string; pageId: number; contentHash: string }): Promise<ChronicleLedgerRow | null> {diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 5c8860189e..25db605e04 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -20,7 +20,7 @@ export interface ChronicleAction {}/**- * Where a code is decided (same stages as Lane 1's `src/core/chronicle/contract.ts`): `decision` when+ * Where a code is decided: `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.*/@@ -95,6 +95,8 @@ export const CHRONICLE_REASONS = {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.' },+ already_extracted: { stage: 'decision',+ meaning: () => 'This exact content was already extracted; its events are current, so no new call is made.' },superseded: { stage: 'execution',meaning: () => 'A newer revision replaced this content before extraction ran; the newer revision carries its own decision.' },daily_limit: { stage: 'execution',@@ -150,7 +152,7 @@ export type ChronicleReasonCode = keyof typeof CHRONICLE_REASONS;const NOT_CHRONICLE_SHAPED = /^(kind:|diary_excluded$|event_self$|subagent_scratch$)/;/**- * The write-time decision (capy/chronicle-lane-core `decideChronicle`): `pending` with no reason is+ * The write-time decision (ledger.ts `decideChronicle`): `pending` with no reason is* queued for the next cycle; `pending` with a reason (`not_yet_happened`) waits and reports that* reason like a skip; `skipped` carries its reason.*/diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.tsindex 2c120e7b80..0da69e8d71 100644--- a/src/core/cycle/chronicle.ts+++ b/src/core/cycle/chronicle.ts@@ -28,10 +28,10 @@ import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenancePreflight, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { resolveExtractAtomsCostGate, settleExtractAtomsCostGate } from './extract-atoms-cost-gate.ts';-import { chronicleSettings, chronicleTz, isAutoChronicleEnabled } from '../chronicle/config.ts';+import { CHRONICLE_ACTIVATED_AT_KEY, chronicleSettings, chronicleTz, isAutoChronicleEnabled } from '../chronicle/config.ts';import {- CHRONICLE_CONFIG, CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, RUN_NOW_COMMAND,- type ChronicleLedgerRow, type ChronicleReason, type ChronicleRunDetails,+ CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, RUN_NOW_COMMAND,+ type ChronicleLedgerRow, type ChronicleRunDetails,} from '../chronicle/contract.ts';import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES } from '../chronicle/eligibility.ts';import { claimChronicleRow, executeChronicleRow } from '../chronicle/execute.ts';@@ -39,6 +39,7 @@ import { defaultJudge, type ChronicleJudge } from '../chronicle/extract-events.timport {RETIRE_REASONS, chronicleDailyRemaining, decideChronicle, pruneChronicleReservations, upsertChronicleRow,} from '../chronicle/ledger.ts';+import { CHRONICLE_REASONS, type ChronicleReasonCode } from '../chronicle/reasons.ts';export interface ChroniclePhaseOpts {dryRun?: boolean;@@ -128,7 +129,7 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhaslet activatedAt = settings.activatedAt;if (!activatedAt) {activatedAt = now();- if (!dryRun) await engine.setConfig(CHRONICLE_CONFIG.activatedAt, activatedAt.toISOString());+ if (!dryRun) await engine.setConfig(CHRONICLE_ACTIVATED_AT_KEY, activatedAt.toISOString());}const details: ChronicleRunDetails & Record<string, unknown> = {dry_run: dryRun, sources: 0, candidates: 0, judged: 0, extracted: 0, no_events: 0, failed: 0, reasons: {},@@ -138,7 +139,7 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhas};const count = (reason: string | null) => {if (!reason) return;- details.reasons[reason as ChronicleReason] = (details.reasons[reason as ChronicleReason] ?? 0) + 1;+ details.reasons[reason as ChronicleReasonCode] = (details.reasons[reason as ChronicleReasonCode] ?? 0) + 1;};if (!dryRun) {@@ -175,8 +176,8 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhasconst judge = opts.judge ?? (isAvailable('chat') ? defaultJudge(engine) : null);if (!judge) {details.reason = 'no_chat_provider';- details.next_command = 'gbrain config set models.chat <provider:model>';- return result('skipped', `chronicle: no chat provider is configured; ${details.candidates} page(s) wait. Ask the user which chat model to configure, then run: gbrain config set models.chat <provider:model>`, details);+ details.fix = CHRONICLE_REASONS.no_chat_provider.fix();+ return result('skipped', `chronicle: no chat provider is configured; ${details.candidates} page(s) wait. ${details.fix.why}`, details);}const model = getChatModel();const pricingOverrides = await loadPricingOverrides(engine);diff --git a/test/auto-chronicle-surfaces-5876.test.ts b/test/auto-chronicle-surfaces-5876.test.tsindex 712c4ca715..f2b0d069eb 100644--- a/test/auto-chronicle-surfaces-5876.test.ts+++ b/test/auto-chronicle-surfaces-5876.test.ts@@ -9,7 +9,7 @@* 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).+ * Seams: gateway chat transport/unconfigure test seams; ledger rows seeded on the real migration.*/import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -21,7 +21,7 @@ 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';+import { insertChronicleLedgerRow } from './helpers/chronicle-ledger-rows.ts';let engine: PGLiteEngine;const advisorCtx = () => ({ engine, remote: false, now: new Date('2026-10-04T12:00:00Z') } as unknown as AdvisorContext);@@ -37,7 +37,6 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- await createChronicleLedgerStub(engine);}, 120_000);afterAll(async () => { await engine.disconnect(); });beforeEach(async () => {diff --git a/test/chronicle-auto-decision.test.ts b/test/chronicle-auto-decision.test.tsindex e9d6c5d1bd..4c6f714111 100644--- a/test/chronicle-auto-decision.test.ts+++ b/test/chronicle-auto-decision.test.ts@@ -19,6 +19,7 @@ import { operationsByName } from '../src/core/operations.ts';import { decideChronicle, recordChronicleDecision } from '../src/core/chronicle/ledger.ts';import { isChronicleEligible } from '../src/core/chronicle/eligibility.ts';import { autoChronicleSetting } from '../src/core/chronicle/config.ts';+import { CHRONICLE_REASONS, chronicleBackfillArgv } from '../src/core/chronicle/reasons.ts';import { prepareFactsBackstop } from '../src/core/persistence/effect-facts.ts';import type { WriteAuthority, WriteRequest } from '../src/core/persistence/model.ts';import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';@@ -46,7 +47,7 @@ describe('managed put_page', () => {test('an eligible meeting records one pending row with the writer; a no-op re-put changes nothing', () => brain(async ({ engine, ctx }) => {expect(await engine.getConfig('chronicle.activated_at')).toBeNull();const receipt = await put(ctx, 'meetings/sync', meeting());- expect(receipt.chronicle_backstop).toEqual({ pending: 'next_cycle', daily_remaining: 200, next_command: 'gbrain dream --phase chronicle' });+ expect(receipt.chronicle_backstop).toEqual({ pending: 'next_cycle', daily_remaining: 200 });expect(await engine.getConfig('chronicle.activated_at')).not.toBeNull(); // the first decision activates the automatic pathconst [row] = await rows(engine);const [request] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=$1', [receipt.request_id]);@@ -62,11 +63,13 @@ describe('managed put_page', () => {expect(await rows(engine)).toEqual([]);}), 120_000);- test('auto_chronicle false and an invalid word both skip with auto_chronicle_off; unset is on', () => brain(async ({ engine, ctx }) => {+ test('auto_chronicle false skips with auto_chronicle_off (no fix: off by choice); an invalid word skips auto_chronicle_invalid; unset is on', () => brain(async ({ engine, ctx }) => {await engine.setConfig('auto_chronicle', 'false');- expect((await put(ctx, 'meetings/a', meeting())).chronicle_backstop).toEqual({ skipped: 'auto_chronicle_off', next_command: 'gbrain config set auto_chronicle true', ask_user: true });+ expect((await put(ctx, 'meetings/a', meeting())).chronicle_backstop)+ .toEqual({ skipped: 'auto_chronicle_off', stage: 'decision', why: CHRONICLE_REASONS.auto_chronicle_off.meaning() });await engine.setConfig('auto_chronicle', 'flase');- expect((await put(ctx, 'meetings/b', meeting())).chronicle_backstop).toMatchObject({ skipped: 'auto_chronicle_off' });+ expect((await put(ctx, 'meetings/b', meeting())).chronicle_backstop)+ .toMatchObject({ skipped: 'auto_chronicle_invalid', fix: { argv: ['gbrain', 'config', 'set', 'auto_chronicle', 'true'], consent: ['paid'] } });await engine.unsetConfig('auto_chronicle');expect((await put(ctx, 'meetings/c', meeting())).chronicle_backstop).toMatchObject({ pending: 'next_cycle' });expect(autoChronicleSetting(null)).toBe('on');@@ -75,14 +78,15 @@ describe('managed put_page', () => {test('a page dated last year skips history with a scoped backfill command', () => brain(async ({ ctx }) => {const receipt = await put(ctx, 'meetings/old', meeting(`date: ${lastYear}\n`));- expect(receipt.chronicle_backstop).toEqual({ skipped: 'history', ask_user: true,- next_command: `gbrain chronicle-backfill --dated-since ${lastYear} --limit 50 --dry-run` });+ expect(receipt.chronicle_backstop).toMatchObject({ skipped: 'history', stage: 'decision', fix: {+ preview_argv: chronicleBackfillArgv({ sourceId: 'default', since: today, dryRun: true }),+ argv: chronicleBackfillArgv({ sourceId: 'default', since: today, dryRun: false }), consent: ['paid'] } });}), 120_000);test('a future invite is not_yet_happened and waits until its end', () => brain(async ({ engine, ctx }) => {const end = new Date(Date.now() + 2 * 86_400_000).toISOString();const receipt = await put(ctx, 'calendar/2026/10/standup', meeting(`start: ${end}\nend: ${end}\n`));- expect(receipt.chronicle_backstop).toEqual({ skipped: 'not_yet_happened', next_command: null, ask_user: false });+ expect(receipt.chronicle_backstop).toEqual({ skipped: 'not_yet_happened', stage: 'decision', why: CHRONICLE_REASONS.not_yet_happened.meaning() });const [row] = await engine.executeRaw<{ state: string; next_attempt_at: Date }>('SELECT state,next_attempt_at FROM chronicle_page_state');expect(row.state).toBe('pending');expect(new Date(row.next_attempt_at).getTime()).toBeGreaterThanOrEqual(new Date(end).getTime());diff --git a/test/chronicle-auto-phase.test.ts b/test/chronicle-auto-phase.test.tsindex fa317cab7e..fa15d3b796 100644--- a/test/chronicle-auto-phase.test.ts+++ b/test/chronicle-auto-phase.test.ts@@ -62,7 +62,7 @@ afterEach(() => { __setChatTransportForTests(null); resetGateway(); _resetBudgetdescribe('execution path (D10) and settle (D4)', () => {test('PGLite: write a meeting, run the phase, read the events', () => brain(async ({ engine, ctx }) => {const receipt = await put(ctx, 'meetings/sync', meeting('Sync'));- expect(receipt.chronicle_backstop).toEqual({ pending: 'next_cycle', daily_remaining: 200, next_command: 'gbrain dream --phase chronicle' });+ expect(receipt.chronicle_backstop).toEqual({ pending: 'next_cycle', daily_remaining: 200 });const judge = countingJudge(() => ({ events: [ev('Alice agreed to ship the beta')] }));expect((await runPhaseChronicle(engine, { judge })).details).toMatchObject({ judged: 0 }); // still settlingawait settle(engine);@@ -160,7 +160,7 @@ describe('judge failure classes (E2/D5)', () => {await settle(engine);const r = await runPhaseChronicle(engine);expect(r.status).toBe('skipped');- expect(r.details).toMatchObject({ reason: 'no_chat_provider', next_command: 'gbrain config set models.chat <provider:model>' });+ expect(r.details).toMatchObject({ reason: 'no_chat_provider', fix: { actor: 'user', consent: ['credentials'] } });expect((await rows(engine))[0]).toMatchObject({ state: 'pending', attempts: 0 });}), 120_000);@@ -309,7 +309,8 @@ describe('ledger and discovery (E1/E6/D12)', () => {await settle(engine); await runPhaseChronicle(engine, { judge });await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} B.`));const back = await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} A.`));- expect(back.chronicle_backstop).toEqual({ skipped: 'already_extracted', next_command: null, ask_user: false });+ expect(back.chronicle_backstop).toMatchObject({ skipped: 'already_extracted', stage: 'decision' });+ expect(back.chronicle_backstop).not.toHaveProperty('fix');await settle(engine); await runPhaseChronicle(engine, { judge });expect(judge.calls).toBe(1);expect((await events(engine)).map((e) => [e.what, e.deleted])).toEqual([['Version A decision', false]]);@@ -331,7 +332,7 @@ describe('ledger and discovery (E1/E6/D12)', () => {await engine.setConfig('chronicle.auto_settle_seconds', '0');const end = new Date(Date.now() + 1500).toISOString();const receipt = await put(ctx, 'calendar/2026/10/standup', meeting('Standup', BODY, `start: ${new Date().toISOString()}\nend: ${end}\n`));- expect(receipt.chronicle_backstop).toMatchObject({ skipped: 'not_yet_happened', ask_user: false });+ expect(receipt.chronicle_backstop).toMatchObject({ skipped: 'not_yet_happened', stage: 'decision' });const judge = countingJudge(() => ({ events: [] }));await runPhaseChronicle(engine, { judge });expect(judge.calls).toBe(0);diff --git a/test/e2e/chronicle-surfaces-postgres.test.ts b/test/e2e/chronicle-surfaces-postgres.test.tsindex c7b8e1255a..7428ba4ab2 100644--- a/test/e2e/chronicle-surfaces-postgres.test.ts+++ b/test/e2e/chronicle-surfaces-postgres.test.ts@@ -2,8 +2,7 @@* #5876 (T11) on real Postgres: the chronicle ledger rollups behind doctor `auto_chronicle` and the* advisor (FILTER aggregates, numeric -> float8 spend, the reservation/ledger join for writer* shares, interval windows) return the same numbers as on PGLite- * (test/auto-chronicle-surfaces-5876.test.ts). Uses the TEMPORARY ledger stub until Lane 1's- * `chronicle_page_state` migration merges.+ * (test/auto-chronicle-surfaces-5876.test.ts). Rows are seeded on the real ledger migration.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';@@ -11,19 +10,16 @@ import { readChronicleLedgerStats } from '../../src/core/chronicle/ledger-stats.import { autoChronicleEntry } from '../../src/commands/doctor/checks/auto-chronicle.ts';import type { DoctorContext } from '../../src/commands/doctor/context.ts';import type { Check } from '../../src/commands/doctor.ts';-import { createChronicleLedgerStub, insertChronicleLedgerRow } from '../helpers/chronicle-ledger-stub.ts';+import { insertChronicleLedgerRow } from '../helpers/chronicle-ledger-rows.ts';const d = hasDatabase() ? describe : describe.skip;beforeAll(async () => {if (!hasDatabase()) return;await setupDB();- await createChronicleLedgerStub(getEngine());});afterAll(async () => {if (!hasDatabase()) return;- await getEngine().executeRaw('DROP TABLE IF EXISTS chronicle_page_state');- await getEngine().executeRaw('DROP TABLE IF EXISTS chronicle_judge_reservations');await teardownDB();});beforeEach(async () => {diff --git a/test/helpers/chronicle-ledger-rows.ts b/test/helpers/chronicle-ledger-rows.tsnew file mode 100644index 0000000000..d6112248bc--- /dev/null+++ b/test/helpers/chronicle-ledger-rows.ts@@ -0,0 +1,33 @@+/**+ * Seeds `chronicle_page_state` rows (#5876) on a brain that ran the real ledger migration: each row+ * gets a real page (the ledger's foreign keys hold), and judged automatic rows also get the+ * reservation the chronicle phase takes before each judge call.+ */+import type { BrainEngine } from '../../src/core/engine.ts';++export interface LedgerRowSeed {+ slug: string; state: 'pending' | 'skipped' | 'extracted' | 'failed'; reason?: string; trigger?: 'auto' | 'backfill';+ principal?: [string, string]; cost?: number | null; unpriced?: boolean; hoursAgo?: number;+ /** Extra judge calls (retries) for this content; each takes its own reservation. */+ retries?: number;+}++let hashSeq = 1;+export async function insertChronicleLedgerRow(engine: BrainEngine, row: LedgerRowSeed): Promise<void> {+ const page = await engine.getPage(row.slug, { sourceId: 'default' })+ ?? await engine.putPage(row.slug, { type: 'meeting', title: row.slug, compiled_truth: `Seeded meeting ${row.slug}.` }, { sourceId: 'default' });+ const pageId = Number(page.id);+ const hash = `seed-${hashSeq++}`;+ 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, 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 + (row.retries ?? 0) : 0, row.cost ?? null, row.unpriced ?? false, hoursAgo]);+ for (let i = 0; judged && (row.trigger ?? 'auto') === 'auto' && i <= (row.retries ?? 0); i++) {+ 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]);+ }+}diff --git a/test/helpers/chronicle-ledger-stub.ts b/test/helpers/chronicle-ledger-stub.tsdeleted file mode 100644index 257515a9e6..0000000000--- a/test/helpers/chronicle-ledger-stub.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * TEMPORARY (Lane 2 of the #5876 wave): Lane 1's `chronicle_page_state` and- * `chronicle_judge_reservations` DDL (capy/chronicle-lane-core a643de5bd, 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,- 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 '{}', event_hashes 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: 'pending' | 'skipped' | 'extracted' | 'failed'; reason?: string; trigger?: 'auto' | 'backfill';- principal?: [string, string]; cost?: number | null; unpriced?: boolean; hoursAgo?: number;- /** Extra judge calls (retries) for this content; each takes its own reservation. */- retries?: 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, 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 + (row.retries ?? 0) : 0, row.cost ?? null, row.unpriced ?? false, hoursAgo]);- for (let i = 0; judged && (row.trigger ?? 'auto') === 'auto' && i <= (row.retries ?? 0); i++) {- 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]);- }-}