Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: ledger-aware backfill with consent, global limit and cost estimate (#5876 T9)
garrytana643de5bd131
diff --git a/src/core/chronicle/backfill.ts b/src/core/chronicle/backfill.tsnew file mode 100644index 0000000000..5c68bc0b7f--- /dev/null+++ b/src/core/chronicle/backfill.ts@@ -0,0 +1,157 @@+/**+ * `gbrain chronicle-backfill` core (#5876, D6/E10): the history path.+ *+ * Discovers meeting, conversation and calendar pages by type AND by the+ * rescue slug prefixes (any type), applies the shared eligibility rules+ * (invite end always; recency only with `recent`), consults the ledger so+ * content already extracted or queued is never paid for again (the ledger+ * survives `gbrain jobs prune`), and queues `pending` rows with+ * trigger='backfill' up to one global limit. The `chronicle` phase executes+ * them (`gbrain dream --phase chronicle`); backfill rows are exempt from the+ * daily limit and run even when automatic extraction is off. A dry run+ * changes nothing and reports the candidates, an estimated cost and the skip+ * reasons. Spending needs explicit consent (`yes`), keyed on the flag only.+ */+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 { chronicleSettings } from './config.ts';+import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES, chroniclePageDate, isChronicleEligible } from './eligibility.ts';+import { upsertChronicleRow } from './ledger.ts';++export interface ChronicleBackfillOpts {+ /** Only pages updated on/after this date (YYYY-MM-DD). */+ since?: string;+ /** Only pages whose own date (authored effective_date, else frontmatter date/start) is on/after this date. */+ datedSince?: string;+ /** Apply the automatic path's recency window (chronicle.auto_recent_days). */+ recent?: boolean;+ /** Global cap on pages queued in this run, across types and sources. */+ limit?: number;+ dryRun?: boolean;+ /** Explicit consent to queue paid extraction. Required unless dryRun. */+ yes?: boolean;+ /** Source scope (resolved by the op layer). */+ sourceId?: string;+ sourceIds?: string[];+ /** Model whose price the estimate uses (the configured chat model). */+ model?: string;+ now?: Date;+}++export interface ChronicleBackfillResult {+ dry_run: boolean;+ scanned: number;+ eligible: number;+ /** Pages this run queued (or, on a dry run, would queue). */+ queued: number;+ /** Current content already extracted, queued or running: never paid for twice. */+ already_done: number;+ skipped: Record<string, number>;+ limit: number;+ limit_reached: boolean;+ estimated_usd: number | 'unpriced';+ /** Per-page cap the estimate is clamped to (chronicle.job_budget_usd). */+ job_budget_usd: number;+ next_command: string;+ ask_user: boolean;+ message: string;+}++const DEFAULT_LIMIT = 1000;+const PAGE_BATCH = 500;+const JUDGE_OVERHEAD_CHARS = 900;+const EST_OUTPUT_TOKENS = 800;++function quote(value: string): string {+ return /^[\w.:/@+=-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;+}++export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleBackfillOpts): Promise<ChronicleBackfillResult> {+ const dryRun = opts.dryRun === true;+ const limit = opts.limit && opts.limit > 0 ? Math.floor(opts.limit) : DEFAULT_LIMIT;+ const now = opts.now ?? new Date();+ const settings = await chronicleSettings(engine);+ const overrides = await loadPricingOverrides(engine);+ const datedSince = opts.datedSince ? new Date(opts.datedSince) : null;+ const params: unknown[] = [[...CHRONICLE_TYPES], RESCUE_SLUG_PREFIXES.map((p) => `${p}%`), CHRONICLE_EXTRACTOR_VERSION];+ let scope = '';+ if (opts.sourceIds?.length) { params.push(opts.sourceIds); scope += ` AND p.source_id = ANY($${params.length}::text[])`; }+ else if (opts.sourceId) { params.push(opts.sourceId); scope += ` AND p.source_id = $${params.length}`; }+ if (opts.since) { params.push(opts.since); scope += ` AND p.updated_at >= $${params.length}::date`; }++ const result: ChronicleBackfillResult = {+ dry_run: dryRun, scanned: 0, eligible: 0, queued: 0, already_done: 0, skipped: {}, limit, limit_reached: false,+ estimated_usd: 0, job_budget_usd: settings.jobBudgetUsd, next_command: '', ask_user: true, message: '',+ };+ const skip = (reason: string) => { result.skipped[reason] = (result.skipped[reason] ?? 0) + 1; };+ let estimate = 0;+ let unpriced = false;+ let lastId = 0;+ for (;;) {+ params.push(lastId);+ const cursor = params.length;+ const pages = await engine.executeRaw<{+ id: number; source_id: string; 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 | null; done: boolean;+ }>(+ `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+ FROM pages p+ WHERE 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);+ params.pop();+ if (pages.length === 0) break;+ lastId = Number(pages[pages.length - 1].id);+ for (const page of pages) {+ result.scanned++;+ 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,+ effectiveDateSource: page.effective_date_source, frontmatter: page.frontmatter,+ }, { now, recentDays: opts.recent ? settings.recentDays : null });+ if (!eligible.ok) { skip(eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason); continue; }+ if (datedSince) {+ const dated = chroniclePageDate({ effectiveDate: page.effective_date, effectiveDateSource: page.effective_date_source, frontmatter: page.frontmatter });+ if (!dated || dated.getTime() < datedSince.getTime()) { skip('before_dated_since'); continue; }+ }+ if (!page.content_hash) { skip('no_content_hash'); continue; }+ result.eligible++;+ if (page.done) { result.already_done++; continue; }+ if (result.queued >= limit) { result.limit_reached = true; continue; }+ result.queued++;+ const chars = Math.min((page.compiled_truth ?? '').length, 12_000) + JUDGE_OVERHEAD_CHARS;+ const cost = opts.model ? usageCostUsd(opts.model, Math.ceil(chars / 4), EST_OUTPUT_TOKENS, 'chat', overrides) : null;+ if (cost === null) unpriced = true;+ else estimate += Math.min(cost, settings.jobBudgetUsd);+ if (dryRun || !opts.yes) continue;+ await upsertChronicleRow(engine, { sourceId: page.source_id, pageId: Number(page.id), contentHash: page.content_hash,+ slug: page.slug, state: 'pending', reason: null, trigger: 'backfill', nextAttemptAt: null });+ }+ }+ result.estimated_usd = unpriced ? 'unpriced' : Math.round(estimate * 10_000) / 10_000;+ const flags = [opts.since ? `--since ${quote(opts.since)}` : '', opts.datedSince ? `--dated-since ${quote(opts.datedSince)}` : '',+ opts.recent ? '--recent' : '', `--limit ${limit}`].filter(Boolean).join(' ');+ const cost = result.estimated_usd === 'unpriced'+ ? 'The chat model has no registered price, so the cost is unknown and no per-page cap applies'+ : `Estimated cost ~$${result.estimated_usd.toFixed(2)} (each page capped at $${settings.jobBudgetUsd.toFixed(2)})`;+ if (dryRun || !opts.yes) {+ result.next_command = result.queued > 0 ? `gbrain chronicle-backfill ${flags} --yes` : '';+ result.ask_user = result.queued > 0;+ result.message = result.queued === 0+ ? `Nothing to backfill: ${result.eligible} eligible page(s), ${result.already_done} already extracted or queued.`+ : `${result.queued} page(s) would be extracted (one paid chat call each). ${cost}. Ask the user before running: ${result.next_command}` ++ (dryRun ? '' : ' (backfill spends money, so it needs --yes; nothing was queued).');+ if (!dryRun) result.dry_run = true;+ return result;+ }+ result.next_command = result.queued > 0 ? RUN_NOW_COMMAND : '';+ result.ask_user = false;+ result.message = result.queued === 0+ ? `Nothing queued: ${result.eligible} eligible page(s), ${result.already_done} already extracted or queued.`+ : `Queued ${result.queued} page(s). ${cost}. They run in the next cycle (at most 50 per run); to run now: ${RUN_NOW_COMMAND}` ++ (result.limit_reached ? `. More pages remain: rerun gbrain chronicle-backfill ${flags} --yes after these finish.` : '.');+ return result;+}diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.tsindex 01da87a983..43078f8220 100644--- a/src/core/ops/chronicle.ts+++ b/src/core/ops/chronicle.ts@@ -277,73 +277,40 @@ const chronicle_backfill: Operation = {name: 'chronicle_backfill',outputRedaction: 'no_stored_text',description:- 'Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by ' +- 'enqueuing chronicle_extract jobs (one per eligible page). A page whose current content was already ' +- 'enqueued is skipped (already_enqueued), so repeat runs move on to pages not yet swept. --dry-run counts ' +- 'without enqueuing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.',+ 'Life Chronicle: queue existing meeting/conversation/calendar pages (by type or under meetings/, conversations/, ' ++ 'cal/, calendar/) for timeline-event extraction. One paid chat call per page, so it needs --yes; --dry-run ' ++ 'reports the candidates, an estimated cost and skip reasons. The chronicle_page_state ledger skips content ' ++ 'already extracted or queued, so repeats never pay twice. Queued pages run in the `chronicle` cycle phase ' ++ '(`gbrain dream --phase chronicle`), exempt from the daily limit. Local-only bulk op. ' ++ 'CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--dated-since YYYY-MM-DD] [--recent] [--limit N] [--dry-run | --yes]`.',scope: 'admin',mutating: true,localOnly: true,params: {- since: { type: 'string', description: 'Only pages updated on/after this date (YYYY-MM-DD).' },- limit: { type: 'number', description: 'Max pages per type to enqueue in this run (default 1000); pages already enqueued for their current content do not count.' },- dry_run: { type: 'boolean', description: 'Count eligible pages without enqueuing.' },+ since: { type: 'string', description: 'Only pages UPDATED on/after this date (YYYY-MM-DD). Use --dated-since for the page\'s own date.' },+ dated_since: { type: 'string', description: "Only pages whose own date (authored effective date, else frontmatter date/start) is on/after this date (YYYY-MM-DD)." },+ recent: { type: 'boolean', description: 'Only pages within chronicle.auto_recent_days (the automatic path\'s window).' },+ limit: { type: 'number', description: 'Max pages queued in this run, across all types and sources (default 1000).' },+ dry_run: { type: 'boolean', description: 'Count candidates, estimate cost and report skip reasons without queuing.' },+ yes: { type: 'boolean', description: 'Consent to queue paid extraction (one chat call per page). Ask the user first.' },},handler: async (ctx, p) => {- const { isChronicleEligible } = await import('../chronicle/eligibility.ts');- const TYPES = ['meeting', 'conversation', 'calendar-event'] as const;- const PAGE_BATCH = 200;- const limit = typeof p.limit === 'number' ? p.limit : 1000;- const updated_after = typeof p.since === 'string' ? p.since : undefined;- const dryRun = p.dry_run === true;+ const { runChronicleBackfill } = await import('../chronicle/backfill.ts');+ const { getChatModel } = await import('../ai/gateway.ts');+ let model: string | undefined;+ try { model = getChatModel(); } catch { model = undefined; }const scope = sourceScopeOpts(ctx);- type QueueLike = { add: (n: string, d: Record<string, unknown>, o?: { idempotency_key?: string }) => Promise<{ coalesced?: boolean }> };- let queue: QueueLike | null = null;- if (!dryRun) {- const { MinionQueue } = await import('../minions/queue.ts');- queue = new MinionQueue(ctx.engine) as unknown as QueueLike;- }- // #5329: one job per (source, page, content). The key makes a repeat run- // skip pages already enqueued or extracted for their current content and- // page past them, so the tail of the corpus is reached; an edited page- // gets a new key and is swept again.- const jobKey = (page: { source_id?: string; slug: string; content_hash?: string; updated_at?: Date | string }) =>- `chronicle_extract:${page.source_id ?? 'default'}:${page.slug}:${page.content_hash ?? String(page.updated_at ?? '')}`;- let scanned = 0, eligible = 0, enqueued = 0, alreadyEnqueued = 0;- const errors: { slug: string; error: string }[] = [];- for (const type of TYPES) {- let taken = 0;- for (let offset = 0; taken < limit; offset += PAGE_BATCH) {- const pages = await ctx.engine.listPages({ type, updated_after, limit: PAGE_BATCH, offset, ...scope });- const candidates = pages.filter((page) => {- scanned++;- const dreamGenerated = (page.frontmatter as Record<string, unknown> | undefined)?.dream_generated === true;- return isChronicleEligible({ type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated }).ok;- });- eligible += candidates.length;- const keys = candidates.map(jobKey);- const known = new Set(keys.length === 0 ? [] : (await ctx.engine.executeRaw<{ idempotency_key: string }>(- `SELECT idempotency_key FROM minion_jobs WHERE idempotency_key = ANY($1::text[]) AND status NOT IN ('dead', 'cancelled')`,- [keys],- )).map((row) => row.idempotency_key));- for (const [i, page] of candidates.entries()) {- if (taken >= limit) break;- if (known.has(keys[i])) { alreadyEnqueued++; continue; }- taken++;- if (dryRun || !queue) continue;- try {- const job = await queue.add('chronicle_extract', { slug: page.slug, sourceId: page.source_id }, { idempotency_key: keys[i] });- if (job.coalesced) alreadyEnqueued++;- else enqueued++;- } catch (e) {- // Never swallow — surface per-page failures (the #2057 no-swallow pattern).- errors.push({ slug: page.slug, error: e instanceof Error ? e.message : String(e) });- }- }- if (pages.length < PAGE_BATCH) break;- }- }- return { scanned, eligible, enqueued, already_enqueued: alreadyEnqueued, dry_run: dryRun, errors };+ return runChronicleBackfill(ctx.engine, {+ since: typeof p.since === 'string' ? p.since : undefined,+ datedSince: typeof p.dated_since === 'string' ? p.dated_since : undefined,+ recent: p.recent === true,+ limit: typeof p.limit === 'number' ? p.limit : undefined,+ dryRun: p.dry_run === true,+ yes: p.yes === true,+ sourceId: scope.sourceId,+ sourceIds: scope.sourceIds,+ model,+ });},cliHints: { name: 'chronicle-backfill' },};diff --git a/test/chronicle-backfill.test.ts b/test/chronicle-backfill.test.tsindex fbb2b9e558..2fc75c8042 100644--- a/test/chronicle-backfill.test.ts+++ b/test/chronicle-backfill.test.ts@@ -1,14 +1,31 @@/**- * v0.42.x — Life Chronicle (#2390) backfill op (Phase A.8).+ * v0.42.x — Life Chronicle (#2390) backfill op (Phase A.8); #5876 ledger semantics.+ *+ * Protects: backfill queues ledger rows (trigger 'backfill') the `chronicle`+ * phase executes; it needs explicit consent (--yes) and a dry run changes+ * nothing; discovery finds rescue-prefix pages of any type; --limit is one+ * global cap; --since filters on the update date and --dated-since on the+ * page's own date; --recent applies the recency window; the dry run reports+ * an estimated cost and skip reasons; repeat runs progress through every page+ * (#5329) and never re-queue content already extracted or queued.+ * Seams: none; in-memory PGLite.*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operationsByName } from '../src/core/operations.ts';import type { OperationContext } from '../src/core/operations.ts';+import { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';let engine: PGLiteEngine;const mkCtx = (): OperationContext => ({ engine, remote: false, sourceId: 'default' } as unknown as OperationContext);const LONG = 'B'.repeat(120);+type R = { queued: number; already_done: number; eligible: number; skipped: Record<string, number>; estimated_usd: number | 'unpriced';+ next_command: string; ask_user: boolean; dry_run: boolean; limit_reached: boolean; message: string };+const run = async (p: Record<string, unknown>, ctx = mkCtx()) => await operationsByName.chronicle_backfill.handler(ctx, p) as R;+async function queued() {+ return (await engine.executeRaw<{ slug: string; source_id: string }>(+ "SELECT slug, source_id FROM chronicle_page_state WHERE trigger='backfill' AND state='pending' ORDER BY slug")).map((r) => `${r.source_id}:${r.slug}`);+}beforeAll(async () => {engine = new PGLiteEngine();@@ -17,77 +34,98 @@ beforeAll(async () => {});afterAll(async () => { await engine.disconnect(); });beforeEach(async () => {- await engine.executeRaw(`DELETE FROM minion_jobs WHERE name = 'chronicle_extract'`);- await engine.executeRaw(`DELETE FROM pages WHERE type IN ('meeting','diary')`);+ await engine.executeRaw('DELETE FROM chronicle_page_state');+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'meetings/%' OR slug LIKE 'conversations/%' OR slug LIKE 'life/%'`);});describe('chronicle_backfill op', () => {- test('dry-run counts eligible meetings without enqueuing', async () => {+ test('dry-run counts eligible meetings without queuing; a live run without --yes queues nothing and asks', async () => {await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });await engine.putPage('meetings/m2', { type: 'meeting', title: 'm2', compiled_truth: LONG });await engine.putPage('life/diary/d1', { type: 'diary', title: 'd1', compiled_truth: LONG }); // excluded- const r = await operationsByName.chronicle_backfill.handler(mkCtx(), { dry_run: true }) as { eligible: number; enqueued: number };- expect(r.eligible).toBe(2);- expect(r.enqueued).toBe(0);- const jobs = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name='chronicle_extract'`);- expect(Number(jobs[0].n)).toBe(0);+ const dry = await run({ dry_run: true });+ expect(dry).toMatchObject({ eligible: 2, queued: 2, dry_run: true, ask_user: true, next_command: 'gbrain chronicle-backfill --limit 1000 --yes' });+ const unconsented = await run({});+ expect(unconsented).toMatchObject({ queued: 2, dry_run: true, ask_user: true });+ expect(unconsented.message).toContain('needs --yes; nothing was queued');+ expect(await queued()).toEqual([]);});- test('enqueues one chronicle_extract per eligible meeting', async () => {+ test('--yes queues one backfill row per eligible meeting and names the run command', async () => {await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });await engine.putPage('meetings/m2', { type: 'meeting', title: 'm2', compiled_truth: LONG });- const r = await operationsByName.chronicle_backfill.handler(mkCtx(), {}) as { eligible: number; enqueued: number; errors: unknown[] };- expect(r.eligible).toBe(2);- expect(r.enqueued).toBe(2);- expect(r.errors).toHaveLength(0);- const jobs = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name='chronicle_extract'`);- expect(Number(jobs[0].n)).toBe(2);+ const r = await run({ yes: true });+ expect(r).toMatchObject({ eligible: 2, queued: 2, dry_run: false, ask_user: false, next_command: 'gbrain dream --phase chronicle' });+ expect(await queued()).toEqual(['default:meetings/m1', 'default:meetings/m2']);});- test('unscoped backfill enqueues each page under its own source', async () => {+ test('unscoped backfill queues each page under its own source', async () => {await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other-src', 'other-src') ON CONFLICT (id) DO NOTHING`);await engine.putPage('meetings/default-src', { type: 'meeting', title: 'default', compiled_truth: LONG });await engine.putPage('meetings/other-src', { type: 'meeting', title: 'other', compiled_truth: LONG }, { sourceId: 'other-src' });- const ctx = { engine, remote: false } as unknown as OperationContext;-- const r = await operationsByName.chronicle_backfill.handler(ctx, {}) as { eligible: number; enqueued: number; errors: unknown[] };-- expect(r.eligible).toBe(2);- expect(r.enqueued).toBe(2);- expect(r.errors).toHaveLength(0);- const jobs = await engine.executeRaw<{ data: { slug: string; sourceId: string } }>(- `SELECT data FROM minion_jobs WHERE name='chronicle_extract' ORDER BY data->>'slug'`- );- expect(jobs.map((j) => j.data)).toEqual([- { slug: 'meetings/default-src', sourceId: 'default' },- { slug: 'meetings/other-src', sourceId: 'other-src' },- ]);+ const r = await run({ yes: true }, { engine, remote: false } as unknown as OperationContext);+ expect(r.queued).toBe(2);+ expect(await queued()).toEqual(['default:meetings/default-src', 'other-src:meetings/other-src']);});// #5329: repeat runs used to enqueue the same head pages forever.- test('#5329: repeat runs with a small limit progress through every page, then enqueue nothing', async () => {+ test('#5329: repeat runs with a small limit progress through every page, then queue nothing', async () => {for (const n of [1, 2, 3]) await engine.putPage(`meetings/m${n}`, { type: 'meeting', title: `m${n}`, compiled_truth: LONG });- type R = { enqueued: number; already_enqueued: number };- const run = async () => await operationsByName.chronicle_backfill.handler(mkCtx(), { limit: 1 }) as R;- for (let i = 0; i < 3; i++) expect((await run()).enqueued).toBe(1);- await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE name = 'chronicle_extract'`);- const again = await run();- expect(again.enqueued).toBe(0);- expect(again.already_enqueued).toBe(3);- const slugs = await engine.executeRaw<{ slug: string }>(`SELECT data->>'slug' AS slug FROM minion_jobs WHERE name = 'chronicle_extract' ORDER BY 1`);- expect(slugs.map(r => r.slug)).toEqual(['meetings/m1', 'meetings/m2', 'meetings/m3']);+ for (let i = 0; i < 3; i++) expect((await run({ limit: 1, yes: true })).queued).toBe(1);+ await engine.executeRaw(`UPDATE chronicle_page_state SET state = 'extracted'`);+ const again = await run({ limit: 1, yes: true });+ expect(again).toMatchObject({ queued: 0, already_done: 3 });+ expect((await engine.executeRaw('SELECT 1 FROM chronicle_page_state')).length).toBe(3);});- test('#5329: an edited page is swept again; a dead job does not block a retry', async () => {+ test('#5329: an edited page is swept again; a row that exhausted its attempts does not block a retry', async () => {await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });await engine.putPage('meetings/m2', { type: 'meeting', title: 'm2', compiled_truth: LONG });- await operationsByName.chronicle_backfill.handler(mkCtx(), {});+ await run({ yes: true });+ await engine.executeRaw(`UPDATE chronicle_page_state SET state = 'extracted' WHERE slug = 'meetings/m1'`);await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG + ' edited' });- await engine.executeRaw(`UPDATE minion_jobs SET status = 'dead' WHERE name = 'chronicle_extract' AND data->>'slug' = 'meetings/m2'`);- const dry = await operationsByName.chronicle_backfill.handler(mkCtx(), { dry_run: true }) as { eligible: number; already_enqueued: number };- expect(dry.already_enqueued).toBe(0);- const r = await operationsByName.chronicle_backfill.handler(mkCtx(), {}) as { enqueued: number; already_enqueued: number };- expect(r.enqueued).toBe(2);- expect(r.already_enqueued).toBe(0);+ await engine.executeRaw(`UPDATE chronicle_page_state SET state = 'failed', attempts = 5 WHERE slug = 'meetings/m2'`);+ const r = await run({ yes: true });+ expect(r).toMatchObject({ queued: 2, already_done: 0 });+ });+});++describe('#5876 discovery and filters (D6/E10)', () => {+ test('a note-typed page under meetings/ is found (rescue prefix)', async () => {+ await engine.putPage('meetings/typed-note', { type: 'note', title: 'n', compiled_truth: LONG });+ expect((await run({ dry_run: true })).eligible).toBe(1);+ });++ test('--limit is one global cap across types', async () => {+ await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });+ await engine.putPage('conversations/c1', { type: 'conversation', title: 'c1', compiled_truth: LONG });+ const r = await run({ limit: 1, yes: true });+ expect(r).toMatchObject({ queued: 1, limit_reached: true });+ expect(await queued()).toHaveLength(1);+ });++ test('--dated-since filters on the page date; --since on the update date; --recent applies the window', async () => {+ await engine.putPage('meetings/old', { type: 'meeting', title: 'old', compiled_truth: LONG, frontmatter: { date: '2024-01-05' } });+ await engine.putPage('meetings/new', { type: 'meeting', title: 'new', compiled_truth: LONG, frontmatter: { date: new Date().toISOString().slice(0, 10) } });+ expect((await run({ dry_run: true, dated_since: '2025-01-01' }))).toMatchObject({ queued: 1, skipped: { before_dated_since: 1 } });+ expect((await run({ dry_run: true, since: '2020-01-01' })).queued).toBe(2); // both were updated today+ expect((await run({ dry_run: true, recent: true }))).toMatchObject({ queued: 1, skipped: { history: 1 } });+ expect((await run({ dry_run: true })).queued).toBe(2); // backfill is the history path: no recency by default+ });++ test('a dry run estimates USD at the model price, or says unpriced', async () => {+ await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });+ const priced = await runChronicleBackfill(engine, { dryRun: true, model: 'anthropic:claude-sonnet-4-6' });+ expect(typeof priced.estimated_usd).toBe('number');+ expect(priced.estimated_usd as number).toBeGreaterThan(0);+ expect(priced.estimated_usd as number).toBeLessThanOrEqual(0.25);+ expect(priced.message).toContain('Ask the user before running');+ expect((await runChronicleBackfill(engine, { dryRun: true, model: 'openai:gpt-unpriced-example' })).estimated_usd).toBe('unpriced');+ });++ test('a future invite is skipped as not_yet_happened', async () => {+ const end = new Date(Date.now() + 86_400_000).toISOString();+ await engine.putPage('meetings/invite', { type: 'meeting', title: 'i', compiled_truth: LONG, frontmatter: { start: end, end } });+ expect(await run({ dry_run: true })).toMatchObject({ queued: 0, skipped: { not_yet_happened: 1 } });});});