Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: the global chronicle cycle phase, budget scope and daily reservation (#5876 T2/T4/T5)
garrytan521b6e4a9c43
diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.tsindex ef2d13d4ac..602438136f 100644--- a/src/core/chronicle/contract.ts+++ b/src/core/chronicle/contract.ts@@ -56,6 +56,9 @@ export interface ChronicleLedgerRow {unpriced: boolean;/** Event page slugs this content produced (the generation reconciliation reads). */event_slugs: string[];+ /** content_hash of each event page as the extractor wrote it, parallel to event_slugs. An event whose+ * live hash is no longer in any row of its depth page was edited by an operator and is never touched. */+ event_hashes: string[];decided_at: Date | string;updated_at: Date | string;}diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsnew file mode 100644index 0000000000..d5df6e9043--- /dev/null+++ b/src/core/chronicle/execute.ts@@ -0,0 +1,227 @@+/**+ * Life Chronicle execution (#5876): run one ledger row to its outcome.+ *+ * Shared by the `chronicle` cycle phase and the `chronicle_extract` job+ * handler. Order: live-content check → time rules (shared eligibility) →+ * rolling daily reservation (automatic rows only, taken immediately before the+ * judge; attempts and retries count) → judge one immutable snapshot inside a+ * BudgetTracker scope labelled `chronicle:<trigger>` with the per-page cap →+ * explicit post-call budget check → publish with re-validation and+ * reconciliation → ledger outcome. A failed or superseded run never retires+ * the previous generation.+ */+import type { BrainEngine } from '../engine.ts';+import { BudgetTracker, type PricingOverrides } from '../budget/budget-tracker.ts';+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 type { ChronicleSettings } from './config.ts';+import { isChronicleEligible } from './eligibility.ts';+import { buildChronicleEvents, chronicleJudgeContext, isValidProposal, type ChronicleJudge, type ChronicleJudgeResult } from './extract-events.ts';+import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';+import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';++export interface ChronicleExecContext {+ engine: BrainEngine;+ settings: ChronicleSettings;+ judge: ChronicleJudge;+ gate: ExtractAtomsCostGate;+ pricingOverrides?: PricingOverrides;+ tz: string;+ now?: () => Date;+ signal?: AbortSignal;+ /** Managed maintenance authority of the row's source; null on an unmanaged brain. */+ maintenance: MaintenanceAuthority | null;+ /** BudgetTracker label; `chronicle:<trigger>` by default. */+ label?: string;+}++export type ChronicleRowOutcome =+ | { kind: 'waiting'; reason: string }+ | { kind: 'deferred'; reason: 'daily_limit' }+ | { kind: 'done'; state: ChronicleLedgerRow['state']; reason: string | null; judged: boolean;+ written: number; retired: number; costUsd: number | null; unpriced: boolean };++const CONFIG_BLOCKED = new Set(['judge_llm_unavailable', 'no_pricing']);+const LEASE_MS = 15 * 60_000;++function key(row: ChronicleLedgerRow) {+ return [row.source_id, Number(row.page_id), row.content_hash, CHRONICLE_EXTRACTOR_VERSION] as const;+}++/** Lease one claimable row so a second executor (another host's cycle, a job) skips it. */+export async function claimChronicleRow(engine: BrainEngine, row: ChronicleLedgerRow): Promise<ChronicleLedgerRow | null> {+ const [claimed] = await engine.executeRaw<ChronicleLedgerRow>(+ `UPDATE chronicle_page_state SET next_attempt_at = now() + ($5::int * interval '1 millisecond')+ WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 AND state=$6+ AND (next_attempt_at IS NULL OR next_attempt_at <= now())+ RETURNING *`, [...key(row), LEASE_MS, row.state]);+ return claimed ?? null;+}++async function setNextAttempt(engine: BrainEngine, row: ChronicleLedgerRow, at: Date | null): Promise<void> {+ await engine.executeRaw(+ `UPDATE chronicle_page_state SET next_attempt_at=$5::timestamptz+ WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4`,+ [...key(row), at ? at.toISOString() : null]);+}++async function finish(engine: BrainEngine, row: ChronicleLedgerRow, patch: {+ state: ChronicleLedgerRow['state']; reason: string | null; nextAttemptAt: Date | null;+ costUsd?: number | null; unpriced?: boolean; events?: Array<{ slug: string; hash: string }>;+}): Promise<void> {+ await engine.executeRaw(+ `UPDATE chronicle_page_state SET state=$5, reason=$6, next_attempt_at=$7::timestamptz,+ cost_usd=COALESCE($8::numeric, cost_usd), unpriced=COALESCE($9::boolean, unpriced),+ event_slugs=COALESCE($10::text[], event_slugs), event_hashes=COALESCE($11::text[], event_hashes), updated_at=now()+ WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4`,+ [...key(row), patch.state, patch.reason, patch.nextAttemptAt ? patch.nextAttemptAt.toISOString() : null,+ patch.costUsd ?? null, patch.unpriced ?? null,+ patch.events ? patch.events.map((e) => e.slug) : null, patch.events ? patch.events.map((e) => e.hash) : null]);+}++function backoff(attempts: number, now: Date): Date | null {+ if (attempts >= CHRONICLE_DEFAULTS.maxAttempts) return null;+ return new Date(now.getTime() + Math.min(6 * 3_600_000, 5 * 60_000 * 2 ** Math.max(0, attempts - 1)));+}++/** Copy a child scope's spend onto the ambient tracker so an enclosing budget sees it. */+function propagateSpend(parent: BudgetTracker | null, child: BudgetTracker): void {+ if (!parent || parent === child) return;+ for (const m of child.snapshot().models) {+ recordOnTracker(parent, { modelId: m.model, inputTokens: m.input_tokens, outputTokens: m.output_tokens, label: 'chronicle', kind: 'chat' });+ }+}++/** 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 {+ 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' };+ return { state: 'failed', reason: 'judge_chat_error' };+ }+ switch (result?.failure) {+ case undefined: break;+ case 'refused': return { state: 'skipped', reason: 'judge_refused' };+ case 'llm_unavailable': return { state: 'failed', reason: 'judge_llm_unavailable' };+ case 'chat_error': return { state: 'failed', reason: 'judge_chat_error' };+ case 'truncated': return { state: 'failed', reason: 'judge_truncated' };+ case 'parse_failed': return { state: 'failed', reason: 'judge_parse_failed' };+ }+ const events = Array.isArray(result?.events) ? result!.events : [];+ if (!events.every(isValidProposal)) return { state: 'failed', reason: 'malformed_proposal' };+ return null;+}++/** Run one claimed row. The caller claimed it (lease) and owns its outcome. */+export async function executeChronicleRow(ctx: ChronicleExecContext, row: ChronicleLedgerRow): Promise<ChronicleRowOutcome> {+ const { engine, settings } = ctx;+ const now = ctx.now?.() ?? new Date();+ const done = (state: ChronicleLedgerRow['state'], reason: string | null, extra: Partial<Extract<ChronicleRowOutcome, { kind: 'done' }>> = {}): ChronicleRowOutcome =>+ ({ kind: 'done', state, reason, judged: false, written: 0, retired: 0, costUsd: 0, unpriced: false, ...extra });++ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!snapshot || Number(snapshot.page.id) !== Number(row.page_id)) {+ await finish(engine, row, { state: 'skipped', reason: 'page_missing', nextAttemptAt: null });+ return done('skipped', 'page_missing');+ }+ if (String(snapshot.page.content_hash ?? '') !== row.content_hash) {+ await finish(engine, row, { state: 'skipped', reason: 'superseded', nextAttemptAt: null });+ return done('skipped', 'superseded');+ }+ const pin = pinDepth(snapshot);++ // An ineligible revision of a page that once produced events retires them (E8). No model call.+ if (row.state === 'skipped') {+ const generation = await publishChronicleGeneration(engine, { sourceId: row.source_id, pin, events: [],+ decisionRequestId: null, maintenance: ctx.maintenance, signal: ctx.signal });+ await setNextAttempt(engine, row, null);+ return done('skipped', row.reason, { retired: generation.retired.length });+ }++ if (row.no_extract) {+ await finish(engine, row, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });+ return done('skipped', 'no_extract');+ }+ const auto = row.trigger === 'auto';+ const eligible = isChronicleEligible({+ type: snapshot.page.type, slug: snapshot.page.slug, body: snapshot.page.compiled_truth ?? '',+ dreamGenerated: snapshot.page.frontmatter?.dream_generated === true,+ effectiveDate: snapshot.page.effective_date ?? null, effectiveDateSource: snapshot.page.effective_date_source ?? null,+ frontmatter: snapshot.page.frontmatter ?? null, changedAt: row.decided_at,+ }, { now, recentDays: auto ? settings.recentDays : null, settleSeconds: auto ? settings.settleSeconds : null });+ if (!eligible.ok) {+ if ('wait' in eligible) {+ await setNextAttempt(engine, row, eligible.until);+ return { kind: 'waiting', reason: eligible.reason };+ }+ const reason = eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason;+ const retire = (RETIRE_REASONS as readonly string[]).includes(reason);+ await finish(engine, row, { state: 'skipped', reason, nextAttemptAt: retire ? now : null });+ return done('skipped', reason);+ }++ if (auto && !(await reserveChronicleSlot(engine, settings.dailyLimit, { sourceId: row.source_id, pageId: Number(row.page_id), contentHash: row.content_hash }))) {+ await setNextAttempt(engine, row, null);+ return { kind: 'deferred', reason: 'daily_limit' };+ }+ const [{ attempts }] = await engine.executeRaw<{ attempts: number }>(+ `UPDATE chronicle_page_state SET attempts=attempts+1 WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 RETURNING attempts`,+ [...key(row)]);++ const judgeCtx = chronicleJudgeContext(snapshot.page);+ const tracker = new BudgetTracker({+ maxCostUsd: ctx.gate.enforceCap ? settings.jobBudgetUsd : undefined,+ label: ctx.label ?? `chronicle:${row.trigger}`,+ pricingOverrides: ctx.pricingOverrides,+ });+ let result: ChronicleJudgeResult | null = null;+ let thrown: unknown = null;+ const parent = getCurrentBudgetTracker();+ try {+ result = await withBudgetTracker(tracker, () => ctx.judge(judgeCtx.input));+ } catch (error) {+ if ((error as Error)?.name === 'AbortError') throw error;+ thrown = error ?? new Error('judge failed');+ } finally {+ propagateSpend(parent, tracker);+ }+ const models = tracker.snapshot().models;+ const unpriced = models.some((m) => m.cost_usd === null && m.calls > 0);+ const spend = { costUsd: unpriced ? null : tracker.totalSpent, unpriced };+ const judged = { judged: true, ...spend };++ // E4: gateway accounting defers a breach to the next reservation; check the cap explicitly.+ const overCap = tracker.cap !== undefined && tracker.totalSpent > tracker.cap;+ const failure = overCap && !thrown ? { state: 'failed' as const, reason: 'budget_exhausted' as const } : classifyJudge(result, thrown);+ if (failure) {+ const next = failure.state === 'skipped' || CONFIG_BLOCKED.has(failure.reason) ? null : backoff(attempts, now);+ await finish(engine, row, { state: failure.state, reason: failure.reason, nextAttemptAt: next, ...spend });+ return done(failure.state, failure.reason, judged);+ }++ const proposals = result?.events ?? [];+ let generation;+ try {+ generation = await publishChronicleGeneration(engine, {+ sourceId: row.source_id, pin, decisionRequestId: row.request_id, maintenance: ctx.maintenance, signal: ctx.signal,+ events: buildChronicleEvents(proposals, judgeCtx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, ctx.tz),+ });+ } catch (error) {+ if ((error as Error)?.name === 'AbortError') throw error;+ console.warn(`[chronicle] ${row.slug}: publishing events failed (${error instanceof Error ? error.message : String(error)}); the row retries with backoff. Run now: gbrain dream --phase chronicle`);+ await finish(engine, row, { state: 'failed', reason: 'publish_error', nextAttemptAt: backoff(attempts, now), ...spend });+ return done('failed', 'publish_error', judged);+ }+ if (generation.superseded) {+ await finish(engine, row, { state: 'skipped', reason: 'superseded', nextAttemptAt: null, events: generation.written, ...spend });+ return done('skipped', 'superseded', { ...judged, written: generation.written.length });+ }+ const reason = proposals.length === 0 ? 'no_events' : null;+ await finish(engine, row, { state: 'extracted', reason, nextAttemptAt: null, events: generation.written, ...spend });+ return done('extracted', reason, { ...judged, written: generation.written.length, retired: generation.retired.length });+}++export type { ChronicleDepthPin };diff --git a/src/core/chronicle/job.ts b/src/core/chronicle/job.tsnew file mode 100644index 0000000000..1c6f37c0c6--- /dev/null+++ b/src/core/chronicle/job.ts@@ -0,0 +1,66 @@+/**+ * One-page Life Chronicle extraction outside the cycle (the legacy+ * `chronicle_extract` job). Records the page in the ledger as trusted local+ * work and runs the shared executor.+ */+import type { BrainEngine } from '../engine.ts';+import { getChatModel, isAvailable } from '../ai/gateway.ts';+import { loadPricingOverrides } from '../budget/budget-tracker.ts';+import { resolveExtractAtomsCostGate } from '../cycle/extract-atoms-cost-gate.ts';+import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';+import { chronicleSettings, chronicleTz } from './config.ts';+import { claimChronicleRow, executeChronicleRow } from './execute.ts';+import { defaultJudge, type ChronicleJudge } from './extract-events.ts';+import { readChronicleRow, upsertChronicleRow } from './ledger.ts';+import { noPricingMessage } from '../budget/no-pricing.ts';++export interface ChronicleJobResult {+ slug: string;+ status: 'extracted' | 'no_events' | 'skipped' | 'failed';+ reason?: string;+ events_written?: number;+ events_retired?: number;+ /** A failed run worth retrying with backoff (provider error, publish error). */+ retry?: boolean;+}++const RETRYABLE = new Set(['judge_chat_error', 'publish_error', 'judge_parse_failed']);++export async function runChronicleJob(engine: BrainEngine, opts: {+ slug: string; sourceId: string; contentHash?: string; trigger: 'auto' | 'backfill' | 'legacy';+ judge?: ChronicleJudge; signal?: AbortSignal;+}): Promise<ChronicleJobResult> {+ const { slug, sourceId } = opts;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return { slug, status: 'skipped', reason: 'page_missing' };+ const contentHash = String(snapshot.page.content_hash ?? '');+ if (opts.contentHash && opts.contentHash !== contentHash) return { slug, status: 'skipped', reason: 'superseded' };+ const key = { sourceId, pageId: Number(snapshot.page.id), contentHash };+ const existing = await readChronicleRow(engine, key);+ if (existing?.state === 'extracted') return { slug, status: 'skipped', reason: 'already_extracted' };+ const judge = opts.judge ?? (isAvailable('chat') ? defaultJudge(engine) : null);+ if (!judge) return { slug, status: 'failed', reason: 'judge_llm_unavailable' };+ const settings = await chronicleSettings(engine);+ const pricingOverrides = await loadPricingOverrides(engine);+ const model = getChatModel();+ const gate = resolveExtractAtomsCostGate(model, null, pricingOverrides, { explicitBudget: settings.explicitBudget });+ if (gate.refusal) return { slug, status: 'failed', reason: `no_pricing: ${noPricingMessage(gate.refusal, { capUsd: settings.jobBudgetUsd })}` };+ const trigger = opts.trigger === 'auto' ? 'auto' : 'backfill';+ // A write decision or backfill already queued this content: the cycle phase owns it.+ if (existing?.state === 'pending') return { slug, status: 'skipped', reason: 'queued_for_cycle' };+ await upsertChronicleRow(engine, { ...key, slug, state: 'pending', reason: null, trigger, nextAttemptAt: null });+ const row = await readChronicleRow(engine, key);+ const claimed = row && await claimChronicleRow(engine, row);+ if (!claimed) return { slug, status: 'skipped', reason: 'claimed_elsewhere' };+ const outcome = await executeChronicleRow({+ engine, settings, judge, gate, pricingOverrides, tz: await chronicleTz(engine), signal: opts.signal,+ maintenance: await maintenancePreflight(engine, sourceId),+ label: opts.trigger === 'legacy' ? 'chronicle:legacy' : undefined,+ }, claimed);+ if (outcome.kind !== 'done') return { slug, status: 'skipped', reason: outcome.reason };+ if (outcome.state === 'failed') return { slug, status: 'failed', reason: outcome.reason ?? 'failed', retry: RETRYABLE.has(outcome.reason ?? '') };+ if (outcome.state === 'extracted') {+ return { slug, status: outcome.reason === 'no_events' ? 'no_events' : 'extracted', events_written: outcome.written, events_retired: outcome.retired };+ }+ return { slug, status: 'skipped', reason: outcome.reason ?? undefined };+}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 1acd691d63..278ccae7a1 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -80,6 +80,11 @@ export type CyclePhase =// soft-band takes against recent timeline evidence; report-only in v1// (writes reports/drift-<date>; auto_update mutates nothing).| 'drift'+ // #5876 — Life Chronicle: extracts timeline events from meeting,+ // conversation and calendar pages decided at write time (ledger rows),+ // bounded per run and by a rolling daily limit. Default ON+ // (`gbrain config set auto_chronicle false` opts out).+ | 'chronicle'| 'embed' | 'orphans' | 'purge'// v0.39 T12: schema-suggest passive trigger (D3 + D4 plan-eng-review).// Wraps runSuggest() — same library the CLI verb + EIIRP call.@@ -169,6 +174,9 @@ export const ALL_PHASES: CyclePhase[] = [// the calibration trio (fresh take resolutions) and BEFORE embed so the// drift report page gets embedded same-cycle. Report-only in v1.'drift',+ // #5876 — Life Chronicle events. Global (scans every source with per-source+ // fairness). AFTER drift, BEFORE embed so new event pages embed same-cycle.+ 'chronicle',// v0.41.11.0 — opt-in conversation-facts backfill. Default OFF; reads// cycle.conversation_facts_backfill.enabled gate inside the wrapper.// Ordered AFTER calibration_profile (matches the runCycle dispatch@@ -327,6 +335,8 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['calibration_profile',// #2653 — writes the reports/drift-<date> page.'drift',+ // #5876 — writes event pages, projections and the chronicle ledger.+ 'chronicle',// v0.41 T9 — extract_atoms writes atom-typed pages via put_page;// synthesize_concepts writes concept-typed pages + tier updates. Both// mutate DB state and need the lock.@@ -2735,6 +2745,38 @@ export async function runCycle(await safeYield(opts.yieldBetweenPhases);}+ // ── #5876: Life Chronicle ──────────────────────────────────+ // Default ON. Executes ledger rows decided at write time (and backfill+ // rows): ≤50 items and a wall-time bound per run, per-source fairness,+ // a rolling daily reservation and a per-page BudgetTracker scope.+ if (phases.includes('chronicle')) {+ checkAborted(cycleSignal);+ if (!engine) {+ phaseResults.push({+ phase: 'chronicle',+ status: 'skipped',+ duration_ms: 0,+ summary: 'no database connected',+ details: { reason: 'no_database' },+ });+ } else {+ progress.start('cycle.chronicle');+ const { runPhaseChronicle } = await import('./cycle/chronicle.ts');+ const { result, duration_ms } = await timePhase(() =>+ runPhaseChronicle(engine, {+ dryRun,+ signal: cycleSignal,+ yieldDuringPhase: opts.yieldDuringPhase,+ deadlineAtMs: opts.deadlineAtMs ?? null,+ }), 'chronicle',+ );+ result.duration_ms = duration_ms;+ phaseResults.push(result);+ progress.finish();+ }+ await safeYield(opts.yieldBetweenPhases);+ }+// ── v0.41.11.0: conversation_facts_backfill ─────────────────// Opt-in (default OFF). Walks long-form conversation/meeting/slack/// email pages, segments by 30-min gap, runs facts extractor with adiff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.tsnew file mode 100644index 0000000000..2c120e7b80--- /dev/null+++ b/src/core/cycle/chronicle.ts@@ -0,0 +1,248 @@+/**+ * #5876 — cycle phase `chronicle`: Life Chronicle automatic extraction.+ *+ * Default ON (`gbrain config set auto_chronicle false` opts out). One global+ * phase under the cycle lock executes `chronicle_page_state` ledger rows:+ *+ * 1. Housekeeping: rows whose content is no longer live become+ * `superseded`; reservations older than two days are pruned.+ * 2. Discovery per active source (bounded): pages changed since activation+ * with no row for their current content. Unmanaged brains (trusted+ * local writers) get a decision here; managed brains, where every+ * coordinated publication decides at write time, record+ * `no_write_decision` (an older binary wrote it) and leave it to backfill.+ * 3. Execution: settled pending rows (automatic first, then backfill),+ * due retries and retire-only rows, round-robin across sources, at most+ * 50 items and a wall-time bound per run. Automatic rows take a rolling+ * daily reservation immediately before the judge; with automatic+ * extraction off only backfill rows run.+ *+ * No chat provider → no calls and no churn (reason `no_chat_provider`). An+ * explicit `chronicle.job_budget_usd` with an unpriced model refuses with the+ * no_pricing guidance; a default cap on an unpriced model warns and runs.+ */+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult, PhaseStatus } from '../cycle.ts';+import { getChatModel, isAvailable } from '../ai/gateway.ts';+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_CONFIG, CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, RUN_NOW_COMMAND,+ type ChronicleLedgerRow, type ChronicleReason, type ChronicleRunDetails,+} from '../chronicle/contract.ts';+import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES } from '../chronicle/eligibility.ts';+import { claimChronicleRow, executeChronicleRow } from '../chronicle/execute.ts';+import { defaultJudge, type ChronicleJudge } from '../chronicle/extract-events.ts';+import {+ RETIRE_REASONS, chronicleDailyRemaining, decideChronicle, pruneChronicleReservations, upsertChronicleRow,+} from '../chronicle/ledger.ts';++export interface ChroniclePhaseOpts {+ dryRun?: boolean;+ signal?: AbortSignal;+ /** Test seam; the gateway judge otherwise. */+ judge?: ChronicleJudge;+ now?: () => Date;+ maxItems?: number;+ maxRunMs?: number;+ yieldDuringPhase?: () => Promise<void>;+ deadlineAtMs?: number | null;+}++/** Config key prefix of a recorded no_pricing refusal (doctor reads it); the gate is brain-wide. */+export const CHRONICLE_NO_PRICING_KEY_PREFIX = 'chronicle.no_pricing.';+const DISCOVERY_PER_SOURCE = 200;++/** Record a row for every chronicle-shaped page changed since activation that has none for its live content. */+async function discover(engine: BrainEngine, sourceId: string, ctx: {+ managed: boolean; enabled: boolean; activatedAt: Date; settings: Awaited<ReturnType<typeof chronicleSettings>>; now: Date; dryRun: boolean;+}): Promise<number> {+ const prefixes = RESCUE_SLUG_PREFIXES.map((p) => `${p}%`);+ const pages = await engine.executeRaw<{+ id: number; slug: string; type: string; compiled_truth: string | null; frontmatter: Record<string, unknown> | null;+ effective_date: Date | string | null; effective_date_source: string | null; content_hash: string; updated_at: Date | string;+ }>(+ `SELECT p.id, p.slug, p.type, p.compiled_truth, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash, p.updated_at+ FROM pages p+ WHERE p.source_id=$1 AND p.deleted_at IS NULL AND p.content_hash IS NOT NULL AND p.updated_at >= $2::timestamptz+ AND p.type <> 'event' AND p.slug NOT LIKE 'life/%'+ AND (p.type = ANY($3::text[]) OR p.slug LIKE ANY($4::text[]) OR EXISTS (SELECT 1 FROM chronicle_page_state e+ WHERE e.page_id=p.id AND e.state='extracted' AND cardinality(e.event_hashes) > 0))+ AND NOT EXISTS (SELECT 1 FROM chronicle_page_state c+ WHERE c.page_id=p.id AND c.content_hash=p.content_hash AND c.extractor_version=$5)+ ORDER BY p.updated_at, p.id LIMIT $6`,+ [sourceId, ctx.activatedAt.toISOString(), [...CHRONICLE_TYPES], prefixes, CHRONICLE_EXTRACTOR_VERSION, DISCOVERY_PER_SOURCE]);+ if (ctx.dryRun) return pages.length;+ for (const page of pages) {+ const base = { sourceId, pageId: Number(page.id), contentHash: page.content_hash, slug: page.slug, trigger: 'auto' as const };+ const shaped = (CHRONICLE_TYPES as string[]).includes(page.type) || RESCUE_SLUG_PREFIXES.some((p) => page.slug.startsWith(p));+ if (!shaped) {+ await upsertChronicleRow(engine, { ...base, state: 'skipped', reason: 'not_chronicle_shaped', nextAttemptAt: ctx.now });+ continue;+ }+ if (ctx.managed) {+ await upsertChronicleRow(engine, { ...base, state: 'skipped', reason: 'no_write_decision', nextAttemptAt: null });+ continue;+ }+ const decision = decideChronicle({ page, authority: null, noExtract: false, enabled: ctx.enabled, settings: ctx.settings, now: ctx.now });+ const settled = new Date(new Date(page.updated_at).getTime() + ctx.settings.settleSeconds * 1000);+ const retire = decision.state === 'skipped' && (RETIRE_REASONS as readonly string[]).includes(String(decision.reason));+ await upsertChronicleRow(engine, { ...base, state: decision.state, reason: decision.reason,+ nextAttemptAt: decision.state === 'pending' && decision.reason === null ? settled : retire ? ctx.now : decision.nextAttemptAt });+ }+ return pages.length;+}++/** Claimable rows of one source, retire-only rows first, then automatic, then backfill, oldest decision first. */+async function candidates(engine: BrainEngine, sourceId: string, enabled: boolean, limit: number): Promise<ChronicleLedgerRow[]> {+ return engine.executeRaw<ChronicleLedgerRow>(+ `SELECT c.* FROM chronicle_page_state c+ JOIN pages p ON p.id=c.page_id AND p.source_id=c.source_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL+ WHERE c.source_id=$1 AND c.extractor_version=$2+ AND (c.next_attempt_at IS NULL OR c.next_attempt_at <= now())+ AND ((c.state='pending' AND ($3 OR c.trigger='backfill'))+ OR (c.state='failed' AND c.attempts < $4 AND ($3 OR c.trigger='backfill')+ AND (c.next_attempt_at IS NOT NULL OR c.reason IN ('judge_llm_unavailable','no_pricing')))+ OR (c.state='skipped' AND c.next_attempt_at IS NOT NULL AND c.reason = ANY($5::text[])))+ ORDER BY (c.state='skipped') DESC, (c.trigger='auto') DESC, c.decided_at, c.page_id+ LIMIT $6`,+ [sourceId, CHRONICLE_EXTRACTOR_VERSION, enabled, CHRONICLE_DEFAULTS.maxAttempts, [...RETIRE_REASONS], limit]);+}++function result(status: PhaseStatus, summary: string, details: ChronicleRunDetails & Record<string, unknown>): PhaseResult {+ return { phase: 'chronicle', status, duration_ms: 0, summary, details };+}++export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhaseOpts = {}): Promise<PhaseResult> {+ const started = Date.now();+ const now = opts.now ?? (() => new Date());+ const dryRun = opts.dryRun === true;+ const maxItems = opts.maxItems ?? CHRONICLE_DEFAULTS.maxItemsPerRun;+ const remaining = opts.deadlineAtMs ? opts.deadlineAtMs - Date.now() - 30_000 : Infinity;+ const maxRunMs = Math.max(0, Math.min(opts.maxRunMs ?? CHRONICLE_DEFAULTS.maxRunMs, remaining));+ const [settings, enabled, managed] = await Promise.all([+ chronicleSettings(engine), isAutoChronicleEnabled(engine), managedPersistenceEnabled(engine)]);+ let activatedAt = settings.activatedAt;+ if (!activatedAt) {+ activatedAt = now();+ if (!dryRun) await engine.setConfig(CHRONICLE_CONFIG.activatedAt, 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: {},+ events_written: 0, events_retired: 0, deferred_daily_limit: 0, daily_limit: settings.dailyLimit,+ daily_remaining: 0, spent_usd: 0, unpriced_calls: 0, max_items: maxItems, per_source: {},+ auto_chronicle: enabled ? 'on' : 'off',+ };+ const count = (reason: string | null) => {+ if (!reason) return;+ details.reasons[reason as ChronicleReason] = (details.reasons[reason as ChronicleReason] ?? 0) + 1;+ };++ if (!dryRun) {+ await pruneChronicleReservations(engine);+ await engine.executeRaw(+ `UPDATE chronicle_page_state c SET state='skipped', reason='superseded', next_attempt_at=NULL, updated_at=now()+ WHERE c.state IN ('pending','failed') AND NOT EXISTS (SELECT 1 FROM pages p+ WHERE p.id=c.page_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL)`);+ }+ const sources = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map((s) => s.id);+ details.sources = sources.length;+ for (const sourceId of sources) {+ await discover(engine, sourceId, { managed, enabled, activatedAt, settings, now: now(), dryRun });+ }+ const queues = new Map<string, ChronicleLedgerRow[]>();+ for (const sourceId of sources) {+ const rows = await candidates(engine, sourceId, enabled, maxItems);+ if (rows.length) queues.set(sourceId, rows);+ details.candidates += rows.length;+ details.per_source[sourceId] = { candidates: rows.length, judged: 0 };+ }+ details.daily_remaining = await chronicleDailyRemaining(engine, settings.dailyLimit);+ const finishResult = (status: PhaseStatus, summary: string) => {+ if (details.candidates > 0 && !details.next_command) details.next_command = RUN_NOW_COMMAND;+ return result(status, summary, details);+ };+ if (details.candidates === 0) {+ details.reason = enabled ? 'nothing_pending' : 'auto_chronicle_off';+ return result(enabled ? 'ok' : 'skipped', enabled ? 'chronicle: nothing pending'+ : 'chronicle: auto_chronicle is off and no backfill rows are pending (turn on: gbrain config set auto_chronicle true)', details);+ }+ if (dryRun) return finishResult('ok', `chronicle (dry run): ${details.candidates} item(s) ready across ${queues.size} source(s)`);++ const 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);+ }+ const model = getChatModel();+ const pricingOverrides = await loadPricingOverrides(engine);+ const gate = resolveExtractAtomsCostGate(model, null, pricingOverrides, { explicitBudget: settings.explicitBudget });+ const refused = await settleExtractAtomsCostGate(engine, 'brain', gate, { budgetCap: settings.jobBudgetUsd, extractModel: model, dryRun },+ { phase: 'chronicle', keyPrefix: CHRONICLE_NO_PRICING_KEY_PREFIX, rollup: false });+ if (refused) return { ...refused, details: { ...details, ...refused.details } };++ const tz = await chronicleTz(engine);+ const maintenance = new Map<string, MaintenanceAuthority | null>();+ const sourceErrors: Record<string, string> = {};+ let items = 0;+ let limitHit = false;+ let lastYield = Date.now();+ while (queues.size > 0 && items < maxItems && Date.now() - started < maxRunMs) {+ for (const [sourceId, queue] of [...queues]) {+ if (items >= maxItems || Date.now() - started >= maxRunMs) break;+ if (opts.signal?.aborted) { const e = new Error('aborted'); e.name = 'AbortError'; throw e; }+ const next = queue.shift();+ if (!next || queue.length === 0) queues.delete(sourceId);+ if (!next) continue;+ if (limitHit && next.trigger === 'auto' && next.state !== 'skipped') { details.deferred_daily_limit++; continue; }+ if (!maintenance.has(sourceId)) {+ try { maintenance.set(sourceId, await maintenancePreflight(engine, sourceId)); }+ catch (error) {+ sourceErrors[sourceId] = error instanceof Error ? error.message : String(error);+ queues.delete(sourceId);+ continue;+ }+ }+ const claimed = await claimChronicleRow(engine, next);+ if (!claimed) continue;+ const outcome = await executeChronicleRow({ engine, settings, judge, gate, pricingOverrides, tz, now, signal: opts.signal,+ maintenance: maintenance.get(sourceId) ?? null }, claimed);+ if (outcome.kind === 'deferred') {+ // The limit is brain-wide: every remaining automatic row waits for a free slot.+ limitHit = true;+ details.deferred_daily_limit++;+ count('daily_limit');+ continue;+ }+ if (outcome.kind === 'waiting') continue;+ if (outcome.judged) { items++; details.judged++; details.per_source[sourceId].judged++; }+ if (outcome.state === 'extracted') {+ if (outcome.reason === 'no_events') details.no_events++; else details.extracted++;+ }+ if (outcome.state === 'failed') details.failed++;+ if (outcome.state !== 'extracted' || outcome.reason) count(outcome.reason);+ details.events_written += outcome.written;+ details.events_retired += outcome.retired;+ details.spent_usd += outcome.costUsd ?? 0;+ if (outcome.unpriced) details.unpriced_calls++;+ }+ if (opts.yieldDuringPhase && Date.now() - lastYield > 30_000) {+ lastYield = Date.now();+ await opts.yieldDuringPhase().catch(() => undefined);+ }+ }+ details.daily_remaining = await chronicleDailyRemaining(engine, settings.dailyLimit);+ if (Object.keys(sourceErrors).length) details.source_errors = sourceErrors;+ const status: PhaseStatus = details.failed > 0 || Object.keys(sourceErrors).length > 0 ? 'warn' : 'ok';+ const left = [...queues.values()].reduce((n, rows) => n + rows.length, 0);+ const summary = `chronicle: ${details.judged} page(s) judged, ${details.events_written} event(s) written, ` ++ `${details.events_retired} retired, ${details.failed} failed, ~$${details.spent_usd.toFixed(4)} spent` ++ (details.deferred_daily_limit ? `; ${details.deferred_daily_limit} wait for the daily limit (${settings.dailyLimit}/24h)` : '') ++ (left ? `; ${left} left for the next run (${RUN_NOW_COMMAND})` : '');+ if (left > 0) details.next_command = RUN_NOW_COMMAND;+ return finishResult(status, summary);+}diff --git a/src/core/cycle/extract-atoms-cost-gate.ts b/src/core/cycle/extract-atoms-cost-gate.tsindex 8bb7d50323..2c68726b8b 100644--- a/src/core/cycle/extract-atoms-cost-gate.ts+++ b/src/core/cycle/extract-atoms-cost-gate.ts@@ -65,24 +65,37 @@ export function resolveExtractAtomsCostGate(/** Config key holding the last refusal for a source; doctor's extract_health reads every one. */export const ATOMS_NO_PRICING_KEY_PREFIX = 'cycle.extract_atoms.no_pricing.';+/** Who settles a gate: the phase name, its log label and where its refusal is recorded for doctor. */+export interface CostGateTarget {+ phase: 'extract_atoms' | 'chronicle';+ /** Config key prefix of the recorded refusal; the source id is appended. */+ keyPrefix: string;+ /** extract_atoms also counts the refusal in its extraction rollup. */+ rollup: boolean;+}++const ATOMS_TARGET: CostGateTarget = { phase: 'extract_atoms', keyPrefix: ATOMS_NO_PRICING_KEY_PREFIX, rollup: true };+/*** Act on the gate before any work item. Default-cap drop: warn and return* null (the run proceeds uncapped). Refusal: record it for doctor, count the* run as an expected limit (not a halt), and return the `warn` phase result* the caller returns as-is — no model call. Any run past the gate clears the- * source's recorded refusal. A dry run records nothing.+ * source's recorded refusal. A dry run records nothing. extract_atoms and the+ * Life Chronicle phase share this policy through `target`.*/export async function settleExtractAtomsCostGate(engine: BrainEngine,sourceId: string,gate: ExtractAtomsCostGate,run: { budgetCap: number; extractModel: string; dryRun: boolean },+ target: CostGateTarget = ATOMS_TARGET,): Promise<PhaseResult | null> {- const key = `${ATOMS_NO_PRICING_KEY_PREFIX}${sourceId}`;+ const key = `${target.keyPrefix}${sourceId}`;if (!gate.refusal) {if (!gate.enforceCap) {console.error(- `[extract_atoms] ${gate.unpricedKind} model "${gate.unpricedModel}" is not in the pricing maps; ` ++ `[${target.phase}] ${gate.unpricedKind} model "${gate.unpricedModel}" is not in the pricing maps; ` +`running without a cost gate (a default cap cannot be enforced on an unpriced model). Look up its per-token price and register it to restore the cap: ` +`${pricingSetCommand(gate.unpricedModel!, gate.unpricedKind ?? 'chat')} (--rate 0 for local inference).`,);@@ -91,21 +104,21 @@ export async function settleExtractAtomsCostGate(return null;}const message = noPricingMessage(gate.refusal, { capUsd: run.budgetCap });- console.error(`[extract_atoms] ${message}`);+ console.error(`[${target.phase}] ${message}`);if (!run.dryRun) {await engine.setConfig(key, JSON.stringify({ ...gate.refusal, at: new Date().toISOString() })).catch(() => {});- await upsertExtractRollup(engine, { kind: 'atoms', source_id: sourceId, cost_delta: 0, ...classifyRunStop({ budget_exhausted: true }) });+ if (target.rollup) await upsertExtractRollup(engine, { kind: 'atoms', source_id: sourceId, cost_delta: 0, ...classifyRunStop({ budget_exhausted: true }) });}return {- phase: 'extract_atoms',+ phase: target.phase,status: 'warn',duration_ms: 0,- summary: `extract_atoms: ${message}`,+ summary: `${target.phase}: ${message}`,details: {reason: 'no_pricing',source_id: sourceId,no_pricing: gate.refusal,- atoms_extracted: 0,+ ...(target.phase === 'extract_atoms' ? { atoms_extracted: 0 } : {}),budget_usd: run.budgetCap,budget_exhausted: true,model: run.extractModel,diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 6f3e5af24f..5728acd454 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -27,6 +27,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {grade_takes: 'global',calibration_profile: 'global',drift: 'global',+ chronicle: 'global',embed: 'global',orphans: 'global',purge: 'global',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex a7af374662..65ed1f87b6 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -36,6 +36,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>grade_takes: { class: 'no_coordinated_write', reason: 'The cycle runs it with auto-resolve off, so it only caches verdicts in take_grade_cache; opt-in auto-applied resolutions go through the coordinated takes_resolve mutation.' },calibration_profile: { class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },drift: { class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },+ chronicle: { class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },enrich_thin: { class: 'writes', reason: 'Enriched pages publish through the maintenance coordinator.' },skillopt: { class: 'no_coordinated_write', reason: 'Writes skill files and proposals outside the brain database.' },diff --git a/src/core/minions/handlers/chronicle-extract.ts b/src/core/minions/handlers/chronicle-extract.tsindex 66164a0507..569527bfd8 100644--- a/src/core/minions/handlers/chronicle-extract.ts+++ b/src/core/minions/handlers/chronicle-extract.ts@@ -3,29 +3,38 @@*/import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';+import { UnrecoverableError } from '../errors.ts';/**- * v0.42.x (#2390) — Life Chronicle event extraction. NOT protected (bounded- * LLM spend per page; no shell). Enqueued by the put_page chronicle backstop- * and by `gbrain chronicle backfill`. Idempotent (content-addressed event- * slugs + projection upsert), so a retry re-runs to the same state.- * #3387: registered via registerBuiltinJob (gateway-refresh wrap) — the- * judge is a gateway chat call, so a stale worker gateway meant silent- * no_events for every extraction.+ * v0.42.x (#2390) — Life Chronicle event extraction for one page. Nothing+ * enqueues it since #5876 (write decisions and backfill are ledger rows the+ * `chronicle` cycle phase executes); it drains jobs queued by older releases+ * through the same executor, so they get the ledger, the BudgetTracker scope+ * (`chronicle:legacy` unless the job names its trigger), snapshot integrity+ * and reconciliation. Content already extracted is never paid for again; a+ * job whose `content_hash` no longer matches the page is superseded.+ * Failures are failures (D5): a provider error throws (retried with+ * backoff); a missing provider, no_pricing, a budget stop, truncation and+ * malformed output fail the job unrecoverably so its idempotency key is+ * released; only a genuine empty answer completes as `no_events`.+ * #3387: registered via registerBuiltinJob (gateway-refresh wrap).*/export function makeChronicleExtractHandler(engine: BrainEngine): MinionHandler {return async (job) => {const slug = typeof job.data.slug === 'string' ? job.data.slug : undefined;if (!slug) throw new Error('chronicle_extract job requires data.slug');- const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;- const { runChronicleExtract } = await import('../../chronicle/extract-events.ts');- const { chronicleTz } = await import('../../chronicle/config.ts');- const tz = await chronicleTz(engine);- return await runChronicleExtract(engine, {- slug,- sourceId,- tz,+ const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : 'default';+ const { runChronicleJob } = await import('../../chronicle/job.ts');+ const result = await runChronicleJob(engine, {+ slug, sourceId,+ contentHash: typeof job.data.content_hash === 'string' ? job.data.content_hash : undefined,+ trigger: job.data.trigger === 'auto' ? 'auto' : job.data.trigger === 'backfill' ? 'backfill' : 'legacy',signal: (job as { signal?: AbortSignal }).signal,});+ if (result.status === 'failed') {+ if (result.retry) throw new Error(`chronicle_extract ${slug}: ${result.reason}`);+ throw new UnrecoverableError(`chronicle_extract ${slug}: ${result.reason}`);+ }+ return result;};}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 9fb7282347..376da174d3 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1107,6 +1107,7 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (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)diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex f75d562f14..4fefd40ceb 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1816,6 +1816,7 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (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)diff --git a/src/core/schema-migrations/v198-chronicle-page-state.ts b/src/core/schema-migrations/v198-chronicle-page-state.tsindex fc6773b912..02e3095ef9 100644--- a/src/core/schema-migrations/v198-chronicle-page-state.ts+++ b/src/core/schema-migrations/v198-chronicle-page-state.ts@@ -32,6 +32,7 @@ export const v198: Migration = {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)diff --git a/src/schema.sql b/src/schema.sqlindex 34dee6ab37..32bd707301 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1812,6 +1812,7 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (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)diff --git a/test/chronicle-auto-phase.test.ts b/test/chronicle-auto-phase.test.tsnew file mode 100644index 0000000000..3f49b0b086--- /dev/null+++ b/test/chronicle-auto-phase.test.ts@@ -0,0 +1,356 @@+/**+ * #5876 — the Life Chronicle automatic path end to end on managed PGLite:+ * write decision → `chronicle` cycle phase → events, under the rails.+ *+ * Protects: default-on extraction runs on PGLite without a worker; settle,+ * supersede and the rolling daily reservation bound judged calls; judge+ * failures are failures; the per-page budget and the no_pricing policy;+ * snapshot re-validation; generation reconciliation that never touches+ * operator edits; the ledger survives job pruning.+ * Fails when: any rail lets an extra paid call through, a failure is+ * recorded as no_events, or an operator edit is overwritten or retired.+ * Seams: injected judge (`runPhaseChronicle({ judge })`) and the gateway's+ * test chat transport for the budget cases.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';+import type { ChronicleJudge, ChronicleJudgeResult } from '../src/core/chronicle/extract-events.ts';+import { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';+import { _resetBudgetTrackerWarningsForTest } from '../src/core/budget/budget-tracker.ts';+import { makeChronicleExtractHandler } from '../src/core/minions/handlers/chronicle-extract.ts';+import { UnrecoverableError } from '../src/core/minions/errors.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const today = new Date().toISOString().slice(0, 10);+const BODY = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);+const meeting = (title: string, body = BODY, extra = `date: ${today}\n`) => `---\ntype: meeting\ntitle: ${title}\n${extra}---\n\n${body}`;+const ev = (what: string, kind = 'commitment') => ({ when: today, who: ['people/alice-example'], what, kind });++async function put(ctx: OperationContext, slug: string, content: string): Promise<Record<string, unknown>> {+ const current = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });+ return await operationsByName.put_page.handler(ctx, { slug, content, ...(current ? { expected_revision: current.revision } : {}) }) as Record<string, unknown>;+}+/** Let every pending row through its settle window (the row's own next_attempt_at gate). */+async function settle(engine: BrainEngine) {+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");+}+function countingJudge(answer: (n: number) => ChronicleJudgeResult | Promise<ChronicleJudgeResult>) {+ const judge = Object.assign((async () => answer(++judge.calls)) as ChronicleJudge, { calls: 0 });+ return judge;+}+async function rows(engine: BrainEngine) {+ return engine.executeRaw<{ slug: string; state: string; reason: string | null; attempts: number; next_attempt_at: Date | null; unpriced: boolean; cost_usd: string | null }>(+ 'SELECT slug,state,reason,attempts,next_attempt_at,unpriced,cost_usd FROM chronicle_page_state ORDER BY slug, decided_at');+}+async function events(engine: BrainEngine) {+ return engine.executeRaw<{ slug: string; what: string; deleted: boolean; retired_by: string | null }>(+ `SELECT slug, frontmatter->'event'->>'what' AS what, deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by+ FROM pages WHERE type='event' ORDER BY what`);+}++afterEach(() => { __setChatTransportForTests(null); resetGateway(); _resetBudgetTrackerWarningsForTest(); });++describe('execution path (D10) and settle (D4)', () => {+ test('PGLite: write a meeting, run the phase, read the events', () => managedBrain(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' });+ const judge = countingJudge(() => ({ events: [ev('Alice agreed to ship the beta')] }));+ expect((await runPhaseChronicle(engine, { judge })).details).toMatchObject({ judged: 0 }); // still settling+ await settle(engine);+ const r = await runPhaseChronicle(engine, { judge });+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1 });+ const day = await operationsByName.chronicle_day.handler(ctx, { date: today }) as Array<{ summary: string; page_slug: string }>;+ expect(day.map((d) => [d.summary, d.page_slug])).toEqual([['Alice agreed to ship the beta', 'meetings/sync']]);+ }), 120_000);++ test('three puts inside the window → one judged call, one daily slot', () => managedBrain(async ({ engine, ctx }) => {+ for (const n of [1, 2, 3]) await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} Revision ${n}.`));+ const judge = countingJudge(() => ({ events: [ev('Alice agreed to ship the beta')] }));+ await settle(engine);+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(1);+ expect((await rows(engine)).map((r) => [r.state, r.reason])).toEqual([['skipped', 'superseded'], ['skipped', 'superseded'], ['extracted', null]]);+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM chronicle_judge_reservations'))[0].n).toBe(1);+ }), 120_000);+});++describe('daily reservation (E3)', () => {+ test('limit 2, three pages → two judged, the third waits; backfill is exempt', () => managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('chronicle.auto_daily_limit', '2');+ for (const n of [1, 2, 3]) await put(ctx, `meetings/m${n}`, meeting(`M${n}`));+ await settle(engine);+ const judge = countingJudge(() => ({ events: [] }));+ const first = await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(2);+ expect(first.details).toMatchObject({ deferred_daily_limit: 1, daily_remaining: 0 });+ // Workerless days do not burst: further runs inside the window judge nothing.+ await runPhaseChronicle(engine, { judge });+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(2);+ const pending = (await rows(engine)).filter((r) => r.state === 'pending');+ expect(pending).toHaveLength(1);+ const backfill = await runChronicleBackfill(engine, { yes: true });+ expect(backfill.queued).toBe(1);+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(3);+ expect((await rows(engine)).every((r) => r.state === 'extracted')).toBe(true);+ }), 120_000);++ test('retries consume reservations', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const judge = countingJudge(() => ({ events: [], failure: 'chat_error' }));+ await runPhaseChronicle(engine, { judge });+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second'");+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(2);+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM chronicle_judge_reservations'))[0].n).toBe(2);+ expect((await rows(engine))[0]).toMatchObject({ state: 'failed', reason: 'judge_chat_error', attempts: 2 });+ }), 120_000);++ test('opt-out between decision and run → zero calls', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ await engine.setConfig('auto_chronicle', 'false');+ const judge = countingJudge(() => ({ events: [ev('x')] }));+ const r = await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(0);+ expect(r.details.reason).toBe('auto_chronicle_off');+ expect((await rows(engine))[0].state).toBe('pending');+ }), 120_000);+});++describe('judge failure classes (E2/D5)', () => {+ test('a chat error is a failure with backoff, never no_events; [] is no_events; a refusal is judge_refused', () => managedBrain(async ({ engine, ctx }) => {+ for (const n of [1, 2, 3]) await put(ctx, `meetings/m${n}`, meeting(`M${n}`));+ await settle(engine);+ const answers: Record<string, ChronicleJudgeResult> = {+ 'meetings/m1': { events: [], failure: 'chat_error' }, 'meetings/m2': { events: [] }, 'meetings/m3': { events: [], failure: 'refused' },+ };+ await runPhaseChronicle(engine, { judge: async (input) => answers[input.slug] });+ const state = Object.fromEntries((await rows(engine)).map((r) => [r.slug, [r.state, r.reason, r.next_attempt_at !== null]]));+ expect(state).toEqual({+ 'meetings/m1': ['failed', 'judge_chat_error', true],+ 'meetings/m2': ['extracted', 'no_events', false],+ 'meetings/m3': ['skipped', 'judge_refused', false],+ });+ }), 120_000);++ test('the default judge reports a thrown provider error as chat_error', () => managedBrain(async ({ engine, ctx }) => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async () => { throw new Error('provider 503'); });+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const r = await runPhaseChronicle(engine);+ expect(r.details).toMatchObject({ judged: 1, failed: 1, no_events: 0, reasons: { judge_chat_error: 1 } });+ }), 120_000);++ test('no chat provider → no calls, no churn, the row keeps waiting', () => managedBrain(async ({ engine, ctx }) => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: {} });+ await put(ctx, 'meetings/m1', meeting('M1'));+ 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((await rows(engine))[0]).toMatchObject({ state: 'pending', attempts: 0 });+ }), 120_000);++ test('legacy chronicle_extract job: provider error throws, no provider is unrecoverable, [] completes', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/m1', meeting('M1'));+ await engine.executeRaw('DELETE FROM chronicle_page_state'); // a job queued by an older release, no decision row+ const handler = makeChronicleExtractHandler(engine);+ const job = { data: { slug: 'meetings/m1', sourceId: 'default' } } as never;+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: {} });+ await expect(handler(job)).rejects.toBeInstanceOf(UnrecoverableError);+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async () => { throw new Error('provider 503'); });+ const thrown = await handler(job).then(() => null, (e: unknown) => e);+ expect(thrown).toBeInstanceOf(Error);+ expect(thrown).not.toBeInstanceOf(UnrecoverableError);+ __setChatTransportForTests(async (opts: ChatOpts) => chatReply('[]', opts.model));+ expect(await handler(job)).toMatchObject({ status: 'no_events' });+ // Content already extracted is never paid for again.+ expect(await handler(job)).toMatchObject({ status: 'skipped', reason: 'already_extracted' });+ }), 120_000);+});++function chatReply(text: string, model?: string, tokens = { input: 10, output: 10 }): ChatResult {+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: model ?? 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ usage: { input_tokens: tokens.input, output_tokens: tokens.output, cache_read_tokens: 0, cache_creation_tokens: 0 } } as ChatResult;+}++describe('budget (C2/E4)', () => {+ test('a priced model over the default cap stops with budget_exhausted and publishes nothing', () => managedBrain(async ({ engine, ctx }) => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async (opts: ChatOpts) => chatReply(JSON.stringify([ev('Alice agreed to ship the beta')]), opts.model, { input: 10, output: 2_000_000 }));+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const r = await runPhaseChronicle(engine);+ expect(r.details).toMatchObject({ failed: 1, reasons: { budget_exhausted: 1 }, events_written: 0 });+ expect(await events(engine)).toEqual([]);+ expect(Number((await rows(engine))[0].cost_usd)).toBeGreaterThan(0.25);+ }), 120_000);++ test('default cap + unpriced model: warns and runs, spend marked unpriced', () => managedBrain(async ({ engine, ctx }) => {+ configureGateway({ chat_model: 'openai:gpt-unpriced-example', env: { OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async () => chatReply(JSON.stringify([ev('Alice agreed to ship the beta')]), 'openai:gpt-unpriced-example'));+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const r = await runPhaseChronicle(engine);+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, unpriced_calls: 1 });+ expect((await rows(engine))[0]).toMatchObject({ state: 'extracted', unpriced: true });+ }), 120_000);++ test('explicit cap + unpriced model: refuses with the no_pricing register command, zero calls', () => managedBrain(async ({ engine, ctx }) => {+ configureGateway({ chat_model: 'openai:gpt-unpriced-example', env: { OPENAI_API_KEY: 'sk-test' } });+ let calls = 0;+ __setChatTransportForTests(async (opts: ChatOpts) => { calls++; return chatReply('[]', opts.model); });+ await engine.setConfig('chronicle.job_budget_usd', '0.10');+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const r = await runPhaseChronicle(engine);+ expect(calls).toBe(0);+ expect(r.status).toBe('warn');+ expect(r.details.reason).toBe('no_pricing');+ expect(JSON.stringify(r.details.no_pricing)).toContain('gbrain pricing set openai:gpt-unpriced-example --input');+ expect((await rows(engine))[0].state).toBe('pending');+ }), 120_000);+});++describe('snapshot integrity (E5) and reconciliation (E8/C12/E9)', () => {+ test('an edit or a private flip during the judge call publishes nothing', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/edit', meeting('Edit'));+ await put(ctx, 'meetings/flip', meeting('Flip'));+ await settle(engine);+ const judge: ChronicleJudge = async (input) => {+ if (input.slug === 'meetings/edit') await put(ctx, 'meetings/edit', meeting('Edit', `${BODY} Changed while judging.`));+ else await put(ctx, 'meetings/flip', meeting('Flip', BODY, `date: ${today}\nvisibility: private\n`));+ return { events: [ev(`Event of ${input.slug}`)] };+ };+ const r = await runPhaseChronicle(engine, { judge });+ expect(r.details).toMatchObject({ judged: 2, events_written: 0, reasons: { superseded: 2 } });+ expect(await events(engine)).toEqual([]);+ }), 120_000);++ test('re-extraction retires the stale event and never touches an operator-edited sibling', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/sync', meeting('Sync'));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta'), ev('Bob owns the launch email', 'decision')] }) });+ const [, bob] = await events(engine);+ const page = (await engine.readPageSnapshot(bob.slug, { sourceId: 'default' }))!;+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');+ await operationsByName.put_page.handler(ctx, { slug: bob.slug, expected_revision: page.revision,+ content: serializePageToMarkdown({ ...page.page, compiled_truth: 'Bob owns the launch email (confirmed by the operator).' }, page.tags) });+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} Wording changed.`));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta in May')] }) });+ expect((await events(engine)).map((e) => [e.what, e.deleted, e.retired_by])).toEqual([+ ['Alice agreed to ship the beta', true, 'life-chronicle'],+ ['Alice agreed to ship the beta in May', false, null],+ ['Bob owns the launch email', false, null],+ ]);+ }), 120_000);++ test('a genuine [] retires the previous generation; a failed run retires nothing', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/sync', meeting('Sync'));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta')] }) });+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} v2.`));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [], failure: 'parse_failed' }) });+ expect((await events(engine)).map((e) => e.deleted)).toEqual([false]);+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} v3.`));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [] }) });+ expect((await events(engine)).map((e) => [e.deleted, e.retired_by])).toEqual([[true, 'life-chronicle']]);+ }), 120_000);++ test('a depth page that stops being a meeting retires its automatic events without a model call', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/sync', meeting('Sync'));+ await settle(engine);+ await runPhaseChronicle(engine, { judge: async () => ({ events: [ev('Alice agreed to ship the beta')] }) });+ await put(ctx, 'notes/sync', `---\ntype: note\ntitle: Sync\n---\n\n${BODY}`);+ const judge = countingJudge(() => ({ events: [] }));+ const r = await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(0);+ expect(r.details.events_retired).toBe(1);+ expect((await events(engine)).map((e) => e.retired_by)).toEqual(['life-chronicle']);+ }), 120_000);++ test('A → B → A: A\'s events are back after one more judged call', () => managedBrain(async ({ engine, ctx }) => {+ const judge = countingJudge(() => ({ events: [ev(judgeText)] }));+ let judgeText = 'Version A decision';+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} A.`));+ await settle(engine); await runPhaseChronicle(engine, { judge });+ judgeText = 'Version B decision';+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} B.`));+ await settle(engine); await runPhaseChronicle(engine, { judge });+ judgeText = 'Version A decision';+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} A.`));+ await settle(engine); await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(3);+ expect((await events(engine)).map((e) => [e.what, e.deleted])).toEqual([['Version A decision', false], ['Version B decision', true]]);+ }), 120_000);+});++describe('ledger and discovery (E1/E6/D12)', () => {+ test('extract, prune jobs, rerun backfill → zero judged calls', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'meetings/m1', meeting('M1'));+ await settle(engine);+ const judge = countingJudge(() => ({ events: [ev('x')] }));+ await runPhaseChronicle(engine, { judge });+ await engine.executeRaw('DELETE FROM minion_jobs');+ const again = await runChronicleBackfill(engine, { yes: true });+ expect(again).toMatchObject({ queued: 0, already_done: 1 });+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(1);+ }), 120_000);++ test('an invite becomes eligible once its end passes, without an edit', () => managedBrain(async ({ engine, ctx }) => {+ 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 });+ const judge = countingJudge(() => ({ events: [] }));+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(0);+ await Bun.sleep(1700);+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(1);+ }), 120_000);++ test('a managed page written without a decision is left to backfill (no_write_decision)', () => managedBrain(async ({ engine }) => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.putPage('meetings/legacy', { type: 'meeting', title: 'Legacy', compiled_truth: BODY, frontmatter: { date: today } });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const judge = countingJudge(() => ({ events: [] }));+ await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(0);+ expect((await rows(engine)).map((r) => [r.slug, r.state, r.reason])).toEqual([['meetings/legacy', 'skipped', 'no_write_decision']]);+ }), 120_000);+});++describe('unmanaged brain (E6)', () => {+ test('the phase scans pages changed since activation; earlier pages stay with backfill', async () => {+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema();+ try {+ await engine.setConfig('chronicle.auto_settle_seconds', '0');+ await engine.putPage('meetings/before', { type: 'meeting', title: 'Before', compiled_truth: BODY, frontmatter: { date: today } });+ await Bun.sleep(20);+ await engine.setConfig('chronicle.activated_at', new Date().toISOString());+ await Bun.sleep(20);+ await engine.putPage('meetings/after', { type: 'meeting', title: 'After', compiled_truth: BODY, frontmatter: { date: today } });+ const judge = countingJudge(() => ({ events: [ev('Alice agreed to ship the beta')] }));+ const r = await runPhaseChronicle(engine, { judge });+ expect(judge.calls).toBe(1);+ expect(r.details).toMatchObject({ extracted: 1, events_written: 1 });+ expect((await rows(engine)).map((x) => [x.slug, x.state])).toEqual([['meetings/after', 'extracted']]);+ } finally { await engine.disconnect(); }+ }, 120_000);+});diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.tsindex 32266824a9..f0c5287947 100644--- a/test/chronicle-extract.test.ts+++ b/test/chronicle-extract.test.ts@@ -1,15 +1,14 @@/*** v0.42.x — Life Chronicle (#2390) auto-emit extractor (Phase A.3).* PGLite in-memory. Covers eligibility, the extractor's parse barrier +- * idempotent writes (event pages + timeline projection), and the backstop's- * auto_chronicle gating + enqueue. The LLM judge is stubbed so the deterministic+ * idempotent writes (event pages + timeline projection). The write-path+ * decision and execution live in test/chronicle-auto-*.test.ts. The LLM judge is stubbed so the deterministic* write path is tested without a gateway.*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { isChronicleEligible } from '../src/core/chronicle/eligibility.ts';import { runChronicleExtract, parseJudgeJson, type ChronicleJudge } from '../src/core/chronicle/extract-events.ts';-import { runChronicleBackstop } from '../src/core/chronicle/backstop.ts';let engine: PGLiteEngine;const LONG_BODY = 'A'.repeat(120);@@ -172,28 +171,3 @@ describe('parseJudgeJson failure signalling (#2606)', () => {expect(parseJudgeJson('{"events": 1}')).toBeNull();});});--describe('runChronicleBackstop gating', () => {- beforeEach(async () => {- await engine.unsetConfig('auto_chronicle');- await engine.putPage('meetings/bs', { type: 'meeting', title: 'bs', compiled_truth: LONG_BODY });- });-- test('skips when auto_chronicle is off (default)', async () => {- const r = await runChronicleBackstop({ slug: 'meetings/bs', type: 'meeting', compiled_truth: LONG_BODY }, { engine, sourceId: 'default' });- expect(r).toEqual({ enqueued: false, skipped: 'auto_chronicle_off' });- });-- test('skips a diary page before consulting the flag', async () => {- const r = await runChronicleBackstop({ slug: 'life/diary/x', type: 'diary', compiled_truth: LONG_BODY }, { engine, sourceId: 'default' });- expect(r).toEqual({ enqueued: false, skipped: 'diary_excluded' });- });-- test('enqueues a chronicle_extract job when enabled + eligible', async () => {- await engine.setConfig('auto_chronicle', 'true');- const r = await runChronicleBackstop({ slug: 'meetings/bs', type: 'meeting', compiled_truth: LONG_BODY }, { engine, sourceId: 'default' });- expect(r.enqueued).toBe(true);- const jobs = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'chronicle_extract'`);- expect(Number(jobs[0].n)).toBeGreaterThanOrEqual(1);- });-});diff --git a/test/e2e/dream-cycle-phase-order-pglite.test.ts b/test/e2e/dream-cycle-phase-order-pglite.test.tsindex ef1aa30621..31fdc9197f 100644--- a/test/e2e/dream-cycle-phase-order-pglite.test.ts+++ b/test/e2e/dream-cycle-phase-order-pglite.test.ts@@ -143,6 +143,7 @@ const EXPECTED_PHASES: CyclePhase[] = ['grade_takes', // v0.36.1.0'calibration_profile', // v0.36.1.0'drift', // #2653 — drift detection (default OFF, report-only)+ 'chronicle', // #5876 — Life Chronicle events (default ON)'conversation_facts_backfill', // v0.41.11.0 — opt-in conversation backfill'enrich_thin', // v0.41.39 (#1700) — brain-internal stub enrichment (default OFF)'skillopt', // v0.42.0.0 — self-evolving skills (default OFF)diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex a8d1553a88..c5f0b9ec8b 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -27,6 +27,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { ALL_PHASES, runCycle, type CycleOpts, type CyclePhase, type PhaseResult } from '../src/core/cycle.ts';import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';import { runPhaseGradeTakes } from '../src/core/cycle/grade-takes.ts';+import { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';@@ -271,6 +272,20 @@ const MATRIX: Record<CyclePhase, Entry> = {expect((await engine.getPage(slug!, { sourceId: 'default' }))?.compiled_truth).toContain('DRIFTED — notes/drift-example');},},+ chronicle: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'meetings/chronicle-example', page('meeting', 'Weekly sync',+ `${'Alice and Bob reviewed the launch plan and agreed on the next steps. '.repeat(3)}`, `date: ${daysAgo(1)}\n`));+ await runChronicleBackfill(engine, { sourceId, yes: true });+ },+ reply: () => JSON.stringify([{ when: daysAgo(1), who: ['people/alice-example'], what: 'Alice agreed to ship the beta', kind: 'commitment' }]),+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1 });+ const [event] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='event'", [sourceId]);+ expect(await committed(engine, sourceId, event.slug)).not.toHaveLength(0);+ expect(await engine.executeRaw("SELECT state FROM chronicle_page_state WHERE source_id=$1", [sourceId])).toEqual([{ state: 'extracted' }]);+ },+ },conversation_facts_backfill: {config: { 'cycle.conversation_facts_backfill.enabled': 'true' },seed: async ({ engine, sourceId }) => put(engine, sourceId, 'conversations/2026-09-20-example', page('conversation', 'Chat',diff --git a/test/phase-scope-coverage.test.ts b/test/phase-scope-coverage.test.tsindex 957caf47aa..791502d6f1 100644--- a/test/phase-scope-coverage.test.ts+++ b/test/phase-scope-coverage.test.ts@@ -41,16 +41,16 @@ describe('PHASE_SCOPE coverage', () => {expect(invalid).toEqual([]);});- test('all 23 phases covered (regression on accidental omission)', () => {+ test('all 24 phases covered (regression on accidental omission)', () => {// Pin the count so a future PR that adds a phase to ALL_PHASES// without updating PHASE_SCOPE notices here too. The v0.39.1.0// master merge brought in the 17th phase (`schema-suggest`); v0.41// adds 'extract_atoms' + 'synthesize_concepts' (T9 lens packs) +// 'conversation_facts_backfill' (v0.41.11.0) for 20; v0.41.39 (#1700)// adds 'enrich_thin' and v0.42.0.0 adds 'skillopt' for a total of 22;- // #2653 adds 'drift' for 23.- expect(ALL_PHASES.length).toBe(23);- expect(Object.keys(PHASE_SCOPE).length).toBe(23);+ // #2653 adds 'drift' for 23; #5876 adds 'chronicle' for 24.+ expect(ALL_PHASES.length).toBe(24);+ expect(Object.keys(PHASE_SCOPE).length).toBe(24);});test('embed remains global (the headline brain-wide phase)', () => {