Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Count only paid judge failures toward the same-input cap, and re-judge when a dropped proposal's cause changes
garrytana1b75a8c4501
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23b89b9e5a..d139807d1b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,14 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision## [0.60.631.0] - 2026-11-09-**A long conversation that keeps growing is no longer re-extracted, and re-paid for, on every new message.** Automatic event extraction reads a page's title, date, attendees and the first 12,000 characters of its body. On a conversation longer than that, each new message recorded a new revision, and each revision paid for another extraction call on exactly the same text. The model words each event a little differently every time, event pages are named after that wording, and an extraction of a page longer than 12,000 characters never retired the previous one, so every run added a fresh copy of every event. One page could collect dozens of paid calls and hundreds of duplicate events. Now a revision that changes nothing extraction reads (text, title, date, attendees, privacy) makes no call and writes nothing (it records `judge_input_unchanged`); a window the judge keeps failing on is paid for at most the page's attempt limit across all revisions, then records `judge_input_failed` until the text changes or a backfill asks again; and a re-extraction that re-read all the text the page's live events came from (for example after a title change, or the first time a conversation grows past 12,000 characters) replaces those events instead of adding to them. A page whose opening text was edited still keeps its earlier events, as before. Text past the first 12,000 characters is still not extracted; incremental coverage of the tail is tracked in #9013. Reported by @andreineacsu.+**A long conversation that keeps growing is no longer re-extracted, and re-paid for, on every new message.** Automatic event extraction reads a page's title, date, attendees and the first 12,000 characters of its body. On a conversation longer than that, each new message recorded a new revision, and each revision paid for another extraction call on exactly the same text. The model words each event a little differently every time, event pages are named after that wording, and an extraction of a page longer than 12,000 characters never retired the previous one, so every run added a fresh copy of every event. One page could collect dozens of paid calls and hundreds of duplicate events. Now a revision that changes nothing extraction reads (text, title, date, attendees, privacy) makes no call and writes nothing (it records `judge_input_unchanged`); a window the judge keeps failing on (its answer cut off, unreadable, malformed or over the per-page spend cap) is paid for at most the page's attempt limit across all revisions, then records `judge_input_failed` until the text changes, a release changes the extractor, or a backfill asks again (a run a newer revision replaced, or a missing provider or price, never counts toward that limit); and a re-extraction that re-read all the text the page's live events came from (for example after a title change, or the first time a conversation grows past 12,000 characters) replaces those events instead of adding to them. An extraction that dropped proposals over `chronicle.max_events_per_page` is asked again when that setting or the timezone changes, and one that dropped proposals dated after the page's last day is asked again, once, when that day moves. A page whose opening text was edited still keeps its earlier events, as before. Text past the first 12,000 characters is still not extracted; incremental coverage of the tail is tracked in #9013. Reported by @andreineacsu.**Doctor counts the duplicates earlier releases left.** The new `chronicle_duplicate_events` check (info) reports how many pages hold live events from earlier extraction runs beside their newest run's, and how many such events. It changes nothing; a preview-first repair that retires them is tracked in #9012.### Itemized changes-- `src/core/chronicle/execute.ts`: before the daily reservation, a row whose judge input digest equals that of the page's latest decided extracted generation (no ineligible revision or chronicle retirement since) finishes `skipped` / `judge_input_unchanged` with no call; an automatic row whose input already used the attempt limit on earlier revisions without publishing finishes `failed` / `judge_input_failed` (a refused input stays `judge_refused`), with no call; a truncated generation replaces the previous one only when every live chronicle event of the page is recorded by a ledger row whose judged window the new window starts with. Ended-invite projections and held results never count as judged.-- `src/core/chronicle/extract-events.ts`: `chronicleJudgedInput` (digest of the judge input with the body cut to `JUDGE_BODY_CHARS`, the extractor version and the depth page's visibility and source incarnation; the window and its sha256).+- `src/core/chronicle/execute.ts`: before the daily reservation, a row whose judge input digest equals that of the page's latest decided extracted generation (no ineligible revision or chronicle retirement since) finishes `skipped` / `judge_input_unchanged` with no call; an automatic row whose input already used the attempt limit on earlier revisions without publishing finishes `failed` / `judge_input_failed` (a refused input stays `judge_refused`), with no call, counting only `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `budget_exhausted` and `judge_refused` attempts (also on a row a newer revision replaced before its retry; a judged run superseded while publishing records no judged input); a truncated generation replaces the previous one only when every live chronicle event of the page is recorded by a ledger row whose judged window the new window starts with. Ended-invite projections and held results never count as judged, and each finish writes the judged input outright, so a held retry clears what a failed attempt recorded; a generation that dropped future-dated proposals records `cutoffInputHash` (the digest keyed to the screen's cutoff day).+- `src/core/chronicle/extract-events.ts`: `chronicleJudgedInput` (digest of the judge input with the body cut to `JUDGE_BODY_CHARS`, the extractor version, the depth page's visibility and source incarnation, the timezone and `chronicle.max_events_per_page`; the window and its sha256) and `cutoffInputHash`.+- `src/core/cycle/chronicle.ts`: the phase's supersede sweep keeps a row's judged input only when its last attempt was one of the counted failures.- Migration `v297` `chronicle_judge_window`: `chronicle_page_state.judge_input_hash`, `judge_window_chars`, `judge_window_hash`; nullable, no backfill. A row recorded before it has no window, so that page's next revision is judged once more and stays additive.- `src/core/chronicle/reasons.ts`, `src/core/error-registry.ts`: reason codes `judge_input_unchanged` and `judge_input_failed`.- `src/core/chronicle/ledger-stats.ts`, `src/commands/doctor/checks/auto-chronicle.ts`: `readChronicleDuplicateEvents` and the `chronicle_duplicate_events` doctor check.diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.mdindex c4c60d754a..1a0ebb2484 100644--- a/docs/guides/life-chronicle.md+++ b/docs/guides/life-chronicle.md@@ -262,7 +262,7 @@ brackets are filled in with real values on each surface.| `not_chronicle_shaped` | decision | The page is no longer a meeting, conversation or calendar page, so the events extracted from it were retired. | — | — | — || `already_extracted` | decision | This exact content was already extracted; its events are current, so no new call is made. | — | — | — || `judge_input_unchanged` | execution | Nothing the extraction reads changed since the page was last extracted (for example only text past a long page's first 12,000 characters changed), so the earlier events are current and no new call is made. | — | — | — |-| `judge_input_failed` | execution | Earlier revisions of the page already spent every extraction attempt on exactly this text without publishing events (the calls failed, or a newer revision arrived first), so it is not paid for again until the text extraction reads changes. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --yes` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid |+| `judge_input_failed` | execution | Earlier revisions of the page already spent every extraction attempt on exactly this text without publishing events (the judge's answer was cut off, unreadable, malformed or over the per-page spend cap), so it is not paid for again until the text extraction reads changes. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --yes` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid || `superseded` | execution | A newer revision replaced this content before extraction ran; the newer revision carries its own decision. | — | — | — || `daily_limit` | execution | The automatic daily limit (chronicle.auto_daily_limit = 200 calls per rolling 24 hours) is used up; pending pages wait for a free slot. | `gbrain config set chronicle.auto_daily_limit 400` | agent | paid || `judge_llm_unavailable` | execution | No chat provider is configured on the brain host, so extraction cannot run. | — | user | credentials |@@ -305,5 +305,8 @@ only grew at the end), so a re-extraction of it replaces them. A revision thatchanges nothing extraction reads (for example only a long conversation'snewest messages, past the window) makes no call at all and records`judge_input_unchanged`, and text the judge keeps failing on is paid for at-most the attempt limit across revisions (`judge_input_failed`). Text past the+most the attempt limit across revisions (`judge_input_failed`). An extraction+that dropped proposals over `chronicle.max_events_per_page` is asked again+when that setting changes, and one that dropped proposals dated after the+page's last day is asked again once that day moves. Text past thefirst 12,000 characters is not extracted yet.diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.tsindex b6ec8e7442..f557609d6f 100644--- a/src/core/chronicle/contract.ts+++ b/src/core/chronicle/contract.ts@@ -82,8 +82,9 @@ export interface ChronicleLedgerRow {/** content_hash of each event page as the extractor wrote it, parallel to event_slugs. An event whose* live hash is no longer in any row of its depth page was edited by an operator and is never touched. */event_hashes: string[];- /** #8972: digest of the whole judge input this row's run read (extract-events.ts `chronicleJudgedInput`); null when not- * judged, or recorded before the column existed. */+ /** #8972: digest of the whole judge input this row's run read (extract-events.ts `chronicleJudgedInput`, or `cutoffInputHash`+ * when the run dropped future-dated proposals); null when not judged, held, superseded after a judged run, or recorded+ * before the column existed. */judge_input_hash?: string | null;/** #8972: length and sha256 of the body window the judge read; a later generation covers this row when its own window* starts with the same text. */diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex f1bcef5961..df6f0250a9 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -35,7 +35,7 @@ import type { ChronicleReasonCode } from './reasons.ts';import type { ChronicleSettings } from './config.ts';import { chroniclePageDate, isChronicleEligible } from './eligibility.ts';import {- allDroppedReason, buildChronicleEvents, chronicleJudgeContext, chronicleJudgedInput, isValidProposal, JUDGE_BODY_CHARS, lastMessageAt, replacesPreviousGeneration,+ allDroppedReason, buildChronicleEvents, chronicleEventCutoff, chronicleJudgeContext, chronicleJudgedInput, cutoffInputHash, isValidProposal, JUDGE_BODY_CHARS, lastMessageAt, replacesPreviousGeneration,type ChronicleDropCounts, type ChronicleJudge, type ChronicleJudgeResult,} from './extract-events.ts';import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';@@ -69,6 +69,8 @@ export type ChronicleRowOutcome =malformed?: MalformedProposalDiagnostics };const CONFIG_BLOCKED = new Set(['judge_llm_unavailable', 'no_pricing']);+/** #8972: outcomes of a paid judge call that a re-judge of the same input would repeat; only these count toward the same-input cap. */+export const SAME_INPUT_FAILURES = ['judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'budget_exhausted', 'judge_refused'];const LEASE_MS = 15 * 60_000;function key(row: ChronicleLedgerRow) {@@ -114,6 +116,8 @@ async function finish(engine: BrainEngine, row: ChronicleLedgerRow, attempt: numstate: ChronicleLedgerRow['state']; reason: string | null; nextAttemptAt: Date | null;costUsd?: number | null; unpriced?: boolean; events?: Array<{ slug: string; hash: string }>;judged?: ReturnType<typeof chronicleJudgedInput>;+ /** A revision replaced the row before this run judged it: a same-input failure an earlier attempt recorded keeps counting. */+ keepFailedInput?: boolean;}): Promise<void> {if (patch.costUsd != null) {await engine.executeRaw(@@ -124,12 +128,13 @@ async function finish(engine: BrainEngine, row: ChronicleLedgerRow, attempt: numawait engine.executeRaw(`UPDATE chronicle_page_state SET state=$5, reason=$6, next_attempt_at=$7::timestamptz, unpriced=COALESCE($8::boolean, unpriced),event_slugs=COALESCE($9::text[], event_slugs), event_hashes=COALESCE($10::text[], event_hashes),- judge_input_hash=COALESCE($12, judge_input_hash), judge_window_chars=COALESCE($13::int, judge_window_chars),- judge_window_hash=COALESCE($14, judge_window_hash), updated_at=now()+ judge_input_hash=CASE WHEN reason = ANY($15::text[]) THEN judge_input_hash ELSE $12 END, judge_window_chars=$13::int,+ judge_window_hash=$14, updated_at=now()WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 AND attempts=$11`,[...key(row), patch.state, patch.reason, patch.nextAttemptAt ? patch.nextAttemptAt.toISOString() : null, patch.unpriced ?? null,patch.events ? patch.events.map((e) => e.slug) : null, patch.events ? patch.events.map((e) => e.hash) : null, attempt,- patch.judged?.inputHash ?? null, patch.judged?.window.length ?? null, patch.judged?.windowHash ?? null]);+ patch.judged?.inputHash ?? null, patch.judged?.window.length ?? null, patch.judged?.windowHash ?? null,+ patch.keepFailedInput ? SAME_INPUT_FAILURES : []]);}function backoff(attempts: number, now: Date, maxAttempts: number): Date | null {@@ -143,7 +148,7 @@ function backoff(attempts: number, now: Date, maxAttempts: number): Date | null* (an ineligible revision, RETIRE_REASONS); events of it that a chronicle retirement removed since (a deleted and* restored page) mean the page needs judging again.*/-async function judgedOnSameInput(engine: BrainEngine, row: ChronicleLedgerRow, inputHash: string): Promise<boolean> {+async function judgedOnSameInput(engine: BrainEngine, row: ChronicleLedgerRow, inputHashes: string[]): Promise<boolean> {const [latest] = await engine.executeRaw<{ state: string; judge_input_hash: string | null; retired: boolean }>(`SELECT c.state, c.judge_input_hash, EXISTS (SELECT 1 FROM pages e WHERE e.source_id=c.source_id AND e.slug = ANY(c.event_slugs)AND e.deleted_at IS NOT NULL AND e.frontmatter->>'retired_by' = $6) AS retired@@ -152,19 +157,22 @@ async function judgedOnSameInput(engine: BrainEngine, row: ChronicleLedgerRow, iAND (c.state='extracted' OR (c.state='skipped' AND c.reason = ANY($5::text[])))ORDER BY c.decided_at DESC, c.updated_at DESC LIMIT 1`,[row.source_id, Number(row.page_id), CHRONICLE_EXTRACTOR_VERSION, row.content_hash, [...RETIRE_REASONS], CHRONICLE_RETIRED_BY]);- return latest?.state === 'extracted' && latest.judge_input_hash === inputHash && !latest.retired;+ return latest?.state === 'extracted' && latest.judge_input_hash != null && inputHashes.includes(latest.judge_input_hash) && !latest.retired;}/*** #8972: paid attempts earlier revisions of the page already spent on exactly this input without publishing it, so a* judge that keeps failing on an unchanged window (output cap, malformed output, per-page cap) is not paid again for- * every new tail message; `refused` when one of them was refused.+ * every new tail message; `refused` when one of them was refused. Only outcomes a re-judge would repeat count+ * (SAME_INPUT_FAILURES, kept on a row a newer revision replaced before its retry): a judged run a newer revision+ * superseded, a provider or pricing that was not configured, or a chat error never exhausts the page.*/async function failedAttemptsOnSameInput(engine: BrainEngine, row: ChronicleLedgerRow, inputHash: string): Promise<{ attempts: number; refused: boolean }> {const [prior] = await engine.executeRaw<{ attempts: number | string | null; refused: boolean | null }>(`SELECT sum(attempts) AS attempts, bool_or(state='skipped' AND reason='judge_refused') AS refused FROM chronicle_page_state- WHERE source_id=$1 AND page_id=$2 AND extractor_version=$3 AND content_hash<>$4 AND judge_input_hash=$5 AND state<>'extracted'`,- [row.source_id, Number(row.page_id), CHRONICLE_EXTRACTOR_VERSION, row.content_hash, inputHash]);+ WHERE source_id=$1 AND page_id=$2 AND extractor_version=$3 AND content_hash<>$4 AND judge_input_hash=$5 AND state<>'extracted'+ AND (reason = ANY($6::text[]) OR reason = 'superseded')`,+ [row.source_id, Number(row.page_id), CHRONICLE_EXTRACTOR_VERSION, row.content_hash, inputHash, SAME_INPUT_FAILURES]);return { attempts: Number(prior?.attempts ?? 0), refused: prior?.refused === true };}@@ -232,7 +240,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronireturn done('skipped', 'page_missing');}if (String(snapshot.page.content_hash ?? '') !== row.content_hash) {- await finish(engine, row, row.attempts, { state: 'skipped', reason: 'superseded', nextAttemptAt: null });+ await finish(engine, row, row.attempts, { state: 'skipped', reason: 'superseded', nextAttemptAt: null, keepFailedInput: true });return done('skipped', 'superseded');}const pin = await pinDepth(engine, snapshot);@@ -271,9 +279,11 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroniconst judgeCtx = chronicleJudgeContext(page, lastMessage);const invite = endedInviteProposal(page, judgeCtx.attendees, now);- const judgedInput = chronicleJudgedInput(judgeCtx.input, { visibility: pin.visibility, incarnation: pin.incarnation });+ const judgedInput = chronicleJudgedInput(judgeCtx.input,+ { visibility: pin.visibility, incarnation: pin.incarnation, tz: ctx.tz, maxEvents: settings.maxEventsPerPage });+ const cutoff = chronicleEventCutoff(judgeCtx, ctx.tz, now);// #8972: a revision changed only where the judge does not read (a long page's tail) would pay for the same answer.- if (!invite && await judgedOnSameInput(engine, row, judgedInput.inputHash)) {+ if (!invite && await judgedOnSameInput(engine, row, [judgedInput.inputHash, cutoffInputHash(judgedInput.inputHash, cutoff)])) {await finish(engine, row, row.attempts, { state: 'skipped', reason: 'judge_input_unchanged', nextAttemptAt: null, judged: judgedInput });return done('skipped', 'judge_input_unchanged');}@@ -347,13 +357,15 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronireturn done('failed', 'publish_error', { ...judged, dropped });}if (generation.superseded) {- await finish(engine, row, attempts, { state: 'skipped', reason: 'superseded', nextAttemptAt: null, events: generation.written, judged: invite ? undefined : judgedInput, ...spend });+ await finish(engine, row, attempts, { state: 'skipped', reason: 'superseded', nextAttemptAt: null, events: generation.written, ...spend });return done('skipped', 'superseded', { ...judged, written: generation.written.length, dropped });}const reason = events.length > 0 ? null : proposals.length === 0 ? 'no_events' : allDroppedReason(dropped);- // An ended invite's projection and a held result (nothing published) never stand for a judged input.+ // An ended invite's projection and a held result (nothing published) never stand for a judged input; a generation that+ // dropped future-dated proposals stands for it only until the screen's cutoff day moves.await finish(engine, row, attempts, { state: 'extracted', reason, nextAttemptAt: null, events: generation.written,- judged: invite || generation.held ? undefined : judgedInput, ...spend });+ judged: invite || generation.held ? undefined+ : dropped.future_dated ? { ...judgedInput, inputHash: cutoffInputHash(judgedInput.inputHash, cutoff) } : judgedInput, ...spend });return done('extracted', reason, { ...judged, written: generation.written.length, retired: generation.retired.length, dropped });}diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 3c24af5d1d..c12dc92e38 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -192,15 +192,22 @@ export function replacesPreviousGeneration(built: { events: readonly unknown[];/*** #8972: what the judge reads of one snapshot. `inputHash` covers every field the judge sees (page fields and the body's- * first JUDGE_BODY_CHARS), the extractor version and what the events are stamped with (`stamp`: the depth page's- * effective visibility and source incarnation), so an unchanged hash means a re-judge would publish the same events.+ * first JUDGE_BODY_CHARS), the extractor version, what the events are stamped with (`stamp`: the depth page's+ * effective visibility and source incarnation) and the settings that screen the judge's proposals (`stamp.tz`,+ * `stamp.maxEvents`), so an unchanged hash means a re-judge would publish the same events. A generation that dropped+ * proposals as future-dated also depends on the screen's cutoff day: its row records `cutoffInputHash` instead.* `window` is that body window; `windowHash` its sha256.*/-export function chronicleJudgedInput(input: ChronicleJudgeInput, stamp: { visibility: string; incarnation: string }): { inputHash: string; window: string; windowHash: string } {+export function chronicleJudgedInput(input: ChronicleJudgeInput, stamp: { visibility: string; incarnation: string; tz: string; maxEvents: number }): { inputHash: string; window: string; windowHash: string } {const window = input.body.slice(0, JUDGE_BODY_CHARS);return { inputHash: digest(['chronicle-judge-input-v1', CHRONICLE_EXTRACTOR_VERSION, { ...input, body: window }, stamp]), window, windowHash: sha256(window) };}+/** #8972: the judged-input hash of a generation whose future-dated proposals were dropped against `cutoff` (an ISO day). */+export function cutoffInputHash(inputHash: string, cutoff: string): string {+ return digest(['chronicle-judge-input-cutoff-v1', inputHash, cutoff]);+}+/** The latest message timestamp of a chat-shaped body (multi-day conversations end on their last message). */export function lastMessageAt(body: string, fallbackDate: string | undefined): Date | null {const { messages } = parseConversation(body, { fallbackDate, noPolish: true, noFallback: true });diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 98d837b386..1cef674e2e 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -87,7 +87,7 @@ export const CHRONICLE_REASONS = {judge_input_unchanged: { stage: 'execution',meaning: () => 'Nothing the extraction reads changed since the page was last extracted (for example only text past a long page\'s first 12,000 characters changed), so the earlier events are current and no new call is made.' },judge_input_failed: { stage: 'execution',- meaning: () => 'Earlier revisions of the page already spent every extraction attempt on exactly this text without publishing events (the calls failed, or a newer revision arrived first), so it is not paid for again until the text extraction reads changes.',+ meaning: () => 'Earlier revisions of the page already spent every extraction attempt on exactly this text without publishing events (the judge\'s answer was cut off, unreadable, malformed or over the per-page spend cap), so it is not paid for again until the text extraction reads changes.',fix: backfill('agent', 'After fixing the cause the earlier failure named (doctor auto_chronicle), preview and backfill the page if the user agrees to one more paid chat call.') },superseded: { stage: 'execution',meaning: () => 'A newer revision replaced this content before extraction ran; the newer revision carries its own decision.' },diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.tsindex 00d3167b86..0ea76c043a 100644--- a/src/core/cycle/chronicle.ts+++ b/src/core/cycle/chronicle.ts@@ -34,7 +34,7 @@ import {type ChronicleLedgerRow, type ChronicleRunDetails,} from '../chronicle/contract.ts';import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES } from '../chronicle/eligibility.ts';-import { claimChronicleRow, executeChronicleRow } from '../chronicle/execute.ts';+import { claimChronicleRow, executeChronicleRow, SAME_INPUT_FAILURES } from '../chronicle/execute.ts';import { retireOrphanedChronicleEvents } from '../chronicle/publish.ts';import { failExhaustedCampaignRows } from '../chronicle/campaign.ts';import { defaultJudge, type ChronicleDropReason, type ChronicleJudge } from '../chronicle/extract-events.ts';@@ -149,9 +149,10 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhasawait pruneChronicleReservations(engine);await failExhaustedCampaignRows(engine);await engine.executeRaw(- `UPDATE chronicle_page_state c SET state='skipped', reason='superseded', next_attempt_at=NULL, updated_at=now()+ `UPDATE chronicle_page_state c SET state='skipped', reason='superseded', next_attempt_at=NULL, updated_at=now(),+ judge_input_hash=CASE WHEN c.reason = ANY($1::text[]) THEN c.judge_input_hash ENDWHERE c.state IN ('pending','failed') AND NOT EXISTS (SELECT 1 FROM pages p- WHERE p.id=c.page_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL)`);+ WHERE p.id=c.page_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL)`, [SAME_INPUT_FAILURES]);}const sources = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map((s) => s.id);details.sources = sources.length;diff --git a/test/chronicle-long-conversation-8972.test.ts b/test/chronicle-long-conversation-8972.test.tsindex b25ffe280f..6d1e8f2ead 100644--- a/test/chronicle-long-conversation-8972.test.ts+++ b/test/chronicle-long-conversation-8972.test.ts@@ -209,3 +209,127 @@ test('a judge that keeps failing on an unchanged window is paid at most the atteexpect(await liveEvents(engine)).toHaveLength(4);}), 180_000);});++describe('#8972 fix round: what counts as judged, and what exhausts a page', () => {+ /** A judge whose proposals come from `events(n)` on its n-th call (1-based). */+ function scriptedJudge(events: (n: number) => Array<{ when: string; what: string }>) {+ let calls = 0;+ const judge: ChronicleJudge = async () => {+ calls++;+ return { events: events(calls).map((e) => ({ when: e.when, who: ['people/alice-example'], what: e.what, kind: 'decision' as const })) };+ };+ return Object.assign(judge, { calls: () => calls });+ }+ const day = (offset: number) => new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10);++ test('runs on an unconfigured provider never exhaust the page', () => brain(async ({ engine, ctx }) => {+ let body = messages(1, JUDGE_BODY_CHARS + 1_000);+ await put(ctx, conversation(body));+ let unavailable = 0;+ const noProvider: ChronicleJudge = async () => { unavailable++; return { events: [], failure: 'llm_unavailable' }; };+ await run(engine, noProvider);+ for (const n of [1, 2, 3, 4, 5]) {+ body += `\nbob-example: tail message ${n}.`;+ await put(ctx, conversation(body));+ await run(engine, noProvider);+ }+ expect(unavailable).toBe(6);+ const judge = rewordingJudge();+ body += '\nbob-example: the provider is configured now.';+ await put(ctx, conversation(body));+ const r = await run(engine, judge);+ expect(judge.inputs).toHaveLength(1);+ expect(r.details).toMatchObject({ judged: 1, events_written: 2 });+ expect((await ledger(engine)).at(-1)).toEqual(['extracted', null]);+ }), 180_000);++ test('judged runs a newer revision superseded while they ran never exhaust the page', () => brain(async ({ engine, ctx }) => {+ let body = messages(1, JUDGE_BODY_CHARS + 1_000);+ await put(ctx, conversation(body));+ let racing = 0;+ const judge = rewordingJudge();+ const raced: ChronicleJudge = async (input) => {+ racing++;+ body += `\nbob-example: tail message ${racing}, written while the judge ran.`;+ await put(ctx, conversation(body));+ return judge(input);+ };+ for (let n = 0; n < 6; n++) await run(engine, raced);+ expect(racing).toBe(6);+ expect((await ledger(engine)).filter(([, reason]) => reason === 'superseded').length).toBeGreaterThanOrEqual(5);+ expect((await ledger(engine)).filter(([, reason]) => reason === 'judge_input_failed')).toEqual([]);+ const r = await run(engine, judge);+ expect(r.details).toMatchObject({ judged: 1 });+ expect((await ledger(engine)).at(-1)).toEqual(['extracted', null]);+ }), 180_000);++ test('an over_cap generation stays cached at the same cap and is judged again when the cap is raised', () => brain(async ({ engine, ctx }) => {+ await engine.setConfig('chronicle.max_events_per_page', '2');+ let body = messages(1, JUDGE_BODY_CHARS + 1_000);+ await put(ctx, conversation(body));+ const judge = scriptedJudge((n) => [1, 2, 3].map((i) => ({ when: today, what: `Decision ${i} (wording ${n})` })));+ await run(engine, judge);+ expect(await liveEvents(engine)).toHaveLength(2);+ body += '\nbob-example: tail message 1.';+ await put(ctx, conversation(body));+ const same = await run(engine, judge);+ expect(same.details).toMatchObject({ judged: 0, reasons: { judge_input_unchanged: 1 } });+ expect(judge.calls()).toBe(1);+ await engine.setConfig('chronicle.max_events_per_page', '5');+ body += '\nbob-example: tail message 2.';+ await put(ctx, conversation(body));+ const raised = await run(engine, judge);+ expect(judge.calls()).toBe(2);+ expect(raised.details).toMatchObject({ judged: 1, events_written: 3 });+ }), 180_000);++ test('a generation that dropped future-dated proposals is judged again once when the cutoff day moves', () => brain(async ({ engine, ctx }) => {+ const yesterday = day(-1);+ const page = (body: string, end: string) => `---\ntype: conversation\ntitle: Launch thread\ndate: ${yesterday}\nend: ${end}\n---\n\n${body}`;+ let body = messages(1, JUDGE_BODY_CHARS + 1_000);+ await put(ctx, page(body, yesterday));+ const judge = scriptedJudge((n) => [{ when: yesterday, what: `Kickoff (wording ${n})` }, { when: today, what: `Launch (wording ${n})` }]);+ const first = await run(engine, judge);+ expect(first.details).toMatchObject({ judged: 1, events_written: 1 });+ body += '\nbob-example: tail message 1.';+ await put(ctx, page(body, yesterday));+ await run(engine, judge);+ expect(judge.calls()).toBe(1);+ // The conversation now runs into today: the judge reads the same text, but today's proposal is no longer future-dated.+ for (const n of [2, 3]) {+ body += `\nbob-example: tail message ${n}.`;+ await put(ctx, page(body, today));+ await run(engine, judge);+ }+ expect(judge.calls()).toBe(2);+ expect(await liveEvents(engine)).toEqual(['Kickoff (wording 2)', 'Launch (wording 2)']);+ }), 180_000);++ test('a held result after a failed attempt does not stand for the judged input', () => brain(async ({ engine, ctx }) => {+ let body = messages(1, JUDGE_BODY_CHARS + 1_000);+ await put(ctx, conversation(body));+ const four = [1, 2, 3, 4];+ let calls = 0;+ const judge: ChronicleJudge = async () => {+ calls++;+ if (calls === 2) return { events: [], failure: 'truncated' };+ const kept = calls === 1 ? four : [1];+ return { events: kept.map((i) => ({ when: today, who: ['people/alice-example'], what: `Decision ${i} (wording ${calls})`, kind: 'decision' as const })) };+ };+ await run(engine, judge);+ await put(ctx, conversation(`${body}\nbob-example: renamed.`, 'Launch thread (renamed)'));+ await run(engine, judge);+ expect((await ledger(engine)).at(-1)).toEqual(['failed', 'judge_truncated']);+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second' WHERE state='failed'");+ await run(engine, judge); // the retry shrinks four events to one: held, nothing published+ expect(calls).toBe(3);+ expect(await liveEvents(engine)).toHaveLength(4);+ expect((await engine.executeRaw<{ h: string | null }>(+ "SELECT judge_input_hash AS h FROM chronicle_page_state WHERE state='extracted' ORDER BY decided_at DESC, updated_at DESC LIMIT 1"))[0].h).toBeNull();+ body += '\nbob-example: renamed.\nbob-example: tail message 1.';+ await put(ctx, conversation(body, 'Launch thread (renamed)'));+ await run(engine, judge);+ expect(calls).toBe(4);+ }), 180_000);+});+