Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: truthful receipt when the content is already extracted (#5876 D7)
garrytan125758114f40
diff --git a/src/core/chronicle/backfill.ts b/src/core/chronicle/backfill.tsindex 5c68bc0b7f..d968ef7b8e 100644--- a/src/core/chronicle/backfill.ts+++ b/src/core/chronicle/backfill.ts@@ -15,7 +15,7 @@import type { BrainEngine } from '../engine.ts';import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { usageCostUsd } from '../budget/reservation-cost.ts';-import { CHRONICLE_EXTRACTOR_VERSION, RUN_NOW_COMMAND } from './contract.ts';+import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, RUN_NOW_COMMAND } from './contract.ts';import { chronicleSettings } from './config.ts';import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES, chroniclePageDate, isChronicleEligible } from './eligibility.ts';import { upsertChronicleRow } from './ledger.ts';@@ -98,7 +98,7 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleB}>(`SELECT p.id, p.source_id, p.slug, p.type, p.compiled_truth, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash,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=$3 AND (c.state='extracted' OR (c.state IN ('pending','failed') AND c.trigger='backfill' AND c.attempts < 5))) AS done+ AND c.extractor_version=$3 AND (c.state='extracted' OR (c.state IN ('pending','failed') AND c.trigger='backfill' AND c.attempts < ${CHRONICLE_DEFAULTS.maxAttempts}))) AS doneFROM pages pWHERE p.deleted_at IS NULL AND (p.type = ANY($1::text[]) OR p.slug LIKE ANY($2::text[]))${scope} AND p.id > $${cursor}ORDER BY p.id LIMIT ${PAGE_BATCH}`, params);diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.tsindex 602438136f..d71a3f584e 100644--- a/src/core/chronicle/contract.ts+++ b/src/core/chronicle/contract.ts@@ -107,6 +107,7 @@ export const CHRONICLE_REASONS = {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 },diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.tsindex a4c7854ded..060120d2f5 100644--- a/src/core/chronicle/ledger.ts+++ b/src/core/chronicle/ledger.ts@@ -134,8 +134,8 @@ export interface ChronicleRowWrite {* E9); a pending or failed backfill row is never overwritten by an* automatic decision.*/-export async function upsertChronicleRow(engine: BrainEngine, w: ChronicleRowWrite): Promise<void> {- await engine.executeRaw(+export async function upsertChronicleRow(engine: BrainEngine, w: ChronicleRowWrite): Promise<boolean> {+ const written = await engine.executeRaw(`INSERT INTO chronicle_page_state AS c (source_id, page_id, content_hash, extractor_version, slug, state, reason, trigger,principal_kind, principal_id, request_id, no_extract, next_attempt_at)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::uuid, $12, $13::timestamptz)@@ -146,10 +146,12 @@ export async function upsertChronicleRow(engine: BrainEngine, w: ChronicleRowWriWHERE NOT (EXCLUDED.trigger='auto' AND c.trigger='backfill' AND c.state IN ('pending','failed'))AND (c.state <> 'extracted' OR EXISTS (SELECT 1 FROM chronicle_page_state newerWHERE newer.source_id=c.source_id AND newer.page_id=c.page_id AND newer.content_hash<>c.content_hash- AND newer.state='extracted' AND newer.updated_at > c.updated_at))`,+ AND newer.state='extracted' AND newer.updated_at > c.updated_at))+ RETURNING page_id`,[w.sourceId, w.pageId, w.contentHash, CHRONICLE_EXTRACTOR_VERSION, w.slug, w.state, w.reason, w.trigger,w.principalKind ?? null, w.principalId ?? null, w.requestId ?? null, w.noExtract === true,w.nextAttemptAt ? w.nextAttemptAt.toISOString() : null]);+ return written.length > 0;}/** Does an extracted generation with events exist for this page (so an ineligible revision must retire it)? */@@ -192,7 +194,14 @@ export async function recordChronicleDecision(tx: BrainEngine, row: DecidingRequconst decision = decideChronicle({ page, authority: row.authority ?? null, noExtract,enabled: autoChronicleSetting(enabledRaw) === 'on', settings, now: new Date() });if (decision.state === 'skipped') await recordSkip(tx, { ...base, noExtract }, String(decision.reason));- else await upsertChronicleRow(tx, { ...base, noExtract, state: 'pending', reason: decision.reason, nextAttemptAt: decision.nextAttemptAt });+ 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;+ return;+ }+ }const remaining = decision.state === 'pending' && decision.reason === null ? await chronicleDailyRemaining(tx, settings.dailyLimit) : 0;outcome.chronicle_backstop = chronicleReceipt(decision, remaining, page);}diff --git a/test/chronicle-auto-phase.test.ts b/test/chronicle-auto-phase.test.tsindex a709618059..7a3c513160 100644--- a/test/chronicle-auto-phase.test.ts+++ b/test/chronicle-auto-phase.test.ts@@ -303,6 +303,18 @@ describe('snapshot integrity (E5) and reconciliation (E8/C12/E9)', () => {});describe('ledger and discovery (E1/E6/D12)', () => {+ test('returning to extracted content before the newer revision ran costs nothing and says so', () => brain(async ({ engine, ctx }) => {+ const judge = countingJudge(() => ({ events: [ev('Version A decision')] }));+ await put(ctx, 'meetings/sync', meeting('Sync', `${BODY} A.`));+ 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 });+ 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]]);+ }), 120_000);+test('extract, prune jobs, rerun backfill → zero judged calls', () => brain(async ({ engine, ctx }) => {await put(ctx, 'meetings/m1', meeting('M1'));await settle(engine);