Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(chronicle): chronicle-backfill --max-usd hard bound with stamped campaign rows (#6199)

garrytana513673b1443
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index aff0935438..758e79427d 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/budget/cap-flag.ts` — the one USD cost-cap flag parser (D19): `parseCapFlag(flag, raw, { zero })` returns `{ flag, usd }` (`usd: null` for `off`/`unlimited`/`none`) or throws `CapFlagError`; a bare `0` is refused unless the command declares it (`zero: 'off'` for skillopt's legacy `--max-cost-usd 0`, `'cap'` for eval longmemeval's $0 judge cap); `mergeCapFlag` refuses two disagreeing cap flags; `capNotice` renders the one `cap: $X (source; how to remove)` line. Used by brainstorm/lsd, skillopt, enrich, onboard and eval longmemeval. Pinned by `test/budget/cap-flag.test.ts`.
- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`), rendered from `pricingSetArgv`; `noPricingFix(guidance, transport)` is the agent-contract `fix` for a user-cap refusal (the registration argv with `inputs` for each rate and the pricing page). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.
-- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
+- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,campaign,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `--max-usd` (#6199, `campaign.ts`) is a queue-time bound: a page queues only while queued × (per-attempt cap + `chronicleCallCeilingUsd`) × max attempts fits, rows are stamped (`campaign_id`, `attempt_cap_usd`, `max_attempts`, `pricing_policy`, `campaign_max_usd`; migration `chronicle_campaign_stamps`) and `queueCampaignRow` never takes a row another backfill queued or an executor holds; an unpriced model under the cap refuses with `no_pricing`. Executors obey the stamp: `claimChronicleRow` consumes a campaign row's attempt with the lease and refuses it past `max_attempts`, the tracker uses the stamped cap, `finish` sums spend per attempt (`cost_attempts`, so a replay adds nothing) and applies the outcome only while its attempt is the latest (a stale completion is fenced), and `failExhaustedCampaignRows` fails a crashed row whose attempts are spent as `campaign_exhausted`; any other ledger write clears the stamp. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-backfill-max-usd`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
- `src/core/chunkers/` — markdown chunking (`recursive.ts`) and code chunking. `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4643e946af..4dd9c19a9b 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -382,7 +382,7 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../
|---|---|---|---|---|---|---|
| Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step. | A capability this request needs is not configured or not reachable on this brain. | Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user's agreement). | agent | `gbrain doctor --json` | 1 | no |
-Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `future_dated`, `date_imprecise`, `no_chat_provider`.
+Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `campaign_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `future_dated`, `date_imprecise`, `no_chat_provider`.
More: [docs/guides/life-chronicle.md#skip-and-failure-codes](../../docs/guides/life-chronicle.md#skip-and-failure-codes)
diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.md
index 9a9c4dc587..c4371dd779 100644
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@ -188,6 +188,49 @@ gbrain chronicle-backfill --since 2026-09-01 --limit 50 --yes
`--since` filters on the page's last update, not its own date. Re-running is
safe: content already extracted is not paid for again.
+### Bound the spend with `--max-usd`
+
+`--max-usd <usd>` is a hard bound on everything the run queues, retries
+included. A page is queued only while
+
+ queued pages × (chronicle.job_budget_usd + one call's ceiling) × 5 attempts ≤ --max-usd
+
+The ceiling covers the one call that can overshoot the per-page cap before the
+tracker sees it. Each queued row is stamped with the run's campaign id, the
+per-attempt cap, the maximum attempts and the pricing policy, and the
+`chronicle` phase runs it under those values even if you change
+`chronicle.job_budget_usd` later. Attempts are counted when a row is claimed,
+so a crash never earns a page an extra attempt; a page that uses every attempt
+without finishing fails as `campaign_exhausted`. The bound is deliberately
+conservative: real spend is usually near `estimated_usd`, far below
+`worst_case_usd`.
+
+```bash
+gbrain chronicle-backfill --since 2026-09-01 --max-usd 20 --dry-run --json
+gbrain chronicle-backfill --since 2026-09-01 --max-usd 20 --yes
+```
+
+`--json` adds these fields; before this release none of them existed. An
+example with a Sonnet-class model at the default $0.25 per-page cap:
+
+```json
+{ "queued": 8, "estimated_usd": 0.13, "max_usd": 20, "worst_case_usd": 17.9098,
+ "per_page_worst_case_usd": 2.2387, "max_attempts": 5, "fits_under_cap": 8,
+ "cap_reached": true, "campaign_id": "3f0c…", "spent_usd": 0,
+ "next_command": "gbrain dream --phase chronicle" }
+```
+
+`cap_reached: true` means eligible pages were left out. A larger bound is a new
+paid run, so ask the user, then preview it with `--dry-run`. When no page fits,
+nothing is queued, `ask_user` is true and `next_command` is that preview.
+`spent_usd` is the campaign's recorded spend, summed across attempts.
+
+With `--max-usd`, a chat model gbrain has no price for is refused with
+`no_pricing` before anything is queued; the error's `fix` is the
+`gbrain pricing set` registration (look up the rate first). Without
+`--max-usd`, an unpriced model still warns and runs, and the message points at
+price registration and `--max-usd`.
+
## Skip and failure codes
Write receipts, doctor and the advisor use these codes. `decision` codes come
@@ -214,6 +257,7 @@ brackets are filled in with real values on each surface.
| `judge_llm_unavailable` | execution | No chat provider is configured on the brain host, so extraction cannot run. | — | user | credentials |
| `no_pricing` | execution | chronicle.job_budget_usd was set explicitly, and gbrain has no price for <provider:model>, so the cap cannot be enforced. | `gbrain pricing set <provider:model> --input <usd-per-1M-input-tokens> --output <usd-per-1M-output-tokens> --source <pricing-page-url>` | agent | — |
| `budget_exhausted` | execution | The extraction call cost more than chronicle.job_budget_usd allows for one page. | `gbrain config set chronicle.job_budget_usd 0.50` | agent | paid |
+| `campaign_exhausted` | execution | The page used every attempt its capped backfill (chronicle-backfill --max-usd) authorized without finishing, so it stops before spending more. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run` | agent | — |
| `judge_chat_error` | execution | The chat provider returned an error; the page retries with backoff. | — | provider | — |
| `judge_truncated` | execution | The extraction output hit chronicle.judge_max_tokens and was cut off, so nothing was written. | `gbrain config set chronicle.judge_max_tokens 8000` | agent | paid |
| `judge_parse_failed` | execution | The extraction output had no parseable JSON array, so nothing was written; the page retries on a later run. | — | — | — |
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 9755dda05f..59897ef5f9 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -264,7 +264,10 @@ tracker cannot price, the default cap is not enforced: extraction warns and
runs, bounded only by the call count. When you set `chronicle.job_budget_usd`
yourself, an unpriced model refuses with `no_pricing` until you register its
price with `gbrain pricing set`. `gbrain chronicle-backfill` (history, on
-request) is exempt from the daily limit and bounded by its `--limit`.
+request) is exempt from the daily limit and bounded by its `--limit`;
+`--max-usd` adds a hard spend bound that counts retries (an unpriced model then
+refuses with `no_pricing`; see the
+[chronicle guide](../guides/life-chronicle.md#bound-the-spend-with---max-usd)).
```bash
gbrain config set auto_chronicle false # opt out
diff --git a/src/core/chronicle/backfill.ts b/src/core/chronicle/backfill.ts
index 921c4084ce..44c20dee91 100644
--- a/src/core/chronicle/backfill.ts
+++ b/src/core/chronicle/backfill.ts
@@ -11,10 +11,21 @@
* 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.
+ *
+ * `maxUsd` (#6199) is a hard bound fixed at queue time: a page is queued only
+ * while queued × (per-attempt cap + one call's ceiling) × maximum attempts
+ * stays within it, and each queued row carries the campaign stamp every
+ * executor obeys (campaign.ts). An unpriced model cannot be bounded, so a cap
+ * refuses it with `no_pricing` and the register-price fix.
*/
+import { randomUUID } from 'crypto';
import type { BrainEngine } from '../engine.ts';
import { loadPricingOverrides } from '../budget/budget-tracker.ts';
import { usageCostUsd } from '../budget/reservation-cost.ts';
+import { noPricingFix, noPricingGuidance, noPricingMessage, noPricingSteps, pricingSetCommand } from '../budget/no-pricing.ts';
+import { opError } from '../ops/contract.ts';
+import { campaignPageWorstCaseUsd, campaignSpentUsd, chronicleCallCeilingUsd, queueCampaignRow, type ChronicleCampaignStamp } from './campaign.ts';
+import { chronicleJudgeMaxTokens } from './extract-events.ts';
import { CHRONICLE_DEFAULTS, 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';
@@ -37,6 +48,8 @@ export interface ChronicleBackfillOpts {
sourceIds?: string[];
/** Model whose price the estimate uses (the configured chat model). */
model?: string;
+ /** Hard spend bound for everything this run queues, retries included (USD). */
+ maxUsd?: number;
now?: Date;
}
@@ -54,6 +67,22 @@ export interface ChronicleBackfillResult {
estimated_usd: number | 'unpriced';
/** Per-page cap the estimate is clamped to (chronicle.job_budget_usd). */
job_budget_usd: number;
+ /** The --max-usd bound, or null. */
+ max_usd: number | null;
+ /** Most the queued pages can spend: queued × per_page_worst_case_usd; 'unpriced' when it cannot be bounded. */
+ worst_case_usd: number | 'unpriced';
+ /** (per-attempt cap + one call's ceiling) × max_attempts; null when unpriced. */
+ per_page_worst_case_usd: number | null;
+ /** Attempts each queued page may use (stamped on capped rows). */
+ max_attempts: number;
+ /** Pages that fit under max_usd (this run's queued count); null without --max-usd. */
+ fits_under_cap: number | null;
+ /** Eligible pages were left out because max_usd was reached. */
+ cap_reached: boolean;
+ /** Campaign id stamped on the rows this run queued under --max-usd; null otherwise. */
+ campaign_id: string | null;
+ /** Recorded spend of this campaign's rows so far, summed across attempts; null without one. */
+ spent_usd: number | null;
next_command: string;
ask_user: boolean;
message: string;
@@ -74,6 +103,17 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleB
const now = opts.now ?? new Date();
const settings = await chronicleSettings(engine);
const overrides = await loadPricingOverrides(engine);
+ const maxUsd = opts.maxUsd ?? null;
+ const maxAttempts = CHRONICLE_DEFAULTS.maxAttempts;
+ const ceiling = opts.model ? chronicleCallCeilingUsd(opts.model, await chronicleJudgeMaxTokens(engine), overrides) : null;
+ if (maxUsd !== null && ceiling === null) {
+ const g = noPricingGuidance(opts.model ?? 'unknown', 'chat');
+ throw opError('no_pricing', noPricingMessage(g, { label: 'chronicle-backfill', capUsd: maxUsd }), noPricingSteps(g),
+ { fix: noPricingFix(g), docs: g.docs, why: 'A --max-usd bound needs a price for every call; nothing was queued.' });
+ }
+ const perPage = ceiling === null ? null : campaignPageWorstCaseUsd({ attemptCapUsd: settings.jobBudgetUsd, maxAttempts }, ceiling);
+ const stamp: ChronicleCampaignStamp | null = maxUsd !== null && !dryRun && opts.yes
+ ? { campaignId: randomUUID(), attemptCapUsd: settings.jobBudgetUsd, maxAttempts, maxUsd } : null;
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 = '';
@@ -83,8 +123,12 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleB
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: '',
+ estimated_usd: 0, job_budget_usd: settings.jobBudgetUsd, max_usd: maxUsd, worst_case_usd: 0,
+ per_page_worst_case_usd: perPage === null ? null : round(perPage), max_attempts: maxAttempts,
+ fits_under_cap: maxUsd === null ? null : 0, cap_reached: false, campaign_id: stamp?.campaignId ?? null, spent_usd: null,
+ next_command: '', ask_user: true, message: '',
};
+ let worst = 0;
const skip = (reason: string) => { result.skipped[reason] = (result.skipped[reason] ?? 0) + 1; };
let estimate = 0;
let unpriced = false;
@@ -121,22 +165,34 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleB
result.eligible++;
if (page.done) { result.already_done++; continue; }
if (result.queued >= limit) { result.limit_reached = true; continue; }
+ if (maxUsd !== null && worst + perPage! > maxUsd + 1e-9) { result.cap_reached = true; continue; }
+ const row = { sourceId: page.source_id, pageId: Number(page.id), contentHash: page.content_hash, slug: page.slug };
+ if (stamp && !(await queueCampaignRow(engine, row, stamp))) { result.already_done++; continue; }
+ if (!stamp && !dryRun && opts.yes) {
+ await upsertChronicleRow(engine, { ...row, state: 'pending', reason: null, trigger: 'backfill', nextAttemptAt: null });
+ }
result.queued++;
+ worst += perPage ?? 0;
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;
+ result.estimated_usd = unpriced ? 'unpriced' : round(estimate);
+ result.worst_case_usd = perPage === null ? 'unpriced' : round(worst);
+ if (maxUsd !== null) result.fits_under_cap = result.queued;
+ if (stamp) result.spent_usd = await campaignSpentUsd(engine, stamp.campaignId);
const flags = [opts.since ? `--since ${quote(opts.since)}` : '', opts.datedSince ? `--dated-since ${quote(opts.datedSince)}` : '',
- opts.recent ? '--recent' : '', `--limit ${limit}`].filter(Boolean).join(' ');
+ opts.recent ? '--recent' : '', `--limit ${limit}`, maxUsd !== null ? `--max-usd ${maxUsd}` : ''].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)})`;
+ ? `The chat model has no registered price, so the cost is unknown and no per-page cap applies; to bound spend, register its price (${pricingSetCommand(opts.model ?? '<model>', 'chat')}) and pass --max-usd`
+ : `Estimated cost ~$${result.estimated_usd.toFixed(2)} (each page capped at $${settings.jobBudgetUsd.toFixed(2)})` +
+ (maxUsd === null ? '' : `; worst case $${(result.worst_case_usd as number).toFixed(2)} of the $${maxUsd.toFixed(2)} --max-usd bound ` +
+ `($${result.per_page_worst_case_usd!.toFixed(2)} per page: ${maxAttempts} attempts at the per-page cap plus one call's overshoot)`);
+ const capNote = result.cap_reached
+ ? ` More eligible pages did not fit under --max-usd $${maxUsd!.toFixed(2)}; a larger bound is a new paid run, so ask the user first (preview: gbrain chronicle-backfill ${flags} --dry-run).`
+ : '';
if (dryRun || !opts.yes) {
result.next_command = result.queued > 0 ? `gbrain chronicle-backfill ${flags} --yes` : '';
result.ask_user = result.queued > 0;
@@ -144,14 +200,31 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleB
? `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 (result.queued === 0 && result.cap_reached) {
+ result.ask_user = true;
+ result.next_command = `gbrain chronicle-backfill ${flags} --dry-run`;
+ result.message = `No page fits under --max-usd $${maxUsd!.toFixed(2)}: each page can spend up to $${result.per_page_worst_case_usd!.toFixed(2)} ` +
+ `(${maxAttempts} attempts at the $${settings.jobBudgetUsd.toFixed(2)} per-page cap plus one call's overshoot). Ask the user for a larger --max-usd.`;
+ } else result.message += capNote;
if (!dryRun) result.dry_run = true;
return result;
}
result.next_command = result.queued > 0 ? RUN_NOW_COMMAND : '';
result.ask_user = false;
+ if (result.queued === 0 && result.cap_reached) {
+ result.ask_user = true;
+ result.next_command = `gbrain chronicle-backfill ${flags} --dry-run`;
+ result.message = `Nothing queued: no page fits under --max-usd $${maxUsd!.toFixed(2)} (each page can spend up to $${result.per_page_worst_case_usd!.toFixed(2)}). Ask the user for a larger --max-usd.`;
+ return result;
+ }
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; each batch is paid, so ask the user before the next one (preview: gbrain chronicle-backfill ${flags} --dry-run).` : '.');
+ (result.limit_reached ? `. More pages remain; each batch is paid, so ask the user before the next one (preview: gbrain chronicle-backfill ${flags} --dry-run).` : '.') +
+ capNote;
return result;
}
+
+function round(usd: number): number {
+ return Math.round(usd * 10_000) / 10_000;
+}
diff --git a/src/core/chronicle/campaign.ts b/src/core/chronicle/campaign.ts
new file mode 100644
index 0000000000..85508629ed
--- /dev/null
+++ b/src/core/chronicle/campaign.ts
@@ -0,0 +1,90 @@
+/**
+ * `chronicle-backfill --max-usd` campaigns (#6199): a hard spend bound fixed at queue time.
+ *
+ * The executor makes a fresh BudgetTracker per attempt and retries failed pages, and the tracker
+ * sees an overrun only after the call that causes it. So a campaign admits a page only while
+ * queued pages × (per-attempt cap + one call's ceiling) × maximum attempts stays within
+ * `--max-usd`, and stamps each queued ledger row with the campaign, the per-attempt cap, the
+ * maximum attempts and the pricing policy. Every executor reads the stamp, never current
+ * settings; attempts are consumed when a row is claimed (execute.ts), so a crash cannot hand out
+ * an extra attempt. No campaign table and no runtime reservation are needed.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PricingOverrides } from '../budget/budget-tracker.ts';
+import { usageCostUsd } from '../budget/reservation-cost.ts';
+import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow } from './contract.ts';
+import { JUDGE_BODY_CHARS, JUDGE_PROMPT_CHARS } from './extract-events.ts';
+
+/** The only stamped pricing policy: the stamped per-attempt cap is enforced (an unpriced model refuses). */
+export const CAMPAIGN_PRICING_POLICY = 'enforced';
+
+export interface ChronicleCampaignStamp {
+ campaignId: string;
+ attemptCapUsd: number;
+ maxAttempts: number;
+ maxUsd: number;
+}
+
+/**
+ * Upper bound of one judge call in USD: every input character counted as up to three tokens
+ * (its UTF-8 bytes, which bound a byte-level tokenizer) plus the full output cap. Null when the
+ * model is unpriced.
+ */
+export function chronicleCallCeilingUsd(model: string, maxOutputTokens: number, overrides?: PricingOverrides): number | null {
+ return usageCostUsd(model, 3 * (JUDGE_BODY_CHARS + JUDGE_PROMPT_CHARS), maxOutputTokens, 'chat', overrides);
+}
+
+/** The most one queued page can spend: every attempt at its cap plus one call's overshoot. */
+export function campaignPageWorstCaseUsd(stamp: Pick<ChronicleCampaignStamp, 'attemptCapUsd' | 'maxAttempts'>, callCeilingUsd: number): number {
+ return (stamp.attemptCapUsd + callCeilingUsd) * stamp.maxAttempts;
+}
+
+/** A row's attempt limit: its stamp, else the default. */
+export function rowMaxAttempts(row: Pick<ChronicleLedgerRow, 'max_attempts'>): number {
+ return row.max_attempts ?? CHRONICLE_DEFAULTS.maxAttempts;
+}
+
+/**
+ * Queue one page into a campaign. Never takes a row another backfill already queued (pending, or
+ * failed with attempts left), a row an executor holds right now, or current extracted content;
+ * otherwise the row restarts as this campaign's with zero attempts. false = not queued here.
+ */
+export async function queueCampaignRow(engine: BrainEngine,
+ w: { sourceId: string; pageId: number; contentHash: string; slug: string }, stamp: ChronicleCampaignStamp): Promise<boolean> {
+ const written = await engine.executeRaw(
+ `INSERT INTO chronicle_page_state AS c (source_id, page_id, content_hash, extractor_version, slug, state, reason, trigger,
+ campaign_id, attempt_cap_usd, max_attempts, pricing_policy, campaign_max_usd)
+ VALUES ($1, $2, $3, $4, $5, 'pending', NULL, 'backfill', $6, $7::numeric, $8, $9, $10::numeric)
+ ON CONFLICT (source_id, page_id, content_hash, extractor_version) DO UPDATE SET
+ slug=EXCLUDED.slug, state='pending', reason=NULL, trigger='backfill', principal_kind=NULL, principal_id=NULL,
+ request_id=NULL, no_extract=false, next_attempt_at=NULL, attempts=0, cost_attempts='{}',
+ campaign_id=EXCLUDED.campaign_id, attempt_cap_usd=EXCLUDED.attempt_cap_usd, max_attempts=EXCLUDED.max_attempts,
+ pricing_policy=EXCLUDED.pricing_policy, campaign_max_usd=EXCLUDED.campaign_max_usd, decided_at=now(), updated_at=now()
+ WHERE NOT (c.trigger='backfill' AND c.state IN ('pending','failed') AND c.attempts < COALESCE(c.max_attempts, $11))
+ AND NOT (c.state IN ('pending','failed') AND c.attempts > 0 AND c.next_attempt_at > now())
+ 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))
+ RETURNING page_id`,
+ [w.sourceId, w.pageId, w.contentHash, CHRONICLE_EXTRACTOR_VERSION, w.slug, stamp.campaignId, stamp.attemptCapUsd,
+ stamp.maxAttempts, CAMPAIGN_PRICING_POLICY, stamp.maxUsd, CHRONICLE_DEFAULTS.maxAttempts]);
+ return written.length > 0;
+}
+
+/** Recorded spend of a campaign's rows, summed across attempts. */
+export async function campaignSpentUsd(engine: BrainEngine, campaignId: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ usd: number | string | null }>(
+ 'SELECT COALESCE(sum(cost_usd), 0)::float8 AS usd FROM chronicle_page_state WHERE campaign_id=$1', [campaignId]);
+ return Math.round(Number(row?.usd ?? 0) * 10_000) / 10_000;
+}
+
+/**
+ * A campaign row whose attempts are all consumed but which never finished (its executor crashed
+ * after the claim) fails as `campaign_exhausted` once its lease ends, so it stops waiting.
+ */
+export async function failExhaustedCampaignRows(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE chronicle_page_state SET state='failed', reason='campaign_exhausted', next_attempt_at=NULL, updated_at=now()
+ WHERE campaign_id IS NOT NULL AND state='pending' AND attempts >= COALESCE(max_attempts, $1)
+ AND (next_attempt_at IS NULL OR next_attempt_at <= now())`, [CHRONICLE_DEFAULTS.maxAttempts]);
+}
diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.ts
index 09b6cd3f02..f2a4ad0a12 100644
--- a/src/core/chronicle/contract.ts
+++ b/src/core/chronicle/contract.ts
@@ -60,8 +60,21 @@ export interface ChronicleLedgerRow {
attempts: number;
/** Earliest next judge attempt for a failed row with backoff; null = not scheduled. */
next_attempt_at: Date | string | null;
- /** Recorded spend of the last attempt in USD (null when unpriced or not run). */
+ /** Recorded spend in USD, summed across attempts (null when unpriced or not run). */
cost_usd: number | null;
+ /** #6199: attempts whose spend cost_usd already includes (a replayed completion adds nothing). */
+ cost_attempts?: number[];
+ /** #6199: the `chronicle-backfill --max-usd` campaign that queued this row; null outside a capped backfill.
+ * Executors run a stamped row under its stamped cap, attempts and pricing policy, never current settings. */
+ campaign_id?: string | null;
+ /** Per-attempt spend cap stamped at queue time (NUMERIC; a string on Postgres). */
+ attempt_cap_usd?: number | string | null;
+ /** Maximum judge attempts stamped at queue time; null = CHRONICLE_DEFAULTS.maxAttempts. */
+ max_attempts?: number | null;
+ /** 'enforced' = the stamped cap applies even if the model loses its price or settings change. */
+ pricing_policy?: string | null;
+ /** The campaign's --max-usd. */
+ campaign_max_usd?: number | string | null;
/** The judge model had no price, so cost_usd is unknown. */
unpriced: boolean;
/** Event page slugs this content produced (the generation reconciliation reads). */
diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.ts
index 9f46290991..977b2bbfc3 100644
--- a/src/core/chronicle/execute.ts
+++ b/src/core/chronicle/execute.ts
@@ -28,6 +28,7 @@ import {
} from './extract-events.ts';
import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';
import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';
+import { CAMPAIGN_PRICING_POLICY, rowMaxAttempts } from './campaign.ts';
import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';
export interface ChronicleExecContext {
@@ -58,16 +59,28 @@ function key(row: ChronicleLedgerRow) {
return [row.source_id, Number(row.page_id), row.content_hash, CHRONICLE_EXTRACTOR_VERSION] as const;
}
-/** Lease one claimable row so a second executor (another host's cycle, a job) skips it. */
+/**
+ * Lease one claimable row so a second executor (another host's cycle, a job) skips it. A
+ * `--max-usd` campaign row (#6199) consumes its attempt here, atomically with the lease, and is
+ * not claimable once its stamped attempts are used, so a crash between claim and outcome never
+ * yields an extra paid attempt.
+ */
export async function claimChronicleRow(engine: BrainEngine, row: ChronicleLedgerRow): Promise<ChronicleLedgerRow | null> {
const [claimed] = await engine.executeRaw<ChronicleLedgerRow>(
- `UPDATE chronicle_page_state SET next_attempt_at = now() + ($5::int * interval '1 millisecond')
+ `UPDATE chronicle_page_state SET next_attempt_at = now() + ($5::int * interval '1 millisecond'),
+ attempts = attempts + CASE WHEN campaign_id IS NOT NULL AND state IN ('pending','failed') THEN 1 ELSE 0 END
WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 AND state=$6
AND (next_attempt_at IS NULL OR next_attempt_at <= now())
- RETURNING *`, [...key(row), LEASE_MS, row.state]);
+ AND NOT (campaign_id IS NOT NULL AND state IN ('pending','failed') AND attempts >= COALESCE(max_attempts, $7))
+ RETURNING *`, [...key(row), LEASE_MS, row.state, CHRONICLE_DEFAULTS.maxAttempts]);
return claimed ?? null;
}
+/** A claimed row that belongs to a campaign: its attempt was consumed by the claim. */
+function campaignAttempt(row: ChronicleLedgerRow): boolean {
+ return row.campaign_id != null && (row.state === 'pending' || row.state === 'failed');
+}
+
async function setNextAttempt(engine: BrainEngine, row: ChronicleLedgerRow, at: Date | null): Promise<void> {
await engine.executeRaw(
`UPDATE chronicle_page_state SET next_attempt_at=$5::timestamptz
@@ -75,22 +88,32 @@ async function setNextAttempt(engine: BrainEngine, row: ChronicleLedgerRow, at:
[...key(row), at ? at.toISOString() : null]);
}
-async function finish(engine: BrainEngine, row: ChronicleLedgerRow, patch: {
+/**
+ * Record an attempt's outcome. Spend accumulates per attempt (#6199): keyed to `attempt`, so a
+ * replayed completion adds nothing, and recorded even from a stale executor because the money was
+ * spent. The outcome itself applies only while `attempt` is still the row's latest attempt, so a
+ * completion arriving after its lease expired and another executor claimed the row is fenced.
+ */
+async function finish(engine: BrainEngine, row: ChronicleLedgerRow, attempt: number, patch: {
state: ChronicleLedgerRow['state']; reason: string | null; nextAttemptAt: Date | null;
costUsd?: number | null; unpriced?: boolean; events?: Array<{ slug: string; hash: string }>;
}): Promise<void> {
+ if (patch.costUsd != null) {
+ await engine.executeRaw(
+ `UPDATE chronicle_page_state SET cost_usd=COALESCE(cost_usd, 0) + $5::numeric, cost_attempts=array_append(cost_attempts, $6::int)
+ WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 AND NOT ($6::int = ANY(cost_attempts))`,
+ [...key(row), patch.costUsd, attempt]);
+ }
await engine.executeRaw(
- `UPDATE chronicle_page_state SET state=$5, reason=$6, next_attempt_at=$7::timestamptz,
- cost_usd=COALESCE($8::numeric, cost_usd), unpriced=COALESCE($9::boolean, unpriced),
- event_slugs=COALESCE($10::text[], event_slugs), event_hashes=COALESCE($11::text[], event_hashes), updated_at=now()
- WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4`,
- [...key(row), patch.state, patch.reason, patch.nextAttemptAt ? patch.nextAttemptAt.toISOString() : null,
- patch.costUsd ?? null, patch.unpriced ?? null,
- patch.events ? patch.events.map((e) => e.slug) : null, patch.events ? patch.events.map((e) => e.hash) : null]);
+ `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), 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]);
}
-function backoff(attempts: number, now: Date): Date | null {
- if (attempts >= CHRONICLE_DEFAULTS.maxAttempts) return null;
+function backoff(attempts: number, now: Date, maxAttempts: number): Date | null {
+ if (attempts >= maxAttempts) return null;
return new Date(now.getTime() + Math.min(6 * 3_600_000, 5 * 60_000 * 2 ** Math.max(0, attempts - 1)));
}
@@ -131,11 +154,11 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
if (!snapshot || Number(snapshot.page.id) !== Number(row.page_id)) {
- await finish(engine, row, { state: 'skipped', reason: 'page_missing', nextAttemptAt: null });
+ await finish(engine, row, row.attempts, { state: 'skipped', reason: 'page_missing', nextAttemptAt: null });
return done('skipped', 'page_missing');
}
if (String(snapshot.page.content_hash ?? '') !== row.content_hash) {
- await finish(engine, row, { state: 'skipped', reason: 'superseded', nextAttemptAt: null });
+ await finish(engine, row, row.attempts, { state: 'skipped', reason: 'superseded', nextAttemptAt: null });
return done('skipped', 'superseded');
}
const pin = pinDepth(snapshot);
@@ -149,7 +172,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
}
if (row.no_extract) {
- await finish(engine, row, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });
+ await finish(engine, row, row.attempts, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });
return done('skipped', 'no_extract');
}
const auto = row.trigger === 'auto';
@@ -166,7 +189,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
}
const reason = eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason;
const retire = (RETIRE_REASONS as readonly string[]).includes(reason);
- await finish(engine, row, { state: 'skipped', reason, nextAttemptAt: retire ? now : null });
+ await finish(engine, row, row.attempts, { state: 'skipped', reason, nextAttemptAt: retire ? now : null });
return done('skipped', reason);
}
@@ -176,12 +199,15 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
await setNextAttempt(engine, row, null);
return { kind: 'deferred', reason: 'daily_limit' };
}
- const [{ attempts }] = await engine.executeRaw<{ attempts: number }>(
+ const attempts = campaignAttempt(row) ? row.attempts : (await engine.executeRaw<{ attempts: number }>(
`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)]);
+ [...key(row)]))[0].attempts;
+ const maxAttempts = rowMaxAttempts(row);
+ // #6199: a campaign row runs under its stamped cap, whatever the settings or gate say now.
+ const stampedCap = row.pricing_policy === CAMPAIGN_PRICING_POLICY && row.attempt_cap_usd != null ? Number(row.attempt_cap_usd) : undefined;
const tracker = new BudgetTracker({
- maxCostUsd: ctx.gate.enforceCap ? settings.jobBudgetUsd : undefined,
+ maxCostUsd: stampedCap ?? (ctx.gate.enforceCap ? settings.jobBudgetUsd : undefined),
label: ctx.label ?? `chronicle:${row.trigger}`,
pricingOverrides: ctx.pricingOverrides,
});
@@ -205,8 +231,8 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
const overCap = tracker.cap !== undefined && tracker.totalSpent > tracker.cap;
const failure = overCap && !thrown ? { state: 'failed' as const, reason: 'budget_exhausted' as const } : classifyJudge(result, thrown);
if (failure) {
- const next = failure.state === 'skipped' || CONFIG_BLOCKED.has(failure.reason) ? null : backoff(attempts, now);
- await finish(engine, row, { state: failure.state, reason: failure.reason, nextAttemptAt: next, ...spend });
+ const next = failure.state === 'skipped' || CONFIG_BLOCKED.has(failure.reason) ? null : backoff(attempts, now, maxAttempts);
+ await finish(engine, row, attempts, { state: failure.state, reason: failure.reason, nextAttemptAt: next, ...spend });
return done(failure.state, failure.reason, judged);
}
@@ -222,15 +248,15 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
} catch (error) {
if ((error as Error)?.name === 'AbortError') throw error;
console.warn(`[chronicle] ${row.slug}: publishing events failed (${error instanceof Error ? error.message : String(error)}); the row retries with backoff. Run now: gbrain dream --phase chronicle`);
- await finish(engine, row, { state: 'failed', reason: 'publish_error', nextAttemptAt: backoff(attempts, now), ...spend });
+ await finish(engine, row, attempts, { state: 'failed', reason: 'publish_error', nextAttemptAt: backoff(attempts, now, maxAttempts), ...spend });
return done('failed', 'publish_error', { ...judged, dropped });
}
if (generation.superseded) {
- await finish(engine, row, { state: 'skipped', reason: 'superseded', nextAttemptAt: null, events: generation.written, ...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);
- await finish(engine, row, { state: 'extracted', reason, nextAttemptAt: null, events: generation.written, ...spend });
+ await finish(engine, row, attempts, { state: 'extracted', reason, nextAttemptAt: null, events: generation.written, ...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.ts
index 328da382db..ba6abb916b 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -291,6 +291,17 @@ Use the provided attendee slugs for "who" when the text does not name participan
* array). Override via `chronicle.judge_max_tokens`.
*/
const DEFAULT_JUDGE_MAX_TOKENS = 4000;
+/** Page body characters the judge reads at most. */
+export const JUDGE_BODY_CHARS = 12_000;
+/** Judge input outside the body: the system prompt plus headroom for the wrapper, title, attendees and date rule. */
+export const JUDGE_PROMPT_CHARS = JUDGE_SYSTEM.length + 2_000;
+
+/** The judge's output-token cap: `chronicle.judge_max_tokens`, else the default. */
+export async function chronicleJudgeMaxTokens(engine: BrainEngine): Promise<number> {
+ const capRaw = await engine.getConfig('chronicle.judge_max_tokens').catch(() => null);
+ const n = capRaw ? parseInt(capRaw, 10) : NaN;
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_JUDGE_MAX_TOKENS;
+}
export function defaultJudge(engine: BrainEngine): ChronicleJudge {
return async (input) => {
@@ -300,14 +311,9 @@ export function defaultJudge(engine: BrainEngine): ChronicleJudge {
// so keyless daemons reported clean no_events runs forever. Surface it as
// a distinct failure (mapped to status 'skipped' / judge_llm_unavailable).
if (!isAvailable('chat')) return { events: [], failure: 'llm_unavailable' };
- const body = (input.body || '').slice(0, 12_000);
+ const body = (input.body || '').slice(0, JUDGE_BODY_CHARS);
// #2606: configurable cap so event-dense pages have headroom.
- let maxTokens = DEFAULT_JUDGE_MAX_TOKENS;
- const capRaw = await engine.getConfig('chronicle.judge_max_tokens').catch(() => null);
- if (capRaw) {
- const n = parseInt(capRaw, 10);
- if (Number.isFinite(n) && n > 0) maxTokens = n;
- }
+ const maxTokens = await chronicleJudgeMaxTokens(engine);
// extraction.date_grounding: the page date is the observation date; a
// relative "last Tuesday" resolves against it, never against today.
const { isConsumerDateGroundingOn } = await import('../facts/extract.ts');
diff --git a/src/core/chronicle/job.ts b/src/core/chronicle/job.ts
index c563c00499..99f2ac4ed1 100644
--- a/src/core/chronicle/job.ts
+++ b/src/core/chronicle/job.ts
@@ -10,6 +10,7 @@ import { resolveExtractAtomsCostGate } from '../cycle/extract-atoms-cost-gate.ts
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
import { chronicleSettings, chronicleTz } from './config.ts';
import { claimChronicleRow, executeChronicleRow } from './execute.ts';
+import { rowMaxAttempts } from './campaign.ts';
import { defaultJudge, type ChronicleJudge } from './extract-events.ts';
import { readChronicleRow, upsertChronicleRow } from './ledger.ts';
import { noPricingMessage } from '../budget/no-pricing.ts';
@@ -47,7 +48,10 @@ export async function runChronicleJob(engine: BrainEngine, opts: {
if (gate.refusal) return { slug, status: 'failed', reason: `no_pricing: ${noPricingMessage(gate.refusal, { capUsd: settings.jobBudgetUsd })}` };
const trigger = opts.trigger === 'auto' ? 'auto' : 'backfill';
// A write decision or backfill already queued this content: the cycle phase owns it.
- if (existing?.state === 'pending') return { slug, status: 'skipped', reason: 'queued_for_cycle' };
+ // A capped backfill row with attempts left stays under its campaign's stamped bound (#6199).
+ if (existing?.state === 'pending' || (existing?.campaign_id && existing.state === 'failed' && existing.attempts < rowMaxAttempts(existing))) {
+ return { slug, status: 'skipped', reason: 'queued_for_cycle' };
+ }
await upsertChronicleRow(engine, { ...key, slug, state: 'pending', reason: null, trigger, nextAttemptAt: null });
const row = await readChronicleRow(engine, key);
const claimed = row && await claimChronicleRow(engine, row);
diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.ts
index daf9be4955..b641946018 100644
--- a/src/core/chronicle/ledger.ts
+++ b/src/core/chronicle/ledger.ts
@@ -123,7 +123,8 @@ export interface ChronicleRowWrite {
* 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.
+ * automatic decision. A new decision leaves any `--max-usd` campaign
+ * (#6199): its stamp is cleared, and only campaign.ts writes one.
*/
export async function upsertChronicleRow(engine: BrainEngine, w: ChronicleRowWrite): Promise<boolean> {
const written = await engine.executeRaw(
@@ -133,7 +134,8 @@ export async function upsertChronicleRow(engine: BrainEngine, w: ChronicleRowWri
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()
+ no_extract=EXCLUDED.no_extract, next_attempt_at=EXCLUDED.next_attempt_at, decided_at=now(), updated_at=now(),
+ campaign_id=NULL, attempt_cap_usd=NULL, max_attempts=NULL, pricing_policy=NULL, campaign_max_usd=NULL
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
diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.ts
index 82f6fec3f0..2286bea959 100644
--- a/src/core/chronicle/reasons.ts
+++ b/src/core/chronicle/reasons.ts
@@ -105,6 +105,11 @@ export const CHRONICLE_REASONS = {
meaning: () => 'The extraction call cost more than chronicle.job_budget_usd allows for one page.',
fix: () => ({ argv: ['gbrain', 'config', 'set', 'chronicle.job_budget_usd', '0.50'], consent: ['paid'], actor: 'agent',
requires_exclusive: false, why: 'Raising the per-page cap lets long pages finish; ask the user before raising spend.' }) },
+ campaign_exhausted: { stage: 'execution',
+ meaning: () => 'The page used every attempt its capped backfill (chronicle-backfill --max-usd) authorized without finishing, so it stops before spending more.',
+ fix: (ctx) => ({ argv: chronicleBackfillArgv({ sourceId: ctx.sourceId, since: ctx.since, dryRun: true }), consent: [], actor: 'agent',
+ requires_exclusive: false,
+ why: 'Preview what a new backfill would queue (read-only); queuing it again is paid, so ask the user for a new --max-usd first.' }) },
judge_chat_error: { stage: 'execution',
meaning: () => 'The chat provider returned an error; the page retries with backoff.',
fix: () => ({ consent: [], actor: 'provider', requires_exclusive: false,
diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.ts
index 37d4934157..d9e17f8216 100644
--- a/src/core/cycle/chronicle.ts
+++ b/src/core/cycle/chronicle.ts
@@ -35,6 +35,7 @@ import {
} from '../chronicle/contract.ts';
import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES } from '../chronicle/eligibility.ts';
import { claimChronicleRow, executeChronicleRow } from '../chronicle/execute.ts';
+import { failExhaustedCampaignRows } from '../chronicle/campaign.ts';
import { defaultJudge, type ChronicleDropReason, type ChronicleJudge } from '../chronicle/extract-events.ts';
import {
RETIRE_REASONS, chronicleDailyRemaining, decideChronicle, pruneChronicleReservations, upsertChronicleRow,
@@ -104,8 +105,8 @@ async function candidates(engine: BrainEngine, sourceId: string, enabled: boolea
JOIN pages p ON p.id=c.page_id AND p.source_id=c.source_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL
WHERE c.source_id=$1 AND c.extractor_version=$2
AND (c.next_attempt_at IS NULL OR c.next_attempt_at <= now())
- AND ((c.state='pending' AND ($3 OR c.trigger='backfill'))
- OR (c.state='failed' AND c.attempts < $4 AND ($3 OR c.trigger='backfill')
+ AND ((c.state='pending' AND ($3 OR c.trigger='backfill') AND (c.max_attempts IS NULL OR c.attempts < c.max_attempts))
+ OR (c.state='failed' AND c.attempts < COALESCE(c.max_attempts, $4) AND ($3 OR c.trigger='backfill')
AND (c.next_attempt_at IS NOT NULL OR c.reason IN ('judge_llm_unavailable','no_pricing')))
OR (c.state='skipped' AND c.next_attempt_at IS NOT NULL AND c.reason = ANY($5::text[])))
ORDER BY (c.state='skipped') DESC, (c.trigger='auto') DESC, c.decided_at, c.page_id
@@ -144,6 +145,7 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhas
if (!dryRun) {
await 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()
WHERE c.state IN ('pending','failed') AND NOT EXISTS (SELECT 1 FROM pages p
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c035264c34..b950221cc7 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -85,7 +85,7 @@ export const CODES = {
catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
- chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
+ chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },
checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },
claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },
diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.ts
index 2c4e763fa1..f0e4d5ea77 100644
--- a/src/core/ops/chronicle.ts
+++ b/src/core/ops/chronicle.ts
@@ -9,6 +9,7 @@
import type { Operation, OperationContext } from './contract.ts';
import { readPolicyOpts, sourceScopeOpts } from './context.ts';
+import { invalidParam } from './op-fix.ts';
// ── Remote diary redaction (fail-closed) ─────────────────────────────────
// The exact mechanism the ontology siblings use (`ctx.remote !== false` →
@@ -299,8 +300,9 @@ const chronicle_backfill: Operation = {
'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]`.',
+ '(`gbrain dream --phase chronicle`), exempt from the daily limit. --max-usd is a hard bound counting retries: ' +
+ 'pages queue only while their worst case fits, and an unpriced chat model then refuses with no_pricing. Local-only bulk op. ' +
+ 'CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--dated-since YYYY-MM-DD] [--recent] [--limit N] [--max-usd USD] [--dry-run | --yes]`.',
scope: 'admin',
mutating: true,
localOnly: true,
@@ -311,6 +313,7 @@ const chronicle_backfill: Operation = {
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.' },
+ max_usd: { type: 'number', description: 'Hard spend bound in USD for everything this run queues, retries included; pages beyond it are not queued (cap_reached).' },
},
handler: async (ctx, p) => {
const { runChronicleBackfill } = await import('../chronicle/backfill.ts');
@@ -318,6 +321,9 @@ const chronicle_backfill: Operation = {
let model: string | undefined;
try { model = getChatModel(); } catch { model = undefined; }
const scope = sourceScopeOpts(ctx);
+ if (p.max_usd !== undefined && !(typeof p.max_usd === 'number' && Number.isFinite(p.max_usd) && p.max_usd > 0)) {
+ throw invalidParam(ctx, 'chronicle_backfill', 'max_usd', 'chronicle_backfill: max_usd must be a positive number of US dollars.', { example: 5 });
+ }
return runChronicleBackfill(ctx.engine, {
since: typeof p.since === 'string' ? p.since : undefined,
datedSince: typeof p.dated_since === 'string' ? p.dated_since : undefined,
@@ -328,6 +334,7 @@ const chronicle_backfill: Operation = {
sourceId: scope.sourceId,
sourceIds: scope.sourceIds,
model,
+ maxUsd: typeof p.max_usd === 'number' ? p.max_usd : undefined,
});
},
cliHints: { name: 'chronicle-backfill' },
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index cf29584b96..d2c8054a97 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1189,6 +1189,12 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (
event_hashes TEXT[] NOT NULL DEFAULT '{}',
decided_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ campaign_id TEXT,
+ attempt_cap_usd NUMERIC,
+ max_attempts INTEGER CHECK (max_attempts > 0),
+ pricing_policy TEXT,
+ campaign_max_usd NUMERIC,
+ cost_attempts INTEGER[] NOT NULL DEFAULT '{}',
PRIMARY KEY (source_id, page_id, content_hash, extractor_version)
);
CREATE INDEX IF NOT EXISTS chronicle_page_state_work_idx
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 101de9b713..4566433c96 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1914,6 +1914,13 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (
event_hashes TEXT[] NOT NULL DEFAULT '{}',
decided_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- #6199 (migration chronicle_campaign_stamps): the --max-usd campaign stamp.
+ campaign_id TEXT,
+ attempt_cap_usd NUMERIC,
+ max_attempts INTEGER CHECK (max_attempts > 0),
+ pricing_policy TEXT,
+ campaign_max_usd NUMERIC,
+ cost_attempts INTEGER[] NOT NULL DEFAULT '{}',
PRIMARY KEY (source_id, page_id, content_hash, extractor_version)
);
CREATE INDEX IF NOT EXISTS chronicle_page_state_work_idx
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 7177831439..8307655707 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -216,6 +216,7 @@ import { v212 } from './v212-decide-review-proposals.ts';
import { v213 } from './v213-core-edit-notices.ts';
import { v214 } from './v214-wanted-links.ts';
import { v215 } from './v215-facts-attributed-to.ts';
+import { v216 } from './v216-chronicle-campaign-stamps.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -430,4 +431,5 @@ export const MIGRATIONS: Migration[] = [
v213,
v214,
v215,
+ v216,
];
diff --git a/src/core/schema-migrations/v216-chronicle-campaign-stamps.ts b/src/core/schema-migrations/v216-chronicle-campaign-stamps.ts
new file mode 100644
index 0000000000..7eb5448aab
--- /dev/null
+++ b/src/core/schema-migrations/v216-chronicle-campaign-stamps.ts
@@ -0,0 +1,27 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6199: `chronicle-backfill --max-usd` stamps each queued ledger row with its
+// campaign and the spend policy in force at queue time, so every executor (the
+// chronicle phase, the chronicle_extract job) runs the row under those values,
+// not current settings: campaign_id, the per-attempt cap, the maximum
+// attempts, the pricing policy ('enforced') and the campaign's --max-usd.
+// cost_attempts lists the attempts whose spend cost_usd already includes, so a
+// replayed completion never adds the same attempt twice. All nullable or
+// defaulted: metadata-only, no backfill; rows without a campaign keep today's
+// behavior.
+export const v216: Migration = {
+ version: 216,
+ name: 'chronicle_campaign_stamps',
+ idempotent: true,
+ sql: `
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS campaign_id TEXT;
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS attempt_cap_usd NUMERIC;
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS max_attempts INTEGER CHECK (max_attempts > 0);
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS pricing_policy TEXT;
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS campaign_max_usd NUMERIC;
+ ALTER TABLE chronicle_page_state ADD COLUMN IF NOT EXISTS cost_attempts INTEGER[] NOT NULL DEFAULT '{}';
+ `,
+};
diff --git a/src/schema.sql b/src/schema.sql
index ae66bc8505..aebd2e4791 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1910,6 +1910,13 @@ CREATE TABLE IF NOT EXISTS chronicle_page_state (
event_hashes TEXT[] NOT NULL DEFAULT '{}',
decided_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- #6199 (migration chronicle_campaign_stamps): the --max-usd campaign stamp.
+ campaign_id TEXT,
+ attempt_cap_usd NUMERIC,
+ max_attempts INTEGER CHECK (max_attempts > 0),
+ pricing_policy TEXT,
+ campaign_max_usd NUMERIC,
+ cost_attempts INTEGER[] NOT NULL DEFAULT '{}',
PRIMARY KEY (source_id, page_id, content_hash, extractor_version)
);
CREATE INDEX IF NOT EXISTS chronicle_page_state_work_idx
diff --git a/test/chronicle-backfill-max-usd.test.ts b/test/chronicle-backfill-max-usd.test.ts
new file mode 100644
index 0000000000..9013fc3978
--- /dev/null
+++ b/test/chronicle-backfill-max-usd.test.ts
@@ -0,0 +1,217 @@
+/**
+ * #6199 — `chronicle-backfill --max-usd`: a hard spend bound fixed at queue time.
+ *
+ * Protects: pages queue only while queued × (per-attempt cap + one call's
+ * ceiling) × maximum attempts fits under max_usd; queued rows carry the
+ * campaign stamp and every executor obeys it, not current settings;
+ * attempts are consumed at claim, so a crash cannot add an attempt; a stale
+ * completion after its lease expired is fenced and spend is summed per
+ * attempt without double counting; overlapping invocations never share a
+ * page; an unpriced model under a user cap refuses with no_pricing and the
+ * register-price fix, and without a cap it still warns and runs.
+ * Fails when: a retry, crash, restart, settings change or second
+ * invocation lets a campaign spend past its bound.
+ * Seams: injected judge (`runPhaseChronicle({ judge })`) recording spend on
+ * the ambient BudgetTracker; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, 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 { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';
+import { claimChronicleRow } from '../src/core/chronicle/execute.ts';
+import type { ChronicleJudge, ChronicleJudgeResult } from '../src/core/chronicle/extract-events.ts';
+import type { ChronicleLedgerRow } from '../src/core/chronicle/contract.ts';
+import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';
+import { configureGateway, getCurrentBudgetTracker, resetGateway } from '../src/core/ai/gateway.ts';
+import { recordOnTracker } from '../src/core/ai/budget-record.ts';
+import { _resetBudgetTrackerWarningsForTest } from '../src/core/budget/budget-tracker.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const MODEL = 'anthropic:claude-sonnet-4-6';
+const UNPRICED = 'openai:gpt-unpriced-example';
+const LONG = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta release. '.repeat(2);
+/** One recorded judge call: 1000 input + 100 output tokens at the sonnet rate. */
+const CALL = { inputTokens: 1000, outputTokens: 100 };
+
+type Result = Record<string, unknown> & { queued: number; worst_case_usd: number | 'unpriced'; per_page_worst_case_usd: number | null;
+ fits_under_cap: number | null; cap_reached: boolean; campaign_id: string | null; next_command: string; ask_user: boolean; message: string };
+
+function spendingJudge(answer: (n: number) => ChronicleJudgeResult | Promise<ChronicleJudgeResult>) {
+ const judge = Object.assign((async () => {
+ const tracker = getCurrentBudgetTracker();
+ judge.caps.push(tracker?.cap);
+ recordOnTracker(tracker, { modelId: MODEL, ...CALL, label: 'chronicle', kind: 'chat' });
+ return answer(++judge.calls);
+ }) as ChronicleJudge, { calls: 0, caps: [] as Array<number | undefined> });
+ return judge;
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe(`${backend}: chronicle-backfill --max-usd (#6199)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const ctx = (): OperationContext => ({ engine, remote: false } as unknown as OperationContext);
+ const backfill = async (p: Record<string, unknown>) => await operationsByName.chronicle_backfill.handler(ctx(), p) as Result;
+ const ledger = () => engine.executeRaw<ChronicleLedgerRow>('SELECT * FROM chronicle_page_state ORDER BY slug');
+ const pages = async (n: number) => {
+ for (let i = 1; i <= n; i++) await engine.putPage(`meetings/m${i}`, { type: 'meeting', title: `m${i}`, compiled_truth: LONG });
+ };
+ const perPage = async () => (await backfill({ dry_run: true, max_usd: 1000 })).per_page_worst_case_usd!;
+ const expire = () => engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at = now() - interval '1 second'");
+
+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); });
+ afterAll(async () => { await close(); });
+ beforeEach(async () => {
+ configureGateway({ chat_model: MODEL, env: {} });
+ await engine.executeRaw('DELETE FROM chronicle_page_state');
+ await engine.executeRaw("DELETE FROM pages WHERE slug LIKE 'meetings/%' OR slug LIKE 'life/%'");
+ await engine.setConfig('auto_chronicle', 'false');
+ await engine.unsetConfig('chronicle.job_budget_usd');
+ });
+ afterEach(() => { resetGateway(); _resetBudgetTrackerWarningsForTest(); });
+
+ test('a dry run reports the worst case and how many pages fit; nothing is queued', async () => {
+ await pages(3);
+ const unit = await perPage();
+ expect(unit).toBeGreaterThan(0.25 * 5);
+ const r = await backfill({ dry_run: true, max_usd: unit * 2.5 });
+ expect(r).toMatchObject({ queued: 2, fits_under_cap: 2, cap_reached: true, max_usd: unit * 2.5, ask_user: true });
+ expect(r.worst_case_usd).toBeCloseTo(unit * 2, 3);
+ expect(r.next_command).toContain(`--max-usd ${unit * 2.5} --yes`);
+ expect(await ledger()).toEqual([]);
+ });
+
+ test('max_usd that fits 2 of 3 pages queues exactly 2, stamped with the campaign and its policy', async () => {
+ await pages(3);
+ const unit = await perPage();
+ const r = await backfill({ yes: true, max_usd: unit * 2.5 });
+ expect(r).toMatchObject({ queued: 2, fits_under_cap: 2, cap_reached: true, spent_usd: 0 });
+ expect(r.message).toContain('did not fit under --max-usd');
+ const rows = await ledger();
+ expect(rows).toHaveLength(2);
+ for (const row of rows) {
+ expect(row).toMatchObject({ state: 'pending', trigger: 'backfill', campaign_id: r.campaign_id, max_attempts: 5, pricing_policy: 'enforced' });
+ expect(Number(row.attempt_cap_usd)).toBe(0.25);
+ expect(Number(row.campaign_max_usd)).toBeCloseTo(unit * 2.5, 6);
+ }
+ });
+
+ test('max_usd below one page queues nothing and asks for a larger bound', async () => {
+ await pages(2);
+ const r = await backfill({ yes: true, max_usd: 0.5 });
+ expect(r).toMatchObject({ queued: 0, fits_under_cap: 0, cap_reached: true, ask_user: true });
+ expect(r.next_command).toContain('--max-usd 0.5 --dry-run');
+ expect(await ledger()).toEqual([]);
+ });
+
+ test('an unpriced model under a user cap refuses with no_pricing and the register-price fix; nothing is queued', async () => {
+ configureGateway({ chat_model: UNPRICED, env: {} });
+ await pages(2);
+ const err = await backfill({ yes: true, max_usd: 50 }).catch((e) => e);
+ expect(err?.code ?? err?.error).toBe('no_pricing');
+ expect(err.fix.argv.slice(0, 3)).toEqual(['gbrain', 'pricing', 'set']);
+ expect(await ledger()).toEqual([]);
+ });
+
+ test('without max_usd an unpriced model warns and runs, pointing at --max-usd and price registration', async () => {
+ await pages(2);
+ const r = await runChronicleBackfill(engine, { yes: true, model: UNPRICED }) as unknown as Result;
+ expect(r).toMatchObject({ queued: 2, worst_case_usd: 'unpriced', fits_under_cap: null, campaign_id: null });
+ expect(r.message).toContain('--max-usd');
+ expect(r.message).toContain('gbrain pricing set');
+ expect((await ledger()).every((row) => row.campaign_id === null)).toBe(true);
+ });
+
+ test('max_usd must be a positive number', async () => {
+ const err = await backfill({ dry_run: true, max_usd: -1 }).catch((e) => e);
+ expect(err?.code ?? err?.error).toBe('invalid_params');
+ });
+
+ test('the executor runs a campaign row under its stamped cap after the setting changes', async () => {
+ await pages(1);
+ await backfill({ yes: true, max_usd: 100 });
+ await engine.setConfig('chronicle.job_budget_usd', '0.05');
+ const judge = spendingJudge(() => ({ events: [] }));
+ await runPhaseChronicle(engine, { judge });
+ expect(judge.caps).toEqual([0.25]);
+ expect((await ledger())[0]).toMatchObject({ state: 'extracted', attempts: 1 });
+ });
+
+ test('a page that fails once then succeeds stays inside the bound, with spend summed per attempt', async () => {
+ await pages(1);
+ const unit = await perPage();
+ await backfill({ yes: true, max_usd: unit + 0.01 });
+ const judge = spendingJudge((n) => n === 1 ? { events: [], failure: 'chat_error' } : { events: [] });
+ await runPhaseChronicle(engine, { judge });
+ expect((await ledger())[0]).toMatchObject({ state: 'failed', reason: 'judge_chat_error', attempts: 1 });
+ await expire();
+ await runPhaseChronicle(engine, { judge });
+ const [row] = await ledger();
+ expect(row).toMatchObject({ state: 'extracted', attempts: 2 });
+ expect(row.cost_attempts).toEqual([1, 2]);
+ expect(Number(row.cost_usd)).toBeCloseTo(2 * (1000 * 3 + 100 * 15) / 1_000_000, 8);
+ expect(Number(row.cost_usd)).toBeLessThanOrEqual(unit);
+ });
+
+ test('a crash after the claim consumes the attempt; an exhausted row fails without another call', async () => {
+ await pages(1);
+ await backfill({ yes: true, max_usd: 100 });
+ for (let i = 1; i <= 5; i++) {
+ const [row] = await ledger();
+ const claimed = await claimChronicleRow(engine, row);
+ expect(claimed?.attempts).toBe(i);
+ await expire();
+ }
+ const [spent] = await ledger();
+ expect(spent).toMatchObject({ state: 'pending', attempts: 5 });
+ expect(await claimChronicleRow(engine, spent)).toBeNull();
+ const judge = spendingJudge(() => ({ events: [] }));
+ await runPhaseChronicle(engine, { judge });
+ expect(judge.calls).toBe(0);
+ expect((await ledger())[0]).toMatchObject({ state: 'failed', reason: 'campaign_exhausted', attempts: 5 });
+ });
+
+ test('a stale completion after its lease expired is fenced; its spend is recorded once', async () => {
+ await pages(1);
+ await backfill({ yes: true, max_usd: 100 });
+ const judge = spendingJudge(async () => {
+ await expire();
+ const [row] = await ledger();
+ expect((await claimChronicleRow(engine, row))?.attempts).toBe(2);
+ return { events: [] };
+ });
+ await runPhaseChronicle(engine, { judge });
+ const [row] = await ledger();
+ expect(row).toMatchObject({ state: 'pending', attempts: 2, cost_attempts: [1] });
+ });
+
+ test('a restart mid-campaign queues only the rest, each campaign within its own bound', async () => {
+ await pages(4);
+ const unit = await perPage();
+ const first = await backfill({ yes: true, max_usd: unit * 2 + 0.01 });
+ const second = await backfill({ yes: true, max_usd: unit * 2 + 0.01 });
+ expect(first.queued).toBe(2);
+ expect(second.queued).toBe(2);
+ expect(first.campaign_id).not.toBe(second.campaign_id);
+ const rows = await ledger();
+ expect(rows.filter((r) => r.campaign_id === first.campaign_id)).toHaveLength(2);
+ expect(rows.filter((r) => r.campaign_id === second.campaign_id)).toHaveLength(2);
+ expect((await backfill({ yes: true, max_usd: unit * 2 + 0.01 })).queued).toBe(0);
+ });
+
+ test('two overlapping invocations never share a page and neither exceeds its cap', async () => {
+ await pages(6);
+ const unit = await perPage();
+ const [a, b] = await Promise.all([backfill({ yes: true, max_usd: unit * 4 + 0.01 }), backfill({ yes: true, max_usd: unit * 3 + 0.01 })]);
+ const rows = await ledger();
+ expect(rows).toHaveLength(a.queued + b.queued);
+ expect(a.queued * unit).toBeLessThanOrEqual(unit * 4 + 1e-9);
+ expect(b.queued * unit).toBeLessThanOrEqual(unit * 3 + 1e-9);
+ expect(rows.filter((r) => r.campaign_id === a.campaign_id)).toHaveLength(a.queued);
+ expect(rows.filter((r) => r.campaign_id === b.campaign_id)).toHaveLength(b.queued);
+ });
+ });
+}
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 4851a49f6d..4649de5586 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1310,7 +1311,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index fcc9ff0f3e..f806ea99d7 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1310,7 +1311,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index e6ec97798a..50c5aec096 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1306,7 +1307,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index ea749fcf22..fa606b9089 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -8,6 +8,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -976,7 +977,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index a16af3a1db..6704135f17 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -8,6 +8,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -976,7 +977,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 7eeedc59b0..c0c3934a06 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -8,6 +8,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -975,7 +976,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 118dbb6449..e06d6731e5 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -8,6 +8,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -999,7 +1000,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 50d1d60fbc..f42906c4e8 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1311,7 +1312,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 97a39ce559..2887391da6 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1311,7 +1312,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index fb15901417..b379c83f26 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1307,7 +1308,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 13de54f1f9..6f48ce401d 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 207549,
- "stdoutSha256": "ba03674e7846f4d445030acf6a2bb53cd5544abdff7f8d28e480903f1e852586",
+ "stdoutBytes": 207947,
+ "stdoutSha256": "e701d9d6ea58a198e29b939eba243b90349890cb3713631c940fbcbe6781e06d",
"toolNames": [
"remember",
"entity",
@@ -5020,7 +5020,7 @@
"scope": "read"
},
{
- "description": "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]`.",
+ "description": "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. --max-usd is a hard bound counting retries: pages queue only while their worst case fits, and an unpriced chat model then refuses with no_pricing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--dated-since YYYY-MM-DD] [--recent] [--limit N] [--max-usd USD] [--dry-run | --yes]`.",
"idempotent": false,
"local_only": true,
"mutating": true,
@@ -5029,6 +5029,7 @@
"dated_since": "string?",
"dry_run": "boolean?",
"limit": "number?",
+ "max_usd": "number?",
"recent": "boolean?",
"since": "string?",
"yes": "boolean?"
@@ -5048,6 +5049,10 @@
"description": "Max pages queued in this run, across all types and sources (default 1000).",
"type": "number"
},
+ "max_usd": {
+ "description": "Hard spend bound in USD for everything this run queues, retries included; pages beyond it are not queued (cap_reached).",
+ "type": "number"
+ },
"recent": {
"description": "Only pages within chronicle.auto_recent_days (the automatic path's window).",
"type": "boolean"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 8f81c88074..a6f750e588 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -11,6 +11,7 @@
"chat_usage_log.chat_usage_log_pkey": "p PRIMARY KEY (id)",
"chronicle_judge_reservations.chronicle_judge_reservations_pkey": "p PRIMARY KEY (id)",
"chronicle_page_state.chronicle_page_state_attempts_check": "c CHECK ((attempts >= 0))",
+ "chronicle_page_state.chronicle_page_state_max_attempts_check": "c CHECK ((max_attempts > 0))",
"chronicle_page_state.chronicle_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"chronicle_page_state.chronicle_page_state_pkey": "p PRIMARY KEY (source_id, page_id, content_hash, extractor_version)",
"chronicle_page_state.chronicle_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -1310,7 +1311,13 @@
"17 event_slugs ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"18 event_hashes ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
"19 decided_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "20 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "21 campaign_id text/text NULL",
+ "22 attempt_cap_usd numeric/numeric NULL",
+ "23 max_attempts integer/int4 NULL",
+ "24 pricing_policy text/text NULL",
+ "25 campaign_max_usd numeric/numeric NULL",
+ "26 cost_attempts ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 56369fdc79..c7dbb9002d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -14,6 +14,7 @@
test/alias-source-cascade-5094.test.ts
test/attribution-backfill-history.test.ts
test/behavior-change-notice.test.ts
+test/chronicle-backfill-max-usd.test.ts
test/colon-slug-windows-5032.test.ts
test/company-brain-policy.test.ts
test/company-brain-runtime.test.ts