Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(chronicle): project ended calendar invites without a model call
garrytan85c63e934705
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex af1615cd0b..bc0610d25f 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -502,6 +502,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/chronicle-auto-phase-postgres.test.ts","test/e2e/chronicle-event-privacy-postgres.test.ts","test/e2e/chronicle-event-identity-postgres.test.ts",+ "test/e2e/chronicle-invite-projection-postgres.test.ts","test/e2e/chronicle-surfaces-postgres.test.ts",],// #5876: doctor auto_chronicle + the chronicle advisor read the ledger rollups.diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex b4e4e102a2..5db16bd3b5 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -7,7 +7,9 @@* 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+ * reconciliation → ledger outcome. An ended calendar invite takes the judge's+ * place with its deterministic projection (invite-projection.ts): no+ * reservation, no model call. A failed or superseded run never retires* the previous generation.*/import type { BrainEngine } from '../engine.ts';@@ -21,6 +23,7 @@ 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 { endedInviteProposal, markInviteEvents } from './invite-projection.ts';import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';@@ -164,7 +167,9 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronireturn done('skipped', reason);}- if (auto && !(await reserveChronicleSlot(engine, settings.dailyLimit, { sourceId: row.source_id, pageId: Number(row.page_id), contentHash: row.content_hash }))) {+ const judgeCtx = chronicleJudgeContext(snapshot.page);+ const invite = endedInviteProposal(snapshot.page, judgeCtx.attendees, now);+ if (auto && !invite && !(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' };}@@ -172,7 +177,6 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni`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}`,@@ -182,7 +186,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronilet thrown: unknown = null;const parent = getCurrentBudgetTracker();try {- result = await withBudgetTracker(tracker, () => ctx.judge(judgeCtx.input));+ result = await withBudgetTracker(tracker, () => (invite ? Promise.resolve({ events: [invite] }) : ctx.judge(judgeCtx.input)));} catch (error) {if ((error as Error)?.name === 'AbortError') throw error;thrown = error ?? new Error('judge failed');@@ -192,7 +196,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroniconst 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 };+ const judged = { judged: !invite, ...spend };// E4: gateway accounting defers a breach to the next reservation; check the cap explicitly.const overCap = tracker.cap !== undefined && tracker.totalSpent > tracker.cap;@@ -206,9 +210,10 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroniconst proposals = result?.events ?? [];let generation;try {+ const built = buildChronicleEvents(proposals, judgeCtx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, ctx.tz);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),+ events: invite ? markInviteEvents(built) : built,});} catch (error) {if ((error as Error)?.name === 'AbortError') throw error;diff --git a/src/core/chronicle/invite-projection.ts b/src/core/chronicle/invite-projection.tsnew file mode 100644index 0000000000..db1703301a--- /dev/null+++ b/src/core/chronicle/invite-projection.ts@@ -0,0 +1,51 @@+/**+ * Life Chronicle ended-invite projection.+ *+ * A calendar invite page (slug under `calendar/` or `cal/`, or type+ * `calendar-event`) with a title and frontmatter `start` and `end` is fully+ * structured, so once its end has passed the chronicle phase projects it into+ * one event without a model call:+ *+ * when = `start`, who = the page's attendees, where = `location`,+ * kind = `meeting`, what = `Scheduled: <title>`,+ * captured_via = `life-chronicle:invite`.+ *+ * An invite is not proof of attendance: the summary prefix and `captured_via`+ * say the meeting was scheduled, not that it happened. The projection stands+ * in for the judge inside the executor, so publication, ownership, the ledger+ * row and retirement are the judged path's; it takes no daily reservation and+ * records zero cost. An invite that has not ended, or a calendar page without+ * a title, start and end, keeps the judged path.+ */+import type { ChronicleEventProposal } from './extract-events.ts';+import type { BuiltChronicleEvent } from './publish.ts';++const CHRONICLE_INVITE_CAPTURED_VIA = 'life-chronicle:invite';+const SCHEDULED_PREFIX = 'Scheduled: ';+const INVITE_SLUG_PREFIXES = ['calendar/', 'cal/'];++function instant(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 one event an ended invite projects to; null when the page is not a structured, ended invite. */+export function endedInviteProposal(page: { slug: string; type: string; title: string; frontmatter?: Record<string, unknown> | null },+ attendees: string[], now: Date): ChronicleEventProposal | null {+ const fm = page.frontmatter ?? {};+ const invite = page.type === 'calendar-event' || INVITE_SLUG_PREFIXES.some((p) => page.slug.startsWith(p));+ const start = instant(fm.start);+ const end = instant(fm.end);+ const title = (page.title ?? '').trim();+ if (!invite || !start || !end || !title || end.getTime() > now.getTime()) return null;+ const location = typeof fm.location === 'string' && fm.location.trim() ? fm.location.trim() : null;+ return { when: typeof fm.start === 'string' ? fm.start.trim() : start.toISOString(), who: attendees,+ what: `${SCHEDULED_PREFIX}${title}`, where: location, kind: 'meeting' };+}++/** Mark projected events with their provenance. */+export function markInviteEvents(events: BuiltChronicleEvent[]): BuiltChronicleEvent[] {+ return events.map((ev) => ({ ...ev, frontmatter: { ...ev.frontmatter, captured_via: CHRONICLE_INVITE_CAPTURED_VIA } }));+}diff --git a/test/chronicle-auto-phase.test.ts b/test/chronicle-auto-phase.test.tsindex fa15d3b796..afe2a97e25 100644--- a/test/chronicle-auto-phase.test.ts+++ b/test/chronicle-auto-phase.test.ts@@ -337,8 +337,10 @@ describe('ledger and discovery (E1/E6/D12)', () => {await runPhaseChronicle(engine, { judge });expect(judge.calls).toBe(0);await Bun.sleep(1700);- await runPhaseChronicle(engine, { judge });- expect(judge.calls).toBe(1);+ const r = await runPhaseChronicle(engine, { judge });+ // An ended invite projects without a chat call (invite-projection.ts).+ expect(judge.calls).toBe(0);+ expect(r.details).toMatchObject({ extracted: 1, events_written: 1 });}), 120_000);test('a managed page written without a decision is left to backfill (no_write_decision)', () => brain(async ({ engine }) => {diff --git a/test/chronicle-invite-projection.test.ts b/test/chronicle-invite-projection.test.tsnew file mode 100644index 0000000000..ec0375bdd4--- /dev/null+++ b/test/chronicle-invite-projection.test.ts@@ -0,0 +1,128 @@+/**+ * Life Chronicle ended-invite projection (invite-projection.ts).+ *+ * Protects: an ended calendar invite becomes one `Scheduled: <title>` meeting+ * event with no chat call, no daily reservation and a zero-cost extracted+ * ledger row, through the same publication and ownership rules as a judged+ * page; an invite that has not ended waits as before; a calendar page that+ * is not a structured invite is still judged.+ * Fails when: an ended invite reaches the judge, the event reads as attended+ * (no scheduled label), a re-run rewrites or duplicates the event, or a+ * re-projection overwrites an operator's edit.+ * Existing coverage: chronicle-auto-phase pins when an invite becomes+ * eligible, not how it is extracted.+ * Seams: injected judge (`runPhaseChronicle({ judge })`), which must stay uncalled.+ */+import { 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 { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';+import 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';++const databaseUrl = process.env.GBRAIN_TEST_BACKEND === 'postgres' ? requirePostgresTestDatabase() : undefined;+const brain = (run: (b: ManagedBrain) => Promise<void>) => managedBrain(run, { databaseUrl });++const hourAgo = () => new Date(Date.now() - 3_600_000);+const invite = (opts: { start: Date; end: Date; location?: string }) => [+ '---', 'type: meeting', 'title: Weekly sync with alice-example', 'event_id: "evt-1"',+ `start: "${opts.start.toISOString()}"`, `end: "${opts.end.toISOString()}"`, 'all_day: false',+ 'attendees: ["[email protected]", "[email protected]"]', ...(opts.location ? [`location: "${opts.location}"`] : []), '---', '',+ '# Weekly sync with alice-example', '', 'Agenda: review the beta launch checklist and assign the remaining owners for each item.', '',+].join('\n');++async function put(ctx: OperationContext, slug: string, content: string) {+ 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>;+}+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 noJudge() {+ const judge = Object.assign((async () => { judge.calls++; return { events: [] }; }) as ChronicleJudge, { calls: 0 });+ return judge;+}+async function run(engine: BrainEngine, judge: ChronicleJudge) {+ await settle(engine);+ return (await runPhaseChronicle(engine, { judge })).details;+}+async function events(engine: BrainEngine) {+ return engine.executeRaw<{ slug: string; title: string; what: string; kind: string; where: string | null; who: string;+ captured_via: string; content_hash: string; deleted: boolean }>(+ `SELECT slug, title, frontmatter->'event'->>'what' AS what, frontmatter->'event'->>'kind' AS kind,+ frontmatter->'event'->>'where' AS "where", frontmatter->'event'->>'who' AS who,+ frontmatter->>'captured_via' AS captured_via, content_hash, deleted_at IS NOT NULL AS deleted+ FROM pages WHERE type='event' ORDER BY slug`);+}+const reservations = async (engine: BrainEngine) =>+ (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM chronicle_judge_reservations'))[0].n;++test('an ended invite projects to one scheduled meeting event with no chat call', () => brain(async ({ engine, ctx }) => {+ const start = new Date(Date.now() - 2 * 3_600_000);+ await put(ctx, 'calendar/2026/10/weekly-sync', invite({ start, end: hourAgo(), location: 'Room 4' }));+ const judge = noJudge();+ const details = await run(engine, judge);+ expect(judge.calls).toBe(0);+ expect(await reservations(engine)).toBe(0);+ expect(details).toMatchObject({ judged: 0, extracted: 1, events_written: 1, spent_usd: 0 });+ const [event] = await events(engine);+ expect(event).toMatchObject({ title: 'Scheduled: Weekly sync with alice-example', what: 'Scheduled: Weekly sync with alice-example',+ kind: 'meeting', where: 'Room 4', captured_via: 'life-chronicle:invite', deleted: false });+ expect(JSON.parse(event.who)).toEqual(['[email protected]', '[email protected]']);+ const [row] = await engine.executeRaw<{ state: string; reason: string | null; cost_usd: string | null; event_slugs: string[] }>(+ 'SELECT state, reason, cost_usd::text, event_slugs FROM chronicle_page_state');+ expect(row).toMatchObject({ state: 'extracted', reason: null, event_slugs: [event.slug] });+ expect(Number(row.cost_usd)).toBe(0);+ const day = start.toISOString().slice(0, 10);+ expect((await engine.getTimelineForDate(day, {})).map((r) => r.summary)).toContain('Scheduled: Weekly sync with alice-example');+}), 120_000);++test('an invite that has not ended waits and is not projected', () => brain(async ({ engine, ctx }) => {+ const receipt = await put(ctx, 'calendar/2026/10/next-sync', invite({ start: new Date(Date.now() + 3_600_000), end: new Date(Date.now() + 7_200_000) }));+ expect(receipt.chronicle_backstop).toMatchObject({ skipped: 'not_yet_happened' });+ const judge = noJudge();+ await run(engine, judge);+ expect(judge.calls).toBe(0);+ expect(await events(engine)).toEqual([]);+}), 120_000);++test('re-runs and a forced reprocess leave the projected event as it is', () => brain(async ({ engine, ctx }) => {+ await put(ctx, 'calendar/2026/10/weekly-sync', invite({ start: new Date(Date.now() - 2 * 3_600_000), end: hourAgo() }));+ const judge = noJudge();+ await run(engine, judge);+ const first = await events(engine);+ expect((await run(engine, judge))).toMatchObject({ candidates: 0, events_written: 0 });+ await engine.executeRaw('UPDATE chronicle_page_state SET extractor_version=1');+ expect(await runChronicleBackfill(engine, { yes: true })).toMatchObject({ queued: 1 });+ expect(await run(engine, judge)).toMatchObject({ extracted: 1, events_retired: 0 });+ expect(judge.calls).toBe(0);+ expect(await events(engine)).toEqual(first);+}), 120_000);++test('a re-projection never overwrites an operator-edited event', () => brain(async ({ engine, ctx }) => {+ const start = new Date(Date.now() - 2 * 3_600_000);+ await put(ctx, 'calendar/2026/10/weekly-sync', invite({ start, end: hourAgo() }));+ const judge = noJudge();+ await run(engine, judge);+ const [event] = await events(engine);+ const page = (await engine.readPageSnapshot(event.slug, { sourceId: 'default' }))!;+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');+ await operationsByName.put_page.handler(ctx, { slug: event.slug, expected_revision: page.revision,+ content: serializePageToMarkdown({ ...page.page, compiled_truth: 'Weekly sync with alice-example: attended, notes in meetings/.' }, page.tags) });+ const [edited] = await events(engine);+ await put(ctx, 'calendar/2026/10/weekly-sync', invite({ start, end: hourAgo(), location: 'Room 9' }));+ await run(engine, judge);+ expect(judge.calls).toBe(0);+ expect(await events(engine)).toEqual([edited]);+}), 120_000);++test('a calendar page without start and end is still judged', () => brain(async ({ engine, ctx }) => {+ const today = new Date().toISOString().slice(0, 10);+ await put(ctx, 'calendar/2026/10/notes', `---\ntype: meeting\ntitle: Offsite notes\ndate: ${today}\n---\n\n${'Alice and Bob walked through the offsite plan and agreed on owners. '.repeat(3)}`);+ const judge = noJudge();+ await run(engine, judge);+ expect(judge.calls).toBe(1);+}), 120_000);diff --git a/test/e2e/chronicle-invite-projection-postgres.test.ts b/test/e2e/chronicle-invite-projection-postgres.test.tsnew file mode 100644index 0000000000..aeca8830fc--- /dev/null+++ b/test/e2e/chronicle-invite-projection-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../chronicle-invite-projection.test.ts'));