Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chronicle: record the write-time decision in the publication transaction (#5876 T1)

garrytana67325c5c576
diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.ts
new file mode 100644
index 0000000000..a4c7854ded
--- /dev/null
+++ b/src/core/chronicle/ledger.ts
@@ -0,0 +1,205 @@
+/**
+ * Life Chronicle ledger (#5876, E1/E3/E6): the write-time decision and the
+ * durable record of each page content's extraction. See contract.ts for the
+ * columns and reason codes.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';
+import { derivedExtractionSkip } from '../persistence/derived-extraction-gate.ts';
+import { autoChronicleSetting, chronicleSettings, type ChronicleSettings } from './config.ts';
+import {
+ CHRONICLE_EXTRACTOR_VERSION, CHRONICLE_REASONS, RUN_NOW_COMMAND,
+ type ChronicleBackstopReceipt, type ChronicleLedgerRow, type ChronicleReason, type ChronicleTrigger,
+} from './contract.ts';
+import { chroniclePageDate, isChronicleEligible, isChronicleShaped } from './eligibility.ts';
+
+/** Publications that import page content and therefore carry a decision (C1). */
+const DECIDING_OPERATIONS = new Set(['put_page', 'capture', 'edit_page', 'restore_page', 'revert_version']);
+const DECIDING_INTENTS = new Set(['managed_sync_import', 'connector_v2_import']);
+/** Skip reasons after which an earlier extracted generation of the page is retired (E8). */
+export const RETIRE_REASONS = ['not_chronicle_shaped', 'dream_generated', 'too_short'] as const;
+
+export interface ChronicleDecisionPage {
+ type: string;
+ slug: string;
+ compiled_truth?: string | null;
+ frontmatter?: Record<string, unknown> | null;
+ effective_date?: Date | string | null;
+ effective_date_source?: string | null;
+}
+
+export type ChronicleDecision =
+ | { state: 'pending'; reason: null; nextAttemptAt: Date }
+ | { state: 'pending'; reason: 'not_yet_happened'; nextAttemptAt: Date }
+ | { state: 'skipped'; reason: ChronicleReason | string; nextAttemptAt: null };
+
+/**
+ * The automatic-path decision for one revision of a chronicle-shaped page.
+ * `authority` is the writer (null for trusted local unmanaged scans). The
+ * time rules come from the shared eligibility function; the settle window
+ * and the invite end become the row's `next_attempt_at`.
+ */
+export function decideChronicle(input: {
+ page: ChronicleDecisionPage; authority: Pick<WriteAuthority, 'restrictedNamespace' | 'delegated' | 'slugPrefixes' | 'operations'> | null;
+ noExtract: boolean; enabled: boolean; settings: Pick<ChronicleSettings, 'recentDays' | 'settleSeconds'>; now: Date;
+}): ChronicleDecision {
+ const skip = (reason: string): ChronicleDecision => ({ state: 'skipped', reason, nextAttemptAt: null });
+ if (!input.enabled) return skip('auto_chronicle_off');
+ if (input.noExtract) return skip('no_extract');
+ const confined = input.authority ? derivedExtractionSkip(input.authority) : null;
+ if (confined) return skip(confined);
+ const { page } = input;
+ const eligible = isChronicleEligible({
+ type: page.type as never, slug: page.slug, body: page.compiled_truth ?? '',
+ dreamGenerated: page.frontmatter?.dream_generated === true,
+ effectiveDate: page.effective_date ?? null, effectiveDateSource: page.effective_date_source ?? null,
+ frontmatter: page.frontmatter ?? null,
+ }, { now: input.now, recentDays: input.settings.recentDays });
+ if (!eligible.ok) {
+ if ('wait' in eligible) {
+ return { state: 'pending', reason: 'not_yet_happened', nextAttemptAt: new Date(eligible.until.getTime() + input.settings.settleSeconds * 1000) };
+ }
+ return skip(eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason);
+ }
+ return { state: 'pending', reason: null, nextAttemptAt: new Date(input.now.getTime() + input.settings.settleSeconds * 1000) };
+}
+
+/** The exact next command for a skip, with real values where the reason has them. */
+export function chronicleNextCommand(reason: string, page?: ChronicleDecisionPage): string | null {
+ if (reason === 'history' && page) {
+ const dated = chroniclePageDate({ effectiveDate: page.effective_date, effectiveDateSource: page.effective_date_source, frontmatter: page.frontmatter });
+ if (dated) return `gbrain chronicle-backfill --dated-since ${dated.toISOString().slice(0, 10)} --limit 50 --dry-run`;
+ }
+ return (CHRONICLE_REASONS as Record<string, { next: string | null }>)[reason]?.next ?? null;
+}
+
+export function chronicleReceipt(decision: ChronicleDecision, dailyRemaining: number, page?: ChronicleDecisionPage): ChronicleBackstopReceipt {
+ if (decision.state === 'pending' && decision.reason === null) {
+ return { pending: 'next_cycle', daily_remaining: dailyRemaining, next_command: RUN_NOW_COMMAND };
+ }
+ const reason = (decision.reason ?? 'not_yet_happened') as ChronicleReason;
+ const known = (CHRONICLE_REASONS as Record<string, { ask_user: boolean }>)[reason];
+ return { skipped: reason, next_command: chronicleNextCommand(reason, page), ask_user: known?.ask_user ?? false };
+}
+
+/** Automatic judge calls left in the rolling 24 h window. */
+export async function chronicleDailyRemaining(engine: BrainEngine, limit: number): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number | string }>(
+ "SELECT count(*) AS n FROM chronicle_judge_reservations WHERE reserved_at > now() - interval '24 hours'");
+ return Math.max(0, limit - Number(row?.n ?? 0));
+}
+
+/**
+ * E3: take one automatic judge slot immediately before the call. Serialized
+ * across every executor by a transaction-scoped advisory lock, so concurrent
+ * hosts cannot both take the last slot. false = the limit is used up.
+ */
+export async function reserveChronicleSlot(engine: BrainEngine, limit: number,
+ key: { sourceId: string; pageId: number; contentHash: string }): Promise<boolean> {
+ return engine.transaction(async (tx) => {
+ await tx.executeRaw("SELECT pg_advisory_xact_lock(hashtext('gbrain:chronicle:daily_reservation'))");
+ const [row] = await tx.executeRaw<{ n: number | string }>(
+ "SELECT count(*) AS n FROM chronicle_judge_reservations WHERE reserved_at > now() - interval '24 hours'");
+ if (Number(row?.n ?? 0) >= limit) return false;
+ await tx.executeRaw('INSERT INTO chronicle_judge_reservations (source_id, page_id, content_hash) VALUES ($1, $2, $3)',
+ [key.sourceId, key.pageId, key.contentHash]);
+ return true;
+ });
+}
+
+/** Reservations older than the window serve nothing; keep two days for doctor. */
+export async function pruneChronicleReservations(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw("DELETE FROM chronicle_judge_reservations WHERE reserved_at < now() - interval '48 hours'");
+}
+
+export interface ChronicleRowWrite {
+ sourceId: string;
+ pageId: number;
+ contentHash: string;
+ slug: string;
+ state: 'pending' | 'skipped';
+ reason: string | null;
+ trigger: ChronicleTrigger;
+ principalKind?: string | null;
+ principalId?: string | null;
+ requestId?: string | null;
+ noExtract?: boolean;
+ nextAttemptAt: Date | null;
+}
+
+/**
+ * Record a decision. An extracted row stays extracted unless a later
+ * generation of the page was extracted after it (A→B→A re-extracts A once,
+ * 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(
+ `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)
+ ON CONFLICT (source_id, page_id, content_hash, extractor_version) DO UPDATE SET
+ slug=EXCLUDED.slug, state=EXCLUDED.state, reason=EXCLUDED.reason, trigger=EXCLUDED.trigger,
+ principal_kind=EXCLUDED.principal_kind, principal_id=EXCLUDED.principal_id, request_id=EXCLUDED.request_id,
+ no_extract=EXCLUDED.no_extract, next_attempt_at=EXCLUDED.next_attempt_at, decided_at=now(), updated_at=now()
+ WHERE 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 newer
+ WHERE 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))`,
+ [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]);
+}
+
+/** Does an extracted generation with events exist for this page (so an ineligible revision must retire it)? */
+async function hasExtractedEvents(engine: BrainEngine, sourceId: string, pageId: number): Promise<boolean> {
+ const rows = await engine.executeRaw(
+ "SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
+ [sourceId, pageId]);
+ return rows.length > 0;
+}
+
+/** Record a skipped decision and schedule retirement of the page's earlier automatic events when it has any. */
+async function recordSkip(engine: BrainEngine, base: Omit<ChronicleRowWrite, 'state' | 'reason' | 'nextAttemptAt'>, reason: string): Promise<void> {
+ const retire = (RETIRE_REASONS as readonly string[]).includes(reason) && await hasExtractedEvents(engine, base.sourceId, base.pageId);
+ await upsertChronicleRow(engine, { ...base, state: 'skipped', reason, nextAttemptAt: retire ? new Date() : null });
+}
+
+type DecidingRequest = Pick<WriteRequest, 'id' | 'source_id' | 'slug'> & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>;
+
+/**
+ * E1: inside the publication transaction, record the decision for the
+ * published revision and put the receipt hint on the request outcome
+ * (`chronicle_backstop`). Pages that are not chronicle-shaped get neither,
+ * unless an earlier revision produced events that must now be retired.
+ */
+export async function recordChronicleDecision(tx: BrainEngine, row: DecidingRequest, snapshot: PageSnapshot | null,
+ outcome: Record<string, unknown>): Promise<void> {
+ if (!snapshot || snapshot.page.deleted_at || !snapshot.page.content_hash || !row.operation) return;
+ const kind = typeof row.intent?.kind === 'string' ? row.intent.kind : null;
+ if (!DECIDING_OPERATIONS.has(row.operation) && !(row.operation === 'submit_job' && kind && DECIDING_INTENTS.has(kind))) return;
+ const page = snapshot.page;
+ const base = { sourceId: row.source_id, pageId: Number(page.id), contentHash: String(page.content_hash), slug: page.slug,
+ trigger: 'auto' as const, principalKind: row.principal_kind ?? null, principalId: row.principal_id ?? null, requestId: row.id };
+ if (!isChronicleShaped(page.type, page.slug)) {
+ if (await hasExtractedEvents(tx, base.sourceId, base.pageId)) await recordSkip(tx, base, 'not_chronicle_shaped');
+ return;
+ }
+ const processing = row.intent?.processingOptions as { noExtract?: unknown } | undefined;
+ const noExtract = processing?.noExtract === true;
+ const [enabledRaw, settings] = await Promise.all([tx.getConfig('auto_chronicle').catch(() => null), chronicleSettings(tx)]);
+ const 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 });
+ const remaining = decision.state === 'pending' && decision.reason === null ? await chronicleDailyRemaining(tx, settings.dailyLimit) : 0;
+ outcome.chronicle_backstop = chronicleReceipt(decision, remaining, page);
+}
+
+export async function readChronicleRow(engine: BrainEngine, key: { sourceId: string; pageId: number; contentHash: string }): Promise<ChronicleLedgerRow | null> {
+ const [row] = await engine.executeRaw<ChronicleLedgerRow>(
+ 'SELECT * FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4',
+ [key.sourceId, key.pageId, key.contentHash, CHRONICLE_EXTRACTOR_VERSION]);
+ return row ?? null;
+}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index ff26878199..dff16db2fa 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -6,14 +6,15 @@ import { OperationError } from '../ops/contract.ts';
import type { PreparedMutation } from './coordinator.ts';
import { sha256 } from './digest.ts';
import { PARK_AFTER_FAILURES, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';
-import type { SqlEngine } from './model.ts';
+import type { SqlEngine, WriteRequest } from './model.ts';
+import { recordChronicleDecision } from '../chronicle/ledger.ts';
import { isFactsExtractionEnabled } from '../facts/extract.ts';
import { resolveDefaultVisibility } from '../facts/visibility.ts';
import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { refreshFenceClear } from './worktree-refresh-schema.ts';
/** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction. */
-export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest, snapshot: PageSnapshot | null,
+export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,
outcome: Record<string, unknown>, prepared?: PreparedMutation): Promise<void> {
if (prepared?.noop || prepared?.target === 'skill_bundle') return;
await declarePersistenceProtocol(tx);
@@ -38,6 +39,8 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };
else await queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
+ // #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
+ await recordChronicleDecision(tx, row, snapshot, outcome);
}
}
diff --git a/test/chronicle-auto-decision.test.ts b/test/chronicle-auto-decision.test.ts
new file mode 100644
index 0000000000..68c01b920d
--- /dev/null
+++ b/test/chronicle-auto-decision.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #5876 — the Life Chronicle write-time decision (E1/C1/C11/C13/C14/E11/D7).
+ *
+ * Protects: every coordinated page publication that imports a page records
+ * one ledger row for its content and returns a truthful `chronicle_backstop`
+ * hint; non-chronicle pages get no row and no receipt noise; the opt-out,
+ * confinement, --no-extract, recency and invite-end rules decide before any
+ * paid work; default ON when the key is unset.
+ * Fails when: a receipt says queued for content the phase will never run, a
+ * confined or opted-out write records a pending row, or ordinary notes grow a
+ * chronicle field.
+ * Seams: none for the managed put_page path; synthetic write-request rows for
+ * the submit_job intents and grant shapes.
+ */
+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 { decideChronicle, recordChronicleDecision } from '../src/core/chronicle/ledger.ts';
+import { isChronicleEligible } from '../src/core/chronicle/eligibility.ts';
+import { autoChronicleSetting } from '../src/core/chronicle/config.ts';
+import { prepareFactsBackstop } from '../src/core/persistence/effect-facts.ts';
+import type { WriteAuthority, WriteRequest } from '../src/core/persistence/model.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const today = new Date().toISOString().slice(0, 10);
+const lastYear = new Date(Date.now() - 400 * 86_400_000).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 = (extra = `date: ${today}\n`) => `---\ntype: meeting\ntitle: Sync\n${extra}---\n\n${BODY}`;
+
+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 rows(engine: BrainEngine) {
+ return engine.executeRaw<{ slug: string; state: string; reason: string | null; trigger: string; request_id: string | null; principal_kind: string | null }>(
+ 'SELECT slug,state,reason,trigger,request_id,principal_kind FROM chronicle_page_state ORDER BY slug, decided_at');
+}
+
+describe('managed put_page', () => {
+ test('an eligible meeting records one pending row with the writer; a no-op re-put changes nothing', () => managedBrain(async ({ engine, ctx }) => {
+ const receipt = await put(ctx, 'meetings/sync', meeting());
+ expect(receipt.chronicle_backstop).toEqual({ pending: 'next_cycle', daily_remaining: 200, next_command: 'gbrain dream --phase chronicle' });
+ const [row] = await rows(engine);
+ const [request] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=$1', [receipt.request_id]);
+ expect(row).toMatchObject({ slug: 'meetings/sync', state: 'pending', reason: null, trigger: 'auto', principal_kind: 'local_cli', request_id: request.id });
+ const again = await put(ctx, 'meetings/sync', meeting());
+ expect(again.chronicle_backstop).toBeUndefined();
+ expect(await rows(engine)).toHaveLength(1);
+ }), 120_000);
+
+ test('an ordinary note gets neither a row nor a receipt field', () => managedBrain(async ({ engine, ctx }) => {
+ const receipt = await put(ctx, 'notes/plan', `---\ntype: note\ntitle: Plan\n---\n\n${BODY}`);
+ expect('chronicle_backstop' in receipt).toBe(false);
+ expect(await rows(engine)).toEqual([]);
+ }), 120_000);
+
+ test('auto_chronicle false and an invalid word both skip with auto_chronicle_off; unset is on', () => managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('auto_chronicle', 'false');
+ expect((await put(ctx, 'meetings/a', meeting())).chronicle_backstop).toEqual({ skipped: 'auto_chronicle_off', next_command: 'gbrain config set auto_chronicle true', ask_user: true });
+ await engine.setConfig('auto_chronicle', 'flase');
+ expect((await put(ctx, 'meetings/b', meeting())).chronicle_backstop).toMatchObject({ skipped: 'auto_chronicle_off' });
+ await engine.unsetConfig('auto_chronicle');
+ expect((await put(ctx, 'meetings/c', meeting())).chronicle_backstop).toMatchObject({ pending: 'next_cycle' });
+ expect(autoChronicleSetting(null)).toBe('on');
+ expect(autoChronicleSetting('flase')).toBe('invalid');
+ }), 120_000);
+
+ test('a page dated last year skips history with a scoped backfill command', () => managedBrain(async ({ ctx }) => {
+ const receipt = await put(ctx, 'meetings/old', meeting(`date: ${lastYear}\n`));
+ expect(receipt.chronicle_backstop).toEqual({ skipped: 'history', ask_user: true,
+ next_command: `gbrain chronicle-backfill --dated-since ${lastYear} --limit 50 --dry-run` });
+ }), 120_000);
+
+ test('a future invite is not_yet_happened and waits until its end', () => managedBrain(async ({ engine, ctx }) => {
+ const end = new Date(Date.now() + 2 * 86_400_000).toISOString();
+ const receipt = await put(ctx, 'calendar/2026/10/standup', meeting(`start: ${end}\nend: ${end}\n`));
+ expect(receipt.chronicle_backstop).toEqual({ skipped: 'not_yet_happened', next_command: null, ask_user: false });
+ const [row] = await engine.executeRaw<{ state: string; next_attempt_at: Date }>('SELECT state,next_attempt_at FROM chronicle_page_state');
+ expect(row.state).toBe('pending');
+ expect(new Date(row.next_attempt_at).getTime()).toBeGreaterThanOrEqual(new Date(end).getTime());
+ }), 120_000);
+});
+
+describe('submit_job intents and grants (C1/C11)', () => {
+ const authority = (over: Partial<WriteAuthority> = {}): WriteAuthority => ({ version: 1, principal: { kind: 'local_cli', id: 'x' } as never,
+ remote: false, sourceId: 'default', sourceIncarnation: 'i', scopes: ['write'], operations: null, slugPrefixes: null, ...over });
+ async function decide(engine: BrainEngine, slug: string, row: Partial<WriteRequest>) {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const outcome: Record<string, unknown> = {};
+ await recordChronicleDecision(engine, { id: crypto.randomUUID(), source_id: 'default', slug, authority: authority(), principal_kind: 'local_cli', principal_id: 'x', ...row }, snapshot, outcome);
+ return outcome.chronicle_backstop;
+ }
+
+ test('managed sync and connector imports decide; --no-extract skips; other intents never decide', () => managedBrain(async ({ engine, ctx }) => {
+ for (const slug of ['meetings/sync-file', 'calendar/2026/09/invite', 'meetings/no-extract', 'meetings/maintenance']) await put(ctx, slug, meeting());
+ await engine.executeRaw('DELETE FROM chronicle_page_state');
+ expect(await decide(engine, 'meetings/sync-file', { operation: 'submit_job', intent: { kind: 'managed_sync_import', processingOptions: { noExtract: false } } }))
+ .toMatchObject({ pending: 'next_cycle' });
+ expect(await decide(engine, 'calendar/2026/09/invite', { operation: 'submit_job', intent: { kind: 'connector_v2_import' } }))
+ .toMatchObject({ pending: 'next_cycle' });
+ expect(await decide(engine, 'meetings/no-extract', { operation: 'submit_job', intent: { kind: 'managed_sync_import', processingOptions: { noExtract: true } } }))
+ .toMatchObject({ skipped: 'no_extract' });
+ expect(await decide(engine, 'meetings/maintenance', { operation: 'submit_job', intent: { kind: 'managed_maintenance_timeline_extract' } })).toBeUndefined();
+ expect((await rows(engine)).map((r) => [r.slug, r.state, r.reason])).toEqual([
+ ['calendar/2026/09/invite', 'pending', null], ['meetings/no-extract', 'skipped', 'no_extract'], ['meetings/sync-file', 'pending', null]]);
+ }), 120_000);
+
+ test('confined and operation-bound writers skip; the predicate is the one facts uses', () => managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/a', meeting());
+ expect(await decide(engine, 'meetings/a', { operation: 'put_page', authority: authority({ slugPrefixes: ['meetings/'] }) })).toMatchObject({ skipped: 'slug_bound_client' });
+ expect(await decide(engine, 'meetings/a', { operation: 'put_page', authority: authority({ delegated: true }) })).toMatchObject({ skipped: 'slug_bound_client' });
+ expect(await decide(engine, 'meetings/a', { operation: 'put_page', authority: authority({ operations: ['put_page'] }) })).toMatchObject({ skipped: 'operation_bound_client' });
+ expect(await decide(engine, 'meetings/a', { operation: 'put_page', authority: authority({ operations: ['put_page', 'extract_facts'] }) })).toMatchObject({ pending: 'next_cycle' });
+ const page = { slug: 'meetings/a', type: 'meeting', compiled_truth: BODY, frontmatter: {} } as never;
+ expect(await prepareFactsBackstop(engine, { authority: authority({ operations: ['put_page'] }), slug: 'meetings/a' } as never, page))
+ .toEqual({ skipped: 'operation_bound_client' });
+ }), 120_000);
+});
+
+describe('one eligibility function (E13/E11/C13/C14)', () => {
+ const now = new Date();
+ const policy = { now, recentDays: 30 };
+ const base = { type: 'meeting' as const, slug: 'meetings/x', body: BODY };
+ test('recency reads an authored date only; a fallback date counts as undated (recent)', () => {
+ expect(isChronicleEligible({ ...base, effectiveDate: lastYear, effectiveDateSource: 'date' }, policy)).toEqual({ ok: false, reason: 'history' });
+ expect(isChronicleEligible({ ...base, effectiveDate: lastYear, effectiveDateSource: 'fallback' }, policy)).toEqual({ ok: true });
+ expect(isChronicleEligible({ ...base, frontmatter: { start: `${lastYear}T10:00:00Z` } }, policy)).toEqual({ ok: false, reason: 'history' });
+ expect(isChronicleEligible({ ...base, effectiveDate: lastYear, effectiveDateSource: 'date' }, { now, recentDays: null })).toEqual({ ok: true });
+ });
+ test('an invite waits until its end; the settle window waits after a change', () => {
+ const end = new Date(now.getTime() + 3_600_000);
+ expect(isChronicleEligible({ ...base, frontmatter: { end: end.toISOString() } }, policy)).toEqual({ ok: false, reason: 'not_yet_happened', wait: true, until: end });
+ const changedAt = new Date(now.getTime() - 60_000);
+ expect(isChronicleEligible({ ...base, changedAt }, { ...policy, settleSeconds: 180 }))
+ .toEqual({ ok: false, reason: 'settling', wait: true, until: new Date(changedAt.getTime() + 180_000) });
+ });
+ test('decideChronicle orders opt-out, --no-extract and confinement before eligibility', () => {
+ const page = { type: 'meeting', slug: 'meetings/x', compiled_truth: 'short' };
+ const settings = { recentDays: 30, settleSeconds: 180 };
+ expect(decideChronicle({ page, authority: null, noExtract: false, enabled: false, settings, now }).reason).toBe('auto_chronicle_off');
+ expect(decideChronicle({ page, authority: null, noExtract: true, enabled: true, settings, now }).reason).toBe('no_extract');
+ expect(decideChronicle({ page, authority: null, noExtract: false, enabled: true, settings, now }).reason).toBe('too_short');
+ });
+});