Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chronicle: drop future-dated and day-less proposals before publication (CL-1, CL-2)

garrytanfc40fcef0fd1
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 13f925c9a0..65774c8fa5 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -321,7 +321,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step. | A capability this request needs is not configured or not reachable on this brain. | Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user's agreement). | agent | `gbrain doctor --json` | 1 | no |
-Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `no_chat_provider`.
+Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `future_dated`, `date_imprecise`, `no_chat_provider`.
More: [docs/guides/life-chronicle.md#skip-and-failure-codes](../../docs/guides/life-chronicle.md#skip-and-failure-codes)
diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.md
index ad00d959df..dd9f5454f3 100644
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@ -45,6 +45,29 @@ A page is extracted automatically when all of these hold:
The page must also stay unchanged for `chronicle.auto_settle_seconds` (default
180) so a note written in several passes is extracted once.
+## What becomes an event
+
+An event is something the page records as having happened by the end of its
+own day: the meeting or conversation itself, what was decided, said or agreed
+in it, and earlier events the text dates. Plans, follow-ups, deadlines and
+scheduled meetings are not events, even when the page gives them a date.
+
+Two rules are enforced after the model answers, before anything is written:
+
+- **No event after the page's own day.** The page's own day is the latest of
+ its own date (frontmatter `date` or `start`, or an authored effective date),
+ a calendar invite's `end`, and a conversation's last message, read in
+ `chronicle.tz` (default UTC). Anything on that day counts. A proposed event
+ dated later, or after today, is dropped as `future_dated`. "Board meeting in
+ Austin on May 15" in an April 18 meeting note never becomes a May 15 event.
+- **No invented days.** Events are stored by day. A past event the text dates
+ only by year or month ("back in 2024", "last month") is dropped as
+ `date_imprecise` rather than pinned to January 1 or the first of the month.
+
+The phase result reports dropped proposals by reason in `events_dropped`. When
+every proposed event of a page is dropped, its ledger row records that reason
+instead of `no_events`.
+
## Cost and limits
| Setting | Default | What it does |
@@ -154,6 +177,8 @@ brackets are filled in with real values on each surface.
| `judge_refused` | execution | The chat model refused or filtered the page; no events were written. | — | — | — |
| `page_missing` | execution | The page was deleted before extraction ran. | — | — | — |
| `no_events` | execution | Extraction read the page and found no events. | — | — | — |
+| `future_dated` | execution | Every event the extraction proposed was dated after the page's own day (a plan, follow-up or scheduled item), so none was written; only what happened by the end of the page's day becomes an event. | — | — | — |
+| `date_imprecise` | execution | Every event the extraction proposed had only a year or a month ("back in 2024"), so none was written; the timeline stores days and never invents one. | — | — | — |
| `no_chat_provider` | phase | No chat provider is configured on the brain host, so the chronicle phase made no calls. | — | user | credentials |
<!-- chronicle-reasons:end -->
diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.ts
index c40966ee16..18d5a6b8b0 100644
--- a/src/core/chronicle/contract.ts
+++ b/src/core/chronicle/contract.ts
@@ -21,6 +21,7 @@
*/
import { CHRONICLE_RUN_NOW_ARGV, type ChronicleReasonCode } from './reasons.ts';
import type { Action } from '../agent-output.ts';
+import type { ChronicleDropCounts } from './extract-events.ts';
/** Bump to re-extract every page once (the ledger key includes it). */
export const CHRONICLE_EXTRACTOR_VERSION = 1;
@@ -40,7 +41,9 @@ export interface ChronicleLedgerRow {
extractor_version: number;
slug: string;
state: ChronicleLedgerState;
- /** A `ChronicleReasonCode` from reasons.ts (or `no_events` on an extracted row); null on pending/extracted-with-events. */
+ /** A `ChronicleReasonCode` from reasons.ts. An extracted row carries one only when it published no events:
+ * `no_events`, or `future_dated` / `date_imprecise` when every proposed event was dropped. Null on pending
+ * and on extracted-with-events. */
reason: string | null;
trigger: ChronicleTrigger;
/** Writer of the decided revision (`persistence_requests.principal_*`); null on unmanaged scans and backfill. */
@@ -88,12 +91,15 @@ export interface ChronicleRunDetails {
candidates: number;
judged: number;
extracted: number;
+ /** Judged rows that published no events (the judge found none, or every proposal was dropped). */
no_events: number;
failed: number;
- /** Count per reason of rows skipped or failed in this run. */
+ /** Count per reason of rows skipped, failed or extracted without events in this run. */
reasons: Partial<Record<ChronicleReasonCode, number>>;
events_written: number;
events_retired: number;
+ /** Proposed events refused before publication, by reason (`future_dated`, `date_imprecise`); never written. */
+ events_dropped: ChronicleDropCounts;
/** Pending automatic rows left for the next run because the daily limit is used up. */
deferred_daily_limit: number;
daily_limit: number;
diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.ts
index b4e4e102a2..bc3a27ce4f 100644
--- a/src/core/chronicle/execute.ts
+++ b/src/core/chronicle/execute.ts
@@ -20,7 +20,10 @@ import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRo
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';
+import {
+ allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal,
+ type ChronicleDropCounts, type ChronicleJudge, type ChronicleJudgeResult,
+} from './extract-events.ts';
import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';
import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';
@@ -43,7 +46,7 @@ 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 };
+ written: number; retired: number; costUsd: number | null; unpriced: boolean; dropped: ChronicleDropCounts };
const CONFIG_BLOCKED = new Set(['judge_llm_unavailable', 'no_pricing']);
const LEASE_MS = 15 * 60_000;
@@ -121,7 +124,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
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 });
+ ({ kind: 'done', state, reason, judged: false, written: 0, retired: 0, costUsd: 0, unpriced: false, dropped: {}, ...extra });
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
if (!snapshot || Number(snapshot.page.id) !== Number(row.page_id)) {
@@ -204,25 +207,26 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
}
const proposals = result?.events ?? [];
+ const { events, dropped } = buildChronicleEvents(proposals, judgeCtx,
+ { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, { tz: ctx.tz, now });
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),
+ sourceId: row.source_id, pin, decisionRequestId: row.request_id, maintenance: ctx.maintenance, signal: ctx.signal, events,
});
} 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);
+ return done('failed', 'publish_error', { ...judged, dropped });
}
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 });
+ return done('skipped', 'superseded', { ...judged, written: generation.written.length, dropped });
}
- const reason = proposals.length === 0 ? 'no_events' : null;
+ const reason = events.length > 0 ? null : proposals.length === 0 ? 'no_events' : allDroppedReason(dropped);
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 });
+ return done('extracted', reason, { ...judged, written: generation.written.length, retired: generation.retired.length, dropped });
}
export type { ChronicleDepthPin };
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.ts
index 1249dfe7cb..32a7919eed 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -11,6 +11,8 @@
// output) so none is ever recorded as a genuine no_events answer.
import type { BrainEngine } from '../engine.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
+import { parseConversation } from '../conversation-parser/parse.ts';
+import { chroniclePageDate } from './eligibility.ts';
import { buildChronicleEvent, pinDepth, publishChronicleGeneration, type BuiltChronicleEvent } from './publish.ts';
export interface ChronicleEventProposal {
@@ -44,13 +46,24 @@ export interface ChronicleJudgeResult {
}
export type ChronicleJudge = (input: ChronicleJudgeInput) => Promise<ChronicleJudgeResult>;
+/**
+ * Proposals refused before publication, never written:
+ * - 'future_dated': dated after the depth page's own day (a plan, follow-up or scheduled item).
+ * - 'date_imprecise': the judge could not give the day ("back in 2024" → "2024").
+ */
+export type ChronicleDropReason = 'future_dated' | 'date_imprecise';
+export type ChronicleDropCounts = Partial<Record<ChronicleDropReason, number>>;
+
export interface ChronicleExtractResult {
slug: string;
status: 'extracted' | 'no_events' | 'skipped';
events_written: number;
+ /** On `no_events`: the drop reason when the judge proposed events and every one was dropped. */
reason?: string;
/** Owned events of an earlier generation this run retired. */
events_retired?: number;
+ /** Proposals refused before publication, by reason. */
+ events_dropped?: ChronicleDropCounts;
}
const KIND_VOCAB = new Set([
@@ -106,11 +119,75 @@ export interface ChronicleJudgeContext {
input: ChronicleJudgeInput;
effectiveDate: string | null;
attendees: string[];
+ /** The instants that date the page itself: its own date (eligibility's), a meeting's end, a conversation's last message. */
+ pageDates: Date[];
+}
+
+/** A date-only value (YYYY-MM-DD, stored as midnight UTC) is its own day; an instant is its day in `tz`. */
+function pageDay(d: Date, tz: string): string {
+ const iso = d.toISOString();
+ return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : isoDay(iso, tz);
+}
+
+/**
+ * The last day (YYYY-MM-DD in `tz`) an event extracted from this page may carry: the page's own
+ * day (its latest dating instant, so the whole day counts) and never after today. An undated page
+ * is bounded by today alone.
+ */
+export function chronicleEventCutoff(ctx: Pick<ChronicleJudgeContext, 'pageDates'>, tz: string, now: Date): string {
+ const today = isoDay(now.toISOString(), tz);
+ if (ctx.pageDates.length === 0) return today;
+ const own = ctx.pageDates.map((d) => pageDay(d, tz)).reduce((a, b) => (b > a ? b : a));
+ return own < today ? own : today;
+}
+
+const DAY_PRECISION = /^\d{4}-\d{2}-\d{2}(?:$|[T ])/;
+
+/**
+ * CL-1/CL-2: refuse proposals the page cannot support before anything is written. A `when` without
+ * a day (YYYY, YYYY-MM) is `date_imprecise`: the timeline stores days, so pinning it to the first of
+ * the month or year would invent one. A day after the page's own day is `future_dated`.
+ */
+export function screenChronicleProposals(proposals: ChronicleEventProposal[], ctx: Pick<ChronicleJudgeContext, 'pageDates'>,
+ tz: string, now: Date): { kept: ChronicleEventProposal[]; dropped: ChronicleDropCounts } {
+ const cutoff = chronicleEventCutoff(ctx, tz, now);
+ const kept: ChronicleEventProposal[] = [];
+ const dropped: ChronicleDropCounts = {};
+ for (const ev of proposals) {
+ const reason: ChronicleDropReason | null = !DAY_PRECISION.test(ev.when.trim()) ? 'date_imprecise'
+ : isoDay(ev.when.trim(), tz) > cutoff ? 'future_dated' : null;
+ if (reason) dropped[reason] = (dropped[reason] ?? 0) + 1;
+ else kept.push(ev);
+ }
+ return { kept, dropped };
+}
+
+/** The drop reason a page records when the judge proposed events and every one was dropped. */
+export function allDroppedReason(dropped: ChronicleDropCounts): ChronicleDropReason {
+ return (dropped.date_imprecise ?? 0) > (dropped.future_dated ?? 0) ? 'date_imprecise' : 'future_dated';
+}
+
+/** The latest message timestamp of a chat-shaped body (multi-day conversations end on their last message). */
+function lastMessageAt(body: string, fallbackDate: string | undefined): Date | null {
+ const { messages } = parseConversation(body, { fallbackDate, noPolish: true, noFallback: true });
+ let last: Date | null = null;
+ for (const m of messages) {
+ const d = new Date(m.timestamp);
+ if (!Number.isNaN(d.getTime()) && d.getUTCFullYear() > 1970 && (!last || d > last)) last = d;
+ }
+ return last;
+}
+
+function asDate(value: unknown): Date | null {
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
+ if (typeof value !== 'string' || !value.trim()) return null;
+ const d = new Date(value);
+ return Number.isNaN(d.getTime()) ? null : d;
}
/** The judge input for one immutable depth snapshot (E5: the judge never re-reads the page). */
export function chronicleJudgeContext(page: { slug: string; type: string; title: string; compiled_truth?: string | null;
- effective_date?: unknown; frontmatter?: Record<string, unknown> | null }): ChronicleJudgeContext {
+ effective_date?: unknown; effective_date_source?: string | null; frontmatter?: Record<string, unknown> | null }): ChronicleJudgeContext {
const fm = (page.frontmatter ?? {}) as Record<string, unknown>;
const edRaw = page.effective_date as unknown;
const effectiveDate: string | null =
@@ -119,19 +196,26 @@ export function chronicleJudgeContext(page: { slug: string; type: string; title:
: typeof fm.date === 'string' ? fm.date
: null;
const attendees = collectAttendees(fm);
+ const body = page.compiled_truth ?? '';
+ const own = chroniclePageDate({ effectiveDate: page.effective_date as Date | string | null | undefined,
+ effectiveDateSource: page.effective_date_source ?? null, frontmatter: fm });
+ const pageDates = [own, asDate(fm.end), lastMessageAt(body, own?.toISOString().slice(0, 10))].filter((d): d is Date => d !== null);
return {
- effectiveDate, attendees,
- input: { slug: page.slug, type: page.type, title: page.title, body: page.compiled_truth ?? '', effectiveDate, attendees },
+ effectiveDate, attendees, pageDates,
+ input: { slug: page.slug, type: page.type, title: page.title, body, effectiveDate, attendees },
};
}
-/** Proposals → event pages for one depth snapshot. */
+/** Proposals → event pages for one depth snapshot; proposals the page cannot support are dropped first. */
export function buildChronicleEvents(proposals: ChronicleEventProposal[], ctx: ChronicleJudgeContext,
- depth: { slug: string; visibility: 'private' | 'world'; contentHash: string }, tz: string): BuiltChronicleEvent[] {
- return proposals.map((ev) => buildChronicleEvent(ev, {
- depthSlug: depth.slug, attendees: ctx.attendees, effectiveDate: ctx.effectiveDate, tz,
+ depth: { slug: string; visibility: 'private' | 'world'; contentHash: string }, opts: { tz: string; now: Date },
+): { events: BuiltChronicleEvent[]; dropped: ChronicleDropCounts } {
+ const { kept, dropped } = screenChronicleProposals(proposals, ctx, opts.tz, opts.now);
+ const events = kept.map((ev) => buildChronicleEvent(ev, {
+ depthSlug: depth.slug, attendees: ctx.attendees, effectiveDate: ctx.effectiveDate, tz: opts.tz,
visibility: depth.visibility, depthHash: depth.contentHash, isoDay, normalizeKind,
}));
+ return { events, dropped };
}
/**
@@ -176,21 +260,29 @@ export async function runChronicleExtract(
return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'malformed_proposal' };
}
const pin = pinDepth(snapshot);
+ const built = buildChronicleEvents(proposals, ctx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash },
+ { tz, now: new Date() });
const generation = await publishChronicleGeneration(engine, {
- sourceId, pin, maintenance, decisionRequestId: null, signal: opts.signal,
- events: buildChronicleEvents(proposals, ctx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, tz),
+ sourceId, pin, maintenance, decisionRequestId: null, signal: opts.signal, events: built.events,
});
+ const dropped = Object.keys(built.dropped).length ? { events_dropped: built.dropped } : {};
if (generation.superseded) {
return { slug: opts.slug, status: 'skipped', events_written: generation.written.length, reason: generation.superseded,
- events_retired: generation.retired.length };
+ events_retired: generation.retired.length, ...dropped };
+ }
+ if (built.events.length === 0) {
+ return { slug: opts.slug, status: 'no_events', events_written: 0, events_retired: generation.retired.length,
+ ...(proposals.length ? { reason: allDroppedReason(built.dropped) } : {}), ...dropped };
}
- return { slug: opts.slug, status: proposals.length === 0 ? 'no_events' : 'extracted',
- events_written: generation.written.length, events_retired: generation.retired.length };
+ return { slug: opts.slug, status: 'extracted', events_written: generation.written.length, events_retired: generation.retired.length, ...dropped };
}
-const JUDGE_SYSTEM = `You segment a meeting/transcript page into discrete timeline EVENTS.
-Return ONLY a JSON array. Each element: {"when": ISO datetime or YYYY-MM-DD, "who": [entity slugs/names], "what": one-clause summary, "where": optional string, "kind": one of meeting|call|meal|solo|travel|work|commitment|decision|intro|conflict|milestone|event}.
-Prefer the page's known date for "when" when the text gives no explicit time. Use the provided attendee slugs for "who" when the text does not name participants. No prose, no markdown — just the JSON array.`;
+const JUDGE_SYSTEM = `You segment a meeting, conversation or calendar page into the discrete timeline EVENTS it records as having HAPPENED by the end of the page's date.
+Return ONLY a JSON array. Each element: {"when": YYYY-MM-DD or ISO datetime, "who": [entity slugs/names], "what": one-clause summary, "where": optional string, "kind": one of meeting|call|meal|solo|travel|work|commitment|decision|intro|conflict|milestone|event}.
+Extract only what already happened: the meeting or conversation itself, what was decided, said, agreed or done in it, and earlier events the text dates. A commitment made in the meeting is an event on the meeting's day ("Amara agreed to send the deck"), never on its due date.
+Never extract plans, intentions, follow-ups, deadlines, upcoming or scheduled meetings, or anything the text places after the page's date.
+"when": the page's date for the meeting itself and for what happened in it. For an earlier event, use the day the text gives. If the text gives only a year or a month ("back in 2024", "last month"), write just that precision ("2024", "2026-03"); never invent a day such as the first of the month or year, and never move the event to the page's date.
+Use the provided attendee slugs for "who" when the text does not name participants. No prose, no markdown — just the JSON array.`;
/**
* #2606: default output-token cap for the judge. Raised from the original
diff --git a/src/core/chronicle/job.ts b/src/core/chronicle/job.ts
index 1c6f37c0c6..c563c00499 100644
--- a/src/core/chronicle/job.ts
+++ b/src/core/chronicle/job.ts
@@ -60,7 +60,7 @@ export async function runChronicleJob(engine: BrainEngine, opts: {
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: outcome.reason ? 'no_events' : 'extracted', events_written: outcome.written, events_retired: outcome.retired };
}
return { slug, status: 'skipped', reason: outcome.reason ?? undefined };
}
diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.ts
index f275af9a66..82f6fec3f0 100644
--- a/src/core/chronicle/reasons.ts
+++ b/src/core/chronicle/reasons.ts
@@ -125,6 +125,10 @@ export const CHRONICLE_REASONS = {
meaning: () => 'The page was deleted before extraction ran.' },
no_events: { stage: 'execution',
meaning: () => 'Extraction read the page and found no events.' },
+ future_dated: { stage: 'execution',
+ meaning: () => 'Every event the extraction proposed was dated after the page\'s own day (a plan, follow-up or scheduled item), so none was written; only what happened by the end of the page\'s day becomes an event.' },
+ date_imprecise: { stage: 'execution',
+ meaning: () => 'Every event the extraction proposed had only a year or a month ("back in 2024"), so none was written; the timeline stores days and never invents one.' },
no_chat_provider: { stage: 'phase',
meaning: () => 'No chat provider is configured on the brain host, so the chronicle phase made no calls.',
fix: () => ({ consent: ['credentials'], actor: 'user', requires_exclusive: false,
diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.ts
index 0da69e8d71..37d4934157 100644
--- a/src/core/cycle/chronicle.ts
+++ b/src/core/cycle/chronicle.ts
@@ -35,7 +35,7 @@ import {
} 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 { defaultJudge, type ChronicleDropReason, type ChronicleJudge } from '../chronicle/extract-events.ts';
import {
RETIRE_REASONS, chronicleDailyRemaining, decideChronicle, pruneChronicleReservations, upsertChronicleRow,
} from '../chronicle/ledger.ts';
@@ -133,7 +133,7 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhas
}
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,
+ events_written: 0, events_retired: 0, events_dropped: {}, 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',
};
@@ -222,12 +222,15 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhas
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.reason) 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;
+ for (const [reason, n] of Object.entries(outcome.dropped) as Array<[ChronicleDropReason, number]>) {
+ details.events_dropped[reason] = (details.events_dropped[reason] ?? 0) + n;
+ }
details.spent_usd += outcome.costUsd ?? 0;
if (outcome.unpriced) details.unpriced_calls++;
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1ff419a60e..744ad35a90 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -78,7 +78,7 @@ export const CODES = {
cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },
catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
- chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
+ chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },
checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },
claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },
diff --git a/test/chronicle-date-quality.test.ts b/test/chronicle-date-quality.test.ts
new file mode 100644
index 0000000000..b4327f9ca2
--- /dev/null
+++ b/test/chronicle-date-quality.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Life Chronicle date quality (CL-1 premature events, CL-2 invented days) on a managed brain.
+ *
+ * Protects: an event is published only when the page records it as happened by the end of the
+ * page's own day. A plan dated after the page (a follow-up, a scheduled offsite) is dropped as
+ * `future_dated`; a past event the judge can date only by year or month ("back in 2024" → "2024")
+ * is dropped as `date_imprecise` instead of being pinned to YYYY-01-01. Same-day events, ended
+ * invites, a conversation's later messages and generation reconciliation keep working.
+ * Fails when: a proposal dated after the page's day, or without a day, reaches life/events/.
+ * Seams: injected judge (`runPhaseChronicle({ judge })`, `runChronicleExtract({ judge })`).
+ */
+import { 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 {
+ chronicleEventCutoff, chronicleJudgeContext, runChronicleExtract, screenChronicleProposals,
+ type ChronicleEventProposal, type ChronicleJudge,
+} from '../src/core/chronicle/extract-events.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase } from './helpers/test-backends.ts';
+
+/** PGLite in the unit lane; the e2e wrapper reruns every case on an isolated Postgres database. */
+const databaseUrl = process.env.GBRAIN_TEST_BACKEND === 'postgres' ? requirePostgresTestDatabase() : undefined;
+const brain = (run: (b: ManagedBrain) => Promise<void>) => managedBrain(run, { databaseUrl });
+
+const day = (offsetDays: number) => new Date(Date.now() + offsetDays * 86_400_000).toISOString().slice(0, 10);
+const PAGE_DAY = day(-3);
+const BODY = 'Alice and Bob reviewed the launch plan, agreed to ship the beta and scheduled the team offsite. '.repeat(3);
+const meeting = (body = BODY, extra = `date: ${PAGE_DAY}\n`) => `---\ntype: meeting\ntitle: Sync\n${extra}---\n\n${body}`;
+const ev = (when: string, what: string, kind = 'meeting'): ChronicleEventProposal => ({ when, who: ['people/alice-example'], what, kind });
+
+async function put(ctx: OperationContext, slug: string, content: string) {
+ const current = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });
+ return operationsByName.put_page.handler(ctx, { slug, content, ...(current ? { expected_revision: current.revision } : {}) });
+}
+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'");
+}
+async function events(engine: BrainEngine) {
+ return engine.executeRaw<{ day: string; what: string; deleted: boolean }>(
+ `SELECT substring(slug from 13 for 10) AS day, frontmatter->'event'->>'what' AS what, deleted_at IS NOT NULL AS deleted
+ FROM pages WHERE type='event' ORDER BY what`);
+}
+async function ledger(engine: BrainEngine) {
+ return engine.executeRaw<{ slug: string; state: string; reason: string | null }>(
+ 'SELECT slug, state, reason FROM chronicle_page_state WHERE attempts > 0 ORDER BY slug, decided_at');
+}
+async function runOnce(engine: BrainEngine, judge: ChronicleJudge) {
+ await settle(engine);
+ return runPhaseChronicle(engine, { judge });
+}
+
+describe('CL-1: nothing after the page\'s own day', () => {
+ test('a past meeting mentioning a future offsite publishes the meeting, never the offsite', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(PAGE_DAY, 'Alice and Bob reviewed the launch plan'),
+ ev(day(-1), 'Alice to send the beta notes', 'commitment'),
+ ev(day(30), 'Team offsite in Austin', 'travel'),
+ ] }));
+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1, events_dropped: { future_dated: 2 } });
+ expect((await events(engine)).map((e) => [e.day, e.what])).toEqual([[PAGE_DAY, 'Alice and Bob reviewed the launch plan']]);
+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/sync', state: 'extracted', reason: null }]);
+ const offsite = await operationsByName.chronicle_day.handler(ctx, { date: day(30) }) as unknown[];
+ expect(offsite).toEqual([]);
+ }), 120_000);
+
+ test('same-day events are kept, to the end of the page\'s day', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting(BODY, `date: ${PAGE_DAY}\nstart: ${PAGE_DAY}T10:00:00Z\n`));
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(PAGE_DAY, 'The sync itself'),
+ ev(`${PAGE_DAY}T23:30:00Z`, 'Late follow-up call', 'call'),
+ ] }));
+ expect(r.details).toMatchObject({ events_written: 2, events_dropped: {} });
+ expect((await events(engine)).map((e) => e.day)).toEqual([PAGE_DAY, PAGE_DAY]);
+ }), 120_000);
+
+ test('an ended calendar invite still produces its meeting event', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'calendar/standup', `---\ntype: calendar-event\ntitle: Standup\ndate: ${PAGE_DAY}\nstart: ${PAGE_DAY}T16:00:00Z\nend: ${PAGE_DAY}T16:30:00Z\n---\n\n${BODY}`);
+ const r = await runOnce(engine, async () => ({ events: [ev(`${PAGE_DAY}T16:00:00Z`, 'Standup with Alice')] }));
+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1 });
+ expect((await events(engine)).map((e) => [e.day, e.what])).toEqual([[PAGE_DAY, 'Standup with Alice']]);
+ }), 120_000);
+
+ test('a multi-day conversation runs to its last message', () => brain(async ({ engine, ctx }) => {
+ const chat = [`**Alice** (${day(-4)} 9:30 PM): Can we move the launch review?`,
+ `**Bob** (${day(-3)} 10:05 AM): Yes, moved it and shipped the beta build.`,
+ `**Alice** (${day(-3)} 10:07 AM): Great, thanks for shipping it.`].join('\n\n');
+ await put(ctx, 'conversations/launch', `---\ntype: conversation\ntitle: Launch chat\ndate: ${day(-4)}\n---\n\n${chat}\n`);
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(day(-4), 'Alice asked to move the launch review', 'event'),
+ ev(day(-3), 'Bob shipped the beta build', 'work'),
+ ev(day(-2), 'Launch review', 'meeting'),
+ ] }));
+ expect(r.details).toMatchObject({ events_written: 2, events_dropped: { future_dated: 1 } });
+ expect((await events(engine)).map((e) => e.day).sort()).toEqual([day(-4), day(-3)]);
+ }), 120_000);
+
+ test('re-extraction retires the old generation even when every new proposal is dropped', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ await runOnce(engine, async () => ({ events: [ev(PAGE_DAY, 'Alice and Bob reviewed the launch plan')] }));
+ await put(ctx, 'meetings/sync', meeting(`${BODY} Wording changed.`));
+ const r = await runOnce(engine, async () => ({ events: [ev(day(10), 'Offsite planning session')] }));
+ expect(r.details).toMatchObject({ judged: 1, no_events: 1, events_written: 0, events_retired: 1,
+ events_dropped: { future_dated: 1 }, reasons: { future_dated: 1 } });
+ expect((await events(engine)).map((e) => [e.what, e.deleted])).toEqual([['Alice and Bob reviewed the launch plan', true]]);
+ expect((await ledger(engine)).map((row) => [row.state, row.reason])).toEqual([['extracted', null], ['extracted', 'future_dated']]);
+ }), 120_000);
+});
+
+describe('CL-2: no invented days', () => {
+ test('"back in 2024" never becomes a 2024-01-01 event', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting(`${BODY} Back in 2024 Alice ran the first pilot; last month the pilot closed.`));
+ const r = await runOnce(engine, async () => ({ events: [
+ ev('2024', 'Alice ran the first pilot', 'work'),
+ ev('2024-03', 'The pilot closed', 'milestone'),
+ ] }));
+ expect(r.details).toMatchObject({ judged: 1, no_events: 1, events_written: 0,
+ events_dropped: { date_imprecise: 2 }, reasons: { date_imprecise: 1 } });
+ expect(await events(engine)).toEqual([]);
+ expect(await operationsByName.chronicle_day.handler(ctx, { date: '2024-01-01' })).toEqual([]);
+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/sync', state: 'extracted', reason: 'date_imprecise' }]);
+ }), 120_000);
+
+ test('the direct extractor reports drops and keeps the dated events', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ const r = await runChronicleExtract(engine, { slug: 'meetings/sync', judge: async () => ({ events: [
+ ev(PAGE_DAY, 'The sync itself'), ev('2024', 'Pilot', 'work'), ev(day(5), 'Offsite', 'travel'),
+ ] }) });
+ expect(r).toMatchObject({ status: 'extracted', events_written: 1, events_dropped: { date_imprecise: 1, future_dated: 1 } });
+ const none = await runChronicleExtract(engine, { slug: 'meetings/sync', judge: async () => ({ events: [ev(day(5), 'Offsite', 'travel')] }) });
+ expect(none).toMatchObject({ status: 'no_events', reason: 'future_dated', events_written: 0, events_dropped: { future_dated: 1 } });
+ }), 120_000);
+});
+
+describe('cutoff arithmetic', () => {
+ const ctxFor = (frontmatter: Record<string, unknown>, body = BODY) =>
+ chronicleJudgeContext({ slug: 'meetings/x', type: 'meeting', title: 'X', compiled_truth: body, frontmatter });
+ const now = new Date('2026-10-04T12:00:00Z');
+
+ test('a date-only page keeps its own day in any brain timezone', () => {
+ const ctx = ctxFor({ date: '2026-04-18' });
+ expect(chronicleEventCutoff(ctx, 'America/Los_Angeles', now)).toBe('2026-04-18');
+ expect(chronicleEventCutoff(ctx, 'Asia/Tokyo', now)).toBe('2026-04-18');
+ const { kept, dropped } = screenChronicleProposals([
+ ev('2026-04-18T22:00:00-07:00', 'Late call'), ev('2026-04-19', 'Next day'), ev('2026-04', 'Sometime in April'),
+ ], ctx, 'America/Los_Angeles', now);
+ expect(kept.map((k) => k.what)).toEqual(['Late call']);
+ expect(dropped).toEqual({ future_dated: 1, date_imprecise: 1 });
+ });
+
+ test('a meeting\'s end extends the day in the brain timezone; nothing passes today', () => {
+ expect(chronicleEventCutoff(ctxFor({ start: '2026-04-18T23:00:00Z', end: '2026-04-19T01:00:00Z' }), 'UTC', now)).toBe('2026-04-19');
+ expect(chronicleEventCutoff(ctxFor({ start: '2026-04-18T23:00:00Z', end: '2026-04-19T01:00:00Z' }), 'America/Los_Angeles', now)).toBe('2026-04-18');
+ expect(chronicleEventCutoff(ctxFor({ date: '2026-12-01' }), 'UTC', now)).toBe('2026-10-04');
+ expect(chronicleEventCutoff(ctxFor({}), 'UTC', now)).toBe('2026-10-04');
+ });
+});
diff --git a/test/e2e/chronicle-date-quality-postgres.test.ts b/test/e2e/chronicle-date-quality-postgres.test.ts
new file mode 100644
index 0000000000..dd6bb14826
--- /dev/null
+++ b/test/e2e/chronicle-date-quality-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../chronicle-date-quality.test.ts'));